Persisting new Entity to existing Database JPA - database

I've created a database connection and some entities, now I'm trying to test the functionality of my database. I have a User entity class, which has a unique username along with some other information. Right now I'm trying to simply create a new User and Profile and map them together, then persist them. When I test the code, it successfully runs through, but the DB is not updated. Here's what I have:
package servlets;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.UserTransaction;
import entities.Profile;
import entities.User;
#WebServlet("/NewUser")
public class NewUser extends HttpServlet {
#Resource
UserTransaction utx;
#PersistenceUnit
EntityManagerFactory emf;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String email = request.getParameter("email");
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
String phone = request.getParameter("phone");
String address1 = request.getParameter("address1");
String address2 = request.getParameter("address2");
try {
utx.begin();
EntityManager em = emf.createEntityManager();
//create User & Profile
User u = new User();
u.setUsername(username);
Profile p = new Profile();
p.setUser(username);
//add email to profile's list
List<String> emails = new ArrayList<String>();
emails.add(email);
p.setEmails(emails);
//assign the profile to the user
u.setProfile(p);
//persist user to the database
em.persist(u);
utx.commit();
em.close();
emf.close();
} catch (Exception e) {
e.printStackTrace();
}
response.sendRedirect("index.jsp");
}
}
Am I doing something wrong or is the problem somewhere else in the application?
EDIT: I found the following error: Exception Description: Unable to acquire a connection from driver [null], user [null] and URL [null]. Verify that you have set the expected driver class and URL. Check your login, persistence.xml or sessions.xml resource. The jdbc.driver property should be set to a class that is compatible with your database platform
I'm not sure what to make of the error, however...I've checked my db connection and everything seems to be in order. :/
My persistence.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="myPersistenceUnit" >
<jta-data-source>jdbc/mydatasource</jta-data-source>
<class>entities.User</class>
<class>entities.Profile</class>
<class>entities.Message</class>
<class>entities.Image</class>
<properties>
<property name="eclipselink.ddl-generation" value="create-tables"/>
<property name="eclipselink.ddl-generation.output-mode" value="both"/>
</properties>
</persistence-unit>
</persistence>

I have never use container managed transactions but your persistence.xml at least have.
<persistence-unit name="myPersistenceUnit" transaction-type="JTA">

Related

java.lang.IllegalArgumentException due to named query not found

