I am trying to upload file in website using javacode, writing below java code, need help for uploading file - http

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class LoginExample {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost("https://www.example.com/login");
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("username", "user"));
urlParameters.add(new BasicNameValuePair("password", "pass"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuilder result = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result);
HttpGet get = new HttpGet("https://www.example.com/home");
response = client.execute(get);
rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
result = new StringBuilder();
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result);
}
}
This is the code tried
How to upload file in weppage using java, need code sample which can be added to above code so that upload can be done thru java
Also any other alternative solution is there for handling thru java
I am trying to eliminate going thru UI steps and want to handle thru java code

Related

How to include x5t and x5c in JWK output?

I am trying to call some APIs published by the IRS. They require me to create a JWK and send them the public key.
I was able to generate an RSA JWK key using this code:
package com.propfinancing.jwk;
import com.nimbusds.jose.jwk.KeyUse;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.gen.RSAKeyGenerator;
import java.util.UUID;
public class GenerateKey {
public static void main(String[] args)
throws Exception {
RSAKey jwk = new RSAKeyGenerator(2048)
.keyUse(KeyUse.SIGNATURE)
.keyID(UUID.randomUUID().toString())
.generate();
System.out.println(jwk);
System.out.println(jwk.toPublicJWK());
}
}
Here is a sample output:
{"p":"0nDimdByKTsWOOHWHHkOpdNgIgG5vVmd_Bdc1wQG5lCz1Gh_Iu4z0KaBeAlsoqkak3B2Hv--62nBBIdsqWLOZ4iwed_uIkUItZQNADltG_gEfNAVpY0ESN43ZDykBVOw28FVEiN8ewxZ5rmqKidOgEgMEMbHJ45gqfHm9XD2GLM","kty":"RSA","q":"-TFekmWY2i1_U9K3bDBzJL-cFZfB5JX1qMUiSQhoB_TNymY73UlwZsMap732Jb4v5ZDxIZIjBcHAhRwsEZEEkWyF6mxnUifdbAK4OxaKlw7q1EvUUUzMGqegek-d4ZLwxBD54UgdvTbWxUDlgLlXispfJdr0RwEtOKQzZ53vFU8","d":"DvhjUHjNTZfEeFBAajfZvkznePJmYvXn6cPaclNp3OmMuqYgDSWSciVrP5fyieRX6TgYbaClzoP_UUsXqaTdd1WVySyZEEDh4JGja6n0Y7KwD2DAgEgLhSHwznCp-YV4vtfrLOBpFAwem8S2FaC8vujFzvskiJ3yWfidp-qZGJfGo2wdh2Ry8vkgBRJdEjyVvhKYVR2_UeS3otXQwaLgHHy-Cl8ukiWtXNT5Z5I7CvQOSEy3QpzVUWEnPod6g6j0sfhLMfAkj1i7RfDaJB-8SzlwR5DEhvRrgWJxJw3LWkOcHBAlfepDV63eilM5msDkhlcu_gmzmX-WksyvClgSiw","e":"AQAB","use":"sig","kid":"1ca36b31-c202-4242-8e36-80bb06d2219a","qi":"VvLjYgSBL35kShVGEC2j8BiSAUsyI0QL7aZDdYY6gA-Ba2zSsQQJHg6OISr6rHHJKHopCs1i2PPRd38c7apO8gLwjbk8KsyhYRl864BKfdHfcQo4r3XOH2tDZmsNuc3fpVARKACcQgwtrhGMcIr0M9keghv9wuui7ZQnFPuu0Zk","dp":"n9kZdwbLwJ_eOGTrE4Os6a8OxaYT5U2OYK-KWNT5PLcucfjSIcFYYHQpwfk-qKvUwQva3Z8b8YvKDtujYWLpL-G3U0wSgbt4axzDZ1k3lNgm6HvTBYaBK6yH3L7nRBiXLcXEDdwgsQLnwwdix1RGH9EaQSAMpPJUYKKb8fHVLVs","dq":"MtdCv0WhMOpVbwmvyI_9_gJl2vXyZiu-SiemPhZL-0uT7PZ8wkIof57QwmZ8YOjzpreyqrHBGXyVRdMgnpjiwLTOgayKS_W8NDw90DhiID235YZvFANCJTIMCMhTouEy5B2-jZsEDkWw_d-ms2OdG8D8NqH8crwnuMWvgzVywPs","n":"zNhhwMZJ1f3rNlE62Nyj_lL_ANJYNlIzImH8Uk5QkSO2Wy2oP8yqfcLfvlHyQTP4R5-p7ibT_hC4lEr9BPjseX7Dghd6NMCkRtlhsk2qg7SfSQecNczWZgH5cisMtE_DFWONVpgQRfoaIZV3PSoPAClNTXk52Ni9NaK1mVXsBRP0RD_Hx0r8G8De5UQ8BRNcqYF9hhWzEv1RFLJqZTHMAKeSTmiGJ5Dyur0Wv4kxY73iZtM5ld6f21Q-w9bJ0ar1DVFkmsNtt4Ed20zkj7NOKhBnGqI2VbxQ6WQ7T4Ik6ATf6ujBxLDepme153eH63-1IutZ-Waj8Qfjn2Pt4hVOPQ"}
{"kty":"RSA","e":"AQAB","use":"sig","kid":"1ca36b31-c202-4242-8e36-80bb06d2219a","n":"zNhhwMZJ1f3rNlE62Nyj_lL_ANJYNlIzImH8Uk5QkSO2Wy2oP8yqfcLfvlHyQTP4R5-p7ibT_hC4lEr9BPjseX7Dghd6NMCkRtlhsk2qg7SfSQecNczWZgH5cisMtE_DFWONVpgQRfoaIZV3PSoPAClNTXk52Ni9NaK1mVXsBRP0RD_Hx0r8G8De5UQ8BRNcqYF9hhWzEv1RFLJqZTHMAKeSTmiGJ5Dyur0Wv4kxY73iZtM5ld6f21Q-w9bJ0ar1DVFkmsNtt4Ed20zkj7NOKhBnGqI2VbxQ6WQ7T4Ik6ATf6ujBxLDepme153eH63-1IutZ-Waj8Qfjn2Pt4hVOPQ"}
Everything looks good on the output, but the IRS requires the JWK to include x5t and x5c parameters in the output.
How do I add those?
Thanks,
Neil
I was able to figure out how to generate the self-signed certificate using nimbus-jose-jwt.
Here is my sample code:
package jwk;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.KeyUse;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.gen.RSAKeyGenerator;
import com.nimbusds.jose.util.Base64;
import com.nimbusds.oauth2.sdk.id.Issuer;
import com.nimbusds.oauth2.sdk.util.X509CertificateUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.UUID;
public class JWKTest {
public static void main(String[] args)
throws Exception {
// Create a JWK with a random ID
RSAKey rsaJWK = new RSAKeyGenerator(2048)
.keyID(UUID.randomUUID().toString())
.keyUse(KeyUse.SIGNATURE)
.generate();
// Create the cert start and expiration dates
Calendar now = new GregorianCalendar();
now.add(Calendar.DAY_OF_YEAR, -1);
Date certStartDate = now.getTime();
now.add(Calendar.DAY_OF_YEAR, 1);
now.add(Calendar.YEAR, 10);
Date certExpirationDate = now.getTime();
// Generate a self signed certificate
X509Certificate cert = X509CertificateUtils.generateSelfSigned(
new Issuer("My issuer"),
certStartDate,
certExpirationDate,
rsaJWK.toRSAPublicKey(),
rsaJWK.toRSAPrivateKey());
// Create a key store to hold the certificate
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null);
keyStore.setCertificateEntry("My Cert", cert);
FileOutputStream outStream = new FileOutputStream(new File("C://Tmp//key.store"));
keyStore.store(outStream, null);
outStream.close();
// Create private key from the certificate
RSAKey privateJWK = new RSAKey.Builder(rsaJWK)
.x509CertChain(Collections.singletonList(Base64.encode(cert.getEncoded())))
.x509CertThumbprint(rsaJWK.computeThumbprint())
.build();
PrintWriter writer = new PrintWriter(new FileWriter("C://Tmp//private.jwk"));
writer.println(privateJWK);
writer.close();
// Create a public key
JWKSet publicJWK = new JWKSet(rsaJWK);
writer = new PrintWriter(new FileWriter("C://Tmp//public.jwk"));
writer.println(publicJWK);
writer.close();
}
}

