25 Aralık 2020 Cuma

Camel Exception Kavramı

Giriş
Exception Route içinde yakalanır Açıklaması şöyle
The clause can either be included inside a specific route definition in order to handle exceptions thrown in said route as shown in the example, or on top of all route definitions in order to catch exceptions that could be thrown anywhere in the router.

It’s important to mention the clause handled(), which determines what to do when an exception is thrown. In this case, since we want to stop the execution and handle the exception, we used handled(true). If we used handled(false), the exception would be rethrown and it could either be caught in a different onException clause or crash the application. The default value is false, which means if we don’t include the clause, the exception will continue to crash the application.
Örnek
Şöyle yaparız. Burada exception bir route içinde yakalanıyor. handled(true) yapılıyor.
from("direct:say-hi")
  .onException(MissingParameterException.class)
    .handled(true)
    .setBody(constant("Expected a query param 'name' that could not be found."))
  .end()
  .choice()
    .when(isNull(header(NAME_TAG)))
      .throwException(new MissingParameterException())
    .otherwise()
      .setProperty(NAME_TAG, header(NAME_TAG))
  .end()
  .setBody(simple(String.format("Hello, ${property.%s}!", NAME_TAG)))
;

24 Aralık 2020 Perşembe

Camel Exchange Kavramı

Giriş
Exchange kavramına başlamadan önce Header ve Property kavramını bilmek gerekir.

1. Header
- header("headername") şeklinde erişiriz.

Örnek
"localhost:8080/hello?name=john" şeklindeki istekte name header içinde. header("name") şeklinde erişiriz.

Örnek - header'ın varlığına göre işlem
Şöyle yaparız. Burada when() içinde exchange varlığı kontrol ediliyor. Eğer yoksa otherwise() içinde başka bir işlem yapılıyor
@Component
public class Router extends RouteBuilder {
  private static final String NAME_TAG = "name";
  @Override
  public void configure() throws Exception {
    restConfiguration()
      .bindingMode(RestBindingMode.json);
    rest("hello")
      .get()
      .route()
       .choice()
        .when(isNull(header(NAME_TAG)))
          .setProperty(NAME_TAG, constant("world"))
        .otherwise()
          .setProperty(NAME_TAG, header(NAME_TAG))
        .end()
        .setBody(simple(String.format("Hello, ${property.%s}!", NAME_TAG)));
  }
}
Örnek - header değerine erişme
Eğer header değerinin olduğundan eminsek kontrol etmeksizin şöyle yaparız
@Component
public class Soap2Rest extends RouteBuilder{

  @Override
  public void configure() throws Exception {

    from("direct:celsius-to-fahrenheit")
      .removeHeaders("CamelHttp*")
      .process(new Processor() {
        @Override
        public void process(Exchange exchange) throws Exception {
          Double.valueOf(exchange.getIn().getHeader("num"));
          ...
        }
      })
      ...
  }
}
2. Property
Açıklaması şöyle
For now, let’s just say properties are values that, unlike headers, live throughout the entire course of the application.
- setProperty("propertyname",propertyvalue) şeklinde değer atarız
- String.format("${property.%s}!", "propertyname") şeklinde değerine erişiriz

3. Exchange
Route'lar arasında dolaşırlar
- Header ve Body alanlarına sahiptir. Açıklaması şöyle
Headers and bodies are volatile, and they are saved in two different Messages or parts of the Exchange: IN (incoming information) and OUT (outgoing information). We call them volatile because they don’t live throughout the entire course of the application, but rather die after reaching an endpoint or processing information from the exchange.
Processor'lar Exchange'lere erişir. 

Örnek - header atama
Şöyle yaparız
@Component
public class MomentOfDayProcessor implements Processor {
  @Override
  public void process(Exchange exchange) throws Exception {
    String momentOfDay = "...";
    exchange.getOut().setHeader("momentOfDay", momentOfDay);
  }
}
Örnek - body atama
Şöyle yaparız
@Component
public class WeatherAdviserProcessor implements Processor {
  @Override
  public void process(Exchange exchange) throws Exception {
    WeatherResponse weatherResponse = exchange.getIn().getBody(WeatherResponse.class);
    ...
    String advice = "...";
    exchange.getOut().setBody(advice);
  }
}
Örnek - body atama
Şöyle yaparız. Burada getOut().setBody() yerine getMessage().setBody() kullanılıyor.
public class HelloWorldProcessor implements Processor {

