I trying to write simple method that shows alert dialog and ask user for feedback on my email.
My method:
public static void showExceptionDialog(Exception exception) {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
exception.printStackTrace(printWriter);
String exceptionText = stringWriter.toString();
try {
VBox content = FXMLLoader.load(Dialogs.class.getResource("/org/flycraft/minecraft/droplauncher/exception_dialog_content.fxml"));
TextArea exceptionTextArea = (TextArea) content.lookup("#exception_text_area");
exceptionTextArea.setText(exceptionText);
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Ошибка");
alert.setHeaderText("Что-то пошло не так");
alert.getDialogPane().setContent(content);
alert.showAndWait();
} catch (IOException e) {
e.printStackTrace();
}
}
But in real dialog i see:
This is a bug, or something I don't understand?
Yep, fixed. I use this plugin for building JavaFX application with gradle. So I just added this line to my build.gradle:
compileJava.options.encoding = 'UTF-8'
Related
At present, I encounter a problem of converting large HTML files to pdf. It takes more than 10 seconds to convert them. Can I optimize the performance?
This is my code.
public static void htmlToPDF(String htmlUrl, String destUrl, String fontUrl) {
OutputStream os = null;
try {
String url;
url = new File(htmlUrl).toURI().toURL().toString();
os = new FileOutputStream(destUrl);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(url);
ITextFontResolver fontResolver = renderer.getFontResolver();
fontResolver.addFont(fontUrl, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
renderer.layout();
renderer.createPDF(os);
renderer.finishPDF();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I find that layout takes a lot of time. Is there a good way to optimize this?
is there some way on how to open powershell with process builder in javafx and keep it opened to execute any command anytime?
Example code(executing only one command at a time):
try {
ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "powershell -Command \"Add-Type -AssemblyName System.DirectoryServices.AccountManagement; [System.DirectoryServices.AccountManagement.UserPrincipal]::Current.DisplayName\"&&exit");
Process p = builder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
if (!line.trim().isEmpty()) {
displayname = line;
}
}
reader.close();
p.waitFor();
p.destroy();
} catch (IOException | InterruptedException ex) {
Logger.getLogger(AccountStatus.class.getName()).log(Level.SEVERE, null, ex);
}
Reason to keep it opened: loading powershell takes maybe 3 seconds and loading for example active directory plugin takes another maybe 2 seconds everytime i want to execute some command. If there is some way on how to preload powershell and send command to processbuilder anytime it would be very helpfull, thanks for advices.
EDIT:
I have found solution here: Apache Commons exec PumpStreamHandler continuous input
Thanks to MichalVales!
With this quick sample i am able to open powershell, keep it opened, preload some module and execute any new command anytime without loading all again.
public class FXMLDocumentController implements Initializable {
private BufferedWriter writer;
#FXML
private void handleButtonAction(ActionEvent event) {
try {
writer.write("Import-Module ActiveDirectory -Cmdlet Get-ADUser\n");
writer.flush();
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
}
#FXML
private void handleButtonAction2(ActionEvent event) {
try {
writer.write("Get-ADUser somenamehere -Properties * | Select-Object LockedOut\n");
writer.flush();
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void initialize(URL url, ResourceBundle rb) {
ProcessBuilder builder = new ProcessBuilder("powershell.exe");
Process process;
try {
process = builder.start();
writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
StreamReader outputReader = new StreamReader(process.getInputStream(), System.out);
outputReader.start();
StreamReader err = new StreamReader(process.getErrorStream(), System.err);
err.start();
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
StreamReader code can be found on link from MichalVales
EDIT2:
I was trying to pass czech characters with any writer, but without success. I think that its impossible to pass czech characters like "ěščřžýáíé" to powershell without changing system locale, but i dont want to do it. I have tried processbuilder, apache exec, all failed, but i have found super library which works and is really easy to use:
jPowerShell
So if you have problems with keeping powershell alive or problem with characters, this is the best solution.
i try to create an eclipse 4 application but i have a problem: "Menu/New" : when i try to create a new file i receive this error message :
Internal error org.eclipse.E4.core.di.InjectionException:
java.lang.NullPointerException
this's the code:
public class OpenHandler {
#Execute
public void execute(#Named(IServiceConstants.ACTIVE_SHELL) Shell shell, EPartService partService, MApplication application,
EModelService modelService) {
FileDialog dialog = new FileDialog(shell);
String fileName = dialog.open();
if (fileName != null) {
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
String text = scanner.useDelimiter("\\A").next();
scanner.close();
// create part
MPart part = MBasicFactory.INSTANCE.createPart();
part.setLabel(file.getName());
part.setCloseable(true);
part.getTags().add(EPartService.REMOVE_ON_HIDE_TAG);
part.setContributionURI("bundleclass://RCPTextEditor/RCPTextEditor.EditorPart");
// get part stack and show new part
List<MPartStack> stacks = modelService.findElements(application, null, MPartStack.class, null);
stacks.get(0).getChildren().add(part);
partService.showPart(part, PartState.ACTIVATE);
((EditorPart) part.getObject()).styledText.setText(text);
((EditorPart) part.getObject()).model = new EditorModel(text, text);
((EditorPart) part.getObject()).setFile(file);
part.setDirty(false);
} catch (IOException e) {
MessageDialog.openError(shell, "Error opening file", "File " + fileName + " could not be opened.");
}
}
}
}
Can someone help me ??? thanks in advance
Since you haven't show us the stack trace I am just guessing but the line
((EditorPart) part.getObject()).styledText.setText(text);
is probably accessing a styledText field before it has been created.
You need to do this in the #PostConstruct method of your EditorPart when you create the part controls.
i want to create an application which can send a email in blackberry. can i have a sample code or tutorial
thanks alot
U can send Email two types using API Directly or Programatically
public void sendemail(String s){
Message m = new Message();
Address a = null;
try
{
a = new Address("","");
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Address[] addresses = {a};
try
{
m.addRecipients(net.rim.blackberry.api.mail.Message.RecipientType.TO, addresses);
m.setContent(s);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
m.setSubject(" My Croxley ");
Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES, new MessageArguments(m));
}
And Another this way
public boolean SendEmail(String emailFrom, String emailTo, String subject, String messageData, String fileName, byte[] fileData)
{
// create a multipart message
Multipart mp = new Multipart();
TextBodyPart tbp = new TextBodyPart(mp, messageData);
mp.addBodyPart(tbp);
SupportedAttachmentPart sap = new SupportedAttachmentPart(mp, "audio/amr", fileName, fileData);
mp.addBodyPart(sap);
// create a message in the sent items folder
Folder folders[] = Session.getDefaultInstance().getStore().list(Folder.SENT);
Message message = new Message(folders[0]);
// add recipients to the message and send
try
{
Address toAdd = new Address(emailTo, emailTo);
Address toAdds[] = new Address[1];
toAdds[0] = toAdd;
message.addRecipients(Message.RecipientType.TO, toAdds);
message.setSubject(subject);
message.setContent(mp);
//sets priority
//message.setPriority(Message.Priority.HIGH);
net.rim.blackberry.api.mail.Transport.send(message);
return true;
}
catch (Exception e)
{
return false;
}
}
Ypu can get started with this: http://www.blackberry.com/developers/docs/6.0.0api/Messaging-summary.html#MG_1
Could some one tell me how to capture SOAP messages passed between the client and the server webservice applications.
I tried using both tools.
pocket soap
http://www.pocketsoap.com/pocketsoap/
Fiddler
http://www.fiddlertool.com/fiddler/
I may miss some settings, it is not working for me.
help will be more appreciated.
Try tcpmon.
soapUI integrates with tcpmon, and may provide a nicer interface for you.
See also; You can try the MS Visual Roundtrip Analyzer analyzer as well.
if you're interested, you can write a handler in Java which extends the GenericSOAPHandler class, and print the output to wherever you like. In this (simple) case, the server log:
#SuppressWarnings("rawtypes")
public class MyHandler extends GenericSOAPHandler {
private void print(InputStream input, OutputStream out) throws Exception {
try {
DocumentBuilder parser;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
parser = factory.newDocumentBuilder();
Document document = parser.parse(input);
Transformer serializer = TransformerFactory.newInstance().newTransformer();
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
serializer.transform(new DOMSource(document), new StreamResult(out));
} catch (TransformerException e) {
// A fatal error occurred
throw new Exception(e);
}
}
#Override
protected boolean handleInbound(MessageContext msgContext) {
SOAPMessageContext soapMessageCtx = (SOAPMessageContext) msgContext;
SOAPMessage soapMessage = soapMessageCtx.getMessage();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
soapMessage.writeTo(outputStream);
byte[] array = outputStream.toByteArray();
ByteArrayInputStream inputStream = new ByteArrayInputStream(array);
System.out.println("SOAP request message:\n");
print(inputStream, System.out);
} catch (SOAPException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
#Override
protected boolean handleOutbound(MessageContext msgContext) {
SOAPMessageContext soapMessageCtx = (SOAPMessageContext) msgContext;
SOAPMessage soapMessage = soapMessageCtx.getMessage();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
soapMessage.writeTo(outputStream);
byte[] array = outputStream.toByteArray();
ByteArrayInputStream inputStream = new ByteArrayInputStream(array);
System.out.println("SOAP response message:\n");
print(inputStream, System.out);
} catch (SOAPException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
}
You also need to make sure your handler is included in the jaxws-handlers-server.xml of your server implementation:
<handler-chains xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee javaee_web_services_1_2.xsd">
<handler-chain>
<protocol-bindings>##SOAP11_HTTP</protocol-bindings>
<handler>
<handler-name>DebugHandler</handler-name>
<handler-class>handlers.MyHandler</handler-class>
</handler>
</handler-chain>
</handler-chains>
Here my code in C++ for retrieve xml message using Soap Toolkit 3.0 before sending.
.
.
.
Serializer->EndEnvelope();
/* ___________________ */
char * bufferxml = NULL;
_variant_t punt = _variant_t((IUnknown*)Serializer);
punt.lVal += 48;
_variant_t punt1 = *punt.ppunkVal;
punt1.lVal += 32;
_variant_t punt2 = *punt1.ppunkVal;
punt2.lVal += 4;
memcpy(&bufferxml, (char *) *punt2.ppunkVal, sizeof(char *));
punt2.lVal += 4;
int lengxml = *(punt2.pintVal);
bufferxml[lengxml] = '\0';
/* ___________________ */
// Send the message to the web service
Connector->EndMessage();
.
.
.
punt.Detach();
punt1.Detach();
punt2.Detach();
punt.Clear();
punt1.Clear();
punt2.Clear();
Serializer.Release();
.
.
.
I hope really help you, it´s my design and it had worked for me.
There is also TCP/IP Monitor which comes bundled with WTP plugin for eclipse which allows you to set up a monitor on a port to look into the SOAP requests.