Exception in thread "main" java.lang.IllegalArgumentException: Unable to find StyleMasterPage name - coding-style

I'm developing an app that processes files in ODS format.The code snippet is as follows:
public static void main(String[] args) throws IOException {
// Set the platform L&F.
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
display();
//print();
}
private static void display() throws IOException {
// Load the spreadsheet.
final OpenDocument doc = new OpenDocument();
doc.loadFrom("temperature3.ods");
String styleName = "Calibri";
StyleHeader header = new StyleHeader();
header.setStyleDisplay("Testing");
StyleMasterPage page = new StyleMasterPage();
page.setStyleHeader(header);
page.setStyleName(styleName);
OfficeMasterStyles off = new OfficeMasterStyles();
off.addMasterPage(off.getMasterPageFromStyleName(styleName));
doc.setMasterStyles(off);
// Show time !
final JFrame mainFrame = new JFrame("Viewer");
DefaultDocumentPrinter printer = new DefaultDocumentPrinter();
ODSViewerPanel viewerPanel = new ODSViewerPanel(doc, true);
mainFrame.setContentPane(viewerPanel);
mainFrame.pack();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setLocation(10, 10);
mainFrame.setVisible(true);
}
I intend loading the file into a jcomponent for easy manipulation but I'm having this error message in the netbeans console:
Exception in thread "main" java.lang.IllegalArgumentException: Unable to find StyleMasterPage named:Calibri
at org.jopendocument.model.office.OfficeMasterStyles.getMasterPageFromStyleName(Unknown Source)
at starzsmarine1.PrintSpreadSheet.display(PrintSpreadSheet.java:60)
at starzsmarine1.PrintSpreadSheet.main(PrintSpreadSheet.java:45)
Is there an alternative API for this purpose?

Related

Issue with method when called. Program is to create a buffered image for editing

I am very new to programming as you can probably tell from my code! I am creating a program to edit uploaded pictures by creating a buffered image which is then to be modified but I am having issues. My code is
private Scanner sc;
private String inputPath = null;
public String getInputPath() throws Exception {
System.out.println("Please enter the path to the picture you wish to edit.");
sc = new Scanner(System.in);
inputPath = sc.next();
getFile(inputPath);
return inputPath;
}
private File getFile(String inputPath) throws Exception{
File f = new File(inputPath);
while (true) {
if (f.exists()){
bufferedImage(); //line 27
}else{
throw new Exception("Invalid file name!");
}
}
}
public void bufferedImage() throws Exception {
File f = getFile(inputPath); //line 35
BufferedImage bi = ImageIO.read(f);
System.out.println(bi);
return;
}
My error message is:
Exception in thread "main" java.lang.StackOverflowError:
at ie.gmit.dip.ImageWriter.getFile(ImageWriter.java:27)
at ie.gmit.dip.ImageWriter.bufferedImage(ImageWriter.java:35)
I have marked the lines in my code above. Any help on this would be massively appreciated!

Has anyone been able to see a crash attachment with Xamarin Forms and AppCenter.ms?

