Is there an equivalent Builder object for Java?
This code is meant for C#. Does anyone know where the source code is so I can build a Java version of this?
var configBuilder = new ConfigurationBuilder()
.SetBasePath(context.FunctionAppDirectory)
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
.AddJsonFile("secret.settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
Would be easier if there was such a think so I don't need to do this:
protected String readPropertyFromLocalConfig(String propertyName) {
try (FileInputStream fis = new FileInputStream("local.settings.json)) {
String data = IOUtils.toString(fis, ENCODING);
try {
JSONObject jsonObject = new JSONObject(data);
return (String)((JSONObject)jsonObject.get("Values")).get(propertyName);
} catch (JSONException err){
log.error("Error reading file", err.toString());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return StringUtil.EMPTY_STRING;
}
Related
Here follows is my code,how can i deal with it
public ConnectResponse runCommand(UserInfo userInfo, String command, long timeout) {
SshClient sshClient = SshClient.setUpDefaultClient();
sshClient.start();
ChannelExec execChannel = null;
try (ClientSession session = sshClient
.connect(userInfo.getUsername(), userInfo.getTargetIp(), 22)
.verify(CLIENT_VERIFY_TIMEOUT)
.getClientSession();) {
session.addPasswordIdentity(userInfo.getAuthentication());
session.auth().verify(SESSION_VERIFY_TIMEOUT);
execChannel = session.createExecChannel(command);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream err = new ByteArrayOutputStream();
execChannel.setOut(out);
execChannel.setErr(err);
execChannel.open();
Set<ClientChannelEvent> events = execChannel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(timeout));
session.close(false);
if (events.contains(ClientChannelEvent.TIMEOUT)) {
throw new BusinessException(500, String.format("执行命令 {%s} 超时了!", command));
}
return new ConnectResponse(out.toString(), err.toString(), execChannel.getExitStatus());
} catch (Exception e) {
throw new BusinessException(e.getCause(), 500, String.format("执行命令 {%s} 出现了一行了!", command));
} finally {
if (!Objects.isNull(execChannel)) {
try {
execChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I just started learning Vaadin 8 and my first example is Upload button. I was stuck with an issue where I could not solve the problem for many hours and hours.
Here it is,
I am returning PipedOutputStream in the receiveUpload method,
Here is the code for receiveUpload method,
public OutputStream receiveUpload(String filename, String mimeType) {
this.fileName = filename;
this.mimeType = mimeType;
try {
pipedOutputStream = new PipedOutputStream();
pipedInputStream = new PipedInputStream(pipedOutputStream);
if (filename == null || filename.trim().length() == 0) {
upload.interruptUpload();
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
return pipedOutputStream;
}
In the uploadSucceeded method, I need to take the pipedinputstream and send it another method to load the stream into the database
public void uploadSucceeded(SucceededEvent event) {
try {
fileUploadOperation.upload(pipedInputStream); --> I need to push all the stream data in one go into a method to generate a file at the business layer
} catch (Exception e) {
e.printStackTrace();
}
}
When I was running the application, it hangs out for a long time and I could not figure out where it is. Later I could notice that both piped input and piped output streams should be created in separate threads or at least one of them in a separate thread but don't know how to handle it.
Any help
I am pasting the complete class for more information,
public class WebCommunityView implements Receiver, FailedListener, SucceededListener, StartedListener, FinishedListener {
private PipedOutputStream pipedOutputStream = null;
private PipedInputStream pipedInputStream = null;
private Upload upload = null;
private String fileName = null, mimeType = null;
private Grid<FileListProperties> fileListGrid = null;
public final static WebCommunityView newInstance(WebContentScreen screen) {
vw.initBody();
return vw;
}
protected void initBody() {
VerticalLayout verticalLayout = new VerticalLayout();
fileListGrid = new Grid<FileListProperties>();
fileListGrid.addColumn(FileListProperties::getCreatedDate).setCaption("Date");
fileListGrid.addColumn(FileListProperties::getFileName).setCaption("File Name");
fileListGrid.addColumn(FileListProperties::getUserName).setCaption("User Name");
fileListGrid.addComponentColumn(this::buildDownloadButton).setCaption("Download");
fileListGrid.setItems(loadGridWithFileInfo());
upload = new Upload("", this);
upload.setImmediateMode(false);
upload.addFailedListener((Upload.FailedListener) this);
upload.addSucceededListener((Upload.SucceededListener) this);
upload.addStartedListener((Upload.StartedListener) this);
upload.addFinishedListener((Upload.FinishedListener) this);
Label fileUploadLabel = new Label("Label"));
verticalLayout.addComponent(currentListLabel);
verticalLayout.addComponent(fileListGrid);
verticalLayout.addComponent(fileUploadLabel);
verticalLayout.addComponent(upload);
mainbody.addComponent(verticalLayout);
}
#Override
public void uploadSucceeded(SucceededEvent event) {
try {
//Model Layer
fileUploadOperation.upload(pipedInputStream);
fileUploadOperation.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void uploadFailed(FailedEvent event) {
if (event.getFilename() == null) {
Notification.show("Upload failed", Notification.Type.HUMANIZED_MESSAGE);
}
try {
//Model Layer
fileUploadOperation.abort();
} catch (Exception e) {
e.printStackTrace();
}
}
public OutputStream receiveUpload(String filename, String mimeType) {
this.fileName = filename;
this.mimeType = mimeType;
try {
pipedOutputStream = new PipedOutputStream();
new Thread() {
public void run() {
try {
System.out.println("pipedInputStream Thread started");
pipedInputStream = new PipedInputStream(pipedOutputStream);
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
if (filename == null || filename.trim().length() == 0) {
screen.displayMessage("Please select a file to upload !", WebContentScreen.MESSAGE_TYPE_WARNING);
upload.interruptUpload();
} else {
Properties properties = new Properties();
properties.setProperty("NAME", fileName);
properties.setProperty("MIME_TYPE", mimeType);
//Model Layer
fileUploadOperation.initialize(properties);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("pipedOutputStream:"+pipedOutputStream);
return pipedOutputStream;
}
private List<FileListProperties> loadGridWithFileInfo() {
List<FileListProperties> list = null;
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
try {
list = new ArrayList<FileListProperties>(1);
Collection<FileInfo> fileInfoList = fileCommandQuery.lstFilesForDownload();
for (Iterator iterator = fileInfoList.iterator(); iterator.hasNext();) {
FileInfo fileInfo = (FileInfo) iterator.next();
Properties properties = fileInfo.getProperties();
Collection<String> mandatoryParameters = fileInfo.getMandatoryProperties();
FileListProperties fileListProperties = new FileListProperties();
for (Iterator iterator2 = mandatoryParameters.iterator(); iterator2.hasNext();) {
String key = (String) iterator2.next();
String value = properties.getProperty(key);
if (key != null && key.equalsIgnoreCase("NAME")) {
fileListProperties.setFileName(value);
} else if (key != null && key.equalsIgnoreCase("USER_NAME")) {
fileListProperties.setUserName(value);
} else if (key != null && key.equalsIgnoreCase("CREATED_DATE")) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(1550566760000L);
fileListProperties.setCreatedDate(dateFormat.format(calendar.getTime()));
}
}
if (fileListProperties != null) {
list.add(fileListProperties);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
dateFormat = null;
}
return list;
}
private Button buildDownloadButton(FileListProperties fileListProperties) {
Button button = new Button("...");
button.addClickListener(e -> downloadFile(fileListProperties));
return button;
}
private void downloadFile(FileListProperties fileListProperties) {
}
}
The problem in your example is that you need to do the actual file handling in a separate thread. The Viritin add-on contains a component called UploadFileHandler that simplifies this kind of usage a lot. It will provide you InputStream to consume. The integration test for the component contains this kind of usage example.
Also, my recent blog entry about the subject might help.
I just want to know that how i can extract main text and plain text from html using Tika?
maybe one possible solution is to use BoilerPipeContentHandler but do you have some sample/demo codes to show it?
thanks very much in advance
The BodyContentHandler class doesn't use the Boilerpipe code, so you'll have to explicitly use the BoilerPipeContentHandler. The following code worked for me:
public String[] tika_autoParser() {
String[] result = new String[3];
try {
InputStream input = new FileInputStream(new File("test.html"));
ContentHandler textHandler = new BodyContentHandler();
Metadata metadata = new Metadata();
AutoDetectParser parser = new AutoDetectParser();
ParseContext context = new ParseContext();
parser.parse(input, new BoilerpipeContentHandler(textHandler), metadata, context);
result[0] = "Title: " + metadata.get(metadata.TITLE);
result[1] = "Body: " + textHandler.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (TikaException e) {
e.printStackTrace();
}
return result;
}
Here is a sample:
public String[] tika_autoParser() {
String[] result = new String[3];
try {
InputStream input = new FileInputStream(new File("/Users/nazanin/Books/Web crawler.pdf"));
ContentHandler textHandler = new BodyContentHandler();
Metadata metadata = new Metadata();
AutoDetectParser parser = new AutoDetectParser();
ParseContext context = new ParseContext();
parser.parse(input, textHandler, metadata, context);
result[0] = "Title: " + metadata.get(metadata.TITLE);
result[1] = "Body: " + textHandler.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (TikaException e) {
e.printStackTrace();
}
return result;
}
How to send an audio file as attachment in BlackBerry SDK 6?
You can convert the audiofile into a bytearray and then use the following method
public synchronized boolean sendMail(final byte []data,
final boolean licensed)
{
Folder[] folders = store.list(4);
Folder sentfolder = folders[0];
// create a new message and store it in the sent folder
msg = new Message(sentfolder);
multipart = new Multipart();
textPart = new TextBodyPart(multipart,"Audio");
Address recipients[] = new Address[1];
try {
recipients[0] = new Address(address, "XYZ");
msg.addRecipients(Message.RecipientType.TO, recipients);
msg.setSubject("Audio");
try {
Thread thread = new Thread("Send mail") {
public void run() {
emailSenderIsBusy = true;
try {
attach = new SupportedAttachmentPart(
multipart, "application/octet-stream",
"title",data);
multipart.addBodyPart(textPart);
multipart.addBodyPart(attach);
msg.setContent(multipart);
Transport.send(msg);
}
catch(SendFailedException e)
{
}
catch (final MessagingException e) {
}
catch (final Exception e) {
}
}
};
thread.start();
return true;
}
catch (final Exception e)
{
}
}catch (final Exception e) {
}
return false;
}
I'm trying to use RSA encryption on Blackberry with their native API's. I made a public/private key pair in Java and saved the Modulus and Exponents of the keys as strings so i can generate the keys from this for encryption and decryption. The following code is from the client side and i'm getting a InvalidKeyException and the backtrace is null so I don't know what's happening:
public byte[] Encrypt(byte[] data)
{
try {
RSACryptoSystem cryptoSystem = new RSACryptoSystem(1024);
RSAPublicKey publicKey = new RSAPublicKey(cryptoSystem, _publicKeyExponent.getBytes(), _publicKeyModulus.getBytes());
RSAEncryptorEngine encryptorEngine = new RSAEncryptorEngine(publicKey);
PKCS5FormatterEngine formatterEngine = new PKCS5FormatterEngine( encryptorEngine );
ByteArrayOutputStream output = new ByteArrayOutputStream();
BlockEncryptor encryptor = new BlockEncryptor( formatterEngine, output );
encryptor.write(data);
encryptor.close();
output.close();
return output.toByteArray();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
System.out.println();
e.printStackTrace();
} catch (CryptoTokenException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (CryptoUnsupportedOperationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedCryptoSystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
And this is what i did server side to generate my keys:
try {
keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
keyFactory = KeyFactory.getInstance("RSA");
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
}
keyPair = keyPairGenerator.generateKeyPair();
publicKey = keyPair.getPublic();
privateKey = keyPair.getPrivate();
try {
publicKeySpec = keyFactory.getKeySpec(publicKey, RSAPublicKeySpec.class);
privateKeySpec = keyFactory.getKeySpec(privateKey, RSAPrivateKeySpec.class);
} catch (InvalidKeySpecException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
}
privateKeyModulus = privateKeySpec.getModulus().toString();
privateKeyExponent = privateKeySpec.getPrivateExponent().toString();
publicKeyModulus = publicKeySpec.getModulus().toString();
publicKeyExponent = publicKeySpec.getPublicExponent().toString();
Any ideas?
EDIT: i tried doing a simple test on the server by encrypting and decrypting there and when when I try to decrypt I get a IllegalBlockSizeException these are my encrytion and decryption methods (server side):
public byte[] Decrypt(byte[] data)
{
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] cipherData = cipher.doFinal(data);
return cipherData;
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchPaddingException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
} catch(IllegalBlockSizeException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
} catch(InvalidKeyException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
} catch(BadPaddingException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public byte[] Encrypt(byte[] data)
{
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] cipherData = cipher.doFinal(data);
return cipherData;
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchPaddingException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
} catch(IllegalBlockSizeException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
} catch(InvalidKeyException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
} catch(BadPaddingException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
And this is the simple test i'm trying:
userName = Base64.encode(encryptorDecryptor.Encrypt(userName.getBytes()));
password = Base64.encode(encryptorDecryptor.Encrypt(password.getBytes()));
userName = new String(encryptorDecryptor.Decrypt(Base64.decode(userName)));
password = new String(encryptorDecryptor.Decrypt(Base64.decode(password)));
It is a bug to use String as a container for arbitrary random bytes, e.g. userName = new String(encryptorDecryptor.Encrypt(userName.getBytes()));
is wrong.
I'm not familiar with Blackberry's Java API but in usually you cannot encrypt more than one block with RSA
the toString() methods on arrays (e.g. publicKeySpec.getModulus().toString()) don't return anything useful. You should be able to figure this out just by looking at the data. This is really a beginner java mistake more than a cryptography issue.
Don't using the default character set for the String constructor and String.getBytes() methods. Always specify a character set, usually "UTF-8" is perfect.
That's all I had the patience for.