I'm working on a web-based application which would allow users to upload a Word document to Google Docs using the GData Java API.
( I came across this blog where I found out that I could actually use a byte array to upload a doc instead of using a File )
I'm using Netbeans + JDK 1.6
The relevant code in my servlet:
DocsService docsService = new DocsService("care.udhc.co.in");
try {
docsService.setUserCredentials("sbose78#gmail.com", "*******");
DocumentListEntry newDocument = new DocumentListEntry();
String s="hello bose";
byte byteData[]=s.getBytes();
// Load the byte array into a MediaSource
MediaByteArraySource mediaSource = new MediaByteArraySource(byteData, MediaType.fromFileName("bose.doc").getMimeType());
MediaContent content = new MediaContent();
content.setMediaSource(mediaSource);
content.setMimeType(new ContentType(mediaSource.getContentType()));
newDocument.setContent(content);
String gdocsFilename = new String("My Filename");
newDocument.setTitle(new PlainTextConstruct(gdocsFilename));
out.println("OK");
// Push it into Google Docs!!
DocumentListEntry uploadedRef = docsService.insert(new URL("https://docs.google.com/feeds/default/private/full/"), newDocument);
} catch(Exception e) {
out.println(e.toString());
} finally {
out.close();
}
When I run it locally, I encounter the following error:
com.google.gdata.util.InvalidEntryException: We're sorry, a server error occurred. Please try again. GDataInvalidEntryExceptionWe're sorry, a server error occurred. Please try again.
When i run the version deployed on the Internet ( Jelastic cloud ),
I get this:
java.lang.NoClassDefFoundError: com/google/gdata/data/extensions/QuotaBytesTotal
com.google.gdata.data.docs.MetadataEntry.declareExtensions(MetadataEntry.java:86)
com.google.gdata.data.ExtensionProfile.addDeclarations(ExtensionProfile.java:71)
com.google.gdata.data.BaseFeed.declareExtensions(BaseFeed.java:235)
com.google.gdata.client.docs.DocsService.declareExtensions(DocsService.java:171)
com.google.gdata.client.docs.DocsService.<init>(DocsService.java:108)
bose.google.UploadToDocs.processRequest(UploadToDocs.java:30)
bose.google.UploadToDocs.doGet(UploadToDocs.java:79)
javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
Please get me a workaround?
It seems like you are missing one of the required dependencies, probably gdata-core-1.0.jar.
Also, check this page for external dependencies: https://developers.google.com/gdata/articles/java_client_lib
Related
I just started trying to write a simple java code to do some simple OCR, using the code and advice found here.
I have installed libraries, and the project in the IDE (NetBeans) looks like the picture I have attached.
I'm getting these errors:
10:47:30.099 [main] WARN net.sourceforge.tess4j.util.LoadLibs - Source 'C:\Users\Simon%20Bothner\Documents\NetBeansProjects\OCRTest\build\classes\win32-x86-64' does not exist
java.io.FileNotFoundException: Source
'C:\Users\Simon%20Bothner\Documents\NetBeansProjects\OCRTest\build\classes\win32-x86-64' does not exist
at org.apache.commons.io.FileUtils.copyFile(FileUtils.java:1074)
at org.apache.commons.io.FileUtils.copyFile(FileUtils.java:1038)
at net.sourceforge.tess4j.util.LoadLibs.copyResources(LoadLibs.java:138)
at net.sourceforge.tess4j.util.LoadLibs.extractTessResources(LoadLibs.java:105)
at net.sourceforge.tess4j.util.LoadLibs.<clinit>(LoadLibs.java:59)
at net.sourceforge.tess4j.TessAPI.<clinit>(TessAPI.java:42)
at net.sourceforge.tess4j.Tesseract.init(Tesseract.java:367)
at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:280)
at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:212)
at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:196)
at Main.main(Main.java:15)
Exception in thread "main" java.lang.UnsatisfiedLinkError: The specified module could not be found.
at com.sun.jna.Native.open(Native Method)
at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:263)
at com.sun.jna.NativeLibrary.getInstance(NativeLibrary.java:403)
at com.sun.jna.Library$Handler.<init>(Library.java:147)
at com.sun.jna.Native.loadLibrary(Native.java:502)
at com.sun.jna.Native.loadLibrary(Native.java:481)
at net.sourceforge.tess4j.util.LoadLibs.getTessAPIInstance(LoadLibs.java:77)
at net.sourceforge.tess4j.TessAPI.<clinit>(TessAPI.java:42)
at net.sourceforge.tess4j.Tesseract.init(Tesseract.java:367)
at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:280)
at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:212)
at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:196)
at Main.main(Main.java:15)
C:\Users\Simon Bothner\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
I tried to use this tutorial, but I seemed to be missing a .dll, the liblept168.dll...
Can someone help me with this? I'm quite new at this and can't seem to get this to work...
Thanks a lot! :)
Step 1: http://tphangout.com/how-to-use-the-tesseract-api-to-perform-ocr-in-your-java-code/
Open the link above and see how to install Tesseract in Java properly.
Step 2: After reading it, if you still get the error like "library not open", download Microsoft Visual Studio >12.0, and also update your JDK version (I also get the same error).
Step 3:
public class tesserct
{
public static void main(String[] args)
{
//System.setProperty("jna.library.path", "64".equals(System.getProperty("sun.arch.data.model")) ? "lib/win32-x86" : "lib/win32-x86-64");
System.setProperty("jna.library.path", "32".equals(System.getProperty("sun.arch.data.model")) ? "lib/win32-x86" : "lib/win32-x86-64");
File imageFile = new File("F:\\Wallpaper & photo\\wallpaper\\holi wollpepar\\happy-holi-2013-hd-wallpaper1.jpg");
ITesseract instance = new Tesseract(); // JNA Interface Mapping
// ITesseract instance = new Tesseract1(); // JNA Direct Mapping
File tessDataFolder = LoadLibs.extractTessResources("tessdata"); // Maven build bundles English data
instance.setDatapath(tessDataFolder.getParent());
try {
String result = instance.doOCR(imageFile);
System.out.println(result);
} catch (TesseractException e) {
System.err.println(e.getMessage());
}
}
run the code above on your NetBeans, and try it.
I'm using Neo4j API and Gephi API in Eclipse Java, and i want to import my Neo4j Database into Gephi, i'm using this part of code
//Import file
String URL = "/res/test.graphdb";
Container container;
try {
File file = new File(getClass().getResource(URL).toURI());
container = importController.importFile(file);
container.getLoader().setEdgeDefault(EdgeDefault.UNDIRECTED);
} catch (Exception ex) {
ex.printStackTrace();
System.out.println(e);
return;
}
when i execute the code it shows this Error :
java.lang.NullPointerException
Because the variable container is always equal to null. But when i use a file .gexf or .gml in the URL it works perfectly.
So this is my question :
Is there a way to use Neo4j database in Gephi API ? or convert a Neo4j Databse into .graphml or .gexf to use it with Gephi API ?
Earlier I worked with Pentaho reports, where I can create report with pentaho report designer and deploy .prpt file onto into BI server. It will work fine.
Now I am looking for a solution where I can put .prpt file in a Java program and run just like jasper reports (.jrxml files). Because I need to integrate Pentaho reports with my web application.
I may be asking a very basic question. But I did not find the proper document on this. Please point me to some correct location and a sample code will be helpful.
Since the first link in the accepted answer doesn't seem to work anymore, people who are looking for examples might find this more useful: https://github.com/pentaho/pentaho-reporting/blob/master/engine/samples/source/org/pentaho/reporting/engine/classic/samples
The code in some of the samples is a bit convoluted, so i'm posting my own report generator class, which only contains the bare essentials for generating a PDF report:
public class ReportGenerator {
public byte[] generateReport(byte[] templateBytes, Map<String, Object> params) throws Exception {
ClassicEngineBoot.getInstance().start();
MasterReport reportData = loadTemplateDefinition(templateBytes);
addParametersToReport(params, reportData);
byte[] reportBytes = generateReport(reportData);
return reportBytes;
}
private MasterReport loadTemplateDefinition(byte[] templateBytes) throws Exception {
ResourceManager resourceManager = new ResourceManager();
Resource templateResource = resourceManager.createDirectly(templateBytes, MasterReport.class);
return (MasterReport) templateResource.getResource();
}
private void addParametersToReport(Map<String, Object> params, MasterReport reportData) {
if (params != null) {
for (String key : params.keySet()) {
reportData.getParameterValues().put(key, params.get(key));
}
}
}
private byte[] generateReport(MasterReport reportData) throws ReportProcessingException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PdfOutputProcessor outputProcessor = new PdfOutputProcessor(reportData.getConfiguration(), outputStream, reportData.getResourceManager());
AbstractReportProcessor reportProcessor = null;
try {
reportProcessor = new PageableReportProcessor(reportData, outputProcessor);
reportProcessor.processReport();
} finally {
if (reportProcessor != null) {
reportProcessor.close();
}
}
return outputStream.toByteArray();
}
}
The generateReport method accepts the contents of a .prpt file in the templateBytes parameter, and a list of parameters needed to generate the report in the params parameter.
The byte array it returns contains the contents of a generated PDF report.
Also if you are using Maven for your application it is important to include all the necessary dependencies. I used the list i found here: http://wiki.pentaho.com/display/Reporting/How+to+integrate+report+designer+to+your+web+application, and in it i replaced all the pentaho-related library versions with version 6.1.0.1-196
I've embedded successfully the Pentaho Reporting Engine in my Java application. There is a tutorial with the necessary libraries and examples. The only thing you need to consider while starting is to use the same version of Pentaho SDK, Pentaho Reporting Engine and Pentaho Report Designer, to don't get datasource issues. If you don't want troubles about dependencies, you can download Pentaho Report Designer and drag and drop all the libraries into your web application (most of the issues come when you try to use pentaho charts, and they are solved in this way).
Official Pentaho Docs:
http://infocenter.pentaho.com/help/index.jsp?topic=%2Freporting_embedders_guide%2Ftopic_embedding_engine.html
Pentaho Reporting Classic Engine Core (better try with this first):
http://sourceforge.net/projects/jfreereport/files/01.%20Classic%20Engine/
Just import all the libraries in your IDE (I used Eclipse Helios), and use the example provided, it will work as a charm!. Then you can start to modify it depending on your needs. I suggest you to review how to handle the path for the reports.
final FacesContext context = FacesContext.getCurrentInstance();
ClassicEngineBoot.getInstance().start();
try {
// load report definition
ResourceManager manager = new ResourceManager();
manager.registerDefaults();
ExternalContext extContext = context.getExternalContext();
String reportPath = "file:" + extContext.getRealPath("name/name.prpt");
Resource res = manager.createDirectly(new URL(reportPath), MasterReport.class);
MasterReport report = (MasterReport) res.getResource();
................
................
httpServletResponse.setContentType("application/rtf");
httpServletResponse.setHeader("Content-Disposition", "attachment; filename=\"name.rtf\"");
RTFReportUtil.createRTF(report, httpServletResponse.getOutputStream());
FacesContext.getCurrentInstance().responseComplete();
} catch (ReportProcessingException ex) {
I am developing web application using Java + OpenOffice to generate report documents.
A tomcat server and the war file is installed on a Fedora machine.
Below code works fine to create writer documents on Windows OS but giving error on the Fedora machine while calling from client side using war file:
String oooExeFolder = "/usr/lib/openoffice.org3/program";
XComponentContext xContext = BootstrapSocketConnector.bootstrap(oooExeFolder);
XMultiComponentFactory xMultiComponentFactory = xContext.getServiceManager();
XComponentLoader xcomponentloader = (XComponentLoader) UnoRuntime.queryInterface(XComponentLoader.class, xMultiComponentFactory.createInstanceWithContext("com.sun.star.frame.Desktop", xContext));
XComponent xcomp = xcomponentloader.loadComponentFromURL(filep[i], "_blank", 0, new PropertyValue[0]);
This is the Error :
CE> /usr/lib/openoffice.org3/program/soffice.bin X11 error: Can't open display:
CE> Set DISPLAY environment variable, use -display option
CE> or check permissions of your X-Server
CE> (See "man X" resp. "man xhost" for details)
Can anyone help to identify possible causes for this problem?
You need to launch soffice in "headless" mode. I suggest you look at JODReports or Docmosis since they will save you a lot of time in this type of setup problem. Please note I work for the company that created Docmosis.
After Setting display to "1.0" with following code manually problem has been resolved and i am able to access Open Office from web application to generate report
oooExeFolder = "/usr/lib/openoffice.org3/program/";
List<String> oooOptions = OOoServer.getDefaultOOoOptions();
oooOptions.add("-display");
oooOptions.add(":1.0");
OOoServer server = new OOoServer(oooExeFolder, oooOptions);
XComponentContext xContext = BootstrapSocketConnector.bootstrap(oooExeFolder);
I followed these steps in the hopes of getting storage emulator on localhost working.
I am using Windows 8 RTM.
Downloaded Eclipse and copied it to Program Files.
Installed Java JDK 7.
Installed Azure SDK.
Installed Azure plugin for Eclipse.
Launched storage emulator from the "Start" screen.
Created a Java project.
Added External jars in the build path for Azure to this project.
Wrote this simple sample code:
import com.microsoft.windowsazure.services.blob.client.CloudBlobClient;
import com.microsoft.windowsazure.services.blob.client.CloudBlobContainer;
import com.microsoft.windowsazure.services.core.storage.CloudStorageAccount;
public class AzureStore {
public static final String storageConnectionString = "DefaultEndpointsProtocol=http;"
+ "UseDevelopmentStorage=true;"
+ "AccountName=devstoreaccount1;"
+ "BlobEndpoint=http://127.0.0.1:10000;"
+ "AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==";
public static void main(String[] args) throws Exception {
// Retrieve storage account from connection-string
CloudStorageAccount storageAccount = CloudStorageAccount
.parse(storageConnectionString);
// Create the blob client
CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
// Get a reference to a container
// The container name must be lower case
CloudBlobContainer container = blobClient
.getContainerReference("tweet");
try {
// Create the container if it does not exist
System.out.println(container.createIfNotExist());
} catch (Exception e) {
e.printStackTrace();
}
}
}
It gives the following exception:
com.microsoft.windowsazure.services.core.storage.StorageException: The value for one of the HTTP headers is not in the correct format.
at com.microsoft.windowsazure.services.core.storage.StorageException.translateException(StorageException.java:104)
at com.microsoft.windowsazure.services.blob.client.CloudBlobContainer$2.execute(CloudBlobContainer.java:334)
at com.microsoft.windowsazure.services.blob.client.CloudBlobContainer$2.execute(CloudBlobContainer.java:291)
at com.microsoft.windowsazure.services.core.storage.utils.implementation.ExecutionEngine.executeWithRetry(ExecutionEngine.java:110)
at com.microsoft.windowsazure.services.blob.client.CloudBlobContainer.createIfNotExist(CloudBlobContainer.java:339)
at com.microsoft.windowsazure.services.blob.client.CloudBlobContainer.createIfNotExist(CloudBlobContainer.java:257)
at AzureStore.main(AzureStore.java:26)
I am confused at this point, as what might be wrong. Can someone help me?
I think the error is happening because of incorrect storage service version in the API. In your code you're trying to create a blob container in development storage. The "x-ms-version" request header value is sent as "2012-02-12" which though is the latest one but still not supported by the development storage. Development storage still supports "2011-08-18".
If you try your code against cloud storage, you should be able to create that blob container.
If you're only doing your development against development storage, one thing you could do is download the source code from GitHub (https://github.com/WindowsAzure/azure-sdk-for-java/downloads) and modify the following line of code in Constants.java
public static final String TARGET_STORAGE_VERSION = "2012-02-12";
to
public static final String TARGET_STORAGE_VERSION = "2011-08-18";
and compile the source code again. This may break some new functionality introduced in the latest service release (like asynchronous copy blobs etc.)
Other alternative is to wait out for the new SDK to come out and hope that the emulator in that version support the latest storage service version.
More about URI class
See if below works for you.
URI BlobEndPoint = new URI("http://127.0.0.1:10000/devstoreaccount1");
CloudBlobClient bClient = new CloudBlobClient(BlobEndPoint, new StorageCredentialsAccountAndKey(AccountName,
AccountSecurityKey));