  @Override
  public void process(Exchange exchange) throws Exception {
    Map<String, Object> result = new HashMap<>();
    result.put("message", "Hello world");
    exchange.getMessage().setBody(result);
  }
}
Açıklaması şöyle
If using InOnly MEP, methods getIn() and getMessage() returns the same instance of Message.

The logic of getMesage() is simple. If exchange have associated out message, return out. Otherwise return in.

In most cases there will be no out message associated with Exchange. In Apache Camel 3 is getOut() deprecated, reserved for edge cases and internal use for component developers. End users are encouraged to prefer getMessage() instead of getIn() and getOut().


23 Aralık 2020 Çarşamba

Camel RestDefinition Sınıfı

Giriş
1. İsteğe kendimiz cevap verebiliriz.
2. İsteği başka bir bileşene gönderebiliriz.

Örnek - get İsteğine Enpoint İçinde Cevap Verebiliriz
Şöyle yaparız
@Component
public class Router extends RouteBuilder {
  private static final String NAME_TAG = "name";
  @Override
  public void configure() throws Exception {
    restConfiguration()
      .bindingMode(RestBindingMode.json);
    rest("hello")
      .get()
      .route()
       .choice()
        .when(isNull(header(NAME_TAG)))
          .setProperty(NAME_TAG, constant("world"))
        .otherwise()
          .setProperty(NAME_TAG, header(NAME_TAG))
        .end()
        .setBody(simple(String.format("Hello, ${property.%s}!", NAME_TAG)));
  }
}
Örnek - get ile Aynı Sınıftaki Route Tetiklemek
Şöyle yaparız. Bu örnekte istek endpoint'ten from () ile tanımlanan Route'a yönlendiriliyor.
rest()
  .get("hello").route().to("direct:say-hi").endRest()
  .get("bye").route().to("direct:say-bye").endRest()
;
from("direct:say-hi")
  .choice()
    .when(isNull(header(NAME_TAG)))
      .setProperty(NAME_TAG, constant("world"))
    .otherwise()
      .setProperty(NAME_TAG, header(NAME_TAG))
    .end()
    .setBody(simple(String.format("Hello, ${property.%s}!", NAME_TAG)))
;
from("direct:say-bye")
  .setBody(simple("Bye, see you soon!"))
;
Örnek - get ile Başka Sınıftaki Route Tetiklemek
Şöyle yaparız. Bu örnekte istek endpoint'ten from () ile tanımlanan Route'a yönlendiriliyor. Route ise .process(...) aracılığıyla isteği işliyor
@Component
public class RestConfig extends RouteBuilder{

  @Override
  public void configure() throws Exception {
    rest("/convert")

      .get("/celsius/to/fahrenheit/{num}")
        .consumes("text/plain").produces("text/plain")
        .description("Convert a temperature in Celsius to Fahrenheit")
        .param().name("num").type(RestParamType.path)
          .description("Temperature in Celsius")
          .dataType("int").endParam()
        .to("direct:celsius-to-fahrenheit")

      .get("/fahrenheit/to/celsius/{num}")
        .consumes("text/plain").produces("text/plain")
.description("Convert a temperature in Fahrenheit to Celsius")
.param().name("num").type(RestParamType.path)
          .description("Temperature in Fahrenheit")
          .dataType("int").endParam()
.to("direct:fahrenheit-to-celsius");
  }
}
Bu rest noktasını tetiklemek için şöyle yaparız
curl localhost:9090/convert/celcius/to/fahrenheit/50
Parametreye karşı bileşende erişmek için şöyle yaparız
@Component
public class Soap2Rest extends RouteBuilder{

  @Override
  public void configure() throws Exception {

    from("direct:celsius-to-fahrenheit")
      .removeHeaders("CamelHttp*")
      .process(new Processor() {
        @Override
        public void process(Exchange exchange) throws Exception {
          Double.valueOf(exchange.getIn().getHeader("num"));
          ...
        }
      })
      ...
  }
}
Örnek - get ile Aynı Sınıftaki Route Tetiklemek
Şöyle yaparızBu örnekte istek endpoint'ten from () ile tanımlanan Route'a yönlendiriliyor. Route ise .bean(...) metoduyla isteği işliyor
@Component
public class BookRoute extends RouteBuilder {

    private final Environment env;

    public BookRoute(Environment env) {
        this.env = env;
    }

