I have integrated JasperReports on my NetBeans platform and I am able to generate reports using the following code:
Map<String, Object> params = new HashMap<String, Object>();
Connection conn = DriverManager.getConnection("databaseUrl", "userid", "password");
JasperReport jasperReport = JasperCompileManager.compileReport(reportSource);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, conn);
JasperExportManager.exportReportToHtmlFile(jasperPrint, reportDest);
JasperViewer.viewReport(jasperPrint);
This stuff works perfect.
But not I'm trying to integrate JasperReports with GWT. I have my server as GlassFish server.
I am getting the Connection object using the followind code:
public static Connection getConnection() {
try {
String JNDI = "JNDI name";
InitialContext initCtx = new InitialContext();
javax.sql.DataSource ds = (javax.sql.DataSource) initCtx.lookup(JNDI);
Connection conn = (Connection) ds.getConnection();
return conn;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
and then
Map<String, Object> params = new HashMap<String, Object>();
JasperReport jasperReport = JasperCompileManager.compileReport(reportSource);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, getConnection());
JasperExportManager.exportReportToHtmlFile(jasperPrint, reportDest);
JasperViewer.viewReport(jasperPrint);
but i always get an Error. Here is a stacktrace:
com.google.gwt.user.server.rpc.UnexpectedException:
Service method 'public abstract java.lang.Boolean com.client.service.GenerateReport()'
threw an unexpected exception: java.lang.NoSuchMethodError:
net.sf.jasperreports.engine.fonts.SimpleFontFamily.setExportFonts(Ljava/util/Map);
I am implementing this on Server. I am having RPC calls to get this method to work when a button is clicked.
Can you please help me how to work on this. (That is to integrate JasperReports with GWT).
I would highly appreciate any explanation with some code as i am just a beginner.
Thanks
Without the aid of error messages, I would say that you have Google App Engine enabled in your eclipse project preferences. GAE does NOT allow you to write to the file system, or make calls to a database.
Try disabling GAE, and things should work fine.
Related
I am developing a REST client using JBOSS app server and RESTEasy 2.3.6. I've included the following line at the beginning of my code:
RegisterBuiltin.register(ResteasyProviderFactory.getInstance());
Here's the rest of the snippet:
RegisterBuiltin.register(ResteasyProviderFactory.getInstance());
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(host, port, AuthScope.ANY_REALM), new UsernamePasswordCredentials(userid,password));
ClientExecutor executor = createAuthenticatingExecutor(httpclient, host, port);
String uriTemplate = "http://myhost:8080/webapp/rest/MySearch";
ClientRequest request = new ClientRequest(uriTemplate, executor);
request.accept("application/json").queryParameter("query", searchArg);
ClientResponse<SearchResponse> response = null;
List<MyClass> values = null;
try
{
response = request.get(SearchResponse.class);
if (response.getResponseStatus().getStatusCode() != 200)
{
throw new Exception("REST GET failed");
}
SearchResponse searchResp = response.getEntity();
values = searchResp.getValue();
}
catch (ClientResponseFailure e)
{
log.error("REST call failed", e);
}
finally
{
response.releaseConnection();
}
private ClientExecutor createAuthenticatingExecutor(DefaultHttpClient client, String server, int port)
{
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local auth cache
BasicScheme basicAuth = new BasicScheme();
HttpHost targetHost = new HttpHost(server, port);
authCache.put(targetHost, basicAuth);
// Add AuthCache to the execution context
BasicHttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
// Create ClientExecutor.
ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(client, localContext);
return executor;
}
The above is a fairly simple client that employs the ClientRequest/ClientResponse<T> technique. This is documented here. The above code does work (only left out some trivial variable declarations like host and port). It is unclear to me from the JBOSS documentation as to whether I need to run RegisterBuiltin.register first. If I remove the line completely - my code still functions. Do I really need to include the register method call given the approach I have taken? The Docs say I need to run this once per VM. Secondly, if I am required to call it, is it safe to call more than one time in the same VM?
NOTE: I do understand there are newer versions of RESTEasy for JBOSS, we are not there yet.
My program encountered a error:
"org.jboss.remoting3.ProtocolException: Too many channels open"
I have search from internet for some solutions to fix this error.Unfortunately, the suggestions from others is not working for me.
Below is the Code on how I call the jndi remote and the properties that I have used.
public static void createUser(String loginID) throws Exception {
Hashtable props = new Hashtable();
try {
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
props.put(Context.PROVIDER_URL, "remote://" + localhost:4447);
props.put("jboss.naming.client.ejb.context", "true");
props.put(Context.SECURITY_PRINCIPAL, "userJBoss");
props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
context = new InitialContext(props);
context.lookup("ejb:/createUserOperation/CreateUserGenerator!password.api.CreateUserService");
.....
......
LOGGER.info("DONE");
} catch (Exception e) {
LOGGER.error("ERROR");
} finally {
context.close();
}
}
Due to some certain reason I am not able to show all the content of the method.
The "createUser" will be call everytime when there is a needed of create new user. It will be call up to hundred or thousand time.
I did always close the connection when every time it finish execute the method.
Let say I have call the method for 100 times, some of the users will be created successfully whereas some of the users will be failed.
Error below will prompt to me:
2014-12-04 17:23:23,026 - ERROR [Remoting "config-based-naming-client-endpoint" task-4] (org.jboss.ejb.client.remoting.RemotingConnectionEJBReceiver- Line:134) - Failed to open channel for context EJBReceiverContext{clientContext=org.jboss.ejb.client.EJBClientContext#bbaebd6, receiver=Remoting connection EJB receiver [connection=Remoting connection <78e43506>,channel=jboss.ejb,nodename=webdev01]} org.jboss.remoting3.ProtocolException: Too many channels open
Once the error occurred, it required me to restart my jboss.And it comes again after sometimes.
Appreciate it if anyone wound able to help on my problem faced.
Thanks
You are using mixture of context properties.
This should be enough
final Properties ejbProperties = new Properties();
ejbProperties.put("remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED", "false");
ejbProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
ejbProperties.put("remote.connections", "1");
ejbProperties.put("remote.connection.1.host", "localhost");
ejbProperties.put("remote.connection.1.port", "4447");
ejbProperties.put("remote.connection.1.username", "ejbuser");
ejbProperties.put("remote.connection.1.password", "ejbuser123!");
final EJBClientConfiguration ejbClientConfiguration = new PropertiesBasedEJBClientConfiguration(ejbProperties);
final ConfigBasedEJBClientContextSelector selector = new ConfigBasedEJBClientContextSelector(ejbClientConfiguration);
EJBClientContext.setSelector(selector);
final Context context = new InitialContext(ejbProperties);
// lookup
Foo proxy = context.lookup("ejb:/createUserOperation/CreateUserGenerator!password.api.CreateUserService");
when using org.jboss.ejb.client.naming it creates EJBClientContext object.
When closing context you are closing InitialContext not EJBClientContext
to close EJBClientContext:
EJBClientContext.getCurrent().close();
There is a known JBoss bug (EAP 6, AS 7) whereby opening and closing too many InitialContext instances too quickly causes the following error:
ERROR: Failed to open channel for context EJBReceiverContext
Instead of:
final Properties properties = ...
final Context context = new InitialContext( properties );
Try caching the context for a set of properties instead:
private Map<Integer, InitialContext> initialContexts = new HashMap<>();
final Context context = getInitialContext(properties);
private InitialContext getInitialContext(final Properties properties) throws Exception {
final Integer hash = properties.hashCode();
InitialContext result = initialContexts.get(hash);
if (result == null) {
result = new InitialContext(properties);
initialContexts.put(hash, result);
}
return result;
}
Remember to call close() when the context is no longer necessary.
Currently I am using Apache http components client V4.3.5. In my case, I can upload small file(1kb), but it is not working on large file(100kb) when I run the code and get the exception "org.apache.http.NoHttpResponseException: 192.168.128.109:443 failed to respond". Can anyone take a look at my code and let me know what causes my issue?
Here is my code:
public static void main(String[] args) throws IOException,
KeyStoreException {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(
null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslContext,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpClientBuilder builder = HttpClientBuilder.create();
builder.disableContentCompression();
builder.setSSLSocketFactory(sslsf);
SocketConfig config = SocketConfig.custom().setSoKeepAlive(true).setSoTimeout(300000).build();
builder.setDefaultSocketConfig(config);
CloseableHttpClient httpclient = builder.build();
HttpPost httppost = new HttpPost("https://192.168.128.109/upload");
String encodedAuthorization = DatatypeConverter
.printBase64Binary("admin:itronitr".getBytes());
httppost.setHeader("Authorization", "Basic " + encodedAuthorization);
FileBody bin = new FileBody(new File("c:\\test.txt"));
String boundary = "hK1oPL5_XSfbm6lkCNlKI63rltrew5Bqik0ul";
HttpEntity reqEntity = MultipartEntityBuilder.create()
.setBoundary(boundary).addPart("upfile", bin).build();
httppost.setEntity(reqEntity);
System.out.println(httppost.getEntity().getContentLength());
System.out
.println(httppost.getEntity().getContentType().toString());
CloseableHttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
String content = EntityUtils.toString(resEntity);
System.out.println(content);
} catch (Exception exc) {
exc.printStackTrace();
}
}
Thanks,
Bill
Finally I fix the issue and it is caused by buffer size. By default, buffer size of httpclient is 8k. So I change it to 4k and my code works well.
Here is the code that changes buffer size:
ConnectionConfig connectionConfig = ConnectionConfig.custom()
.setBufferSize(4128)
.build();
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultConnectionConfig(connectionConfig)
.build();
This is what worked for me; may or may not work for you!!
I recently encountered the same issue and tried all the suggestions whatever I was able to find on internet i.e upgrading httpClient to latest version and adding a re-try handler ; but none fixed it for me.
I already had a re-try handler built in my code and was running on the latest Apache client, but it was still failing with the exception Caused by: org.apache.http.NoHttpResponseException: xxxxx:443 failed to respond
So, took me almost 2 days to debug this issue and find the root cause (at-least in my case)
There seems to be a bug in older Java versions up to Java 11.0.3 included that prevents Apache HTTP Client from sending payloads bigger than 16368 bytes caused by https://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8214339.
I was running on java 11.0.2 and when I upgraded to 11.0.10, it worked for me and I was able to send the bigger payload without any code changes
I also faced the similar problem. I went through many blogs and forums and tried various things but none worked for me. So, I tried a workaround. I added retry handler as below. And it worked for me:
HttpClientBuilder.create()
.setDefaultCredentialsProvider(provider)
.setRetryHandler(new DefaultHttpRequestRetryHandler() {
#Override
public boolean retryRequest(final IOException exception, final int executionCount, final HttpContext context) {
if (exception instanceof NoHttpResponseException) {
return true;
}
return super.retryRequest(exception, executionCount, context);
}
})
.build();
Although it is not a correct fix and just a workaround but it is working for me for now. I'll stick to this solution till I won't get any permanent solution. Sharing it here in case someone might get benefit from it.
Could someone explain why this httpunit test case keeps failing in wc.getResponse with "bad file descriptor". I added the is.close() as a guess and moved it before and after the failure but that had no effect. This tests put requests to a Dropwizard app.
public class TestCircuitRequests
{
static WebConversation wc = new WebConversation();
static String url = "http://localhost:8888/funl/circuit/test.circuit1";
#Test
public void testPut() throws Exception
{
InputStream is = new FileInputStream("src/test/resources/TestCircuit.json");
WebRequest rq = new PutMethodWebRequest(url, is, "application/json");
wc.setAuthentication("FUNL", "foo", "bar");
WebResponse response = wc.getResponse(rq);
is.close();
}
No responses? So I'll try myself based on what I learned fighting this.
Httpunit is an old familiar tool that I'd use if I could. But it hasn't been updated in more than two years, so I gather its support for #PUT requests isn't right.
So I converted to Jersey-client instead. After a bunch of struggling I wound up with this code which does seem to work:
#Test
public void testPut() throws Exception
{
InputStream is = new FileInputStream("src/test/resources/TestCircuit.json");
String circuit = StreamUtil.readFully(is);
is.close();
Authenticator.setDefault(new MyAuthenticator());
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
com.sun.jersey.api.client.WebResource service = client.resource(url);
Builder builder = service.accept(MediaType.APPLICATION_JSON);
builder.entity(circuit, MediaType.APPLICATION_JSON);
builder.put(String.class, circuit);
return;
}
This intentionally avoids JAX-RS automatic construction of beans from JSON strings.
I hava a socket server is written in Java and the client is written in C#.
If I use the InputStream in a socket server, I can get the request from the Client. My code as below:
InputStream myIN = sock.getInputStream();
byte[] b = new byte[10];
int revByte = myIN.read(b);
but if I use the ObjectInputStream in the socket server, I can not receive any request from the Client.The exception is: "java.io.StreamCorruptedException: invalid stream header"
My code as below:
in = new ObjectInputStream( sock.getInputStream() );
Object value = in.readObject();
So, my question is: can C# client work with ObjectInputStream in Java via socket?
Any helping will be appreciate.Thanks so much, Dan
ObjectInputStream expects a data stream containing serialized representations of java objects... theoretically c# could encode it's objects in java's serialization format, but it wouldn't be pretty.
jspcal is right: Maybe with these classes?
http://mediakey.dk/~cc/java-and-c-client-server-socket-programming/
Java Server
try
{
ServerSocket ss = new ServerSocket(1800);
Socket s = ss.accept();
System.out.println("Client Accepted");
BufferedReader br = new BufferedReader(new
InputStreamReader(s.getInputStream()));
System.out.println(br.readLine());
PrintWriter wr = new PrintWriter(new OutputStreamWriter(s.getOutputStream()),true);
wr.println("Welcome to Socket Programming");
}
catch(Exception e){ System.out.println(e); }
C# Client:
try
{
TcpClient tc = new TcpClient("server",1800);// in the place of server, enter your java server's hostname or Ip
Console.WriteLine("Server invoked");
NetworkStream ns = tc.GetStream();
StreamWriter sw = new StreamWriter(ns);
sw.WriteLine("My name is Pramod.A");
sw.Flush();
StreamReader sr = new StreamReader(ns);
Console.WriteLine(sr.ReadLine());
}
catch(Exception e){ Console.WriteLine(e); }