I can adding to data to database but I am not getting data from database . Okey I am writing my problem,my entity class Product and I store the database operations on ProductRepository.java
Then at my database that;its name jsfjpadb.
productId productName salesPrice
1 Kerem 1235
2 Book 23
I am trying to get the data in the database and I want will show on the ProductOzetSayfasi.xhtml but doesnt come.
public class ProductRepository {
public List<Product> list() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("kerem");
EntityManager manager = factory.createEntityManager();
// String string = "SELECT product FROM Product as product";
// Query query = manager.createNamedQuery(string);
TypedQuery<Product> productQuery = manager.createQuery("SELECT p FROM Product p",Product.class);
List<Product> productList =productQuery.getResultList();
manager.close();
return productList;
}
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd">
<persistence-unit name="kerem" transaction-type="RESOURCE_LOCAL">
<class>com.kerem.inventory.entity.Tablo</class>
<class>com.kerem.inventory.entity.Product</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jsfjpadb"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="kerem2112"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
</properties>
</persistence-unit>
</persistence>
package com.kerem.inventory.faces;
import java.util.*;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import com.kerem.inventory.entity.Product;
import com.kerem.inventory.repository.ProductRepository;
#ManagedBean
public class ProductOzetSayfasiBean {
private List<Product> productList;
public ProductOzetSayfasiBean() {
ProductRepository repository = new ProductRepository();
productList = repository.list();
}
public List<Product> getProductList() {
return productList;
}
}
package com.kerem.inventory.entity;
import java.io.Serializable;
import java.util.List;
import javax.persistence.*;
#Entity
#Table(name = "product")
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int productId;
private String productName;
private double salesPrice;
public Product() {
}
public int getProductId() {
return this.productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductName() {
return this.productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public double getSalesPrice() {
return this.salesPrice;
}
public void setSalesPrice(double salesPrice) {
this.salesPrice = salesPrice;
}
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Product</title>
</h:head>
<h:body>
<h1>Product</h1>
<h:form>
<h:dataTable value="#{productOzetSayfasiBean.productList}" var="product">
<h:column>
<h:outputText value="#{product.productId}"/>
</h:column>
</h:dataTable>
</h:form>
</h:body>
</html>
STACK TRACE
INFO: Creating instance of com.kerem.inventory.faces.ProductOzetSayfasiBean
[EL Info]: 2020-05-01 04:44:00.226--ServerSession(985404382)--EclipseLink, version: Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd
Fri May 01 04:44:00 PDT 2020 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Fri May 01 04:44:01 PDT 2020 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
[EL Info]: connection: 2020-05-01 04:44:02.365--ServerSession(985404382)--file:/D:/EclipseProjeleri/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/kerem/WEB-INF/classes/_kerem login successful
May 01, 2020 4:44:02 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Faces Servlet] in context with path [/kerem] threw exception [NamedQuery of name: select product from Product as product not found.] with root cause
java.lang.IllegalArgumentException: NamedQuery of name: select product from Product as product not found.
at org.eclipse.persistence.internal.jpa.QueryImpl.getDatabaseQueryInternal(QueryImpl.java:351)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createNamedQuery(EntityManagerImpl.java:1124)
at com.kerem.inventory.repository.ProductRepository.list(ProductRepository.java:19)
at com.kerem.inventory.faces.ProductOzetSayfasiBean.<init>(ProductOzetSayfasiBean.java:19)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
at java.base/java.lang.reflect.ReflectAccess.newInstance(ReflectAccess.java:166)
at java.base/jdk.internal.reflect.ReflectionFactory.newInstance(ReflectionFactory.java:404)
at java.base/java.lang.Class.newInstance(Class.java:591)
at org.apache.myfaces.config.annotation.Tomcat7AnnotationLifecycleProvider.newInstance(Tomcat7AnnotationLifecycleProvider.java:56)
at org.apache.myfaces.config.ManagedBeanBuilder.buildManagedBean(ManagedBeanBuilder.java:156)
at org.apache.myfaces.el.unified.resolver.ManagedBeanResolver.createManagedBean(ManagedBeanResolver.java:333)
at org.apache.myfaces.el.unified.resolver.ManagedBeanResolver.getValue(ManagedBeanResolver.java:296)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:63)
at org.apache.myfaces.el.unified.resolver.FacesCompositeELResolver.getValue(FacesCompositeELResolver.java:169)
at org.apache.myfaces.el.VariableResolverImpl.resolveVariable(VariableResolverImpl.java:65)
at org.apache.myfaces.el.convert.VariableResolverToELResolver.getValue(VariableResolverToELResolver.java:123)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:63)
at org.apache.myfaces.el.unified.resolver.FacesCompositeELResolver.getValue(FacesCompositeELResolver.java:169)
at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:94)
at org.apache.el.parser.AstValue.getValue(AstValue.java:137)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
at org.apache.myfaces.view.facelets.el.ContextAwareTagValueExpression.getValue(ContextAwareTagValueExpression.java:96)
at javax.faces.component._DeltaStateHelper.eval(_DeltaStateHelper.java:246)
at javax.faces.component.UIData.getValue(UIData.java:2028)
at javax.faces.component.UIData.createDataModel(UIData.java:1976)
at javax.faces.component.UIData.getDataModel(UIData.java:1953)
at javax.faces.component.UIData.getRowCount(UIData.java:478)
at org.apache.myfaces.shared.renderkit.html.HtmlTableRendererBase.encodeInnerHtml(HtmlTableRendererBase.java:328)
at org.apache.myfaces.shared.renderkit.html.HtmlTableRendererBase.encodeChildren(HtmlTableRendererBase.java:198)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:549)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:749)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:758)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:758)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:758)
at org.apache.myfaces.view.facelets.FaceletViewDeclarationLanguage.renderView(FaceletViewDeclarationLanguage.java:1900)
at org.apache.myfaces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:285)
at org.apache.myfaces.lifecycle.RenderResponseExecutor.execute(RenderResponseExecutor.java:115)
at org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:241)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:199)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:670)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:830)
define named query via annotation or in xml mapping file. createNamedQuery requires name of query but not the actual query. If you dont want to go that way, use createQuery instead. createQuery takes actual query.
Refer Creating Queries using JPQL

