I'm new to htmlunit (2.23) and I can't get this test to work:
I'm getting this ClassCastException thrown out of HtmlUnit and I don't know if it is a bug, or if I am doing something wrong.
java.lang.ClassCastException: com.gargoylesoftware.htmlunit.TextPage cannot be cast to com.gargoylesoftware.htmlunit.html.HtmlPage
at com.gargoylesoftware.htmlunit.WebClient.makeWebResponseForJavaScriptUrl(WebClient.java:1241)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:375)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:304)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:451)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:436)
at org.wyttenbach.dale.mlec.OutageTest.test(OutageTest.java:46)
...
The code
import java.awt.Desktop;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.JavaScriptPage;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.TextPage;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.DomElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class OutageTest {
private static final String SITE_URL = "https://ebill.mlecmn.net/woViewer/";
private static final String OUTAGE_MAP_URL = SITE_URL + "mapviewer.html?config=Outage+Web+Map";
#Test
public void test() throws FailingHttpStatusCodeException, MalformedURLException, IOException {
try (final WebClient webClient = new WebClient()) {
webClient.waitForBackgroundJavaScript(20000);
webClient.setAjaxController(new NicelyResynchronizingAjaxController());
webClient.getOptions().setUseInsecureSSL(true);
Map<String, Page> urls = new HashMap<String, Page>();
LinkedList<String> urlsToVisit = new LinkedList<String>();
urlsToVisit.add(OUTAGE_MAP_URL);
while (!urlsToVisit.isEmpty()) {
String url = urlsToVisit.remove();
if (urls.containsKey(url)) {
continue;
}
Page page = webClient.getPage(url);
urls.put(url, page);
if (page instanceof HtmlPage) {
HtmlPage page2 = (HtmlPage) page;
System.err.println("================================================================");
System.err.println(page2.asXml());
System.err.println("================================================================");
Assert.assertFalse("Outage in Nordland township: " + url, page2.asText().contains("Nordland"));
urlsToVisit.addAll(extractLinks(page2));
} else if (page instanceof JavaScriptPage) {
JavaScriptPage page2 = (JavaScriptPage) page;
Assert.assertFalse("Outage in Nordland township: " + url, page2.getContent().contains("Nordland"));
} else if (page instanceof TextPage) {
TextPage page2 = (TextPage) page;
Assert.assertFalse("Outage in Nordland township: " + url, page2.getContent().contains("Nordland"));
} else {
System.err.println(String.format("%s => %s", url, page.getClass().getName()));
}
}
} catch (AssertionError e) {
reportOutage();
throw e;
}
}
private Collection<String> extractLinks(HtmlPage page) {
List<String> links = new ArrayList<String>();
for (DomElement x : page.getElementsByTagName("script")) {
String src = x.getAttribute("src");
if (!src.contains(":")) {
src = SITE_URL + src;
System.err.println("script src="+src);
}
links.add(src);
}
for (DomElement x : page.getElementsByTagName("link")) {
String href = x.getAttribute("href");
if (!href.contains(":")) {
href = SITE_URL + href;
System.err.println("link href="+href);
}
links.add(href);
}
// Causes ClassCastException com.gargoylesoftware.htmlunit.TextPage cannot be cast to com.gargoylesoftware.htmlunit.html.HtmlPage
//at com.gargoylesoftware.htmlunit.WebClient.makeWebResponseForJavaScriptUrl(WebClient.java:1241)
for (DomElement x : page.getElementsByTagName("iframe")) {
String src = x.getAttribute("src");
if (!src.contains(":")) {
src = SITE_URL + src;
System.err.println("iframe src="+src);
}
links.add(src);
}
return links;
}
private void reportOutage() {
try {
Desktop.getDesktop().browse(new URI(OUTAGE_MAP_URL));
} catch (Exception e) {
e.printStackTrace();
}
}
}
More or less yes - but i have to do a more deeper analysis.
But there is some hope for you ;-)
Your code tries to extract urls from a given web page. During the process you are adding the url 'javascript:""' to your list of urls to be processes. This url results in this class cast exception. If you do not add this url to the list, the test is working (at least for me).
Related
I need to change the page orientation of some parts of a HTML. I followed the accepted answer for this question but the resulting PDF document had neither header nor footer (actually, no style at all).
Here is my first attempt:
package my.awesome.app.html2pdf;
import static com.itextpdf.styledxmlparser.css.media.MediaType.PRINT;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.attach.ITagWorker;
import com.itextpdf.html2pdf.attach.ProcessorContext;
import com.itextpdf.html2pdf.attach.impl.DefaultTagWorkerFactory;
import com.itextpdf.html2pdf.attach.impl.tags.DivTagWorker;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.IPropertyContainer;
import com.itextpdf.layout.element.AreaBreak;
import com.itextpdf.layout.element.Div;
import com.itextpdf.layout.element.IBlockElement;
import com.itextpdf.layout.layout.LayoutContext;
import com.itextpdf.layout.layout.LayoutResult;
import com.itextpdf.layout.renderer.AreaBreakRenderer;
import com.itextpdf.styledxmlparser.css.media.MediaDeviceDescription;
import com.itextpdf.styledxmlparser.node.IElementNode;
#RestController
#RequestMapping("/html2pdf")
public class Html2PdfController {
#PostMapping(produces = MediaType.APPLICATION_PDF_VALUE)
public #ResponseBody byte[] convert(#RequestBody String html) throws IOException {
try (var baos = new ByteArrayOutputStream()) {
var mediaDeviceDescription = new MediaDeviceDescription(PRINT);
var converterProperties = new ConverterProperties();
converterProperties.setMediaDeviceDescription(mediaDeviceDescription);
var pdfDocument = new PdfDocument(new PdfWriter(baos));
converterProperties.setTagWorkerFactory(new CustomTagWorkerFactory(pdfDocument));
var document = new Document(pdfDocument);
var elements = HtmlConverter.convertToElements(html, converterProperties);
for (var element : elements) {
if (element instanceof IBlockElement) {
document.add((IBlockElement) element);
}
}
pdfDocument.close();
return baos.toByteArray();
}
}
private static class CustomTagWorkerFactory extends DefaultTagWorkerFactory {
PdfDocument pdfDocument;
public CustomTagWorkerFactory(PdfDocument pdfDocument) {
this.pdfDocument = pdfDocument;
}
#Override
public ITagWorker getCustomTagWorker(IElementNode tag, ProcessorContext context) {
if ("landscape".equalsIgnoreCase(tag.name())) {
return new LandscapeDivTagWorker(tag, context, pdfDocument);
}
return null;
}
}
private static class LandscapeDivTagWorker extends DivTagWorker {
private PdfDocument pdfDocument;
public LandscapeDivTagWorker(IElementNode tag, ProcessorContext context, PdfDocument pdfDocument) {
super(tag, context);
this.pdfDocument = pdfDocument;
}
#Override
public IPropertyContainer getElementResult() {
IPropertyContainer baseElementResult = super.getElementResult();
if (baseElementResult instanceof Div) {
var div = new Div();
var landscapeAreaBreak = new AreaBreak(new PageSize(PageSize.A4).rotate());
landscapeAreaBreak.setNextRenderer(
new DefaultPageSizeChangingAreaBreakRenderer(landscapeAreaBreak, pdfDocument));
div.add(landscapeAreaBreak);
div.add((IBlockElement) baseElementResult);
var portraitAreaBreak = new AreaBreak(new PageSize(PageSize.A4));
portraitAreaBreak.setNextRenderer(
new DefaultPageSizeChangingAreaBreakRenderer(portraitAreaBreak, pdfDocument));
div.add(portraitAreaBreak);
baseElementResult = div;
}
return baseElementResult;
}
}
private static class DefaultPageSizeChangingAreaBreakRenderer extends AreaBreakRenderer {
private PdfDocument pdfDocument;
private AreaBreak areaBreak;
public DefaultPageSizeChangingAreaBreakRenderer(AreaBreak areaBreak, PdfDocument pdfDocument) {
super(areaBreak);
this.pdfDocument = pdfDocument;
this.areaBreak = areaBreak;
}
#Override
public LayoutResult layout(LayoutContext layoutContext) {
pdfDocument.setDefaultPageSize(areaBreak.getPageSize());
return super.layout(layoutContext);
}
}
}
And here is my first result. There is an additional blank page at its end:
After some small changes in the main method:
#PostMapping(produces = MediaType.APPLICATION_PDF_VALUE)
public #ResponseBody byte[] convert(#RequestBody String html) throws IOException {
try (var baos = new ByteArrayOutputStream()) {
var mediaDeviceDescription = new MediaDeviceDescription(PRINT);
var converterProperties = new ConverterProperties();
converterProperties.setMediaDeviceDescription(mediaDeviceDescription);
var pdfDocument = new PdfDocument(new PdfWriter(baos));
converterProperties.setTagWorkerFactory(new CustomTagWorkerFactory(pdfDocument));
var document = HtmlConverter.convertToDocument(html, pdfDocument, converterProperties);
document.close();
pdfDocument.close();
return baos.toByteArray();
}
}
I've got this PDF with nice headers and footers, except for the rotated pages. Also, only the first in a series is in landscape mode:
Actually the landscape pages do have footers, but they are misaligned.
Is there a way to achieve this using iText7 HTML to PDF conversion?
Hello
I try copy folder assets to external directory but getting permition error from android 11 (Api30).
But Its working well when copy or create folder to internal storage.
please help how to fix.
This is error code;
/com.strong.choosedirectory E/Tag: /storage/0E1A-2619/CTV_USB_EU/channel_list_sub.bin: open failed: EPERM (Operation not permitted)
This is main_activity code;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.krunal.choosedirectory.R;
import com.krunal.choosedirectory.databinding.ActivityMainBinding;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import pub.devrel.easypermissions.EasyPermissions;
import static com.krunal.choosedirectory.ClsGlobal.ClsGlobal.SELECT_DIRECTORY;
import static com.krunal.choosedirectory.ClsGlobal.ClsGlobal.requestPermission;
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
requestPermission(MainActivity.this);
binding.btnSelectDirectory.setOnClickListener(v -> {
Intent i = new Intent(this, SelectDirectoryActivity.class);
startActivityForResult(i, SELECT_DIRECTORY);
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// Forward results to EasyPermissions
EasyPermissions.onRequestPermissionsResult(requestCode,
permissions, grantResults, this);
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == SELECT_DIRECTORY && data != null) {
if (data != null) {
new File(data.getStringExtra("SelectedPath") + "/CTV_USB_EU/").mkdirs();
/////
requestPermission(MainActivity.this);
/////
binding.tvDrSelected.setText(data.getStringExtra("SelectedPath"));
// out = new FileOutputStream("".toString() + (data.getStringExtra("SelectedPath")) + fileName);
}
}
super.onActivityResult(requestCode, resultCode, data);
Button buton = (Button) findViewById(R.id.buton);
buton.setOnClickListener(new View.OnClickListener() { //butona tıklandığı an yapılacaklar
#Override
public void onClick(View view) {
new AlertDialog.Builder(MainActivity.this)
.setTitle("test tiklama calisti")
.setMessage("Seçilen USB Aygıtı " + (data.getStringExtra("SelectedPath")))
.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Tamam butonuna basılınca yapılacak olanlar
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("Files");
} catch (Exception e) {
Log.e("Tag", e.getMessage());
}
for (String fileName : files) {
System.out.println("Files=>" + fileName);
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open("Files/" + fileName);
out = new FileOutputStream("".toString() + "/" + (data.getStringExtra("SelectedPath")) + "/CTV_USB_EU/" + fileName);
copyFiles(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("Tag", e.getMessage());
}
}
// copyAssets();
}
})
.setNegativeButton("İptal", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// İptal butonuna basınca yapılacak olanlar
}
})
.show();
String isim;
isim = ("".toString() + (data.getStringExtra("SelectedPath")));
System.out.println((isim));
}
});
}
private void copyFiles (InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
public void mkDir (String args[])
{
// create an abstract pathname (File object)
File f = new File(toString(), "File");
// check if the directory can be created
// using the abstract path name
if (f.mkdir()) {
Log.d("BG", "Mkdir return: " );
// display that the directory is created
// as the function returned true
System.out.println("Directory is created");
} else {
// display that the directory cannot be created
// as the function returned false
System.out.println("Directory cannot be created");
}
}
}
lklklekflkpewkflkeşlkfeşwf
ewf
ewf
ew
fe
f
ewferw
g
wr
gşirlglwrlg
wrg
wg
e
glrşklgşrlg
w
grlwr
lg
wrlgirl
g
rwglşrwkg
rwk
g
wrgl
rlg
irlg
lrw
gl
wrlg
rwilg
riwlg
irwlg
irw
I want to index the data from dynamo DB to elasticsearch cloud SAAS. My elasticsearch endpoint will be like
elasticsearch endpoint URL
https://d9bc7cbca5ec49ea96a6ea683f70caca.eastus2.azure.elastic-cloud.com:1234
When ever if the CRUD operation happened in AWS dynamo db immediately it should get reflected in the index of elasticsearch cloud.
May i know the best way to achieve this?
Hi All thanks for all your support. I have attached the sample code it does the magic, I am able to index the data from dynamo db to elasticsearch both inside AWS and outside but we have to set a proper permission to lambda function as suggested in above comments.
package com.Firstlambda;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.auth.AWS4Signer;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.ItemUtils;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.lambda.runtime.events.DynamodbEvent;
import com.amazonaws.services.lambda.runtime.events.DynamodbEvent.DynamodbStreamRecord;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HelloWorld implements RequestHandler<DynamodbEvent, String> {
private static String serviceName = "es";
private static String region = "us-east-1";
private static String aesEndpoint = ""
private static String index = "";
private static String type = "_doc";
static final AWSCredentialsProvider credentialsProvider = new DefaultAWSCredentialsProviderChain();
public String handleRequest(DynamodbEvent ddbEvent, Context context) {
for (DynamodbStreamRecord record : ddbEvent.getRecords()) {
System.out.println("EventName : " + record.getEventName());
System.out.println("EventName : " + record.getDynamodb());
//AWS outside
RestHighLevelClient esClient = esClient();
//AWS outside
//AWS Inside
//RestHighLevelClient esClient = esClient(serviceName, region);
//AWS Inside
if (record.getEventName().toLowerCase().equals("insert")) {
String JsonString = getJsonstring(record.getDynamodb().getNewImage());
String JsonUniqueId = GetIdfromJsonString(JsonString);
IndexRequest indexRequest = new IndexRequest(index, type, JsonUniqueId);
indexRequest.source(JsonString, XContentType.JSON);
try {
IndexResponse indexResponse = esClient.index(indexRequest, RequestOptions.DEFAULT);
System.out.println(indexResponse.toString());
return "Successfully processed " + ddbEvent.getRecords().size() + " records.";
} catch (IOException e) {
System.out.println(e.getMessage());
}
} else if (record.getEventName().toLowerCase().equals("modify")) {
String JsonString = getJsonstring(record.getDynamodb().getNewImage());
String JsonUniqueId = GetIdfromJsonString(JsonString);
UpdateRequest request = new UpdateRequest(index, type, JsonUniqueId);
String jsonString = JsonString;
request.doc(jsonString, XContentType.JSON);
try {
UpdateResponse updateResponse = esClient.update(
request, RequestOptions.DEFAULT);
System.out.println(updateResponse.toString());
return "Successfully processed " + ddbEvent.getRecords().size() + " records.";
} catch (IOException e) {
System.out.println(e.getMessage());
}
} else {
System.out.println("remove");
System.out.println("KEYID : " + record.getDynamodb().getKeys().get("ID").getN());
String deletedId = record.getDynamodb().getKeys().get("ID").getN();
DeleteRequest request = new DeleteRequest(index, type, deletedId);
try {
DeleteResponse deleteResponse = esClient.delete(
request, RequestOptions.DEFAULT);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
return "Successfullyprocessed";
}
public String getJsonstring(Map<String, AttributeValue> newIma) {
String json = null;
Map<String, AttributeValue> newImage = newIma;
List<Map<String, AttributeValue>> listOfMaps = new ArrayList<Map<String, AttributeValue>>();
listOfMaps.add(newImage);
List<Item> itemList = ItemUtils.toItemList(listOfMaps);
for (Item item : itemList) {
json = item.toJSON();
}
return json;
}
public String GetIdfromJsonString(String Json) {
JSONObject jsonObj = new JSONObject(Json);
return String.valueOf(jsonObj.getInt("ID"));
}
// Adds the interceptor to the ES REST client
// public static RestHighLevelClient esClient(String serviceName, String region) {
// AWS4Signer signer = new AWS4Signer();
// signer.setServiceName(serviceName);
// signer.setRegionName(region);
// HttpRequestInterceptor interceptor = new AWSRequestSigningApacheInterceptor(serviceName, signer, credentialsProvider);
// return new RestHighLevelClient(RestClient.builder(HttpHost.create(aesEndpoint)).setHttpClientConfigCallback(hacb -> hacb.addInterceptorLast(interceptor)));
// }
public static RestHighLevelClient esClient() {
String host = "d9bc7cbca5ec49ea9gfde6a6ea683f70caca.eastus2.azure.elastic-cloud.com";
int port = 9200;
String userName = "elastic";
String password = "L4Nfnle3wxsfgjgLmV95lPiUb46hp";
String protocol = "https";
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(userName, password));
RestClientBuilder builder = RestClient.builder(new HttpHost(host, port, protocol))
.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
RestHighLevelClient client = new RestHighLevelClient(builder);
return client;
}
}
Does somebody implemented confluent-kafka messages deserializer to consume kafka messages by spring "#KafkaListener"-s ?
Here is my answer, which I've implemented based on: "io.confluent.kafka.serializers.AbstractKafkaAvroDeserializer"
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Map;
import javax.xml.bind.DatatypeConverter;
import org.apache.avro.Schema;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.DecoderFactory;
import org.apache.avro.specific.SpecificDatumReader;
import org.apache.avro.specific.SpecificRecordBase;
import org.apache.kafka.common.errors.SerializationException;
import org.apache.kafka.common.serialization.Deserializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AvroConfluentDeserializer<T extends SpecificRecordBase> implements Deserializer<T> {
private static final Logger LOG = LoggerFactory.getLogger(AvroConfluentDeserializer.class);
protected static final byte MAGIC_BYTE = 0x0;
protected static final int idSize = 4;
private final DecoderFactory decoderFactory = DecoderFactory.get();
protected final Class<T> targetType;
public AvroConfluentDeserializer(Class<T> targetType) {
this.targetType = targetType;
}
#Override
public void close() {
// No-op
}
#Override
public void configure(Map<String, ?> arg0, boolean arg1) {
// No-op
}
#Override
public T deserialize(String topic, byte[] data) {
try {
T result = null;
if (data != null) {
LOG.info("data='{}'", DatatypeConverter.printHexBinary(data));
result = (T) deserializePayload(data, targetType.newInstance().getSchema());
LOG.info("deserialized data='{}'", result);
}
return result;
} catch (Exception ex) {
throw new SerializationException(
"Can't deserialize data '" + Arrays.toString(data) + "' from topic '" + topic + "'", ex);
}
}
protected T deserializePayload(byte[] payload, Schema schema) throws SerializationException {
int id = -1;
try {
ByteBuffer buffer = getByteBuffer(payload);
id = buffer.getInt();
int length = buffer.limit() - 1 - idSize;
int start = buffer.position() + buffer.arrayOffset();
DatumReader<T> reader = new SpecificDatumReader<T>(schema);
return reader.read(null, decoderFactory.binaryDecoder(buffer.array(), start, length, null));
} catch (IOException | RuntimeException e) {
throw new SerializationException("Error deserializing Avro message for id " + id, e);
}
}
private ByteBuffer getByteBuffer(byte[] payload) {
ByteBuffer buffer = ByteBuffer.wrap(payload);
if (buffer.get() != MAGIC_BYTE) {
throw new SerializationException("Unknown magic byte!");
}
return buffer;
}
}
[ERROR] could not initialize proxy - no Session
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:57)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:111)
at org.hibernate.proxy.pojo.cglib.CGLIBLazyInitializer.invoke(CGLIBLazyInitializer.java:150)
at com.model.dto.Distination$$EnhancerByCGLIB$$f4a8517c.getLibileDis(<generated>)
at com.business.impl.MeteobussinesImpl.afficherMeteo1(MeteobussinesImpl.java:30)
at com.test.Tester.main(Tester.java:32)
[ERROR] could not initialize proxy - no Session
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:57)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:111)
at org.hibernate.proxy.pojo.cglib.CGLIBLazyInitializer.invoke(CGLIBLazyInitializer.java:150)
at com.model.dto.Distination$$EnhancerByCGLIB$$f4a8517c.toString(<generated>)
at com.model.dto.Distination$$EnhancerByCGLIB$$f4a8517c.getLibileDis(<generated>)
at com.business.impl.MeteobussinesImpl.afficherMeteo1(MeteobussinesImpl.java:30)
at com.test.Tester.main(Tester.java:32)
1.class main
package com.test;
import java.util.Iterator;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.business.Meteobussines;
import com.business.impl.MeteobussinesImpl;
import com.model.vo.Meteo;
public class Tester {
static public void displayList(List list)
{ Iterator iter = list.iterator();
if (!iter.hasNext())
{ System.out.println("La lsite est vide"); return; }
while (iter.hasNext()) {
Meteo ct = (Meteo) iter.next();
System.out.println("tempsMax :" + ct.getTempMax() + " pays :" + ct.getLibilePays() + " distination :" + ct.getLibileDistination()); }}
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] configArray = new String[] { "/com/resource/spring/ApplicationContext.xml",
"/com/resource/spring/ApplicationContextDao.xml","/com/resource/spring/ApplicationContextBusiness.xml"};
ApplicationContext ctx = new ClassPathXmlApplicationContext(configArray);
Meteobussines mete = (Meteobussines) ctx.getBean("MeteoBuss");
List<Meteo> m = mete.afficherMeteo1("tounes");
displayList(m);
}
}
2.Meteobussiness
package com.business.impl;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.business.Meteobussines;
import com.dao.HistoriqueDao;
import com.dao.impl.HistoriqueDaoImpl;
import com.model.dto.Historique;
import com.model.vo.Meteo;
public class MeteobussinesImpl implements Meteobussines {
HistoriqueDao historiqueDao ;
#SuppressWarnings("null")
#Override
public List<Meteo> afficherMeteo1(String pays) {
List<Historique> hiss= historiqueDao.rechercher(pays);
List<Meteo> m = new ArrayList<Meteo>(); ;
Iterator iter = hiss.iterator();
if (!iter.hasNext())
{ System.out.println("La lsite est vide"); }
while (iter.hasNext()) {
Historique ct = (Historique) iter.next();
Meteo me =new Meteo();
me.setDateHis(ct.getDateHis());
me.setLibileDistination(ct.getDistination().getLibileDis());
me.setLibilePays(ct.getPays().getLibilePays());
me.setLibileVille(ct.getVille().getLibileVille());
me.setTempMax(ct.getTempMax());
me.setTempMin(ct.getTempMin());
m.add(me);
}
return m;
// TODO Auto-generated method stub
}
#Override
public List<Meteo> afficherMeteo2(String pays, String ville) {
// TODO Auto-generated method stub
return null;
}
#Override
public List<Meteo> afficherMeteo3(String pays, String ville,
String distination) {
// TODO Auto-generated method stub
return null;
}
public HistoriqueDao getHistoriqueDao() {
return historiqueDao;
}
public void setHistoriqueDao(HistoriqueDao historiqueDao) {
this.historiqueDao = historiqueDao;
}
}
3.HistroiqueDaao
package com.dao.impl;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.criterion.Expression;
import com.dao.HistoriqueDao;
import com.model.dto.Historique;
#SuppressWarnings("unchecked")
public class HistoriqueDaoImpl extends GenericDaoImpl implements HistoriqueDao {
#Override
public List<Historique> rechercher(String critere1, String critere2,
String critere3) {
Criteria crit = getSession().createCriteria(Historique.class);
crit.setFetchMode("pays", FetchMode.JOIN);
crit.createAlias("pays", "p");
crit.add(Expression.eq("p.libilePays", critere1));
crit.setFetchMode("ville", FetchMode.JOIN);
crit.createAlias("ville", "b");
crit.add(Expression.eq("b.libileVille", critere2));
crit.setFetchMode("distination", FetchMode.JOIN);
crit.createAlias("distination", "d");
crit.add(Expression.eq("d.libileDis", critere3));
List<Historique> his = crit.list();
return his;
}
#Override
public List<Historique> rechercher(String critere1, String critere2) {
// TODO Auto-generated method stub
Criteria crit = getSession().createCriteria(Historique.class);
crit.setFetchMode("pays", FetchMode.JOIN);
crit.createAlias("pays", "p");
crit.add(Expression.eq("p.libilePays", critere1));
crit.setFetchMode("ville", FetchMode.JOIN);
crit.createAlias("ville", "b");
crit.add(Expression.eq("b.libileVille", critere2));
List<Historique> his = crit.list();
return his;
}
#Override
public List<Historique> rechercher(String critere1) {
// TODO Auto-generated method stub
Criteria crit = getSession().createCriteria(Historique.class);
crit.setFetchMode("pays", FetchMode.JOIN);
crit.createAlias("pays", "p");
crit.add(Expression.eq("p.libilePays", critere1));
List<Historique> his = crit.list();
return his;
}
}
3.i use DaoSupport initialize in spring
The stack trace points to this line:
me.setLibileDistination(ct.getDistination().getLibileDis());
ct is a Historique proxy = a fake object whose fields (including the one you obtain through getDistination()) are not yet initiated.
Please initialize the fields you are interested in before committing the Hibernate transaction.
Hibernate.initialize(ct.getDistination());
crit.setFetchMode("pays", FetchMode.JOIN);
crit.setFetchMode("ville", FetchMode.JOIN);
crit.setFetchMode("distination", FetchMode.JOIN);
this the soultion of the problem cause i have in all the case to open the fetchmode.join