  public void configure() throws Exception {

    restConfiguration()
      .contextPath(env.getProperty("camel.component.servlet.mapping.contextPath", "/rest/*"))
      .apiContextPath("/api-doc")
      .apiProperty("api.title", "Spring Boot Camel Postgres Rest API.")
      .apiProperty("api.version", "1.0")
      .apiProperty("cors", "true")
      .apiContextRouteId("doc-api")
      .port(env.getProperty("server.port", "8080"))
      .bindingMode(RestBindingMode.json);

    rest("/book")
      .consumes(MediaType.APPLICATION_JSON_VALUE)
      .produces(MediaType.APPLICATION_JSON_VALUE)
      .get("/{name}").route()
       .to("{{route.findBookByName}}")
      .endRest()
      .get("/").route()
       .to("{{route.findAllBooks}}")
      .endRest()
      .post("/").route()
       .marshal().json()
       .unmarshal(getJacksonDataFormat(Book.class))
       .to("{{route.saveBook}}")
      .endRest()
      .delete("/{bookId}").route()
        .to("{{route.removeBook}}")
      .end();

      from("{{route.findBookByName}}")
        .log("Received header : ${header.name}")
        .bean(BookService.class, "findBookByName(${header.name})");

    from("{{route.findAllBooks}}")
      .bean(BookService.class, "findAllBooks");


    from("{{route.saveBook}}")
     .log("Received Body ${body}")
     .bean(BookService.class, "addBook(${body})");


    from("{{route.removeBook}}")
      .log("Received header : ${header.bookId}")
     .bean(BookService.class, "removeBook(${header.bookId})");
  }

  private JacksonDataFormat getJacksonDataFormat(Class<?> unmarshalType) {
    JacksonDataFormat format = new JacksonDataFormat();
    format.setUnmarshalType(unmarshalType);
    return format;
  }
}
Örnek - get ile Harici Bir Servise Get Yapmak
Şöyle yaparız. toD() ile bir başka servise çağrı yapıyoruz.
from(CamelConstants.WEATHER_ROUTE)
    .setProperty(CITY_TAG, header(CITY_TAG))
    .removeHeaders("*")
    .setHeader(Exchange.HTTP_METHOD, constant(HttpMethods.GET))
    .toD(generateServiceUrl())
    .unmarshal().json(JsonLibrary.Jackson, WeatherResponse.class)
    .process(weatherAdviserProcessor)
toD() ile kullanılan metod şöyle
private static final String WEATHER_SERVICE_URL =
"http://api.weatherstack.com/current?access_key=%s&query=%s&units=m";

@Value(value = "${api.key}")
private String apiKey;

private String generateServiceUrl() {
  return String.format(WEATHER_SERVICE_URL, apiKey,
String.format("${property.%s}", CITY_TAG));
}
Gelen cevabı işleyip çeviren processor şöyle
@Component
public class WeatherAdviserProcessor implements Processor {
  @Override
  public void process(Exchange exchange) throws Exception {
    WeatherResponse weatherResponse = exchange.getIn().getBody(WeatherResponse.class);
    ...
    String advice = "...";
    exchange.getOut().setBody(advice);
  }
}

17 Aralık 2020 Perşembe

Compress ZipFile Sınıfı

Giriş
Şu satırı dahil ederiz.
import org.apache.commons.compress.archivers.zip.ZipFile;
constructor - File
Şöyle yaparız
ZipFile z = new ZipFile(zippath);
Enumeration<ZipArchiveEntry> entries = z.getEntries();

while(entries.hasMoreElements()) {
  ZipArchiveEntry entry = entries.nextElement();
  System.out.println("Entry: "+entry.getName());
  BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(unzipfolder+"\\"+entry.getName())); BufferedInputStream bis = new BufferedInputStream(z.getInputStream(entry)); byte[] buffer=new byte[1000000]; int len=0; while((len=bis.read(buffer,0,1000000))>0) { bos.write(buffer, 0, len) ; } bis.close(); bos.close(); }

1 Aralık 2020 Salı

PDDocument Sınıfı

Giriş
Şu satırı dahil ederiz
import org.apache.pdfbox.pdmodel.PDDocument;
load metodu
Şöyle yaparız
byte[] bytearray = ...;
   
PDDocument pddocument = null;
try {
  pddocument = org.apache.pdfbox.pdmodel.PDDocument.load(this.bytearray);
} catch (IOException e) {
  ...
}