As far as I know I have followed exactly the instructions:
I have set everything up as suggested. Used my secret key, enabled crashes. Had the set up checked by another developer and see the crash happened in appcenter.ms but still I never see any attached information.
Here's an example:
public class Application
{
// This is the main entry point of the application.
static void Main(string[] args)
{
// if you want to use a different Application Delegate class from "AppDelegate"
// you can specify it here.
try
{
UIApplication.Main(args, null, "AppDelegate");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Crashes.TrackError(ex,
new Dictionary<string, string> {
{"Main", "Exception"},
{"Device Model", DeviceInfo.Model },
});
throw;
}
}
}
No matter what, when and how my application crashes I still will not get the attached information.
I am wondering has anyone got the attached data for crashes to work with XF ?
We can use AppCenter only after it has been started which according to official documentation on iOS we do it in AppDelegate class in the method FinishedLaunching. But the point is the class Application in Main.cs file is called before AppDelegate class.
If you want to see the attached info then you can try it for example in a XAML code-behind file by manually throwing an exception. Here is an example for a button's click event:
private void TheButton1_OnClicked(object sender, EventArgs e)
{
try
{
throw new DivideByZeroException("Testing attached info!");
}
catch (Exception exception)
{
Crashes.TrackError(exception,
new Dictionary<string, string> {{"Device Model", "My device model" }});
}
}
The attached info on TrackError() method i.e properties dictionary works on both Android and iOS. To see that info you need to go through this in App Center's panel:
From left panel choose Diagnostics.
From Groups section choose your specific group.
From tabs in top section choose Reports.
Choose your specific device.
The attached info is In Stacktrace tab and in Error properties section.
Just to correct, the additional data you attach with exception in TrackError method are mostly in catch blocks or generated exception in TrackError methods, so it will only displayed with those manually logged(TrackError) exceptions.
Crashes are exceptions that are not handled and logged automatically by appcenter so if you look in crash reports there will not be any attached data available.
Additional data sent with exception as properties can be found in reports section of error on appcenter.
I am sure you have initialized Crash service in OnStart method of App.xaml.cs class with correct app secrets and required platforms(android/ios).
I was able to track the crashes. The only difference is am tracking it from the native projects.
For Android in the MainActivity:
protected override void OnCreate(Bundle savedInstanceState)
{
...
AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
TaskScheduler.UnobservedTaskException += TaskSchedulerOnUnobservedTaskException;
AndroidEnvironment.UnhandledExceptionRaiser += AndroidEnvironment_UnhandledExceptionRaiser;
...
}
private void AndroidEnvironment_UnhandledExceptionRaiser(object sender, RaiseThrowableEventArgs e)
{
var newExc = new Exception("UnhandledExceptionRaiser", e.Exception as Exception);
LogUnhandledException(newExc);
}
private static void TaskSchedulerOnUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs unobservedTaskExceptionEventArgs)
{
var newExc = new Exception("TaskSchedulerOnUnobservedTaskException", unobservedTaskExceptionEventArgs.Exception);
LogUnhandledException(newExc);
}
private static void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs)
{
var newExc = new Exception("CurrentDomainOnUnhandledException", unhandledExceptionEventArgs.ExceptionObject as Exception);
LogUnhandledException(newExc);
}
internal static void LogUnhandledException(Exception exception)
{
try
{
Crashes.TrackError(exception);
...
}
catch (Exception ex)
{
// just suppress any error logging exceptions
}
}
For iOS in the AppDelegate:
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
...
AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
TaskScheduler.UnobservedTaskException += TaskSchedulerOnUnobservedTaskException;
...
}
private static void TaskSchedulerOnUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs unobservedTaskExceptionEventArgs)
{
var newExc = new Exception("TaskSchedulerOnUnobservedTaskException", unobservedTaskExceptionEventArgs.Exception);
LogUnhandledException(newExc);
}
private static void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs)
{
var newExc = new Exception("CurrentDomainOnUnhandledException", unhandledExceptionEventArgs.ExceptionObject as Exception);
LogUnhandledException(newExc);
}
internal static void LogUnhandledException(Exception exception)
{
try
{
...
}
catch
{
// just suppress any error logging exceptions
}
}

Creating a Java code playground in Android application by Janino

I'm trying to create a Java learning Android application.
It should have a code playground for users; which can run simple Java code.
I save users code in a java code and I'm trying to run it.
I'm using JANINO, but the problem is that I can not load external class including users code with it.
Here is my code:
String UsersCodeInput;
public void Run() throws FileNotFoundException, IOException
{
File sourcepath = new File(Environment.getExternalStorageDirectory()+"/MainFolder");
File JavaFile = new File(sourcepath.getPath()+"A.java");
FileOutputStream fos = new FileOutputStream(JavaFile);
fos.write(UsersCodeInput.getBytes());
fos.close();
// now Users Code is Saved.
//trying to run it by means of janino :
ClassLoader cl = new JavaSourceClassLoader(
this.getClass().getClassLoader(), // parentClassLoader
new File[] {sourcepath}, //our sourceFolder
"UTF-8" //Encodeing
);
try
{
// problem is here. next line is not working well; throws classNotFound.
Object o = cl.loadClass(".A").newInstance();
//the class implements runnable.
((Runnable) o).run();
}
catch (ClassNotFoundException e)
{Toast.makeText(this,e.getCause().toString(),Toast.LENGTH_SHORT).show();}
catch (InstantiationException e)
{Toast.makeText(this,e.getCause().toString(),Toast.LENGTH_SHORT).show();}
catch (IllegalAccessException e)
{Toast.makeText(this,e.getCause().toString(),Toast.LENGTH_SHORT).show();}
}
And here is JANINOs tutorial ; Read "source code compiler" part
http://janino-compiler.github.io/janino/
Thanks.