How can i convert a JAVAFX Webvie to Parsing JSOUP?

I want to convert a Webseite loaded by javaFX to JSOUP.
p
ublic class database {
public static ArrayList<String> database = new ArrayList<String>();
public static ArrayList<Integer> laenge = new ArrayList<Integer>();
public static ArrayList<Integer> tiefe = new ArrayList<Integer>();
public static void main(String[] args) throws IOException, JSONException {
// TODO Auto-generated method stub
WebView browser = new WebView();
WebEngine webEngine = browser.getEngine();
String url = "http://www.google.com";
webEngine.load(url);
//get w3c document from webEngine
org.w3c.dom.Document w3cDocument = webEngine.getDocument();
// use jsoup helper methods to convert it to string
String htm = new org.jsoup.helper.W3CDom().asString(webEngine.getDocument());
// create jsoup document by parsing html
Document doc = Jsoup.parse(url, htm);
//Document doc = Jsoup.connect("http://ttp-schreiber.de/Mathematik/index2.html").get();
Element title = doc.body();
/*WebView browser = new WebView();
WebEngine webEngine = browser.getEngine();
webEngine.load("http://ttp-schreiber.de/Mathematik/index2.html");
*/
Elements html = doc.select("html");
Controller(html);
// System.out.println("+--+"+deeper(next(html,html.last()))[0][0]);
databasesafe();
}
I get these Error Message:
Exception in thread "main" java.lang.ExceptionInInitializerError
How is the misttage?
ETC I have the example from here:
How to parse html from javafx webview and transfer this data to Jsoup Document?
In these line ist .get wrong: String html = new org.jsoup.helper.W3CDom().asString(webEngine.get);
This duplicate is probably your best bet. After a page is loaded in WebView, use a Transformer to get its HTML. Then use that HTML string in Jsoup. I am not sure if you will get your expected outcome.
import java.io.File;
import java.nio.file.Files;
import javafx.application.Application;
import javafx.concurrent.Worker;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.jsoup.Jsoup;
import org.w3c.dom.Document;
//import org.jsoup.nodes.Document;
public class App extends Application
{
org.jsoup.nodes.Document jsoupDocument;
#Override
public void start(Stage stage)
{
String url = "http://www.google.com";
WebView webview = new WebView();
final WebEngine webengine = webview.getEngine();
webengine.getLoadWorker().stateProperty().addListener((ov, oldState, newState) ->
{
if (newState == Worker.State.SUCCEEDED) {
Document doc = webengine.getDocument();
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
File file = new File("results.txt");
file.createNewFile();
StreamResult results = new StreamResult(file);
transformer.transform(new DOMSource(doc), results);
String fileContent = Files.readString(file.toPath());
jsoupDocument = Jsoup.parse(fileContent);
System.out.println(jsoupDocument.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
webengine.load("http://stackoverflow.com");
StackPane root = new StackPane(webview);
stage.setTitle("Hello Drag And Drop");
Scene scene = new Scene(root, 400, 200);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args)
{
Application.launch(args);
}
}

Jsoup to parse multiple websites for links published today

I am currently using jsoup (below) to output a .csv of links which include a string date format in the url from just one website.
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import java.io.FileOutputStream;
import java.io.PrintStream;
import org.jsoup.nodes.Element;
public class readAllLinks {
public static Set<String> uniqueURL = new HashSet<String>();
public static String my_site;
public static String published = ("20180731");
public static void main(String[] args) {
readAllLinks obj = new readAllLinks();
my_site = ("news24.com/SouthAfrica/News");
obj.get_links("https://www.news24.com/SouthAfrica/News/");
}
private void get_links(String url) {
try {
Document doc = Jsoup.connect(url).get();
Elements links = doc.select("a");
FileOutputStream fout=new FileOutputStream("links.csv");
PrintStream csv=new PrintStream(fout);
links.stream().map((link) -> link.attr("abs:href")).forEachOrdered((this_url) -> {
boolean add = uniqueURL.add(this_url);
if (add && this_url.contains(my_site) && this_url.contains(published)) {
System.out.println(this_url);
get_links(this_url);
}
if (this_url.contains(published))
csv.println(this_url);
} );
} catch (IOException ex) {
}
}
}
Instead I would like to make a csv of links published today (i.e using today's date) from multiple websites.
How do you specify the .select for the newly published links to get the date contained in a span?
And how do you parse multiple websites from a list?
Many thanks for your help.
This will select all links that contains value of variable 'published'.
Elements links = doc.select("a[href*="+published+"]");

Alert in JAVA FX

I want to display an alert when a file already exists when trying to create the file with same name . I have not completed the code fully. I want to retrieve the button value Yes/No from the UI .
Code:
This is how the controller is coded.
package application;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.TreeMap;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
public class WarningController implements Initializable {
#FXML
public Button yes;
#FXML
public Button no;
public static String type;
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
// TODO Auto-generated method stub
}
public String confirmSelection(ActionEvent event)throws IOException{
Button button = (Button) event.getSource();
type = button.getText();
if(type.equals("Yes")){
Stage stage = (Stage) yes.getScene().getWindow();
stage.close();
//System.out.println("Yes");
return type;
}
else{
//System.out.println("No");
Stage stage1 = (Stage) no.getScene().getWindow();
stage1.close();
return type;
}
}
/********************************************************************************/
public void writesheet(String[][] result,String ComboValue,String[] heading) throws IOException{
//Create blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
//Create a blank sheet
XSSFSheet spreadsheet = workbook.createSheet( " Employee Info ");
//Create row object
XSSFRow row;
String[][] towrite=result;
int rows=towrite.length;
//int cols=towrite[0].length;
// System.out.println(rows +" "+ cols);
Map < String, Object[] > empinfo = new TreeMap < String, Object[] >();
empinfo.put("0", heading);
for(int i=1;i<=rows;i++){
empinfo.put( Integer.toString(i),towrite[i-1]);
}
//Iterate over data and write to sheet
Set < String > keyid = empinfo.keySet();
int rowid = 0;
for (String key : keyid)
{
row = spreadsheet.createRow(rowid++);
Object [] objectArr = empinfo.get(key);
int cellid = 0;
for (Object obj : objectArr)
{
Cell cell = row.createCell(cellid++);
//cell.setCellValue((String)obj);
cell.setCellValue(obj.toString());
}
}
//Write the workbook in file system
File f=new File(("C:\\"+ComboValue+".xlsx"));
if(f.exists()){
Stage primaryStage=new Stage();
Parent root=FXMLLoader.load(getClass().getResource("/application/Warning.fxml"));
Scene scene = new Scene(root,350,150);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
System.out.println(type);
}
FileOutputStream out = new FileOutputStream(f);
workbook.write(out);
out.close();
System.out.println(ComboValue+" "+"Excel document written successfully" );
workbook.close();
}
}
I want to use button value(stored in String type) in writesheet function. Now it is returning NULL.
Please suggest if there is any other way to show warning.I am using two fxml files and this is the second excel file.
[1]: http://i.stack.imgur.com/ZK6UC.jpg
Simply use the Alert class. It provides functionality for most yes/no dialogs that you ever need.
Alert alert = new Alert(AlertType.WARNING,
"File already exists. Do you want to override?",
ButtonType.YES, ButtonType.NO);
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.YES){
// ... user chose YES
} else {
// ... user chose NO or closed the dialog
}
Also here is a good tutorial.
I usually make a method, and call it if certain conditions are not met.
Ex:
if(condition)
alert();
public void alert(){ //alert box
Alert alert = new Alert(AlertType.WARNING,"", ButtonType.YES, ButtonType.NO); //new alert object
alert.setTitle("Warning!"); //warning box title
alert.setHeaderText("WARNING!!!");// Header
alert.setContentText("File already exists. Overwrite?"); //Discription of warning
alert.getDialogPane().setPrefSize(200, 100); //sets size of alert box
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.YES){
// ... user chose YES
} else {
// ... user chose NO or closed the dialog
}
}
I grabbed some code from Jhonny007, credit to him.

generate screenshot and send it to server (not using FileReference.upload)

Do you have any ideas?
Maybe this can help too, this example creates a BitmapData instance, and then sends that as a ByteArray to the server, (in my case, I was using PHP) ... you'll need to write the server side code, but there's nothing quite special here
package
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.ProgressEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestHeader;
import flash.net.URLRequestMethod;
import flash.net.URLVariables;
import flash.utils.ByteArray;
import mx.graphics.codec.PNGEncoder;
import mx.utils.Base64Encoder;
public class DataUpload extends Sprite
{
private var _loader:URLLoader;
public function DataUpload()
{
// create a bitmap data
var bd:BitmapData = createDummyImage();
var png:PNGEncoder = new PNGEncoder();
var ba:ByteArray = png.encode(bd);
var b64:Base64Encoder = new Base64Encoder();
b64.encodeBytes(ba);
// initialize loader
_loader = new URLLoader();
_loader.addEventListener(Event.COMPLETE, loadCompleteHandler);
_loader.addEventListener(ProgressEvent.PROGRESS, loadProgressHandler);
var request:URLRequest = new URLRequest("http://localhost/YOUR_PHP_SCRIPT_URI");
request.method = URLRequestMethod.POST;
var variables:URLVariables = new URLVariables();
variables.fileData = b64;
variables.fileName = "foobar";
request.data = variables;
_loader.load(request);
}
protected function loadCompleteHandler(event:Event):void {
trace("complete");
}
protected function loadProgressHandler(event:ProgressEvent):void {
trace("progress : ", event.bytesLoaded / event.bytesTotal);
}
private function createDummyImage():BitmapData {
var bd:BitmapData = new BitmapData(300, 300, true, 0x00ffffff);
var shape:Shape = new Shape();
shape.graphics.beginFill(0xff0000);
shape.graphics.drawCircle(10, 10, 10);
shape.graphics.endFill();
bd.draw(shape);
return bd;
}
}
}
Step 1: Use ImageSnapshot to capture the screenshot (I assume we're just talking about the Flash screen, not the OS). This can handle the image encoding for you, or you can capture BitmapData and reencode yourself.
Step 2(a): Use a MultipartLoader to post the generated bytes. Flash security in Flash Player 10 will require the HTTP post to occur on user interaction.
or
Step 2(b): Use a regular URLLoader/URLRequest to post the generated bytes (Base64 encoded, say).

Resources