iOS Push Notification - JavaPNS - keystore.p12 file security - ios

I am trying to use Apple's Push Notifications. I am using this tutorial here:
http://www.ibm.com/developerworks/java/library/mo-ios-push/#ibm-pcon
I am on the part where I am trying to create the Push Notification. The sample code is here:
http://code.google.com/p/javapns/wiki/PushNotificationBasic and looks like this:
import javapns.Push;
public class PushTest {
public static void main(String[] args) {
Push.alert("Hello World!", "keystore.p12", "keystore_password", false, "Your token");
}
}
I have everything set up except for the keystore.p12 part. Here is what the documentation says about keystores:
Object keystore: a reference to a keystore file, or the actual keystore content. See Preparing certificates for more information about how to create a keystore. You can pass the following objects to this parameter:
java.io.File: a direct pointer to your keystore file
java.lang.String: a path to your local keystore file
java.io.InputStream: a stream providing the bytes from a keystore
byte[]: the actual bytes of a keystore
java.security.KeyStore: an actual loaded keystore
I do not simply want to type in the path of the keystore on my computer (as they do here Getting error while sending Push Notification to iPhone using Java-PNS?) because I feel like that is unsafe.
Which of the objects should I use? My inclination says to use a java.security.KeyStore.
As a final note, this code needs to be hosted on Amazon Web Service's Elastic Beanstalk (if that matters).
---------Edit 1------------
I have tried to put in Richard J. Ross III's code. But before it is possible to learn if my .p12 file setup is correct, I first need to get around an issue concerning JavaPNS (and file structure I believe). Running the code below gives me this error: HTTP Status 404 - Servlet IosSendGameServlet is not available. When I comment out all of the JavaPNS statements, I get this error: HTTP Status 500 - javax.servlet.ServletException: Parameter recievingAppleDeviceID not found. (because I don't put in the parameters) This leads me to believe that there is a problem with the way that JavaPNS is being accessed. Maybe it is in the wrong place in my file structure? It is in the same place as servlet-api (in lib). Perhaps this is a problem with the way I upload to the AWS Elastic Beanstalk server?
package com.google.android.gcm.demo.server;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javapns.Push; //<--gets commented out to receive 500 error
import javapns.communication.exceptions.CommunicationException;//<--gets commented out to receive 500 error
import javapns.communication.exceptions.KeystoreException;//<--gets commented out to receive 500 error
public class IosSendGameServlet extends BaseServlet {
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException,
ServletException {
String recievingAppleDeviceId = getParameter(req,
"recievingAppleDeviceID");
String sendingUser = getParameter(req, "sendingUser");
InputStream keyStore = this.getClass().getResourceAsStream("/sasSandbox.p12");
//everything below here gets commented out to receive 500 error
try {
Push.alert("Game with " + sendingUser + ": It's your turn!", keyStore, "mypassword", false,
recievingAppleDeviceId);
} catch (CommunicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (KeystoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

You should use an InputStream, and have the .p12 file in your classpath, and use like this:
InputStream keyStore = this.getClass().getResourceAsStream("nameOfMyKeystore.p12");

Related

How to use custom processor on spring cloud data flow?

Here is the Stream I intend to implement:
It is supposed to read records from jdbc, transform to json and write on another database thru jdbc.
For this I have implemented (using the new functional approach):
#SpringBootApplication
public class StreamAppApplication {
private static ObjectMapper objectMapper;
public static void main(String[] args) {
SimpleModule module = new SimpleModule();
module.addSerializer(new ResultSetSerializer());
objectMapper = new ObjectMapper().registerModule(new ParameterNamesModule())
.registerModule(new Jdk8Module())
.registerModule(new JavaTimeModule())
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.registerModule(module);
SpringApplication.run(StreamAppApplication.class, args);
}
#Bean
public Function<ResultSet, String> recordToJson() {
return value -> {
try {
return objectMapper.writeValueAsString(value);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Falha conversão json", e);
}
};
}
}
On the application.properties
spring.cloud.stream.function.definition=recordToJson
Then I have imported it on the web UI as app of type TRANSFORM. It appeared on the UI with the transform classification and no parameters.
How do I use it?
You may want to review and follow the function-bindings recipe from the Microsite to get an understanding of what needs explicitly configured.
From what I can tell, you're likely missing the binding configuration for how your custom processor needs to consume and produce to the relevant channels.
Perhaps even repeat the samples from the recipe on your environment to get an understanding of how it comes together. With that then, you will be able to adapt your custom processor in the same data pipeline to validate it.

How to tell OpenAPI to use context-root of application in it's URL

I am running two different Payara Micro microservices in one cluster.
The issue I have is that when I try to access the OpenAPI URL of MyApp1 like http://mylink.com/myApp1/openapi it does not work. It actually works when I use URL http://mylink.com/openapi.
This becomes an issue when I want to see the API for the other microservice like http://mylink.com/myApp2/openapi which does not work.
Is there a way in Payara Micro of telling OpenAPI to use the application's context in it's path just like all the other URL in the application do?
As you can see in my previous comment, I've also struggled with the same situation.
Context - openapi and microprofile
First let me say that having /openapi URL in the root is the intended behaviour of microprofile-open. Documentation always uses /openapi path as the right to get the document LINK
In the implementation, is very clear that this behaviour is both wanted as enforced:
In the ServletContainerInitializer for OpenApi one can see the following code
// Only deploy to app root
if (!"".equals(ctx.getContextPath())) {
return;
}
Workaround aka Solution.
Now that is clear that we cannot configured this, since it's intended behaviour, one solution ( the one I'm proposing ) is to proxy the request to /YOUR_APP/openapi to /openapi.
Since my application is a jax-rs one, deployed on openshift, and I don't want to have a dedicated proxy application for this, I've just created a simple Resource/Controller to proxy this specific request for me.
The outstanding method behind:
#GET
#Path("")
public Response proxyOpenApiCall(){
log.debug("proxyOpenApiCall called");
String entity = client.target("http://localhost:8080")
.path("openapi").request()
.get(String.class);
return Response.ok(entity).build();
}
I was able to fix this with a small forward proxy. Therefore I create a new REST enpoint wich is callable from public and returns the content of internal http endpoint.
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.enterprise.context.RequestScoped;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
#RequestScoped
#ApplicationPath("/")
#Path("/")
public class OpenApiProxyRestFacade extends Application {
private Client client;
#PostConstruct
public void init() {
this.client = ClientBuilder.newClient();
}
#GET
#Path("/openapi")
#Produces(MediaType.APPLICATION_JSON)
public Response proxyOpenApiCall() {
String entity = client.target("http://localhost:9080").path("openapi").request().get(String.class);
return Response.ok(entity).build();
}
#GET
#Path("/openapi/ui")
#Produces(MediaType.APPLICATION_JSON)
public Response proxyOpenApiUiCall() {
String entity = client.target("http://localhost:9080/openapi").path("ui").request().get(String.class);
return Response.ok(entity).build();
}
#PreDestroy
public void destroy() {
this.client.close();
}
}
For openapi, you can set this property for change of url, so it is configurable after all
mp.openapi.extensions.path=/yourapi/whatever
and for the openapi-UI set this
openapi.ui.yamlUrl=/yourapi/whatever
Sources: I first googled for mp.openapi.xxx parameters, (I found them in source code) which led me to this url
https://download.eclipse.org/microprofile/microprofile-open-api-1.0/microprofile-openapi-spec.html
and after looking for more stuff there was one simple sentence mentioning that there is also mp.openapi.extensions and after googling those further I found this random doc here https://github.com/wildfly/wildfly/blob/main/docs/src/main/asciidoc/_admin-guide/subsystem-configuration/MicroProfile_OpenAPI.adoc

Clear url in browser window using Java code

I am using navigate().to() method to navigate but new url is getting appended to old url as below, after executing navigate.to function thus resulting in 404 error
https://www.google.co.in/www.yahoo.co.in
Can anyone please help how should I get this to work?
public static void main(String[] args) throws InterruptedException {
WebDriver fd = new FirefoxDriver();
fd.get("http://www.google.co.in");
Thread.sleep(3000);
fd.navigate().to("www.yahoo.co.in");
}
}
I'm not sure how to use navigate().to() but this an alternative solution.
import java.awt.Desktop;
import java.net.URI;
....
try {
Desktop d = Desktop.getDesktop();
d.browse(new URI("http://www.google.co.in"));
Thread.sleep(3000);
d.browse(new URI("www.yahoo.co.in"));
} catch (Exception ex) {
ex.printStackTrace();
}
There are two options:
1) use again get() method from the WebDriver to navigate to the new URL.
2) use navigate().to() method, but use fully qualified URL parameter. Eg. "https://www.google.com"
From the WebDriver javadoc: #param url The URL to load. It is best to use a fully qualified URL
The navigate() method is useful for using the context on the current web context. i.e. go back, forward.
Basically, the get() and navigate().to() do the same thing. I just tried both and they work.
Reference: http://www.seleniumeasy.com/selenium-tutorials/difference-between-webdriver-get-and-navigate