Endpoint is not connected in httpclient5-beta

Hi I m trying to use httpcomponents5 beta to make persistent connection, I have tried the example given in their site, the code is as follows,
final IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setSoTimeout(Timeout.ofSeconds(45)).setSelectInterval(10000).setSoReuseAddress(true).setSoKeepAlive(true).build();
final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(new TrustAllStrategy()).build();
final PoolingAsyncClientConnectionManager connectionManager = PoolingAsyncClientConnectionManagerBuilder.create().setConnectionTimeToLive(TimeValue.of(1, TimeUnit.DAYS)).setTlsStrategy(new H2TlsStrategy(sslContext, NoopHostnameVerifier.INSTANCE)).build();
client = HttpAsyncClients.createMinimal(protocol, H2Config.DEFAULT, null, ioReactorConfig, connectionManager);
client.start();
final org.apache.hc.core5.http.HttpHost target = new org.apache.hc.core5.http.HttpHost("localhost", 8000, "https");
Future<AsyncClientEndpoint> leaseFuture = client.lease(target, null);
AsyncClientEndpoint asyncClientEndpoint = leaseFuture.get(60, TimeUnit.SECONDS);
final CountDownLatch latch = new CountDownLatch(1);
final AsyncRequestProducer requestProducer = AsyncRequestBuilder.post(target.getSchemeName()+"://"+target.getHostName()+":"+target.getPort()+locationposturl).addParameter(new BasicNameValuePair("info", requestData)).setEntity(new StringAsyncEntityProducer("json post data will go here", ContentType.APPLICATION_JSON)).setHeader("Pragma", "no-cache").setHeader("from", "http5").setHeader("Custom", customheaderName).setHeader("Secure", secureHeader).build();
locEndPoint.execute(requestProducer, SimpleResponseConsumer.create(), new FutureCallback<SimpleHttpResponse>() {
#Override
public void completed(final SimpleHttpResponse response) {
if (response != null) {
if (response.getCode() > -1) {
try {
System.out.println("http5:: COMPLETED : RESPONSE "+response.getBodyText());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
latch.countDown();
}
#Override
public void failed(final Exception ex) {
System.out.println("http5:: FAILED : "+target+locationposturl);
LoggerUtil.printStackTrace(ex);
System.out.println("http5::Exception Request failed "+LoggerUtil.getStackTrace(ex));
latch.countDown();
}
#Override
public void cancelled() {
System.out.println("http5:: CANCELLED : "+target+locationposturl);
System.out.println(http5::Exception Request cancelled");
latch.countDown();
}
});
latch.await();
This code works without a problem for the first time,but when I send a subsequent requests it throws an exception as follows,
http5:: Exception occured java.lang.IllegalStateException: Endpoint is
not connected at
org.apache.hc.core5.util.Asserts.check(Asserts.java:38) at
org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager$InternalConnectionEndpoint.getValidatedPoolEntry(PoolingAsyncClientConnectionManager.java:497)
at
org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager$InternalConnectionEndpoint.execute(PoolingAsyncClientConnectionManager.java:552)
at
org.apache.hc.client5.http.impl.async.MinimalHttpAsyncClient$InternalAsyncClientEndpoint.execute(MinimalHttpAsyncClient.java:405)
at
org.apache.hc.core5.http.nio.AsyncClientEndpoint.execute(AsyncClientEndpoint.java:81)
at
org.apache.hc.core5.http.nio.AsyncClientEndpoint.execute(AsyncClientEndpoint.java:114)
What may be the problem with endpoint, I m forcing endpoint to keep alive for a day, kindly shed some light on this

how to read the request in chunks in httpcomponents NIO server?

I am using httpcomponenets nio server to handle post request.
Below is the sample code. It gets the complete data in byte array using EntityUtils.toByteArray(). This fails if the requester sends a large file.
I couldnt figure out how to read the data in the request in chunks.
HttpEntity.getContent().read() always returns null
public static void main(String[] args) throws Exception {
int port = 8280;
// Create HTTP protocol processing chain
HttpProcessor httpproc = HttpProcessorBuilder.create()
.add(new ResponseDate())
.add(new ResponseServer("Test/1.1"))
.add(new ResponseContent())
.add(new ResponseConnControl()).build();
// Create request handler registry
UriHttpAsyncRequestHandlerMapper reqistry = new UriHttpAsyncRequestHandlerMapper();
// Register the default handler for all URIs
reqistry.register("/test*", new RequestHandler());
// Create server-side HTTP protocol handler
HttpAsyncService protocolHandler = new HttpAsyncService(httpproc, reqistry) {
#Override
public void connected(final NHttpServerConnection conn) {
System.out.println(conn + ": connection open");
super.connected(conn);
}
#Override
public void closed(final NHttpServerConnection conn) {
System.out.println(conn + ": connection closed");
super.closed(conn);
}
};
// Create HTTP connection factory
NHttpConnectionFactory<DefaultNHttpServerConnection> connFactory;
connFactory = new DefaultNHttpServerConnectionFactory(
ConnectionConfig.DEFAULT);
// Create server-side I/O event dispatch
IOEventDispatch ioEventDispatch = new DefaultHttpServerIODispatch(protocolHandler, connFactory);
// Set I/O reactor defaults
IOReactorConfig config = IOReactorConfig.custom()
.setIoThreadCount(1)
.setSoTimeout(3000)
.setConnectTimeout(3000)
.build();
// Create server-side I/O reactor
ListeningIOReactor ioReactor = new DefaultListeningIOReactor(config);
try {
// Listen of the given port
ioReactor.listen(new InetSocketAddress(port));
// Ready to go!
ioReactor.execute(ioEventDispatch);
} catch (InterruptedIOException ex) {
System.err.println("Interrupted");
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
}
System.out.println("Shutdown");
}
public static class RequestHandler implements HttpAsyncRequestHandler<HttpRequest> {
public void handleInternal(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) throws HttpException, IOException {
HttpEntity entity = null;
if (httpRequest instanceof HttpEntityEnclosingRequest)
entity = ((HttpEntityEnclosingRequest)httpRequest).getEntity();
byte[] data;
if (entity == null) {
data = new byte [0];
} else {
data = EntityUtils.toByteArray(entity);
}
System.out.println(new String(data));
httpResponse.setEntity(new StringEntity("success response"));
}
#Override public HttpAsyncRequestConsumer<HttpRequest> processRequest(HttpRequest request, HttpContext context) throws HttpException, IOException {
return new BasicAsyncRequestConsumer();
}
#Override
public void handle(HttpRequest request, HttpAsyncExchange httpExchange, HttpContext context) throws HttpException, IOException {
HttpResponse response = httpExchange.getResponse();
handleInternal(request, response, context);
httpExchange.submitResponse(new BasicAsyncResponseProducer(response));
}
}
Please consider implementing a custom AbstractAsyncRequestConsumer instead of BasicAsyncRequestConsumer if you want to have full control over request processing.
You might use these classes as a starting point [1][2]. Please note these are response consumers though one can use the same approach to create custom request consumers:
[1] http://hc.apache.org/httpcomponents-asyncclient-4.1.x/httpasyncclient/xref/org/apache/http/nio/client/methods/AsyncCharConsumer.html
[2] http://hc.apache.org/httpcomponents-asyncclient-4.1.x/httpasyncclient/xref/org/apache/http/nio/client/methods/AsyncByteConsumer.html

Resources