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":"VvLjYgS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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();
}
}
Related
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
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);
}
}
I am using a text file to load information to a javafx gui. Is there a way I can use a text value there to select a radio button in a toggle group.
I think '''toggleGroup.selectedValue(toggle value)''' is the function I need, but it does not take a string. Is there a way to convert the string to a toggle value, indirectly?
The following does not work because '''selectToggle()''' takes a toggle not a text value and neither an implicit nor explicit '''(toggle)''' cast seem to work.
tgrpSex.selectToggle(read.nextLine());
This should be reproducible:
package programmingassignment1;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.*;
//import javafx.scene.layout.StackPane;
//import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import java.io.*; //input/output
import java.util.Scanner;
//import java.util.*; //scanner, user input
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
//import javafx.scene.shape.Rectangle;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
public class Address extends Application {
RadioButton rbMale = new RadioButton("Male");
RadioButton rbFemale = new RadioButton("Female");
ToggleGroup tgrpSex = new ToggleGroup();
GridPane rootPane = new GridPane();
#Override
public void start(Stage primaryStage){
//Setting an action for the Open Contact button
Button btOpenContact = new Button("Open Contact");
File file = new File("AddressBook.txt");
btOpenContact.setOnAction(event -> {
try {
openContact(file);
} catch (Exception e) {
e.printStackTrace();
}
});
//Setting an action for the Save button
Button btSave = new Button("Save");
btSave.setOnAction(
new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent e){
try{saveContact(file);}
catch(Exception f){f.getMessage();}
}});
//associate radio buttons with a toggle group
rbMale.setToggleGroup(tgrpSex);
rbFemale.setToggleGroup(tgrpSex);
rbMale.setOnAction(e -> {
if(rbMale.isSelected()){int maleContact = 1;}
});
rbFemale.setOnAction(e -> {
if(rbFemale.isSelected()){int maleContact = 0;}
});
rootPane.add(new Label("Sex"), 3, 1);
rootPane.add(rbFemale, 3, 2);
rootPane.add(rbMale, 3, 3);
rootPane.add(btOpenContact, 1, 13);
Scene scene = new Scene(rootPane, 1000, 500);
primaryStage.setTitle("Address Book");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
public void saveContact(File file) throws FileNotFoundException, Exception{ //declaration
//this code might cause a FileNotFoundException
//if it does it creates an exception object of the above type
try{
//PrintWriter output = new PrintWriter (file);
PrintStream output = new PrintStream(file);
output.println(tfContactFirst.getText());
output.println(tfContactLast.getText());
output.println(tfSpouseFirst.getText());
output.println(tfSpouseLast.getText());
output.println(cboWorkHome.getValue());
output.println(tfStreet.getText());
output.println(tfCity.getText());
output.println(tfState.getText());
output.println(tfZip.getText());
output.close();
}
//what do do with exception
//here the catch clause with create another exception
//that is passed the result of the getMessage() method from the original exception
catch(FileNotFoundException e){
throw new Exception(e.getMessage());
}
}
//read same text file you save too
public void openContact(File file) throws FileNotFoundException, Exception{
try{
Scanner read = new Scanner(file);
while(read.hasNextLine()){
//how do I save the imageFileName
tfContactFirst.setText(read.nextLine());
tfContactLast.setText(read.nextLine());
tgrpSex.selectToggle(read.nextLine());
tfSpouseFirst.setText(read.nextLine());
tfSpouseLast.setText(read.nextLine());
//tfSpouseGender.setText(read.nextLine());
cboWorkHome.setValue(read.nextLine());
tfStreet.setText(read.nextLine());
tfCity.setText(read.nextLine());
tfState.setText(read.nextLine());
tfZip.setText(read.nextLine());
//taNotes.setText(read.nextLine());
}
}
catch(FileNotFoundException e){
throw new Exception(e.getMessage());
}
}
}
No results <- syntax error
Sorry. I got the answer. I didn't know what a toggle type object was. I looked up an examples of selectToggle() and learned you can pass a radio button object to it. So I put that in an if then statement. if(read.nextLine().equals("Male")){tgrpSex.selectToggle(rbMale);}
else{tgrpSex.selectToggle(rbFemale);}
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+"]");
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).