14 Aralık 2022 Çarşamba

Apache Commons Exec

Giriş
Bir shell script veya başar bir uygulamayı çalıştırıp çıktısını okumak için kullanılır
DefaultExecutor harici uygulamayı çalıştırır
PumpStreamHandler çıktıyı toparlar

Gradle
Şu satırı dahil ederiz
implementation group: 'org.apache.commons', name: 'commons-exec', version: '1.3'

5 Aralık 2022 Pazartesi

HttpComponents HttpClientBuilder Sınıfı

Giriş
Şu satırı dahil ederiz.
import org.apache.http.impl.client.HttpClientBuilder;
setDefaultRequestConfig metodu
Tüm client için timeout ayarları yapılabilir.
Örnek
Şöyle yaparız
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

HttpGet request = new HttpGet("https://httpbin.org/get");

// 5 seconds timeout
RequestConfig requestConfig = RequestConfig.custom()
  .setConnectionRequestTimeout(5_000)
  .setConnectTimeout(5_000)
  .setSocketTimeout(5_000)
  .build();

try (CloseableHttpClient httpClient = HttpClientBuilder.create()
  .setDefaultRequestConfig(requestConfig)
  .build();
   CloseableHttpResponse response = httpClient.execute(request)) {
  ...
}
setUserAgent metodu
Şöyle yaparız.
CloseableHttpClient httpClient = HttpClients.custom()
  .setUserAgent(HTTP_USER_AGENT).
  .build();
HttpGet request = new HttpGet(url);
HttpResponse response = httpClient.execute(request);
setSSLSocketFactory metodu
Örnek
Şöyle yaparız
HttpClientBuilder builder = HttpClients.custom();
javax.net.ssl.SSLContext sslContext = SSLContext.getInstance("TLSv1.1");
javax.net.ssl.KeyManager[] clientKeyManagers = ...;
javax.net.ssl.TrustManager[] clientTrustManagers = ...;
sslContext.init(clientKeyManagers, clientTrustManagers, new SecureRandom());