How to pass error message to the error page via ExceptionHandler?

My debut J2EE 6 app.
I am using a solder ExceptionHandler to deal with exceptions, but I'm not liking it much. It seems way too complicated for what I want to do.
For example
import java.io.IOException;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jboss.solder.exception.control.CaughtException;
import org.jboss.solder.exception.control.Handles;
import org.jboss.solder.exception.control.HandlesExceptions;
/**
* Handle exceptions and redirect page.
*/
#HandlesExceptions
public class ExceptionHandlers {
void noResult(
#Handles CaughtException<dne.nmst.ond.exceptions.OfficeNotFoundException> caught,
HttpServletRequest request, HttpServletResponse response) {
caught.handled();
try {
String msg = caught.getException().getMessage();
response.sendRedirect(request.getContextPath()
+ "/searchOffice.xhtml");
} catch (IOException e) {
e.printStackTrace();
}
}
I would like to display the error message from OfficeNotFoundException in searchOffice.xhtml. How do I get it from here to there?
One thing I considered was putting the error into the flash context, but I get NPE when trying to reference FacesContext from this exception handling class.
I tried an error-page entry in web.xml. I could not get it to work.
I know I could pass it as a request parameter in the redirect, but that seems like a workaround. I want to do it the simplest and "most correct" way (whatever that means).
I miss Seam 2 where we could just do this in pages.xml:
<exception class="dne.nmst.ond.exceptions.OfficeNotFoundException">
<redirect include-page-params="false" view-id="searchOffice.xhtml">
<message severity="warn"/>
</redirect>
with
<h:messages />
in the view.
You can set the error message in your code and specify which h:messages tag the message should appear in. Refer the answer below.
https://stackoverflow.com/a/4194098/2450373

Upload Youtube using Proxy, per connection and not system wide

I have a Java code using youtube-api to upload videos. Until now I was using the system configuration to set the proxy (http and https) and everything is working fine that way. But now I have a new requirement regarding the way we use proxy on the server. As we have other services running on the very same server, they asked me to not configure the proxy using system wide approach, because this affect all the services using JVM.
System.setProperty("http.proxyHost", httpProxyHost);
System.setProperty("http.proxyPort", httpProxyPort);
and
System.setProperty("https.proxyHost", httpsProxyHost);
System.setProperty("https.proxyPort", httpsProxyPort);
I have spent the last couple days researching that on the Internet and didn't find anything useful. I found a explanation on the C# API what seems to be setting the proxy to the connection and I didn't find a way to implement this same approach on Java.
I want to do something like this:
service = new YouTubeService(APPLICATION_NAME, DEVELOPER_KEY);
service.setUserCredentials(userName, password);
uploader = new ResumableGDataFileUploader.Builder(
service, new URL(RESUMABLE_UPLOAD_URL), ms, newVideoEntry)
.title(videoTitle)
.trackProgress(listener, PROGRESS_UPDATE_INTERVAL)
.chunkSize(DEFAULT_CHUNK_SIZE).build();
// fictional code to show what I want to do
uploader.setProxyHttp(httpProxyHost, httpProxyPort);
uploader.setProxyHttps(httpsProxyHost, httpsProxyPort);
uploader.start();
This is very similar to what Java already allow us to do. See this http://docs.oracle.com/javase/6/docs/technotes/guides/net/proxies.html
I just resolved with the following code. Adapt the method setPersonalUrlConnectionFactory to set your proxy and call it passing as argument your uploader.
package com.google.gdata.client.uploader;
import com.google.gdata.client.media.ResumableGDataFileUploader;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
public class PersonalUrlConnectionInjector {
public static void setPersonalUrlConnectionFactory(ResumableGDataFileUploader uploader) {
try {
java.lang.reflect.Field field = uploader.getClass().getSuperclass().getDeclaredField("urlConnectionFactory");
field.setAccessible(true);
java.lang.reflect.Field modifiersField = java.lang.reflect.Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~java.lang.reflect.Modifier.FINAL);
field.set(uploader, new UrlConnectionFactory() {
#Override
public HttpURLConnection create(URL url) throws IOException {
return new sun.net.www.protocol.http.HttpURLConnection(url, MY_PROXY);
}
});
} catch (Exception e) {
/* DO LOG */
}
}
}

Resources