Is there any way to send a media file as part of a request in Spring Boot?

I am new in programming and seeking for a solution to my problem. Here, I am going to describe my problem in as much clarity as I can.
So, I am working on a problem where I have to create an API which is going to accept (String1, String2, Mediafile(mp3), Mediafile(txt)) and then I have to upload these files somewhere else.
Here, I want to know do we expect Media Files in the byte[] format or is there any way that I can get that Mediafile as it is(Not in Byte format).
package com.self.projects;
import java.io.IOException;
import org.springframework.boot.json.JsonParseException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
#RestController
#RequestMapping("/hellomedia")
public class TestMediafile {
#RequestMapping(value = "addDetails", method = RequestMethod.POST , consumes = "multipart/form-data")
public StudentClassReport addProduct(
#RequestParam String studentReportJson,
#RequestParam MultipartFile report,
#RequestParam MultipartFile transcription,
#RequestParam int marks) throws JsonParseException, JsonMappingException, IOException {
studentClassReport studentReport = new objectMapper().readValue(studentReportJson, StudentClassReport.class);
byte[] myReport = report.getBytes();
byte[] myTranscription = transcription.getBytes();
studentReport.setTranscription(myTranscription);
studentReport.setReport(myReport);
return studentReport;
}
}

Programmatically accessing a Google App Engine Standard servlet that requires Google login

The following is a simple Google App Engine Standard servlet that displays a user’s Google e-mail address if the user is logged in. How can I invoke this programmatically (e.g. using curl or Java code) while providing Google credentials (e.g. for a user or service account). I think I need to obtain an OAuth2 token, but I could use some help coming up with a step-by-step process.
package com.example.appengine.java8;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
#WebServlet(name = "HelloAppEngine", value = "/hello")
public class HelloAppEngine extends HttpServlet {
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
if(user == null) {
out.print("not authenticated");
}
else {
out.print(user.getEmail());
}
}
}
Here is a live version of this servlet:
https://servlet-authentication-test.appspot.com/hello
You can use the following link to login with a Google account and then access the servlet while authenticated:
https://accounts.google.com/signin/v2/identifier?service=ah&passive=true&continue=https%3A%2F%2Fappengine.google.com%2F_ah%2Fconflogin%3Fcontinue%3Dhttps%3A%2F%2Fservlet-authentication-test.appspot.com%2Fhello&flowName=GlifWebSignIn&flowEntry=ServiceLogin
You can use GoogleAuthorizationCodeFlow from Google API Client Library to generate a callback request to Google to handle signing in to a Google account. For a detailed example you can take a look at this documentation or at GitHub for the source code.

Datastore export logic in Java