builder.setSSLSocketFactory(
  new org.apache.http.conn.ssl.SSLConnectionSocketFactory(sslContext,
    SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
);
CloseableHttpClient client = builder.build();

27 Ekim 2022 Perşembe

Failable Sınıfı - Lambda İçinde Exception İçindir

Giriş
Şu satırı dahil ederiz
import org.apache.commons.lang3.function.Failable;
Örnek
Şöyle yaparız
Stream<String> stream = Stream.of("...", "...", "...");
Failable.stream(stream)
  //throws a ClassNotFoundException wrapped in an UndeclaredThrowableException at runtime. 
  .map(Class::forName)  
  .forEach(System.out::println);



23 Eylül 2022 Cuma

Camel Choice ve When - Content Based Routing İçindir

Giriş
Açıklaması şöyle
Apache Camel contains a powerful feature called content-based routers. This allows you to process the message differently relying on the content.

They are quite similar to the if/else statement in Java. Regardless, in Camel, the equivalent words are when and otherwise.
Örnek
Şöyle yaparız
import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;

@Component
public class ChoiceWhenRoute extends RouteBuilder {
  @Override
  public void configure() throws Exception {

    from("direct:startWhenChoiceRoute")
      .routeId("direct:startWhenChoiceRoute")
      .log( "${body}")
      .choice()
      .when(body().isNull())
      .log("Message body is empty.")
      .log("${body}")
      .end();
  }
}
Test için şöyle yaparız
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.ExchangeBuilder;

@RestController
public class Controler {

  @Autowired
  private ProducerTemplate producerTemplate;

  @Autowired
  private CamelContext camelContext;

  @GetMapping
  public void function() {
    Exchange requestExchange = ExchangeBuilder
      .anExchange(camelContext)
      .build();

    producerTemplate
      .send("direct:startWhenChoiceRoute",requestExchange);

  }
}



18 Nisan 2022 Pazartesi

Jena - Semantic Web

Gradle
Şu satırı dahil ederiz
implementation "org.apache.jena:apache-jena-libs:4.0.0"
Örnek
Şöyle yaparız
OntModel model = ModelFactory.createOntologyModel("http://www.w3.org/2000/01/rdf-schema#");
RDFParser.source("https://schema.org/version/latest/schemaorg-current-https.jsonld")
  .parse(model);



13 Aralık 2021 Pazartesi

Camel Resequence

Giriş
İki çeşit resequence işlemi var
1. Batch resequencing
2. Stream resequencing

2. Stream resequencing
Örnek
Elimizde şöyle bir comparator olsun
import org.apache.camel.Exchange;
import org.apache.camel.Expression;
import org.apache.camel.processor.resequencer.ExpressionResultComparator;

@NoArgsConstructor(staticName = "of")
class CustomPriorityComparator implements ExpressionResultComparator {

  @Override
  public void setExpression(Expression expression) {// do nothing}

  @Override
  public boolean predecessor(Exchange o1, Exchange o2) {return false;}

  @Override
  public boolean successor(Exchange o1, Exchange o2) {return false;}

  @Override
  public boolean isValid(Exchange exchange) {
    return exchange.getMessage().getBody() instanceof String;
  }

  @Override
  public int compare(Exchange exchange1, Exchange exchange2) {
    return getMessageAsString(exchange1).compareTo(getMessageAsString(exchange2));
  }

  private static String getMessageAsString(Exchange exchange) {
    return String.valueOf(exchange.getMessage().getBody());
  }
}
Şöyle yaparız
import org.springframework.stereotype.Component;

@Component
public class ResequenceRoute extends RouteBuilder {

  private static final String TOPIC_TO_CONSUME = "incoming_channel";
  private static final String TOPIC_TO_FORWARD = "outgoing_channel";
  private static final String BOOTSTRAP_URL = "localhost:9092";
  private static final String CONSUMER_GROUP = "resequencer";
  private static final Integer RESEQUENCER_CAPACITY = 100;
  private static final Long RESEQUENCER_TIMEOUT = 5000L;
   

  @Override
  public void configure() {
    from("kafka:" + TOPIC_TO_CONSUME + "?brokers=" + BOOTSTRAP_URL + "&groupId=" + CONSUMER_GROUP)
      .resequence()
      .body()
      .stream()
      .capacity(RESEQUENCER_CAPACITY)
      .timeout(RESEQUENCER_TIMEOUT)
      .comparator(CustomPriorityComparator.of())
      .to("kafka:" + TOPIC_TO_FORWARD + "?brokers=" + BOOTSTRAP_URL);
    }
}

28 Ekim 2021 Perşembe

POI Kullanımı

Maven
Şu satırı dahil ederiz
<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi</artifactId>
  <version>4.1.2</version>
</dependency>
<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml</artifactId>
  <version>4.1.2</version>
</dependency>
Yazma
Her şey XSSWorkbook sınıfı etrafında dönüyor.
Örnek
Şöyle yaparız
ByteArrayOutputStream bos = new ByteArrayOutputStream();

try (Workbook workbook = new XSSFWorkbook()) {
  ...
} catch (Exception e) {
  ...
} finally {
  bos.close();
}
return bos.toByteArray();
Yazarken Font ve fontların kullanılacağı CellStyle nesnelerini oluşturmak gerekir. Şöyle yaparız
//setting up the basic styles for the workbook Font boldFont = getBoldFont(workbook); Font genericFont = getGenericFont(workbook); CellStyle headerStyle = getLeftAlignedCellStyle(workbook, boldFont); CellStyle currencyStyle = setCurrencyCellStyle(workbook); CellStyle centerAlignedStyle = getCenterAlignedCellStyle(workbook); CellStyle genericStyle = getLeftAlignedCellStyle(workbook, genericFont);
Daha sonra bir Sheet oluşturulur. Şöyle yaparız
String sheetName = ...
Sheet sheet = workbook.createSheet(sheetName);
Daha sonra bir başlık oluşturulur. Şöyle yaparız
int tempRowNo = 0;

//set spreadsheet titles
Row mainRow = sheet.createRow(tempRowNo++);

for (int i = 0; i < columnTitles.length; i++) {
  Cell columnTitleCell = mainRow.createCell(i);
  columnTitleCell.setCellStyle(headerStyle);
  columnTitleCell.setCellValue(columnTitles[i]);
}
Daha sonra veriyi sütunlar halinde yazarız. Şöyle yaparız
//looping the dataset
for (T record : data) {
  
  Row mainRow = sheet.createRow(tempRowNo++);
  Cell compositeNewCell = mainRow.createCell(cellIndex);
  cell.setCellValue(...);
  Hyperlink link = workbook.getCreationHelper().createHyperlink(HyperlinkType.URL);
  link.setAddress(...);
  cell.setHyperlink(link);
  ...
}
Tabi bu işleri yaparken bir sürü yardımcı metod gerekiyor. Bunları hep kodlamak lazım

Örnek
Elimizde şöyle bir kod olsun
public class ExcelGenerator {
  private List < Student > studentList = ...;
  private XSSFWorkbook workbook = new XSSFWorkbook();
  private XSSFSheet sheet;

  private void writeHeader() {
    sheet = workbook.createSheet("Student");
    Row row = sheet.createRow(0);
    CellStyle style = workbook.createCellStyle();
    XSSFFont font = workbook.createFont();
    font.setBold(true);
    font.setFontHeight(16);
    style.setFont(font);
    createCell(row, 0, "ID", style);
    createCell(row, 1, "Student Name", style);
    createCell(row, 2, "Email", style);
    createCell(row, 3, "Mobile No.", style);
  }
  private void createCell(Row row, int columnCount, Object valueOfCell,
    CellStyle style) {
    sheet.autoSizeColumn(columnCount);
    Cell cell = row.createCell(columnCount);
    if (valueOfCell instanceof Integer) {
      cell.setCellValue((Integer) valueOfCell);
    } else if (valueOfCell instanceof Long) {
      cell.setCellValue((Long) valueOfCell);
    } else if (valueOfCell instanceof String) {
      cell.setCellValue((String) valueOfCell);
    } else {
      cell.setCellValue((Boolean) valueOfCell);
    }
    cell.setCellStyle(style);
  }
  private void write() {
    int rowCount = 1;
    CellStyle style = workbook.createCellStyle();
    XSSFFont font = workbook.createFont();
    font.setFontHeight(14);
    style.setFont(font);
    for (Student record: studentList) {
      Row row = sheet.createRow(rowCount++);
      int columnCount = 0;
      createCell(row, columnCount++, record.getId(), style);
      createCell(row, columnCount++, record.getStudentName(), style);
      createCell(row, columnCount++, record.getEmail(), style);
      createCell(row, columnCount++, record.getMobileNo(), style);
    }
  }
}
Şöyle yaparız. Burada Excep direkt servlet cevabına yazılıyor
public class ExcelGenerator {
  
  public void generateExcelFile(HttpServletResponse response) throws IOException {
    writeHeader();
    write();
    ServletOutputStream outputStream = response.getOutputStream();
    workbook.write(outputStream);
    workbook.close();
    outputStream.close();
  }
}
Dosya İndirme
Örnek - SpringBoot
Şöyle yaparız
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

@Controller
public class UserController {

  @Autowired
  private UserService userService;

  @RequestMapping(method = RequestMethod.POST, value = "/download-users")
  public ResponseEntity downloadUsersExcel() {
    try {
      final byte[] data = userService.getUserXlsData();
      HttpHeaders header = new HttpHeaders();
      header.setContentType(MediaType.parseMediaType(
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8"));
      header.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename= users.xlsx");
      header.setContentLength(data.length);
      return new ResponseEntity<>(data, header, HttpStatus.OK);
    } catch (Exception e) {
      return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
}