Java

…little Java stuff worth to write down…

Java little stuff

shebang support

#!/usr/bin/java --source 11
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hallo Java shebang");
    }
}

find files

File directory = new File("rschumm/");

Optional<Path> foundFile = Files.find(
        directory.toPath(), 
        3,
        (path, basicFileAttributes) -> path.toFile().getName().matches("blabla.*.yml")
        )
.sorted(Comparator.comparing(Path::getFileName))
.findFirst(); 

quick File as String:

String s = Files.lines(Paths.get("jekyll.md")).collect(Collectors.joining()); 

very quick and dirty templating find- and replace

String template = Files.lines(Paths.get("../nfs/pv-nfs.yml")).collect(Collectors.joining("\n")); 
String out = template.replaceAll("0001", ""+i).replaceAll("general", "general/"+i); 	
Files.write(Paths.get("pv"+i+".yml"), out.getBytes(), StandardOpenOption.CREATE); 

Java Stream stuff

Collect To List:

List<Stuff> stuffInCar = internalStuffs.stream().filter(d -> car.contains(d)).collect(Collectors.toList()); 
List<Stuff> stuffInCar = internalStuffs.stream().filter(car::contains).collect(Collectors.toList()); 

Collect to Array:

Coordinate[] coordinates = points.stream().map(p -> new Coordinate(p.x , p.y)).toArray(Coordinate[]::new);

Arrays:

Coordinate[] coordinates = new Coordinate[] {
    new Coordinate(1.0 , 1.0), 
    new Coordinate(1.0 , 100.0), 
    new Coordinate(100.0 , 100.0), 
    new Coordinate(100.0 , 1.0), 
    new Coordinate(1.0 , 1.0), 		                                            
}; 

Serializer- and Marshaller-Stuff

Jackson Json Object Mapper:


public static void writeJson(File f, MyModel i)
    throws JsonGenerationException, JsonMappingException, IOException {
  ObjectMapper mapper = new ObjectMapper();
  mapper.enable(SerializationFeature.INDENT_OUTPUT);
  mapper.writeValue(f, i);
}

public static MyModel readJson(File f) throws JsonParseException, JsonMappingException, IOException {
  ObjectMapper mapper = new ObjectMapper();
  // TODO validate to Schema 
  return mapper.readValue(f, MyModel.class); 
}


JAXB Marshaller:


public void marshall(File file) throws Exception {
  JAXBContext context = JAXBContext.newInstance(MyModel.class);
    Marshaller mar= context.createMarshaller();
    mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    
    mar.marshal(getMyModel(), file); 
}

JAXB Schema Class Generator


<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>jaxb2-maven-plugin</artifactId>
  <version>2.5.0</version>
  <executions>
    <execution>
      <id>xjc</id>
      <goals>
        <goal>xjc</goal>
      </goals>
    </execution>
  </executions>
  <configuration>
    <xjbSources>
      <xjbSource>src/main/resources/global.xjb</xjbSource>
    </xjbSources>
    <sources>
      <source>src/main/resources/schema/mySchema.xsd</source>
    </sources>
    <!-- <outputDirectory>${basedir}/src/main/java</outputDirectory> -->
    <clearOutputDir>false</clearOutputDir>
  </configuration>
</plugin>


JAXB Dependencies

<dependency>
  <groupId>javax.xml.bind</groupId>
  <artifactId>jaxb-api</artifactId>
  <version>2.3.1</version>
</dependency>

<dependency>
  <groupId>org.glassfish.jaxb</groupId>
  <artifactId>jaxb-runtime</artifactId>
  <version>2.3.1</version>
</dependency>
<!-- JAXB needs javax.activation module (jdk9) -->
<dependency>
  <groupId>javax.activation</groupId>
  <artifactId>javax.activation-api</artifactId>
  <version>1.2.0</version>
</dependency>

Framework-Blueprints

Rest-Client UniRest - super easy Rest-Client
Rest-assured used by Quarkus
Database Migration flyway
Spark Java WebApp Framework
HTML Parser jsoup
Json Parsing: Jackson or Gson cf hier Yaml Parsing: Jackson, cf Studrepos Example
git access: cf ebenda.

JavaScript

Quick and dirty Json-Load:

 <script src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>

///... 

<script>

function load(){
  $.ajax({
    url: '/hallo/logbuch',
    type: 'GET',
    success: function (response) {
        var trHTML = '';
        $.each(response, function (i, item) {
            trHTML += '<tr><th scope="row">' + item.id + '</th><td>' + item.text + '</td></tr>';
        });
        $('#nt').empty();
        $('#nt').append(trHTML);
    }
  });
}

load(); 

</script>

Quick and dirty Intercooler-Stuff:


<script src="https://intercoolerjs.org/release/intercooler-1.2.2.js"></script>

...  


<form>
    <div class="input-group">
      <input type="text" class="form-control" placeholder="Nachricht an Rémy" aria-label="Input group example" aria-describedby="btnGroupAddon" name="textinput">
      <button type="submit" class="btn btn-primary btn-default" ic-post-to="/hallo/sali" ic-target="#nachricht" ic-on-success="load();">
        Click Me!
      </button>
    </div>
</form>

and Quarkus Backend

@POST
@Transactional
@Produces(MediaType.TEXT_PLAIN)
@Path("/sali")
public String saliPost(@FormParam("textinput") String name) {
    Message message = new Message();
    message.text = name;
    message.date = LocalDate.now();
    message.persist();
    return service.sagHallo(name);
}

zurück zum Seitenanfang