J2ME XML Parsing - java-me

I have another question about a "JDWP Error: 21" logged: Unexpected JDWP Error 21
I am trying to parse some XML I gather from a servlet into a J2ME MIDlet with the code below. So far unsuccessfully, I think due to the JDWP error on my HttpConnection how ever the InputStream is filled with XML and once parsed everything inside the Document is null.
Has anyone got and ideas about the JDWP error, and also does that code look like it should work?
In MIDlet I am using JSR-172 API javax.xml.parsers.*.
if(d==form1 && c==okCommand)
{
// Display Webpage
webPage = new TextBox(txtField.getString(),
"",
100000,
TextField.ANY
);
Display.getDisplay(this).setCurrent(webPage);
try
{
HttpConnection conn = (HttpConnection)Connector.open("http://localhost:8080/Blogging_Home/Interface?Page=Bloggers&Action=VIEW&Type=XML");
conn.setRequestMethod(HttpConnection.GET);
int rc = conn.getResponseCode();
getConnectionInformation(conn, webPage);
webPage.setString(webPage.getString() + "Starting....");
String methodString = getStringFromURL("");
if (rc == HttpConnection.HTTP_OK)
{
InputStream is = null;
is = createInputStream(methodString);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
Document document;
try
{
builder = factory.newDocumentBuilder();
document = builder.parse(is);
} catch (Exception e) {
e.printStackTrace();
}
}
else
{
webPage.setString(webPage.getString() + "ERROR:" + rc);
}
}
catch(Exception ex)
{
// Handle here
webPage.setString("Error" + ex.toString());
}

Related

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

Plugin code to update another entity when case is created mscrm 2011

Im new with plugin. my problem is, When the case is created, i need to update the case id into ledger. What connect this two is the leadid. in my case i rename lead as outbound call.
this is my code. I dont know whether it is correct or not. Hope you guys can help me with this because it gives me error. I manage to register it. no problem to build and register but when the case is created, it gives me error.
using System;
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Client;
using System.Net;
using System.Web.Services;
/*
* Purpose: 1) To update case number into lejar
*
* Triggered upon CREATE message by record in Case form.
*/
namespace UpdateLejar
{
public class UpdateLejar : IPlugin
{
/*public void printLogFile(String exMessage, String eventMessage, String pluginFile)
{
DateTime date = DateTime.Today;
String fileName = date.ToString("yyyyMdd");
String timestamp = DateTime.Now.ToString();
string path = #"C:\CRM Integration\PLUGIN\UpdateLejar\Log\" + fileName;
//open if file exist, check file..
if (File.Exists(path))
{
//if exist, append
using (StreamWriter sw = File.AppendText(path))
{
sw.Write(timestamp + " ");
sw.WriteLine(pluginFile + eventMessage + " event: " + exMessage);
sw.WriteLine();
}
}
else
{
//if no exist, create new file
using (StreamWriter sw = File.CreateText(path))
{
sw.Write(timestamp + " ");
sw.WriteLine(pluginFile + eventMessage + " event: " + exMessage);
sw.WriteLine();
}
}
}*/
public void Execute(IServiceProvider serviceProvider)
{
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
//for update and create event
if (context.InputParameters.Contains("Target") &&
context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parmameters.
Entity targetEntity = (Entity)context.InputParameters["Target"];
// Verify that the entity represents a connection.
if (targetEntity.LogicalName != "incident")
{
return;
}
else
{
try
{
//triggered upon create message
if (context.MessageName == "Create")
{
Guid recordid = new Guid(context.OutputParameters["incidentid"].ToString());
EntityReference app_inc_id = new EntityReference();
app_inc_id = targetEntity.GetAttributeValue<EntityReference>("new_outboundcalllid");
Entity member = service.Retrieve("new_lejer", ((EntityReference)targetEntity["new_outboundcallid"]).Id, new ColumnSet(true));
//DateTime createdon = targetEntity.GetAttributeValue<DateTime>("createdon");
if (app_inc_id != null)
{
if (targetEntity.Attributes.Contains("new_outboundcallid") == member.Attributes.Contains("new_outboundcalllistid_lejer"))
{
member["new_ringkasanlejarid"] = targetEntity.Attributes["incidentid"].ToString();
service.Update(member);
}
}
}
tracingService.Trace("Lejar updated.");
}
catch (FaultException<OrganizationServiceFault> ex)
{
//printLogFile(ex.Message, context.MessageName, "UpdateLejar plug-in. ");
throw new InvalidPluginExecutionException("An error occurred in UpdateLejar plug-in.", ex);
}
catch (Exception ex)
{
//printLogFile(ex.Message, context.MessageName, "UpdateLejar plug-in. ");
tracingService.Trace("UpdateLejar: {0}", ex.ToString());
throw;
}
}
}
}
}
}
Please check,
is that entity containing the attributes or not.
check it and try:
if (targetEntity.Contains("new_outboundcallid"))
((EntityReference)targetEntity["new_outboundcallid"]).Id
member["new_ringkasanlejarid"] = targetEntity.Attributes["incidentid"].ToString();
What is new_ringkasanlejarid's type? You're setting a string to it. If new_ringkasanlejarid is an entity reference, this might be causing problems.
You might want to share the error details or trace log, all we can do is assume what the problem is at the moment.

Windows Phone C#, UnauthorizedAccessException when creating BitmapImage

I am trying to download image from Internet using async call like this:
private void DoGetAlbumart(object sender, DoWorkEventArgs e)
{
string req = (string)e.Argument;
WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(ReadWebRequestCallback);
wc.OpenReadAsync(new Uri(req));
}
void ReadWebRequestCallback( object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null && !e.Cancelled)
{
try
{
BitmapImage image = new BitmapImage();
image.SetSource(e.Result);
SecondTile.Source = image;
}
catch (Exception ex)
{
}
}
else
{
}
}
It seems that when breakpoint hits at BitmapImage image = new BitmapImage(), I got the following exception:
ex = {System.UnauthorizedAccessException: Invalid cross-thread access.
at MS.Internal.XcpImports.CheckThread()
at System.Windows.DependencyObject..ctor(UInt32 nativeTypeIndex, IntPtr constructDO)
at System.Windows.Media.Imaging.BitmapImage..ctor()
What else can I try to get rid of this error?
Callback methods run in background threads, not the UI thread. Unfortunately, BitmapImages can only be instantiated in the UI thread. If you need to access the UI thread from a callback, try the following:
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
BitmapImage image = new BitmapImage();
image.SetSource(e.Result);
SecondTile.Source = image;
});

