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 */
}
}
}
Related
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
I am working on a project, that used GRPC microservices. Normally GRPC used protobuf as his default method to serialized data. But, we are using JSON as placed of protobuf. In general, we defined message and services in protobuf and complied with protoc , then merged generated file with the project. But somehow google made tough to merged JSON in GRPC. I thought Google should make a documentation like this (https://grpc.io/blog/grpc-with-json) for iOS developer too. But unfortunately, there is no separate documentation in Swift. I found it hard to used JSON type in GRPC. How will I call methods in CLIENT-SIDE code in Swift?
I want to pass two variable (data: String, idToken: String) i.e defined in Request struct after that services should give me a Response. In that way, I would understand both get and post method used in GRPC.
https://grpc.io/blog/grpc-with-json , In this link, we can check how java works with JSON+GRPC. I am adding this java code example for more understanding oh what I want to make in Swift, Maybe it will do some help.
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import io.grpc.MethodDescriptor;
public class UserManagerRpcGson {
private static final String SERVICE_NAME = "url";
public static final class Request {
public String data;
public String idToken;
}
public static final MethodDescriptor<Request, Response> REGISTER_METHOD =
MethodDescriptor.newBuilder(
marshallerFor(Request.class),
marshallerFor(Response.class))
.setFullMethodName(
MethodDescriptor.generateFullMethodName(SERVICE_NAME, "registerUser"))
.setType(MethodDescriptor.MethodType.UNARY)
.setSampledToLocalTracing(true)
.build();
static <T> MethodDescriptor.Marshaller<T> marshallerFor(Class<T> clz) {
return new MethodDescriptor.Marshaller<T>() {
#Override
public InputStream stream(T value) {
return new ByteArrayInputStream(GsonUtil.gson.toJson(value, clz).getBytes(StandardCharsets.UTF_8));
}
#Override
public T parse(InputStream stream) {
return GsonUtil.gson.fromJson(new InputStreamReader(stream, StandardCharsets.UTF_8), clz);
}
};
}
}
I have developed an Atlasian Bitbucket plugin which globally listens for push/PR and send repository details to databases using REST API.
I need to configure REST API URL and credential so that my plugin can make an API call. Currently I have hardcoded REST API URL and credential in my plugin properties file. Which I don't like because every time if I need to create a package to target my test environment or production, I have to change. Also, I don't like to keep credentials in the source code.
What is the best way to add configuration screen in the bitbucket plugin? I would like to have form for URL, username and password (once I installed the plugin) and update the storage in Bitbucket only once. If I need to restart my bitbucket, I do not want to lose saved data.
I tried to search on how to configure a bitbucket plugin, however I could not find an easy way. I do see multiple approaches, for example to add "Configure" button which will open a servelet to take user input. Seems very cryptic to me. Also, I see so many recommendations for template, for example velocity, soy etc which confused me a lot.
Since I am new to plugin development therefore not able to explore. Looking for some help.
I have solution for this case:
From pom.xml please add more library:
<dependency>
<groupId>com.atlassian.plugins</groupId>
<artifactId>atlassian-plugins-core</artifactId>
<version>5.0.0</version>
<scope>provided</scope>
</dependency>
Create new abc-server.properties on resources/ folder with following content:
server.username=YOUR_USERNAME
server.password=YOUR_PASSWORD
Get value from abc-server.properties on service class as the following:
import com.atlassian.plugin.util.ClassLoaderUtils;
...
final Properties p = new Properties();
final InputStream is = ClassLoaderUtils.getResourceAsStream("abc-server.properties", this.getClass());
try {
if (is != null) {
p.load(is);
String username = p.getProperty("server.username");
String password = p.getProperty("server.password");
}
} catch (IOException e) {
e.printStackTrace();
}
Please try to implement it. Thanks!
One possibility for a simple configuration file, is to read somefile.properties from the Bitbucket home directory, this way the config file will survive application updates.
Create somefile.properties in BITBUCKET_HOME
server.username=YOUR_USERNAME
server.password=YOUR_PASSWORD
Read the properties in your plugin class like this
// imports
import com.atlassian.bitbucket.server.StorageService;
import com.atlassian.plugin.spring.scanner.annotation.imports.ComponentImport;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
private final StorageService storageService;
// StorageService injected via constructor injection
public SomePlugin(#ComponentImport final StorageService storageService) {
this.storageService = storageService;
}
Properties p = new Properties();
File file = new File(storageService.getHomeDir().toString(), "somefile.properties");
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(file);
p.load(fileInputStream);
String username = p.getProperty("server.username");
String password = p.getProperty("server.password");
} catch (IOException e) {
//handle exception
}
I'm new in dart's programming and I'm building a dart app and I would like to start it from the server side. Like loading my homepage when I enter the url of my webpage.
On my server side I have this code that I took from tutorials from dart's webpage:
var server;
try{
server = await HttpServer.bind(InternetAddress.LOOPBACK_IP_V6, 4040);
}catch(e){
print("Couldn't bind to port 4044: $e");
exit(-1);
}
await for(HttpRequest req in server){
var file = new File('index.html');
if(await file.exists()){
print("Serving index.html.");
req.response.headers.contentType = ContentType.HTML;
try{
await file.openRead().pipe(req.response);
}catch(e){
print("Couldn't read file: $e");
exit(-1);
}
}else{
print("Couldn't open index.html");
req.response..statusCode = HttpStatus.NOT_FOUND..close();
}
}
But now my problem is about the client side, my elements are not loading, like css, images, etc.
You can see the appearance here
I think that I need to set something at my server side to load that. What is it?
Using the core dart:io methods for serving files is often not the easiest way. Take a look at shelf, f.e. It's a really neat framework for creating server applications that has a lot of plugins and extensions for middleware etc.
In your case, it seems like you just want to serve static content. I'd suggest you use shelf_static. It would go like this:
import 'package:shelf/shelf_io.dart' as io;
import 'package:shelf_static/shelf_static.dart';
void main() {
var handler = createStaticHandler('your-web-directory/',
defaultDocument: 'index.html');
io.serve(handler, InternetAddress.LOOPBACK_IP_V6, 4040);
}
can I use Spring Security or Shiro Security with Ninja Framework or Spark Framework? I can't find any example to integrate this security frames with web frames. there is not any information in the ninja web site about user auth and web app security.
This question is quite old, but I am unable to find any example of integrating Apache Shiro with Ninja Framework, so here are my findings about this.
Ninja Framework requires an instance of AbstractModule, it shows me an error when you try something like the configuration that is recommended here:
package conf;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import org.apache.shiro.config.Ini;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.guice.ShiroModule;
class Module extends ShiroModule {
protected void configureShiro() {
try {
bindRealm().toConstructor(IniRealm.class.getConstructor(Ini.class));
} catch (NoSuchMethodException e) {
addError(e);
}
}
#Provides
Ini loadShiroIni() {
return Ini.fromResourcePath("classpath:shiro.ini");
}
}
However checking the source code of ShiroModule class I noticed that it extends PrivateModule so this should work, at least I get no compilation errors:
package conf;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import org.apache.shiro.config.Ini;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.guice.ShiroModule;
public class Module extends AbstractModule
{
#Override
protected void configure()
{
install(new ShiroModule()
{
#Override
protected void configureShiro()
{
//shiro recomended configuration
try {
bindRealm().toConstructor(IniRealm.class.getConstructor(Ini.class));
} catch (NoSuchMethodException e) {
addError(e);
}
}
#Provides
Ini loadShiroIni()
{
return Ini.fromResourcePath("classpath:shiro.ini");
}
});
}
}
Spark has the notion of filters. http://sparkjava.com/documentation.html#filters therefore you can add the Shiro or Spring Security filter. That said, it isn't as simple as dropping in a filter for either of these security frameworks. But in theory...
if you want to secure web restful api, suggest use the sureness - https://github.com/tomsun28/sureness
It is no specific framework dependency(support springboot, quarkus, javalin, ktor and more).
The essence of sureness is to intercept all rest requests for authenticating and Authorizing.
The interceptor can be a filter or a spring interceptor, it intercepts all request to check them.
What you need to know is that sureness is a project created by us, welcome to use.