Github java api - java

I am using org.kohsuke.github java api, and I am trying to create a new subdirectories in an existing Directory in my git repo. Everytime I run my code, I get the same exception:
org.kohsuke.github.GHFileNotFoundException:
{"message":"Not Found",
"documentation_url":"https://developer.github.com/enterprise/2.13/
v3/git/trees/#create-a-tree"}
at org.kohsuke.github.Requester.handleApiError(Requester.java:699)
at org.kohsuke.github.Requester._to(Requester.java:306)
at org.kohsuke.github.Requester.to(Requester.java:247)
at org.kohsuke.github.GHTreeBuilder.create(GHTreeBuilder.java:88)
at GitTest.main(GitTest.java:50)
This is my code:
OkHttpClient okHttpClient = new OkHttpClient();
repository = initGithub(okHttpClient);
GHTree test = getTree();
System.out.println(test.getUrl());
System.out.println(test.getSha());
GHTreeBuilder builder = repository.createTree();
try {
builder.baseTree(test.getSha()).entry("SUB", "040000", "tree",
test.getSha(), null).create();
} catch (IOException e) {
e.printStackTrace();
}
I have tested with different params for the.entry() method. Did anybody use this api before? I don't know what I am doing wrong.

Related

Why do I get NullPointerException when trying to access resource file?

I want to make so a file in the program is packaged in the jar file because it is needed in my program. It is the firebase credentials file. I read that I need to add it to the resource folder but now I cannot access it because I get NullPointerException. I think the path is valid and everything seems okay but I get null every time. Here is the code:
ClassLoader classLoader = EmailSender.class.getClassLoader();
File file = new File(Objects.requireNonNull(classLoader.getResource("/parkingsystem-cf164-firebase-adminsdk-5jjuk-2be72bfcce.json")).getFile());
And here is the code structure:
code structure
If there is another method to add file to jar I am open to hear it, it is just what I found on the Internet but it does not work for me. Any help is appreciated!
Edit: So apparently it works when the / is removed but then I need to convert it to FileInputStream and there I get FileNotFoundExcpetion. The rest of the code:
FileInputStream serviceAccount = null;
try {
serviceAccount = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
FirebaseOptions options = null;
try {
options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.build();
} catch (IOException e) {
e.printStackTrace();
}

Can static content on spring-boot-web application be dynamic (refreshed)?

I am still searching around this subject, but I cannot find a simple solution, and I don't sure it doesn't exist.
Part 1
I have a service on my application that's generating an excel doc, by the dynamic DB data.
public static void
notiSubscribersToExcel(List<NotificationsSubscriber>
data) {
//generating the file dynamically from DB's data
String prefix = "./src/main/resources/static";
String directoryName = prefix + "/documents/";
String fileName = directoryName + "subscribers_list.xlsx";
File directory = new File(directoryName);
if (! directory.exists()){
directory.mkdir();
// If you require it to make the entire directory path including parents,
// use directory.mkdirs(); here instead.
}
try (OutputStream fileOut = new FileOutputStream(fileName)) {
wb.write(fileOut);
fileOut.close();
wb.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Part 2
I want to access it from the browser, so when I call it will get downloaded.
I know that for the static content, all I need to do is to call to the file, from the browser like that:
http://localhost:8080/documents/myfile.xlsx
After I would be able to do it, all I need is to create link to this url from my client app.
The problem -
Currently if I call to the file as above, it will download only the file which have been there in the compiling stage, but if I am generating a new files after the app is running the content won't be available.
It seems that the content is (as it's called) "static" and cannot be changed after startup.
So my question is
is there is a way to define a folder on the app structure that will be dynamic? I just want to access the new generated file.
BTW I found this answer and others which doing configuration methods, or web services, but I don't want all this. And I have tried some of them, but the result is the same.
FYI I don't bundle my client app with the server app, I run them from different hosts
The problem is to download the file with the dynamic content from a Spring app.
This can be solved with Spring BOOT. Here is the solution as shown in this illustration - when i click Download report, my app generates a dynamic Excel report and its downloaded to the browser:
From a JS, make a get request to a Spring Controller:
function DownloadReport(e){
//Post the values to the controller
window.location="../report" ;
}
Here is the Spring Controller GET Method with /report:
#RequestMapping(value = ["/report"], method = [RequestMethod.GET])
#ResponseBody
fun report(request: HttpServletRequest, response: HttpServletResponse) {
// Call exportExcel to generate an EXCEL doc with data using jxl.Workbook
val excelData = excel.exportExcel(myList)
try {
// Download the report.
val reportName = "ExcelReport.xls"
response.contentType = "application/vnd.ms-excel"
response.setHeader("Content-disposition", "attachment; filename=$reportName")
org.apache.commons.io.IOUtils.copy(excelData, response.outputStream)
response.flushBuffer()
} catch (e: Exception) {
e.printStackTrace()
}
}
This code is implemented in Kotlin - but you can implement it as easily in Java too.

Unable to clone a remote repository(On Premise) to a S3 Bucket using aws lambda function

I am trying to make a connection from my On Premise git repository(Remote Url), which i am able to connect on my local using credentials, to AWS code build or code pipeline.
To achieve this, I have got solution statement from AWS side--
Currently CodeBuild only supports BitBucket repositories hosted on bitbucket.org , BitBucket Server (on-premise BitBucket) is not supported at this time. There is an existing feature request regarding supporting BitBucket Server in CodeBuild to which I've added your interest. I am unable to share an ETA as to when this feature may be released however you can keep an eye on the following sites for updates regarding this feature:
-- AWS CodeBuild Release History: https://docs.aws.amazon.com/codebuild/latest/userguide/history.html
-- What's New: http://aws.amazon.com/new/
-- AWS Blogs: https://aws.amazon.com/blogs/aws/
There is a possible workaround by making a custom bridge between the Git repository and AWS, which can be done by creating a Lambda function that will clone the repository into a S3 bucket which can then be used as source in CodeBuild, you can read more about this here [1].
Hope that helps, if you have any questions please let me know, I'll be happy to help.
[1] https://aws.amazon.com/quickstart/architecture/git-to-s3-using-webhooks/
So i have implemented a lambda function like this:
public String handleRequest(S3Event event, Context context) {
final String REMOTE_URL = "https://username#stash.some.com/scm/something/dpautomation.git";
CredentialsProvider cp = new UsernamePasswordCredentialsProvider("username", "password");
try (Git result = Git.cloneRepository().setURI(REMOTE_URL).setDirectory(cretaeS3()).setCredentialsProvider(cp)
.call()) {
System.out.println("Having repository: " + result.getRepository().getDirectory());
} catch (InvalidRemoteException e) {
e.printStackTrace();
} catch (TransportException e) {
e.printStackTrace();
} catch (GitAPIException e) { // TODO Auto-generated
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return "sucess";
}
public File cretaeS3() throws IOException {
String bucketName = "selenium-lambda-java";
String destinationKey ="screenshots_on_failure/testdata1";
String filename="\"+temp";
AmazonS3 s3Client =
AmazonS3ClientBuilder.standard().withRegion("us-east-1").withCredentials(new
ProfileCredentialsProvider()).build();
File src = new File(filename);
s3Client.putObject(new PutObjectRequest(bucketName, destinationKey, src));
return src;
}
In the above code, as i have to copy Remote url repo files to directly to s3 bucket, so i used jgit.api.Git where when i tried to clone remote repo, i need to give some path in File format into setDirectory parameter while should ideally a bucket path so i tried the above code. i am getting below error:
{
"errorMessage": "Unable to calculate MD5 hash: \"+temp (No such file or directory)",
"errorType": "com.amazonaws.SdkClientException",
"stackTrace": [
"com.amazonaws.services.s3.AmazonS3Client.getInputStream(AmazonS3Client.java:1852)", "com.amazonaws.services.s3.AmazonS3Client.uploadObject(AmazonS3Client.java:1770)", "com.amazonaws.services.s3.AmazonS3Client.putObject(AmazonS3Client.java:1749)", "com.amazonaws.lambda.demo.LambdaFunctionHandler.cretaeS3(LambdaFunctionHandler.java:79)", "com.amazonaws.lambda.demo.LambdaFunctionHandler.handleRequest(LambdaFunctionHandler.java:52)", "com.amazonaws.lambda.demo.LambdaFunctionHandler.handleRequest(LambdaFunctionHandler.java:1)" ], "cause": { "errorMessage": "\"+temp (No such file or directory)",
"errorType": "java.io.FileNotFoundException",
"stackTrace": [
"java.io.FileInputStream.open0(Native Method)",
"java.io.FileInputStream.open(FileInputStream.java:195)",
"java.io.FileInputStream.<init>(FileInputStream.java:138)",
"com.amazonaws.util.Md5Utils.computeMD5Hash(Md5Utils.java:97)",
"com.amazonaws.util.Md5Utils.md5AsBase64(Md5Utils.java:104)",
"com.amazonaws.services.s3.AmazonS3Client.getInputStream(AmazonS3Client.java:1848)",
"com.amazonaws.services.s3.AmazonS3Client.uploadObject(AmazonS3Client.java:1770)",
"com.amazonaws.services.s3.AmazonS3Client.putObject(AmazonS3Client.java:1749)",
"com.amazonaws.lambda.demo.LambdaFunctionHandler.cretaeS3(LambdaFunctionHandler.java:79)",
"com.amazonaws.lambda.demo.LambdaFunctionHandler.handleRequest(LambdaFunctionHandler.java:52)",
"com.amazonaws.lambda.demo.LambdaFunctionHandler.handleRequest(LambdaFunctionHandler.java:1)"
]
}
}
I am stuck from last 5 days please some body help me on this.

GWT Java how to convert List<File> to something the client side can use?

EDITED
This is probably a stupid question but I can't figure it out. I am using Java with GWT in Eclipse to create a RPC application to get google drive metadata. All is working (I am getting back the metadata on the server side) but I can't figure out how to pass this data over to the client side so that I can display it.
I am getting a list of metadata for google drive docs as follows:
public List<File> getFromRemoteServer()
throws HowToListingException {
List<File> lista = null;
try {
lista = retrieveAllFiles(getDriveService("email#xxxx.org"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GeneralSecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return lista;
}
My question is, how do I change the List type to something that the client side can use? i.e what do I put here (fill in the blank)? And how would I convert lista to that type?
asyncSvc.getFromRemoteServer( {
new AsyncCallback<____________>() {
}
A bit more hopefully clarifying information:
I know to make this work I have to serialize the File object. I'm just not sure if I can or where to put this.
http://www.gwtproject.org/doc/latest/tutorial/RPC.html#serialize
In the server side implementation, I am using this File:
import com.google.api.services.drive.model.File;
Which I need to use to have this code work properly:
public static Drive getDriveService(String userEmail) throws GeneralSecurityException,
IOException, URISyntaxException {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(Arrays.asList(DriveScopes.DRIVE))
.setServiceAccountUser(userEmail)
.setServiceAccountPrivateKeyFromP12File(
new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))
.build();
Drive service = new Drive.Builder(httpTransport, jsonFactory, null)
.setHttpRequestInitializer(credential).build();
return service;
}
private static List<File> retrieveAllFiles(Drive service) throws IOException {
List<File> result = new ArrayList<File>();
Files.List request = null;
try {
request = service.files().list();
FileList files = request.setQ("'"+"0B9lpwZZfxxxxxxxxVeEJFR3M"+"' in parents and trashed=false").execute();
result.addAll(files.getItems());
request.setPageToken(files.getNextPageToken());
}
catch (IOException e)
{
System.out.println("An error occurred: " + e);
request.setPageToken(null);
}
for(File f:result)
{
System.out.println(f.getTitle());
System.out.println(f.getOwners());
System.out.println(f.getModifiedDate());
}
return result;
}
The problem comes when I try to use
import com.google.api.services.drive.model.File;
on the client side in the synchronous and asynchronous interfaces and the client code (entry point). I get the error message about "did you forget to inherit a required module - no code found for this import." I am assuming that means I can't use this on the client side. I've tried to import java.io.File instead but then I get messages that I can't convert between the two types.
I feel like I am close, I just need a push in the right direction. Any help appreciated.
You can only pass classes that implement Serializable. I don't know what File class is, but if it's not serializable, you cannot pass it using RPC.
If File implements Serializable, you can pass ArrayList<File> to AsyncCallback. Note that with GWT it is always better to use a specific implementation (ArrayList instead of List) in order to reduce the compiled code.
Design your own class that contains the info you need to display. And maybe a unique path. Send that class, which should be Serializable to the client.

PayPal REST API java sdk - custom config file

Good afternoon all!
I use PayPal REST API java sdk and I want to have different configurations for different environments of my application. Here is how I'm trying to do so:
private static boolean IS_PRODUCTION = false;
private static String PAYPAL_ACCESS_TOKEN;
private static void initPayPal() {
InputStream is = null;
try {
is = ApplicationConfig.class.getResourceAsStream(
IS_PRODUCTION? "/my_paypal_sdk_config.properties" : "/my_paypal_sdk_config_test.properties");
PayPalResource.initConfig(is);
String clientID = ConfigManager.getInstance().getConfigurationMap().get("clientID");
String clientSecret = ConfigManager.getInstance().getConfigurationMap().get("clientSecret");
PAYPAL_ACCESS_TOKEN = new OAuthTokenCredential(clientID, clientSecret).getAccessToken();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
IOUtils.closeQuietly(is);
}
}
and while trying to get the clientID I have
java.io.IOException: Resource 'sdk_config.properties' could not be found
Strange behavior - I thought I've just configured the sdk to use my own properties file.
Please advice how could I set up those settings properly!
So here is the solution I found:
Create an empty sdk_config.properties file in default location
Load your own properties:
private static void initPayPal() {
InputStream is = null;
try {
is = ApplicationConfig.class.getResourceAsStream(
IS_PRODUCTION ? "/my_paypal_sdk_config.properties" : "/my_paypal_sdk_config_test.properties");
Properties props = new Properties();
props.load(is);
PayPalResource.initConfig(props);
ConfigManager.getInstance().load(props);
String clientID = ConfigManager.getInstance().getConfigurationMap().get("clientID");
String clientSecret = ConfigManager.getInstance().getConfigurationMap().get("clientSecret");
PAYPAL_ACCESS_TOKEN = new OAuthTokenCredential(clientID, clientSecret).getAccessToken();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
IOUtils.closeQuietly(is);
}
}
We have made some good improvements to the PayPal Java SDK on integration steps. We are removing the need for sdk_config.properties file as they do not work as well, specially for multi-configuration settings.
Now, all you do is create an APIContext instance with clientId, clientSecret, and mode. You pass that context object for any API operation from there on.
Here is how the code would look like for different configurations:
APIContext defaultContext = new APIContext(clientId1, clientSecret1, "sandbox");
APIContext sandboxContext = new APIContext(clientId2, clientSecret2, "sandbox");
APIContext someOtherContext = new APIContext(clientId3, clientSecret3, "live");
APIContext liveContext = new APIContext(clientId, clientSecret, "live");
// Now pass any of the above context in these calls, and it would use those configurations.
Payment payment = new Payment();
// Fill in all the details.
payment.create(defaultContext);
// Replace that defaultContext with any of those other contexts.
Here is the wiki page explaining that: https://github.com/paypal/PayPal-Java-SDK/wiki/Making-First-Call
I had the same error with SDK 0.11 version. I use my own properties file, but code still looked for "sdk_config.properties". I put it into root in my CLASSPATH, but still got the same error. Then I made obvious and horrible solution: put empty "sdk_config.properties" into "rest-api-sdk-0.11.0.jar" library. This street magic solved my problem.

Categories