Thankfully, Google announced the export logic from cloud Datastore. I would like to set up schedule-export in my platform. However, it's not Python, but Java. So I need to use cron.xml and Java logic to design this logic.
Is there any reference to design Datastore export logic (cloud_datastore_admin.py) in Java? Especially, I need to transform this part in Java
app = webapp2.WSGIApplication(
[
('/cloud-datastore-export', Export),
], debug=True)
https://cloud.google.com/datastore/docs/schedule-export
You can create the skeleton for App Egnine by following these instructions.
Once you have the skeleton, add something like this to handle export requests:
CloudDatastoreExport.java
package com.google.example.datastore;
import com.google.appengine.api.appidentity.AppIdentityService;
import com.google.appengine.api.appidentity.AppIdentityServiceFactory;
import com.google.apphosting.api.ApiProxy;
import com.google.common.io.CharStreams;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Logger;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
#WebServlet(name = "CloudDatastoreExport", value = "/cloud-datastore-export")
public class CloudDatastoreExport extends HttpServlet {
private static final Logger log = Logger.getLogger(CloudDatastoreExport.class.getName());
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
// Verify outputURL parameter
String outputUrlPrefix = request.getParameter("output_url_prefix");
if (outputUrlPrefix == null || !outputUrlPrefix.matches("^gs://.*")) {
response.setStatus(HttpServletResponse.SC_CONFLICT);
response.setContentType("text/plain");
response.getWriter().println("Error: Must provide a valid output_url_prefix.");
} else {
// Get project ID
String projectId = ApiProxy.getCurrentEnvironment().getAppId();
// Remove partition information to get plain app ID
String appId = projectId.replaceFirst("(.*~)", "");
// Get access token
ArrayList<String> scopes = new ArrayList<String>();
scopes.add("https://www.googleapis.com/auth/datastore");
final AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
final AppIdentityService.GetAccessTokenResult accessToken =
appIdentity.getAccessToken(scopes);
// Read export parameters
// If output prefix does not end with slash, add a timestamp
if (!outputUrlPrefix.substring(outputUrlPrefix.length() - 1).contentEquals("/")) {
String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
outputUrlPrefix = outputUrlPrefix + "/" + timeStamp + "/";
}
String[] namespaces = request.getParameterValues("namespace_id");
String[] kinds = request.getParameterValues("kind");
// Build export request
JSONObject exportRequest = new JSONObject();
exportRequest.put("output_url_prefix", outputUrlPrefix);
JSONObject entityFilter = new JSONObject();
if (kinds != null) {
JSONArray kindsJSON = new JSONArray(kinds);
entityFilter.put("kinds", kinds);
}
if (namespaces != null) {
JSONArray namespacesJSON = new JSONArray(namespaces);
entityFilter.put("namespaceIds", namespacesJSON);
}
exportRequest.put("entityFilter", entityFilter);
URL url = new URL("https://datastore.googleapis.com/v1/projects/" + appId + ":export");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.addRequestProperty("Content-Type", "application/json");
connection.addRequestProperty("Authorization", "Bearer " + accessToken.getAccessToken());
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
exportRequest.write(writer);
writer.close();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
JSONTokener exportResponseTokens = new JSONTokener(connection.getInputStream());
JSONObject exportResponse = new JSONObject(exportResponseTokens);
response.setContentType("text/plain");
response.getWriter().println("Export started:\n" + exportResponse.toString(4));
} else {
InputStream s = connection.getErrorStream();
InputStreamReader r = new InputStreamReader(s, StandardCharsets.UTF_8);
String errorMessage =
String.format(
"got error (%d) response %s from %s",
connection.getResponseCode(), CharStreams.toString(r), connection.toString());
log.warning(errorMessage);
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.setContentType("text/plain");
response.getWriter().println("Failed to initiate export.");
}
}
}
}
You can use the same cron.yaml from the docs:
cron:
- description: "Daily Cloud Datastore Export"
url: /cloud-datastore-export?namespace_id=&output_url_prefix=gs://BUCKET_NAME[/NAMESPACE_PATH]
target: cloud-datastore-admin
schedule: every 24 hours
Use gcloud to deploy the cron job:
gcloud app deploy cron.yaml
Make sure you complete this part to give GAE export and bucket permissions or else
you'll get permission denied errors:
https://cloud.google.com/datastore/docs/schedule-export#before_you_begin
The code snippet you showed is just a part of the typical GAE app skeleton specific for 1st generation standard environment python apps. You can easily recognize it in the main.py section of the python quickstart Hello World code review.
The code initializes the app variable (from the main python module, i.e. the main.py file) which is referenced in the app.yaml handler config as script: main.app.
The corresponding java app skeleton is significantly different, see the java quickstart Hello World code review. But no worries, you shouldn't need to specifically transform that code snippet, you just need to build your java app skeleton and focus on what the app handler actually does - making those POST requests to the datastore. Sorry I can't help more, but I'm not a java user.
What I really realized is that app.yaml is like Web.xml in java
and cloud-datastore-export is a servlet that communicates with gae to export data but I can't do more