Problems reading from Microsoft Messaging Queues in C#

I have problems reading from my MSMQ. When I write to the queue, it works perfectly, but when I try to read that message from the queue, I get the following exception: "The queue does not exist or you do not have sufficient permissions to perform the operation." The queue does exists, and I have full permissions on the machine and queue. Here is my code:
public string path = #".\private$\";
public void WriteToQueue(string QueueName, object messageObject)
{
try
{
path = path + QueueName;
MessageQueue msmq = null;
if (!MessageQueue.Exists(path))
{
msmq = MessageQueue.Create(path);
}
else
{
msmq = new MessageQueue(path);
}
msmq.Formatter = new XmlMessageFormatter(new Type[] { typeof(string)});
msmq.Send(messageObject);
msmq.Close();
}
catch (MessageQueueException ex)
{
System.ArgumentException argEx = neArgumentException(ex.ToString());
throw argEx;
}
path = #".\private$\";
}
public string ReadQueue(string QueueName)
{
try
{
path = path + QueueName;
MessageQueue msmq = new MessageQueue(path);
string msg;
msmq.Formatter = new XmlMessageFormatter(new Type[] { typeof(string)});
msg = msmq.Receive().Body.ToString(); //exception is thrown here
path = #".\private$\";
return msg;
}
catch (Exception ex)
{
return null;
}
}
can the problem maybe be with reading it as type of string? Maybe not in the right format?
Try this:
public string path = ".\\private$\\";
'#' doesn't work for me too.

groovy HTTP Builder not returning results

I have the following code in groovy
HTTPBuilder http = new HTTPBuilder("https://ronna-afghan.harmonieweb.org/_layouts/searchrss.aspx")
http.request(Method.GET, groovyx.net.http.ContentType.XML) {
// set username and password for basic authentication
// set username and password for basic auth
//http.auth.basic(ConfigurationHolder.config.passportService.userName,
// ConfigurationHolder.config.passportService.password)
headers.'User-Agent' = 'Mozilla/5.0'
uri.query = [k:'execution']
// response handler for a success response code:
response.success = {resp, xml ->
println resp.statusLine
log.debug "response status: ${resp.statusLine}"
log.debug xml.toString()
}
// handler for any failure status code:
response.failure = {resp ->
log.error " ${resp.statusLine.statusCode} : ${resp.statusLine.reasonPhrase}"
}
}
when I run the code, it doesn't give me the rss feed which I'm suppose to get
When I have the same code in java
try {
// Create a URLConnection object for a URL
URL oracle = new URL(
"https://ronna-afghan.harmonieweb.org/_layouts/srchrss.aspx?k=execution&count=1&format=rss");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
it returns the xml Rss. I can't figure what the issue might be. Everything looks okay to me in the groovy code and also the Http return code is 200.
The code that you have described in Java is the equivalent of the following code in Groovy:
def oracle = "https://ronna-afghan.harmonieweb.org/_layouts/srchrss.aspx?k=execution&count=1&format=rss".toURL().text

Resources