ClassCastException on thinClient in Apache Ignite - hashmap

ClientConfiguration cfg = new ClientConfiguration().setAddresses("127.0.0.1:10800");
try (IgniteClient igniteClient = Ignition.startClient(cfg)) {
System.out.println(">>> Thin client put-get example started.");
final String CACHE_NAME = "put-get-example";
ClientCache<Integer, Object> cache = igniteClient.getOrCreateCache(CACHE_NAME);
Person p = new Person();
//put
HashMap<Integer, Person> hm = new HashMap<Integer, Person>();
hm.put(1, p);
cache.put(1, hm);
//get
HashMap<Integer, Person> map = (HashMap<Integer, Person>)cache.get(1);
Person p2 = map.get(1);
System.out.format(">>> Loaded [%s] from the cache.\n",p2);
}
catch (ClientException e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
catch (Exception e) {
System.err.format("Unexpected failure: %s\n", e);
e.printStackTrace();
}
I use the thin client of apache-ignite.
I Create a hashmap and put the Person class(org.apache.ignite.examples.model.Person) object into it.
And when I take it out of the hashmap, I get the following exceptions:
> java.lang.ClassCastException:
> org.apache.enite.internal.binary.BinaryObjectImpl cannot be cast to
> org.apache.engite.examples.model.Person.
An exception is given in the code below.
Person p2 = map.get(1);
However, there is no exception if I modify the code as follows:
BinaryObject bo = (BinaryObject) map.get(1);
Person p2 = bo.deserialize();
I don't think that's necessary. Is there another solution?

Change client Cache definition
ClientCache<Integer, Person> cache = igniteClient.getOrCreateCache(CACHE_NAME)

Related

lotus.domino.local.Item cannot be cast to lotus.domino.RichTextItem

I try to put a file into a richtext but it crashes !
In my first code, I try to use directly "getFirstItem", in first time it was ok but now i try to use it again and it crashed.
In second time i pass with an object and it find my obj doesn't an richtextItem (instanceof) ???
I don't understand.
I have the message : "lotus.domino.local.Item cannot be cast to lotus.domino.RichTextItem" ?
Could you help me ?
public void copieFichierDansRichText(String idDocument, String nomRti, File file,
String nameFichier, String chemin) throws NotesException {
lotus.domino.Session session = Utils.getSession();
lotus.domino.Database db = session.getCurrentDatabase();
lotus.domino.Document monDoc = db.getDocumentByUNID(idDocument);
lotus.domino.RichTextItem rtiNew = null;
try {
try {
if (monDoc != null) {
// if (monDoc.getFirstItem(nomRti) != null) {
// rtiNew = (lotus.domino.RichTextItem)
// monDoc.getFirstItem(nomRti);
// } else {
// rtiNew = (lotus.domino.RichTextItem)
// monDoc.createRichTextItem(nomRti);
// }
Object obj = null;
if (monDoc.getFirstItem(nomRti) != null) {
obj = monDoc.getFirstItem(nomRti);
if (obj instanceof lotus.domino.RichTextItem) {
rtiNew = (lotus.domino.RichTextItem) obj;
}
} else {
obj = monDoc.createRichTextItem(nomRti);
if (obj instanceof lotus.domino.RichTextItem) {
rtiNew = (lotus.domino.RichTextItem) obj;
}
}
PieceJointe pieceJointe = new PieceJointe();
pieceJointe = buildPieceJointe(file, nameFichier, chemin);
rtiNew.embedObject(EmbeddedObject.EMBED_ATTACHMENT, "", pieceJointe.getChemin()
+ pieceJointe.getNomPiece(), pieceJointe.getNomPiece());
monDoc.computeWithForm(true, false);
monDoc.save(true);
}
} finally {
rtiNew.recycle();
monDoc.recycle();
db.recycle();
session.recycle();
}
} catch (Exception e) {
e.printStackTrace();
}
}
EDIT : I try to modify my code with yours advices but the items never considerate as richtextitem. It is my problem. I don't understand why, because in my field it is a richtext ! For it, the item can't do :
rtiNew = (lotus.domino.RichTextItem) item1;
because item1 not be a richtext !!!
I was trying to take all the fields and pass in the item one by one, and it never go to the obj instance of lotus.domini.RichTextItem....
Vector items = doc.getItems();
for (int i=0; i<items.size(); i++) {
// get next element from the Vector (returns java.lang.Object)
Object obj = items.elementAt(i);
// is the item a RichTextItem?
if (obj instanceof RichTextItem) {
// yes it is - cast it as such // it never go here !!
rt = (RichTextItem)obj;
} else {
// nope - cast it as an Item
item = (Item)obj;
}
}
A couple of things. First of all I would set up a util class method to handle the object recycling in a neater way:
public enum DominoUtil {
;
public static void recycle(Base... bases) {
for (Base base : bases) {
if (base != null) {
try {
base.recycle();
} catch (Exception e) {
// Do nothing
}
}
}
}
}
Secondly I would remove the reduntants try/catch blocks and simplify it like this:
private void copieFichierDansRichText(String idDocument, String nomRti, File file,
String nameFichier, String chemin) {
Session session = DominoUtils.getCurrentSession();
Database db = session.getCurrentDatabase();
Document monDoc = null;
try {
monDoc = db.getDocumentByUNID(idDocument);
Item item = monDoc.getFirstItem(nomRti);
if (item == null) {
item = monDoc.createRichTextItem(nomRti);
} else if (item.getType() != Item.RICHTEXT) {
// The item is not a rich text item
// What are you going to do now?
}
RichTextItem rtItem = (RichTextItem) item;
PieceJointe pieceJointe = new PieceJointe();
pieceJointe = buildPieceJointe(file, nameFichier, chemin);
rtItem.embedObject(EmbeddedObject.EMBED_ATTACHMENT, "", pieceJointe.getChemin()
+ pieceJointe.getNomPiece(), pieceJointe.getNomPiece());
monDoc.computeWithForm(true, false);
monDoc.save(true);
} catch (NotesException e) {
throw new FacesException(e);
} finally {
DominoUtil.recycle(monDoc);
}
}
Finally, apart from the monDoc, you need not recycle anything else. Actually Session would be automatically recycled and anything beneath with it (so no need to recycle db, let alone the session!, good rule is don't recycle what you didn't instantiate), but it's not bad to keep the habit of keeping an eye on what you instantiate. If it were a loop with many documents you definitively want to do that. If you also worked with many items you would want to recycle them as early as possible. Anyway, considered the scope of the code it's sufficient like this. Obviously you would call DominoUtil.recycle directly from the try block. If you have multiple objects you can recycle them at once possibly by listing them in the reverse order you set them (eg. DominoUtil.recycle(item, doc, view)).
Also, what I think you miss is the check on the item in case it's not a RichTextItem - and therefore can't be cast. I put a comment where I think you should decide what to do before proceeding. If you let it like that and let the code proceed you will have the code throw an error. Always better to catch the lower level exception and re-throw a higher one (you don't want the end user to know more than it is necessary to know). In this case I went for the simplest thing: wrapped NotesException in a FacesException.

JXLS unable to output excel to servlet for user download

Hello im trying to output an excel file generated from a template xls using jxls library but I dont find the way to do so.
My code look like this:
ServletContext contexto = request.getServletContext();
String path = contexto.getRealPath("/lib/xlsx/plantilla.xlsx");
Conexion conexion = new Conexion();
List<Conexion> conexiones = new ArrayList<Conexion>();
ResultSet rs = CargarConsultas.ejecutarConsulta("CONS_GET_TABLA_CONEXION");
try {
while(rs.next()) {
conexion.setIp(rs.getString("ori_ip"));
conexion.setMac(rs.getString("ori_mac"));
conexion.setUrl_destino(rs.getString("url_dest"));
conexion.setSolicitud(rs.getString("time_stamp_solicitud"));
conexion.setUser_id(rs.getString("user_id"));
conexion.setSubida(rs.getString("icoming"));
conexion.setBajada(rs.getString("outgoing"));
conexion.setAutorizacion(rs.getString("time_stamp_autorizacion"));
conexion.setRenovacion(rs.getString("time_stamp_renovacion"));
conexion.setFin_sesion(rs.getString("time_stamp_fin_sesion"));
conexion.setGw_adress(rs.getString("gw_address"));
conexion.setGw_port(rs.getString("gw_port"));
conexiones.add(conexion);
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
File salida = new File(path);
InputStream is = new FileInputStream(salida);
try (FileOutputStream os = new FileOutputStream("salida.xlsx")) {
Context context = new Context();
context.putVar("conexiones", conexiones);
JxlsHelper.getInstance().processTemplate(is, os, context);
} catch (Exception e) {
e.printStackTrace();
}
Please let me knoew if you know how to output it and no save it to server disk.The code works fine. Thanks alot

how to get values from SqlDataReader to forloop execution?

Here I coding for get each and every StudyUID(as string) from database to SqlDataReader,but i need to know how the reader value call to forloop execution.
Get to read each and every StudyUID for execution.Here is the code :.
public void automaticreport()
{
//string autsdyid="";
SqlConnection con = new SqlConnection(constr);
con.Open();
string autoquery = "Select StudyUID From StudyTable Where status='2'";
SqlCommand cmd = new SqlCommand(autoquery, con);
SqlDataReader rdr = cmd.ExecuteReader();
for()
{
//how to call each StudyUId from database through for loop
if (!this.reportchk)
{
Reportnew cf = new Reportnew();
ThreadPool.QueueUserWorkItem((WaitCallback)(o => cf.ReportRetrive(this, autsdyid, true)));
}
else
{
int num = (int)System.Windows.Forms.MessageBox.Show("Reports checking in progress, Please wait sometime and try again later", "OPTICS", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
con.Close();
}
Like #R.T and others have mentioned you can use the Read method on the data reader. Looking at your sample code you might want to refactor it slightly to meet more of the SOLID principles and make sure you're not leaking database connections
Here's an example of code that has been refactored a bit.
public void automaticreport()
{
foreach (var autsdyid in LoadStudyIdentifiers())
{
if (!this.reportchk)
{
Reportnew cf = new Reportnew();
ThreadPool.QueueUserWorkItem((WaitCallback)(o => cf.ReportRetrive(this, autsdyid, true)));
}
else
{
int num = (int)System.Windows.Forms.MessageBox.Show("Reports checking in progress, Please wait sometime and try again later", "OPTICS", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
}
}
private string[] LoadStudyIdentifiers()
{
var results = new List<string>();
// adding a using statement will close the database connection if there are any errors
// avoiding consuming the database connection pool
using (var con = new SqlConnection(constr))
{
conn.Open();
var autoquery = "Select StudyUID From StudyTable Where status='2'";
using (var cmd = new SqlCommand(autoquery, con))
{
SqlDataReader rdr = cmd.ExecuteReader();
while(rdr.Read())
{
results.Add(rdr.GetString(rdr.GetOrdinal("StudyUID")));
}
}
}
return results.ToArray();
}
Note: I wrote this in notepad so there is no guarantee it will compile but should give an indication as to how you could refactor your code.
if (rdr.HasRows)
{
while (rdr.Read())
{
Console.WriteLine(rdr.getString("columnName"));
}
}
You can use something like:
while (reader.Read())
{
string value = reader.getString("columnName");
}
You may use the while loop like this:
while (rdr.Read())
{
string s = rdr.GetString(rdr.GetOrdinal("Column"));
//Apply logic to retrieve here
}

XAdES-BES countersignature cannot resolve reference error

I implemented verification for XAdES-BES and after testing everything works now besides counter-signatures. The same error occurs not only for files signed with xades4j but also using other software so it is not related to any mistakes in my countersignature implementation. I wonder if I should implement additional ResourceResolver? I added a countersigned file as the attachment with 'REMOVED' for some private entries here.
Below is the code for verification. certDataList is a list with all certificates from the document in String and getCert will return List. DummyCertificateValidationProvider returns ValidationData with a list of previously constructed x509certs.
public boolean verify(final File file) {
if (!Dictionaries.valid()) {
return true;
}
certList = null;
try {
final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
final DocumentBuilder db = dbf.newDocumentBuilder();
final Document doc = db.parse(file);
doc.getDocumentElement().normalize();
final NodeList nList = doc.getElementsByTagName("ds:Signature");
Element elem = null;
for (int temp = 0; temp < nList.getLength(); temp++) {
final Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
elem = (Element) nNode;
}
}
final NodeList nList2 = doc.getElementsByTagName("ds:X509Certificate");
final List<String> certDataList = new ArrayList<String>();
for (int temp = 0; temp < nList2.getLength(); temp++) {
final Node nNode = nList2.item(temp);
certDataList.add(nNode.getTextContent());
}
certList = getCert(certDataList);
final CertificateValidationProvider certValidator = new DummyCertificateValidationProvider(certList);
final XadesVerificationProfile p = new XadesVerificationProfile(certValidator);
final XadesVerifier v = p.newVerifier();
final SignatureSpecificVerificationOptions opts = new SignatureSpecificVerificationOptions();
// for relative document paths
final String baseUri = "file:///" + file.getParentFile().getAbsolutePath().replace("\\", "/") + "/";
LOGGER.debug("baseUri:" + baseUri);
opts.useBaseUri(baseUri);
v.verify(elem, opts);
return true;
} catch (final IllegalArgumentException | XAdES4jException | CertificateException | IOException | ParserConfigurationException | SAXException e) {
LOGGER.error("XML not validated!", e);
}
return false;
}
Here is the stacktrace:
21:31:48,203 DEBUG ResourceResolver:158 - I was asked to create a ResourceResolver and got 0
21:31:48,203 DEBUG ResourceResolver:101 - check resolvability by class org.apache.xml.security.utils.resolver.ResourceResolver
21:31:48,204 DEBUG ResolverFragment:137 - State I can resolve reference: "#xmldsig-5de7b1d0-be70-4dde-b746-3f4d4d6de39f-sigvalue"
21:31:48,204 ERROR SignComponent:658 - XML not validated!
xades4j.XAdES4jXMLSigException: Error verifying the signature
at xades4j.verification.XadesVerifierImpl.doCoreVerification(XadesVerifierImpl.java:284)
at xades4j.verification.XadesVerifierImpl.verify(XadesVerifierImpl.java:188)
at com.signapplet.sign.SignComponent.verify(SignComponent.java:655)
...
Caused by: org.apache.xml.security.signature.MissingResourceFailureException: The Reference for URI #xmldsig-5de7b1d0-be70-4dde-b746-3f4d4d6de39f-sigvalue has no XMLSignatureInput
Original Exception was org.apache.xml.security.signature.ReferenceNotInitializedException: Cannot resolve element with ID xmldsig-5de7b1d0-be70-4dde-b746-3f4d4d6de39f-sigvalue
Original Exception was org.apache.xml.security.utils.resolver.ResourceResolverException: Cannot resolve element with ID xmldsig-5de7b1d0-be70-4dde-b746-3f4d4d6de39f-sigvalue
at org.apache.xml.security.signature.Manifest.verifyReferences(Manifest.java:414)
at org.apache.xml.security.signature.SignedInfo.verify(SignedInfo.java:259)
at org.apache.xml.security.signature.XMLSignature.checkSignatureValue(XMLSignature.java:724)
at org.apache.xml.security.signature.XMLSignature.checkSignatureValue(XMLSignature.java:656)
at xades4j.verification.XadesVerifierImpl.doCoreVerification(XadesVerifierImpl.java:277)
... 39 more
Caused by: org.apache.xml.security.signature.ReferenceNotInitializedException: Cannot resolve element with ID xmldsig-5de7b1d0-be70-4dde-b746-3f4d4d6de39f-sigvalue
Edit:
The same error occurs when I try to validate file provided with xades4j unit tests document.signed.bes.cs.xml.
Caused by: org.apache.xml.security.signature.MissingResourceFailureException: The Reference for URI #xmldsig-281967d1-74f8-482c-8222-ed58dbd1909b-sigvalue has no XMLSignatureInput
Original Exception was org.apache.xml.security.signature.ReferenceNotInitializedException: Cannot resolve element with ID xmldsig-281967d1-74f8-482c-8222-ed58dbd1909b-sigvalue
Caused by: org.apache.xml.security.signature.ReferenceNotInitializedException: Cannot resolve element with ID xmldsig-281967d1-74f8-482c-8222-ed58dbd1909b-sigvalue
The problem was with ds:Signature. In counter signatures you will have more than one ds:Signature entry. In my verification method I used the for loop:
for (int temp = 0; temp < nList.getLength(); temp++) {
final Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
elem = (Element) nNode;
}
}
As you can see, there was no break when element was found so I ended up with the last ds:Signature, not the first one so all previous signatures could not be found.

CRM 2011 development: Get the following error if I try to get related entity: Object reference not set to an instance of an object

I try to get a related entity and get this error: Object reference not set to an instance of an object.
See below my code:
public IEnumerable<RUBAnnotation> GetAnnotationsByServiceRequestId(string serviceRequestId)
{
List<Annotation> annotationList = new List<Annotation>();
try
{
using (OrganizationServiceProxy organizationProxy = new OrganizationServiceProxy(organisationWebServiceUri, null, userCredentials, deviceCredentials))
{
organizationProxy.EnableProxyTypes();
var service = (IOrganizationService)organizationProxy;
OrganizationServiceContext orgContext = new OrganizationServiceContext(service);
Relationship rel = new Relationship("Incident_Annotation");
// get all incidents by incidentId
IEnumerable<Incident> incidents = from c in orgContext.CreateQuery<Incident>()
where c.Id == new Guid(serviceRequestId)
select c;
return GetAnnotationsEntities(incidents);
}
}
catch (Exception)
{
throw;
}
return null;
}
private List<RUBAnnotation> GetAnnotationsEntities(IEnumerable<Incident> incidents)
{
List<RUBAnnotation> annotationsList = new List<RUBAnnotation>();
try
{
foreach (Incident incident in incidents)
{
foreach (var annotation in incident.Incident_Annotation) // HERE OCCURS THE EXCEPTION!!
{
if (!string.IsNullOrEmpty(annotation.NoteText))
{
var customAnnotation = new RUBAnnotation();
customAnnotation.Id = annotation.Id.ToString();
if (annotation.Incident_Annotation != null)
{
customAnnotation.ServiceRequestId = annotation.Incident_Annotation.Id.ToString();
}
customAnnotation.Message = annotation.NoteText;
customAnnotation.CreatedOn = (DateTime)annotation.CreatedOn;
customAnnotation.UserId = annotation.CreatedBy.Id.ToString();
annotationsList.Add(customAnnotation);
}
}
}
}
catch (Exception e)
{
throw e;
}
return annotationsList;
}
Why do I get this error when I try to get incident.Incident_Annotation ? I think incident.Incident_Annotation is NULL, but why? Al my incidents have minimal 1 or more annotations.
Related entities must be explicitly loaded, you can find more information on this MSDN article:
MSDN - Access Entity Relationships

Resources