Apache Camel box component file dowload, how do I use the output parameter?

I have been trying to download a file from Box using the Apache Camel Box component. I cannot seem to unserstand how to use the required parameter output with the uri box://files/downloadFile.
I am able to upload files fine (code not listed), so I am confident that this is a problem configure this particular endpoint and not with, for example, my org.apache.camel.component.box.BoxConfiguration.
How do I use camel-box and box://files/downloadFile to download a file? Specifically what I am expected to pass as the output parameter of the endpoint uri?
I've been referring to this documentation:
https://github.com/apache/camel/blob/master/components/camel-box/camel-box-component/src/main/docs/box-component.adoc
Here's what I am working with:
camel-core 2.19.3,camel-box 2.19.3,camel-spring-javaconfig 2.19.3
Here's the route, BoxRoute.java that I cant figure out:
package [REDACTED];
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
#Component
public class BoxRoute extends RouteBuilder{
private static final Logger LOG = LoggerFactory.getLogger(BoxRoute.class);
#Override
public void configure() throws Exception {
from("box://files/downloadFile?fileId=[REDACTED]&output=#outputStream") //I expect this to refer to the outputStream #Bean
.process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
for(String key: exchange.getProperties().keySet()){
LOG.debug("ex prop {} = {}", key, exchange.getProperty(key));
}
for(String key: exchange.getIn().getHeaders().keySet()){
LOG.debug("he prop {} = {}", key, exchange.getIn().getHeader(key));
}
}
})
.to("file:c:/_/dat/camel/out");
}
}
So I think I'm giving this uri what it needs. Namely, a reference to my outputStream been which is an OutputStream, defined in the next listing.
My application's main method is in BoxApplication.java:
package [REDACTED];
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import org.apache.camel.spring.javaconfig.CamelConfiguration;
import org.apache.camel.spring.javaconfig.Main;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
#Configuration
#ComponentScan
#ImportResource("classpath:/META-INF/spring/box-context.xml")
public class BoxApplication extends CamelConfiguration{
public static void main(String[] args) throws Exception {
Main main = new Main();
main.setConfigClass(BoxApplication.class);
main.setDuration(10);
main.run();
}
#Bean()
public OutputStream outputStream(){
System.out.println("I AM GETTING REGISTERED"); // I see this in stdout, so this bean is available to Camel (right?)
return new ByteArrayOutputStream();
}
}
The contents of box-context.xml are (I can use camel box to upload, so I doubt my problems is here):
?xml version="1.0" encoding="UTF-8"?>
beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="box" class="org.apache.camel.component.box.BoxComponent">
<property name="configuration">
<bean class="org.apache.camel.component.box.BoxConfiguration">
<property name="userName" value="[REDACTED]" />
<property name="userPassword" value="[REDACTED]" />
<property name="clientId" value="[REDACTED]" />
<property name="clientSecret" value="[REDACTED]" />
<property name="authenticationType" value="STANDARD_AUTHENTICATION" />
</bean>
</property>
</bean>
Alas, I get this error, and I am stumped. Any help would be appreciated.
2017-10-07 18:05:00.128 [main] INFO o.s.c.a.AnnotationConfigApplicationContext(583) - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#bd8db5a: startup date [Sat Oct 07 18:05:00 EDT 2017]; root of context hierarchy
2017-10-07 18:05:00.216 [main] INFO o.s.b.f.xml.XmlBeanDefinitionReader(317) - Loading XML bean definitions from class path resource [META-INF/spring/box-context.xml]
2017-10-07 18:05:00.500 [main] INFO o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker(325) - Bean 'boxApplication' of type [com.hqcllc.box.BoxApplication$$EnhancerBySpringCGLIB$$4e7e4dfa] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
I AM GETTING REGISTERED
Exception in thread "main" org.apache.camel.spring.javaconfig.CamelSpringJavaconfigInitializationException: org.apache.camel.RuntimeCamelException: Error invoking downloadFile with {output=, listener=Consumer[box://files/downloadFile?fileId=[REDACTED]&output=%23outputStream], fileId=[REDACTED]}: object is not an instance of declaring class
at org.apache.camel.spring.javaconfig.RoutesCollector.onApplicationEvent(RoutesCollector.java:88)
at org.apache.camel.spring.javaconfig.RoutesCollector.onApplicationEvent(RoutesCollector.java:33)
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:167)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:393)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:347)
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:883)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546)
at org.apache.camel.spring.javaconfig.Main.createDefaultApplicationContext(Main.java:148)
at org.apache.camel.spring.Main.doStart(Main.java:154)
at org.apache.camel.support.ServiceSupport.start(ServiceSupport.java:61)
at org.apache.camel.main.MainSupport.run(MainSupport.java:168)
at com.hqcllc.box.BoxApplication.main(BoxApplication.java:22)
Caused by: org.apache.camel.RuntimeCamelException: Error invoking downloadFile with {output=, listener=Consumer[box://files/downloadFile?fileId=[REDACTED]&output=%23outputStream], fileId=[REDACTED]}: object is not an instance of declaring class
at org.apache.camel.util.component.ApiMethodHelper.invokeMethod(ApiMethodHelper.java:514)
at org.apache.camel.component.box.BoxConsumer.doStart(BoxConsumer.java:98)
at org.apache.camel.support.ServiceSupport.start(ServiceSupport.java:61)
at org.apache.camel.impl.DefaultCamelContext.startService(DefaultCamelContext.java:3514)
at org.apache.camel.impl.DefaultCamelContext.doStartOrResumeRouteConsumers(DefaultCamelContext.java:3831)
at org.apache.camel.impl.DefaultCamelContext.doStartRouteConsumers(DefaultCamelContext.java:3767)
at org.apache.camel.impl.DefaultCamelContext.safelyStartRouteServices(DefaultCamelContext.java:3687)
at org.apache.camel.impl.DefaultCamelContext.doStartOrResumeRoutes(DefaultCamelContext.java:3451)
at org.apache.camel.impl.DefaultCamelContext.doStartCamel(DefaultCamelContext.java:3305)
at org.apache.camel.impl.DefaultCamelContext.access$000(DefaultCamelContext.java:202)
at org.apache.camel.impl.DefaultCamelContext$2.call(DefaultCamelContext.java:3089)
at org.apache.camel.impl.DefaultCamelContext$2.call(DefaultCamelContext.java:3085)
at org.apache.camel.impl.DefaultCamelContext.doWithDefinedClassLoader(DefaultCamelContext.java:3108)
at org.apache.camel.impl.DefaultCamelContext.doStart(DefaultCamelContext.java:3085)
at org.apache.camel.support.ServiceSupport.start(ServiceSupport.java:61)
at org.apache.camel.impl.DefaultCamelContext.start(DefaultCamelContext.java:3022)
at org.apache.camel.spring.javaconfig.RoutesCollector.onApplicationEvent(RoutesCollector.java:84)
... 12 more
Caused by: java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.camel.util.component.ApiMethodHelper.invokeMethod(ApiMethodHelper.java:506)
... 28 more
This is my first Camel project fyi.

Resources