I am calling a external process (git command) from inside of doPost method of my servlet. The post request comes to the servlet via an xhttpRequest() call when user clicks on a button.
In my code I am printing out the response HTML using the writer object of the response. And weirdly when the code reaches the process part it executes fine in the background but I don't see the correct response. Does someone has some insights to this problem? I am using streamgobbler class as described in this link: http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html?page=2
Snippet of the process part of the code from the doPost() method is below.
try {
String line;
List<String> lines = new ArrayList<String>();
Process cloneProcess = Runtime.getRuntime().exec("git clone " +
hvafModifiedXMLRepository + " " +
xmlRepoPath.toString());
StreamGobbler errorGlobber = new StreamGobbler(cloneProcess.getErrorStream(), "CMDTOOL-E",resp.getWriter());
StreamGobbler outputGlobber = new StreamGobbler(cloneProcess.getInputStream(), "CMDTOOL-O",resp.getWriter());
errorGlobber.start();
outputGlobber.start();
cloneProcess.waitFor();
if (cloneProcess.exitValue() != 0)
throw new IOException(org.apache.commons.lang.StringUtils.join(lines, "\n"));
System.out.println("Done.");
} catch (IOException ex) {
sendLogHead(resp);
sendLog(resp, "Unable to clone Modified XML repository.", ex);
sendLogTail(resp);
return;
}
Here is my POST request.
function sendSelectedTestCasesToServlet(paramData, projName, uniqueInstanceName, configCapabilities) {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200)
document.getElementById('content').parentElement.removeChild(document.getElementById('content'));
document.getElementById('footer').parentElement.removeChild(document.getElementById('footer'));
var el = document.createElement('html');
el.innerHTML = xhttp.responseText;
var newBody = document.createElement('div');
newBody.innerHTML = AJS.$(el.getElementsByTagName('body')[0]).html();
document.body.appendChild(newBody);
window.stop();
}
else if (xhttp.readyState == 4 && xhttp.status == 404) {
return;
} else if (xhttp.readyState == 4 && xhttp.status == 500) {
document.getElementById('content').parentElement.removeChild(document.getElementById('content'));
document.getElementById('footer').parentElement.removeChild(document.getElementById('footer'));
var el = document.createElement('html');
el.innerHTML = xhttp.responseText;
var newBody = document.createElement('div');
newBody.innerHTML = AJS.$(el.getElementsByTagName('body')[0]).html();
document.body.appendChild(newBody);
window.stop();
}
};var baseurl = window.location.protocol + '//' + window.location.host + new URI(window.location.href).path()
xhttp.open('POST', baseurl + '?test-cases-for-configs=' + paramData + '&project-name=' + projName + '&job-instance-uniqueId=' + uniqueInstanceName + '&havf-config-capabilities=' + configCapabilities, true);
xhttp.send()
}
Related
I'm trying to write a program that uses Imgur's API to download images based on an account name.
private volatile int threadCount;
private volatile double totalFileSize;
private volatile List<String> albums = new ArrayList<>();
private volatile Map<JSONObject, String> images = new HashMap<>();
private final ExecutorService executorService = Executors.newFixedThreadPool(100, (Runnable r) -> {
Thread t = Executors.defaultThreadFactory().newThread(r);
t.setDaemon(true);
return t;
});
private void downloadAlbums(List<String> albums) {
threadCount = 0;
albums.forEach((albumHash) -> {
if (hasRemainingRequests()) {
incThreadCount();
executorService.execute(() -> {
try {
String responseString;
String dirTitle;
String albumUrl = URL_ALBUM + albumHash;
String query = String.format("client_id=%s", URLEncoder.encode(CLIENT_ID, CHARSET));
URLConnection connection = new URL(albumUrl + "?" + query).openConnection();
connection.setRequestProperty("Accept-Charset", CHARSET);
InputStream response = connection.getInputStream();
try (Scanner scanner = new Scanner(response)) {
responseString = scanner.useDelimiter("\\A").next();
JSONObject obj = new JSONObject(responseString).getJSONObject("data");
dirTitle = obj.getString("title");
String temp = "";
// Get save path from a TextField somewhere else on the GUI
ObservableList<Node> nodes = primaryStage.getScene().getRoot().getChildrenUnmodifiable();
for (Node node : nodes) {
if (node instanceof VBox) {
ObservableList<Node> vNodes = ((VBox) node).getChildrenUnmodifiable();
for (Node vNode : vNodes) {
if (vNode instanceof DestinationBrowser) {
temp = ((DestinationBrowser) vNode).getDestination().trim();
}
}
}
}
final String path = temp + "\\" + formatPath(accountName) + "\\" + formatPath(dirTitle);
JSONArray arr = obj.getJSONArray("images");
arr.forEach((jsonObject) -> {
totalFileSize += ((JSONObject) jsonObject).getDouble("size");
images.put((JSONObject) jsonObject, path);
});
}
} catch (IOException ex) {
//
} catch (Exception ex) {
//
} finally {
decThreadCount();
if (threadCount == 0) {
Platform.runLater(() -> {
DecimalFormat df = new DecimalFormat("#.#");
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);// 714833218
alert.setHeaderText("Found " + images.size() + " images (" + (totalFileSize < 1000000000 ? df.format(totalFileSize / 1000000) + " MB)" : df.format(totalFileSize / 1000000000) + " GB)"));
alert.setContentText("Proceed with download and save images?");
Optional<ButtonType> alertResponse = alert.showAndWait();
if (alertResponse.get() == ButtonType.OK) {
progressBar.setTotalWork(images.size());
executorService.execute(() -> {
for (JSONObject obj : images.keySet()) {
(new File(images.get(obj))).mkdirs();
downloadImage(obj, images.get(obj));
}
});
}
});
}
}
});
}
});
}
albums is a List of codes that are required to send a GET request to Imgur in order to receive that album's images. The data returned is then used in another method which downloads the images themselves.
Now, all of this works fine, but when the program is making all the GET requests the JavaFX thread hangs (GUI becomes unresponsive). And after all the GET requests have been executed, the JavaFX thread stops hanging and the alert shows up with the correct information.
I just don't understand why the GUI becomes unresponsive when I'm not (I believe I'm not) blocking it's thread and I'm using an ExecutorService to do all the network requests.
I made script for checking all link in one page, but all of the link always give 403 response code, it will opened normally with browser but if checking it by getting response code using selenium java always give 403(Forbidden), i also bring all cookies but it doesn't work, if anyone have solution please let me know.
Thanks in advance.
this is my code to store all cookie and bring them in all link response check
private int getHttpResponseStatusCode(String webPageUrl) {
int ret = -1;
try {
if (webPageUrl != null && !"".equals(webPageUrl.trim())) {
URL urlObj = new URL(webPageUrl.trim());
HttpURLConnection httpConn = (HttpURLConnection) urlObj.openConnection();
Set <Cookie> cookies = driver.manage().getCookies();
String cookieString = "";
for (Cookie cookie: cookies) {
cookieString += cookie.getName() + "=" + cookie.getValue() + ";";
}
httpConn.addRequestProperty("Cookies", cookieString);
httpConn.setRequestMethod("HEAD");
httpConn.connect();
ret = httpConn.getResponseCode();
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
System.out.println("Http Status Code : " + ret + " , Url : " + webPageUrl);
return ret;
}
};
this is how i get all the link from the page
private List <String> parseOutAllUrlLinksInWebPage(String webPageUrl) {
List <String> retList = new ArrayList <String> ();
if (webPageUrl != null && !"".equals(webPageUrl.trim())) {
/* Get current page belongs domain. */
String urlDomain = this.getPageBelongDomain(webPageUrl);
/* First parse out all a tag href urls. */
By byUrlLink = By.tagName("a");
List <WebElement> aLinkList = driver.findElements(byUrlLink);
if (aLinkList != null) {
int aLinkSize = aLinkList.size();
for (int i = 0; i <aLinkSize; i++) {
WebElement aLink = aLinkList.get(i);
String href = aLink.getAttribute("href");
if (href != null && !"".equals(href.trim())) {
/* Only return same domain page url. */
if (href.toLowerCase().startsWith("http://" + urlDomain) || href.toLowerCase().startsWith("https://" + urlDomain)) {
retList.add(href);
}
}
}
}
/* Second parse out all img tag src urls. */
By byImg = By.tagName("img");
List <WebElement> imgList = driver.findElements(byImg);
if (imgList != null) {
int imgSize = imgList.size();
for (int i = 0; i <imgSize; i++) {
WebElement imgElement = imgList.get(i);
String src = imgElement.getAttribute("src");
if (src != null && !"".equals(src.trim())) {
/* Only return same domain page url. */
if (src.toLowerCase().startsWith("http://" + urlDomain) || src.toLowerCase().startsWith("https://" + urlDomain)) {
retList.add(src);
}
}
}
}
}
System.out.println("Parse out url completed successfully.");
return retList;
};
I have a special need in Alfresco, I'm unfortunately new in using this product.
Actually My intention is to show, in the workflow, only documents whose the coordinator is the logged on user and which are not in active workflows.
Any idea please :)
I'm back with a solution even if I'm not sure if it's the best. Any way that solved my problem.
I modified the method ObjectRenderer_renderCellAdd of object-finder.js to check if the user is the document coordinator and if there is no other active workflow linked to the document.
Instead of :
elCell.innerHTML = '<a id="' + containerId + '" href="#" ' + style + ' class="add-item add-' + scope.eventGroup + '" title="' + scope.msg("form.control.object-picker.add-item") + '" tabindex="0"><span class="addIcon"> </span></a>';
I put :
var showSelectLink = true;
if(oRecord.getData("type") == "cm:content"){
showSelectLink = false;
//Checking if the document is already in an other active worflow
var xmlHttp = new XMLHttpRequest();
var url = window.location.href;
var arr = url.split("/");
xmlHttp.open( "GET", (arr[0] + "//" + arr[2]).concat("/alfresco/s/api/node/").concat((oRecord.getData("nodeRef")).replace(":/","")).concat("/workflow-instances"), false );
xmlHttp.send( null );
if(json.data.length == 0){
//Checking if the logged on user is the document coordinator
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", (arr[0] + "//" + arr[2]).concat("/alfresco/s/slingshot/doclib/permissions/").concat((oRecord.getData("nodeRef")).replace(":/","")), false );
xmlHttp.send( null );
var json = JSON.parse(xmlHttp.responseText);
var hasDirectPermission = false;
//Direct permission
if(json.direct.length != 0){
var permission;
for(var index = 0; index < json.direct.length; index++){
permission = json.direct[index];
if(permission.role == "Coordinator"){
showSelectLink = true;
hasDirectPermission = true;
break;
}
}
}
//Inherited Permission
if(!hasDirectPermission && json.inherited.length != 0){
var permission;
for(var index = 0; index < json.inherited.length; index++){
permission = json.inherited[index];
if(permission.role == "Coordinator"){
showSelectLink = true;
break;
}
}
}
}
}
if(showSelectLink){
elCell.innerHTML = '<a id="' + containerId + '" href="#" ' + style + ' class="add-item add-' + scope.eventGroup + '" title="' + scope.msg("form.control.object-picker.add-item") + '" tabindex="0"><span class="addIcon"> </span></a>';
}
Regards,
I'm writing a special permission forms program using MySQL, Javascript, and HTML code, which both respond to. I'm doing all of this using singleton pattern access and facade code(s) in java, and a services code, which responds to the singleton pattern codes.
I'm trying To retrieve a form (AKA 1 Result) by the variables, courseDept & courseNm.
This is a snippet of code I'm using to do all this:
FormDataFacade.java code snippet:
#Path("/specialPermissions/sp")
#GET
#Produces("text/plain")
public Response getSpecialPermissionFormByDeptAndRoomNm(#QueryParam("courseDept") String theDept, #QueryParam("courseNm") String theNm)
throws NamingException, SQLException, ClassNotFoundException
{
//Referenciation to FormDataFacade class.
FormDataFacade iFacade = FormDataFacade.getInstance();
int intNm = 0;
try {
intNm = Integer.parseInt(theNm);
}catch (NumberFormatException FAIL) {
intNm = 1;
}
//Aiming for forms with matching departments & room numbers by calling FormDataFacade
//method, getSpecialPermissionFormByDeptAndRoomNm.
SpecialPermissionForms[] orgaForm = iFacade.getSpecialPermissionFormByDeptAndRoomNm(theDept, intNm);
//Json String Representation...
if (orgaForm != null)
{
Gson neoArcadia = new Gson();
String result = neoArcadia.toJson(orgaForm);
//Json String added to response message body...
ResponseBuilder rb = Response.ok(result, MediaType.TEXT_PLAIN);
rb.status(200); //HTTP Status code has been set!
return rb.build(); //Creating & Returning Response.
}
else
{ //In case of finding no form data for the procedure...
return Response.status(700).build();
}
}
FormDataServices.java code snippet:
public SpecialPermissionForms[] getSpecialPermissionFormByDeptAndRoomNm(String theDept, int theNm) throws SQLException, ClassNotFoundException
{
Connection con = zeon.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT formID, studentName, courseDept, courseNm, semester, year, reasonCode FROM spforms WHERE courseDept = ? & courseNm = ?");
pstmt.setString(1, theDept);
pstmt.setInt(2, theNm);
ResultSet rs = pstmt.executeQuery();
SpecialPermissionForms[] neoForm = new SpecialPermissionForms[50];
int current = 0;
while (rs.next())
{
int formID3 = rs.getInt("formID");
String studentName3 = rs.getString("studentName");
String courseDept3 = rs.getString("courseDept");
String courseNm3 = rs.getString("courseNm");
String semester3 = rs.getString("semester");
int year3 = rs.getInt("year");
String reasonCode3 = rs.getString("reasonCode");
SpecialPermissionForms neo = new SpecialPermissionForms(formID3, studentName3, courseDept3, courseNm3, semester3, year3, reasonCode3);
neoForm[current] = neo;
current++;
}
if (current > 0)
{
neoForm = Arrays.copyOf(neoForm, current);
return neoForm;
}
else
{
return null;
}
}
Forms.html code snippet which both pieces of java code respond to:
$("#btnOneName").click(function() {
alert("clicked");
var inputId1=document.getElementById("t_specialFormCourseDept").value;
var inputId2=document.getElementById("t_specialFormCourseNm").value;
var theData = "courseDept=" + inputId1 + "&" + "courseNm=" + inputId2;
alert("Sending: " + theData);
var theUrl = "http://localhost:8080/onlineforms/services/enrollment/specialPermissions/sp?courseDept=&courseNm="+ theData;
$.ajax( {
url: theUrl,
type: "GET",
dataType: "text",
success: function(result) {
alert("success");
var neoForm = JSON.parse(result);
alert(neoForm);
var output="<h3>Current Form Lists:</h3>";
output += "<ul>";
for (var current = 0; current < neoForm.length; current++)
{
output += "<li>" + neoForm[current].formID + ": " + neoForm[current].studentName + " (" + neoForm[current].courseDept + " - " + neoForm[current].courseNm + ") " +
" (" + neoForm[current].semester + " - " + neoForm[current].year + ") " + " - " + neoForm[current].reasonCode + "</li>";
}
output += "</ul>";
alert(output);
$("#p_retrieveOneName").html(output);
},
error:function(xhr) {
alert("error");
$("#p_retrieveOneName").html("Error:"+xhr.status+" "+xhr.statusText);}
} );
});
});
Now, when I go test this code in my webservice after successfully compiling it, it does work, however it retrieves everything, including the specific results I was searching for - I only want to return the results I have specifically searched for and nothing else. What exactly am I doing wrong here in these snippets of code?
Any suggestions or steps in the right direction are highly welcome.
I need to send a mail with attachment in java using sendgrid api. I am mentioning files like [filename.xls]=bytearray. I am getting this byte array using jxl api. I am able to send the mail ,but xls is not having the values.
Code :
sendgridUrl+"?api_user="+apiUser + "&api_key=" + apiPassword + ""
+ to + "&subject=" + (subject.replaceAll(" ", "%20")) + "&fromname="
+ senderPersonal + "&files[" + fileName + "]=" + value2
+ "&html=" + message + "&from=" + AppConfig.getProperty("senderemail");
private static bool SendMailUsingSendgrid(EmailSendRequestDTO request)
{
try
{
string htmlContent = string.Empty;
string plainTextContent = string.Empty;
// Set apikey
var apiKey = ConfigReader.Read(CommonEnums.ConfigKeys.SendgridApiKey);
// Initialize sendgrid client.
var client = new SendGridClient(apiKey);
// From address
var from = new EmailAddress(request.FromAddress, request.FromDisplayName);
// Subject
var subject = request.Subject;
// Send mail to multiple recepients.
var recepientList = new List<EmailAddress>();
if (!string.IsNullOrEmpty(request.ToAddresses))
{
foreach (var toAddress in request.ToAddresses.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
{
recepientList.Add(new EmailAddress(toAddress));
}
}
// If content in html format
if (request.IsHtmlFormat)
{
htmlContent = request.Body;
}
else
{
plainTextContent = request.Body;
}
// Creat object to send mail message.
var mailMessage = MailHelper.CreateSingleEmailToMultipleRecipients(from, recepientList, subject, plainTextContent, htmlContent);
// add multiple cc.
var ccList = new List<EmailAddress>();
if (!string.IsNullOrEmpty(request.CCAddresses))
{
foreach (var ccAddress in request.CCAddresses.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
{
ccList.Add(new EmailAddress(ccAddress));
}
}
// add multiple bcc.
var bccList = new List<EmailAddress>();
if (!string.IsNullOrEmpty(request.BCCAddresses))
{
foreach (var bccAddress in request.BCCAddresses.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
{
bccList.Add(new EmailAddress(bccAddress));
}
}
// Attachments
if (!string.IsNullOrEmpty(request.AttachmentFile))
{
foreach (var attachmentFile in request.AttachmentFile.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
{
SendGrid.Helpers.Mail.Attachment messageAttachment = new SendGrid.Helpers.Mail.Attachment();
mailMessage.Attachments.Add(messageAttachment);
}
}
var response = client.SendEmailAsync(mailMessage).Result;
return true;
}
catch (Exception)
{
return false;
}
}