List of usage examples for java.net URLConnection setDoOutput
public void setDoOutput(boolean dooutput)
From source file:edu.caltechUcla.sselCassel.projects.jMarkets.frontdesk.web.data.SessionBean.java
/** * Connect to the JMarkets server and start the session defined by the given SessionDef object. * Return the session Id of the created session */// www .j a v a 2s . co m private int executeSession(String path, String name, SessionDef session) { try { URL servlet = new URL(path + "/servlet/ServletReceiver"); Request req = new Request(Request.SERVER_INIT_REQUEST); req.addIntInfo("numClients", numSubjects); req.addIntInfo("updateProtocol", JMConstants.HTTP_UPDATE_PROTOCOL); req.addIntInfo("updateTime", 100); req.addStringInfo("name", name); req.addInfo("session", session); URLConnection servletConnection = servlet.openConnection(); servletConnection.setDoInput(true); servletConnection.setDoOutput(true); servletConnection.setUseCaches(false); servletConnection.setDefaultUseCaches(false); servletConnection.setRequestProperty("Content-Type", "application/octet-stream"); ObjectOutputStream outputToServlet = new ObjectOutputStream(servletConnection.getOutputStream()); outputToServlet.writeObject(req); outputToServlet.flush(); outputToServlet.close(); ObjectInputStream inputFromServlet = new ObjectInputStream(servletConnection.getInputStream()); Response res = (Response) inputFromServlet.readObject(); int sessionId = res.getIntInfo("sessionId"); inputFromServlet.close(); return sessionId; } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return -1; }
From source file:au.org.ala.layers.dao.LayerIntersectDAOImpl.java
ArrayList<String> remoteSampling(IntersectionFile[] intersectionFiles, double[][] points, IntersectCallback callback) {/*from ww w .j a v a 2 s . c om*/ logger.info("begin REMOTE sampling, number of threads " + intersectConfig.getThreadCount() + ", number of layers=" + intersectionFiles.length + ", number of coordinates=" + points.length); ArrayList<String> output = null; try { long start = System.currentTimeMillis(); URL url = new URL(intersectConfig.getLayerIndexUrl() + "/intersect/batch"); URLConnection c = url.openConnection(); c.setDoOutput(true); OutputStreamWriter out = null; try { out = new OutputStreamWriter(c.getOutputStream()); out.write("fids="); for (int i = 0; i < intersectionFiles.length; i++) { if (i > 0) { out.write(","); } out.write(intersectionFiles[i].getFieldId()); } out.write("&points="); for (int i = 0; i < points.length; i++) { if (i > 0) { out.write(","); } out.write(String.valueOf(points[i][1])); out.write(","); out.write(String.valueOf(points[i][0])); } out.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (out != null) { try { out.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } JSONObject jo = JSONObject.fromObject(IOUtils.toString(c.getInputStream())); String checkUrl = jo.getString("statusUrl"); //check status boolean notFinished = true; String downloadUrl = null; while (notFinished) { //wait 5s before querying status Thread.sleep(5000); jo = JSONObject.fromObject(IOUtils.toString(new URI(checkUrl).toURL().openStream())); if (jo.containsKey("error")) { notFinished = false; } else if (jo.containsKey("status")) { String status = jo.getString("status"); if ("finished".equals(status)) { downloadUrl = jo.getString("downloadUrl"); notFinished = false; } else if ("cancelled".equals(status) || "error".equals(status)) { notFinished = false; } } } ZipInputStream zis = null; CSVReader csv = null; InputStream is = null; ArrayList<StringBuilder> tmpOutput = new ArrayList<StringBuilder>(); long mid = System.currentTimeMillis(); try { is = new URI(downloadUrl).toURL().openStream(); zis = new ZipInputStream(is); ZipEntry ze = zis.getNextEntry(); csv = new CSVReader(new InputStreamReader(zis)); for (int i = 0; i < intersectionFiles.length; i++) { tmpOutput.add(new StringBuilder()); } String[] line; int row = 0; csv.readNext(); //discard header while ((line = csv.readNext()) != null) { //order is consistent with request for (int i = 2; i < line.length && i - 2 < tmpOutput.size(); i++) { if (row > 0) { tmpOutput.get(i - 2).append("\n"); } tmpOutput.get(i - 2).append(line[i]); } row++; } } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (zis != null) { try { zis.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } if (is != null) { try { is.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } if (csv != null) { try { csv.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } output = new ArrayList<String>(); for (int i = 0; i < tmpOutput.size(); i++) { output.add(tmpOutput.get(i).toString()); tmpOutput.set(i, null); } long end = System.currentTimeMillis(); logger.info("sample time for " + 5 + " layers and " + 3 + " coordinates: get response=" + (mid - start) + "ms, write response=" + (end - mid) + "ms"); } catch (Exception e) { logger.error(e.getMessage(), e); } return output; }
From source file:org.dataconservancy.dcs.access.http.dataPackager.ZipPackageCreator.java
void downloadFileStream(SeadFile file, OutputStream destination) throws EntityNotFoundException, EntityTypeException { String filePath = null;/* w w w .j av a2 s . com*/ if (file.getPrimaryLocation().getType() != null && file.getPrimaryLocation().getType().length() > 0 && file.getPrimaryLocation().getLocation() != null && file.getPrimaryLocation().getLocation().length() > 0 && file.getPrimaryLocation().getName() != null && file.getPrimaryLocation().getName().length() > 0) { if ((file.getPrimaryLocation().getName() .equalsIgnoreCase(ArchiveEnum.Archive.IU_SCHOLARWORKS.getArchive())) || (file.getPrimaryLocation().getName() .equalsIgnoreCase(ArchiveEnum.Archive.UIUC_IDEALS.getArchive()))) { URLConnection connection = null; try { String location = file.getPrimaryLocation().getLocation(); location = location.replace("http://maple.dlib.indiana.edu:8245/", "https://scholarworks.iu.edu/"); connection = new URL(location).openConnection(); connection.setDoOutput(true); final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(final X509Certificate[] chain, final String authType) { } @Override public void checkServerTrusted(final X509Certificate[] chain, final String authType) { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } } }; if (connection.getURL().getProtocol().equalsIgnoreCase("https")) { final SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); ((HttpsURLConnection) connection).setSSLSocketFactory(sslSocketFactory); } IOUtils.copy(connection.getInputStream(), destination); } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (KeyManagementException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } return; } else if (file.getPrimaryLocation().getType() .equalsIgnoreCase(ArchiveEnum.Archive.SDA.getType().getText()) && file.getPrimaryLocation().getName().equalsIgnoreCase(ArchiveEnum.Archive.SDA.getArchive())) { filePath = file.getPrimaryLocation().getLocation(); String[] pathArr = filePath.split("/"); try { Sftp sftp = new Sftp(config.getSdahost(), config.getSdauser(), config.getSdapwd(), config.getSdamount()); sftp.downloadFile(filePath.substring(0, filePath.lastIndexOf('/')), pathArr[pathArr.length - 1], destination); sftp.disConnectSession(); } catch (JSchException e) { e.printStackTrace(); } catch (SftpException e) { e.printStackTrace(); } } } else { if (file.getSecondaryDataLocations() != null && file.getSecondaryDataLocations().size() > 0) { for (SeadDataLocation dataLocation : file.getSecondaryDataLocations()) { if (dataLocation.getType().equalsIgnoreCase(ArchiveEnum.Archive.SDA.getType().getText()) && dataLocation.getName().equalsIgnoreCase(ArchiveEnum.Archive.SDA.getArchive())) { filePath = dataLocation.getLocation(); String[] pathArr = filePath.split("/"); try { Sftp sftp = new Sftp(config.getSdahost(), config.getSdauser(), config.getSdapwd(), config.getSdamount()); sftp.downloadFile(filePath.substring(0, filePath.lastIndexOf('/')), pathArr[pathArr.length - 1], destination); sftp.disConnectSession(); } catch (JSchException e) { e.printStackTrace(); } catch (SftpException e) { e.printStackTrace(); } } } } } return; }
From source file:de.bps.course.nodes.vc.provider.adobe.AdobeConnectProvider.java
private String sendRequest(Map<String, String> parameters) { URL url = createRequestUrl(parameters); URLConnection urlConn; try {/* www . j a v a 2 s. c o m*/ urlConn = url.openConnection(); // setup url connection urlConn.setDoOutput(true); urlConn.setUseCaches(false); // add content type urlConn.setRequestProperty("Content-Type", CONTENT_TYPE); // add cookie information if (cookie != null) urlConn.setRequestProperty("Cookie", COOKIE + cookie); // send request urlConn.connect(); // read response BufferedReader input = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); StringBuilder response = new StringBuilder(); String line; while ((line = input.readLine()) != null) response.append(line); input.close(); if (isLogDebugEnabled()) { logDebug("Requested URL: " + url); logDebug("Response: " + response); } return response.toString(); } catch (IOException e) { logError("Sending request to Adobe Connect failed. Request: " + url.toString(), e); return ""; } }
From source file:com.hpe.application.automation.tools.srf.run.RunFromSrfBuilder.java
private String loginToSrf() throws MalformedURLException, IOException, ConnectException { String authorizationsAddress = _ftaasServerAddress.concat("/rest/security/authorizations/access-tokens"); // .concat("/?TENANTID="+_tenant); Writer writer = null;// ww w .ja v a2s . com // login // JSONObject login = new JSONObject(); login.put("loginName", _app); login.put("password", _secret); OutputStream out; URL loginUrl = new URL(authorizationsAddress); URLConnection loginCon; if (_ftaasServerAddress.startsWith("http://")) { loginCon = (HttpURLConnection) loginUrl.openConnection(); loginCon.setDoOutput(true); loginCon.setDoInput(true); ((HttpURLConnection) loginCon).setRequestMethod("POST"); loginCon.setRequestProperty("Content-Type", "application/json"); out = loginCon.getOutputStream(); } else { loginCon = loginUrl.openConnection(); loginCon.setDoOutput(true); loginCon.setDoInput(true); ((HttpsURLConnection) loginCon).setRequestMethod("POST"); loginCon.setRequestProperty("Content-Type", "application/json"); ((HttpsURLConnection) loginCon).setSSLSocketFactory(_factory); out = loginCon.getOutputStream(); } writer = new OutputStreamWriter(out); writer.write(login.toString()); writer.flush(); out.flush(); out.close(); int responseCode = ((HttpURLConnection) loginCon).getResponseCode(); systemLogger.fine(String.format("SRF login received response code: %d", responseCode)); BufferedReader br = new BufferedReader(new InputStreamReader((loginCon.getInputStream()))); StringBuffer response = new StringBuffer(); String line; while ((line = br.readLine()) != null) { response.append(line); } String tmp = response.toString(); int n = tmp.length(); return tmp.substring(1, n - 1); }
From source file:com.krawler.spring.mailIntegration.mailIntegrationController.java
public ModelAndView mailIntegrate(HttpServletRequest request, HttpServletResponse response) throws ServletException { KwlReturnObject kmsg = null;//from w w w . ja v a2 s .c o m JSONObject obj = new JSONObject(); String url = storageHandlerImpl.GetSOAPServerUrl(); String res = ""; boolean isFormSubmit = false; boolean isDefaultModelView = true; ModelAndView mav = null; try { if (!StringUtil.isNullOrEmpty(request.getParameter("action")) && request.getParameter("action").equals("getoutboundconfid")) { String str = ""; url += "getOutboundConfiId.php"; URL u = new URL(url); URLConnection uc = u.openConnection(); uc.setDoOutput(true); uc.setUseCaches(false); uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); PrintWriter pw = new PrintWriter(uc.getOutputStream()); pw.println(str); pw.close(); BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream())); String line = ""; while ((line = in.readLine()) != null) { res += line; } in.close(); } else if (!StringUtil.isNullOrEmpty(request.getParameter("emailUIAction")) && request.getParameter("emailUIAction").equals("uploadAttachment")) { isDefaultModelView = false; url += "krawlermails.php"; String pass = ""; String currUser = sessionHandlerImplObj.getUserName(request) + "_"; String userid = sessionHandlerImplObj.getUserid(request); String jsonStr = profileHandlerDAOObj.getUser_hash(userid); JSONObject currUserAuthInfo = new JSONObject(jsonStr); if (currUserAuthInfo.has("userhash")) { currUser += currUserAuthInfo.getString("subdomain"); pass = currUserAuthInfo.getString("userhash"); } Enumeration en = request.getParameterNames(); String str = "username=" + currUser + "&user_hash=" + pass; while (en.hasMoreElements()) { String paramName = (String) en.nextElement(); String paramValue = request.getParameter(paramName); str = str + "&" + paramName + "=" + URLEncoder.encode(paramValue); } List fileItems = null; HashMap<String, String> arrParam = new HashMap<String, String>(); ArrayList<FileItem> fi = new ArrayList<FileItem>(); // if (request.getParameter("email_attachment") != null) { DiskFileUpload fu = new DiskFileUpload(); fileItems = fu.parseRequest(request); // crmDocumentDAOObj.parseRequest(fileItems, arrParam, fi, fileUpload); FileItem fi1 = null; for (Iterator k = fileItems.iterator(); k.hasNext();) { fi1 = (FileItem) k.next(); if (fi1.isFormField()) { arrParam.put(fi1.getFieldName(), fi1.getString("UTF-8")); } else { if (fi1.getSize() != 0) { fi.add(fi1); } } } // } long sizeinmb = 10; // 10 MB long maxsize = sizeinmb * 1024 * 1024; if (fi.size() > 0) { for (int cnt = 0; cnt < fi.size(); cnt++) { if (fi.get(cnt).getSize() <= maxsize) { try { byte[] filecontent = fi.get(cnt).get(); URL u = new URL(url + "?" + str); URLConnection uc = u.openConnection(); uc.setDoOutput(true); uc.setUseCaches(false); uc.setRequestProperty("Content-Type", "multipart/form-data; boundary=---------------------------4664151417711"); uc.setRequestProperty("Content-length", "" + filecontent.length); uc.setRequestProperty("Cookie", ""); OutputStream outstream = uc.getOutputStream(); String newline = "\r\n"; String b1 = ""; b1 += "-----------------------------4664151417711" + newline; b1 += "Content-Disposition: form-data; name=\"email_attachment\"; filename=\"" + fi.get(cnt).getName() + "\"" + newline; b1 += "Content-Type: text" + newline; b1 += newline; String b2 = ""; b2 += newline + "-----------------------------4664151417711--" + newline; String b3 = ""; b3 += "-----------------------------4664151417711" + newline; b3 += "Content-Disposition: form-data; name=\"addval\";" + newline; b3 += newline; String b4 = ""; b4 += newline + "-----------------------------4664151417711--" + newline; outstream.write(b1.getBytes()); outstream.write(b1.getBytes()); outstream.write(b1.getBytes()); outstream.write(fi.get(cnt).get()); outstream.write(b4.getBytes()); PrintWriter pw = new PrintWriter(outstream); pw.println(str); pw.close(); outstream.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream())); String line = ""; while ((line = in.readLine()) != null) { res += line; } in.close(); } catch (Exception e) { throw ServiceException.FAILURE(e.getMessage(), e); } } else { JSONObject jerrtemp = new JSONObject(); jerrtemp.put("Success", "Fail"); jerrtemp.put("errmsg", "Attachment size should be upto " + sizeinmb + "mb"); res = jerrtemp.toString(); } } } else { JSONObject jerrtemp = new JSONObject(); jerrtemp.put("Success", "Fail"); jerrtemp.put("errmsg", "Attachment file size should be greater than zero"); res = jerrtemp.toString(); } } else { url += "krawlermails.php"; String pass = ""; String currUser = sessionHandlerImplObj.getUserName(request) + "_"; String userid = sessionHandlerImplObj.getUserid(request); String jsonStr = profileHandlerDAOObj.getUser_hash(userid); JSONObject currUserAuthInfo = new JSONObject(jsonStr); if (currUserAuthInfo.has("userhash")) { currUser += currUserAuthInfo.getString("subdomain"); pass = currUserAuthInfo.getString("userhash"); } Enumeration en = request.getParameterNames(); String str = "username=" + currUser + "&user_hash=" + pass; while (en.hasMoreElements()) { String paramName = (String) en.nextElement(); String paramValue = request.getParameter(paramName); str = str + "&" + paramName + "=" + URLEncoder.encode(paramValue); } URL u = new URL(url); URLConnection uc = u.openConnection(); uc.setDoOutput(true); uc.setUseCaches(false); uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); PrintWriter pw = new PrintWriter(uc.getOutputStream()); pw.println(str); pw.close(); if ((!StringUtil.isNullOrEmpty(request.getParameter("emailUIAction")) && request.getParameter("emailUIAction").equals("getMessageListXML")) || (!StringUtil.isNullOrEmpty(request.getParameter("emailUIAction")) && request .getParameter("emailUIAction").equals("getMessageListKrawlerFoldersXML"))) { //response.setContentType("text/xml;charset=UTF-8"); isFormSubmit = true; int totalCnt = 0; int unreadCnt = 0; JSONObject jobj = new JSONObject(); JSONArray jarr = new JSONArray(); DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(uc.getInputStream()); NodeList cntentity = doc.getElementsByTagName("TotalCount"); Node cntNode = cntentity.item(0); if (cntNode.getNodeType() == Node.ELEMENT_NODE) { Element firstPersonElement = (Element) cntNode; totalCnt = Integer.parseInt(firstPersonElement.getChildNodes().item(0).getNodeValue()); } cntentity = doc.getElementsByTagName("UnreadCount"); cntNode = cntentity.item(0); if (cntNode.getNodeType() == Node.ELEMENT_NODE) { Element firstPersonElement = (Element) cntNode; unreadCnt = Integer.parseInt(firstPersonElement.getChildNodes().item(0).getNodeValue()); } String dateFormatId = sessionHandlerImpl.getDateFormatID(request); String timeFormatId = sessionHandlerImpl.getUserTimeFormat(request); String timeZoneDiff = sessionHandlerImpl.getTimeZoneDifference(request); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // check for Mail server protocol boolean isYahoo = false; if (request.getParameter("mbox").equals("INBOX")) { u = new URL(url); uc = u.openConnection(); uc.setDoOutput(true); uc.setUseCaches(false); uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); str = "username=" + currUser + "&user_hash=" + pass + "&action=EmailUIAjax&emailUIAction=getIeAccount&ieId=" + request.getParameter("ieId") + "&module=Emails&to_pdf=true"; pw = new PrintWriter(uc.getOutputStream()); pw.println(str); pw.close(); BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream())); String line = ""; while ((line = in.readLine()) != null) { res += line; } in.close(); JSONObject ieIDInfo = new JSONObject(res); if (ieIDInfo.getString("server_url").equals("pop.mail.yahoo.com")) isYahoo = true; } sdf.setTimeZone(TimeZone.getTimeZone("GMT+00:00")); DateFormat userdft = null; if (!isYahoo) userdft = KwlCommonTablesDAOObj.getUserDateFormatter(dateFormatId, timeFormatId, timeZoneDiff); else userdft = KwlCommonTablesDAOObj.getOnlyDateFormatter(dateFormatId, timeFormatId); NodeList entity = doc.getElementsByTagName("Emails"); NodeList email = ((Element) entity.item(0)).getElementsByTagName("Email"); for (int i = 0; i < email.getLength(); i++) { JSONObject tmpObj = new JSONObject(); Node rowElement = email.item(i); if (rowElement.getNodeType() == Node.ELEMENT_NODE) { NodeList childNodes = rowElement.getChildNodes(); for (int j = 0; j < childNodes.getLength(); j++) { Node node = childNodes.item(j); if (node.getNodeType() == Node.ELEMENT_NODE) { Element firstPersonElement = (Element) node; if (firstPersonElement != null) { NodeList textFNList = firstPersonElement.getChildNodes(); if (textFNList.item(0) != null) { if (request.getSession().getAttribute("iPhoneCRM") != null) { String body = ((Node) textFNList.item(0)).getNodeValue().trim(); if (body.contains("<")) body = body.replace("<", "<"); if (body.contains(">")) body = body.replace(">", ">"); tmpObj.put(node.getNodeName(), body); } else { String value = ((Node) textFNList.item(0)).getNodeValue().trim(); if (node.getNodeName().equals("date")) { value = userdft.format(sdf.parse(value)); } tmpObj.put(node.getNodeName(), value); } } } } } } jarr.put(tmpObj); } jobj.put("data", jarr); jobj.put("totalCount", totalCnt); jobj.put("unreadCount", unreadCnt); res = jobj.toString(); } else { BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream())); String line = ""; while ((line = in.readLine()) != null) { res += line; } in.close(); if ((!StringUtil.isNullOrEmpty(request.getParameter("emailUIAction")) && request.getParameter("emailUIAction").equals("fillComposeCache"))) { isFormSubmit = true; } else if (!StringUtil.isNullOrEmpty(request.getParameter("emailUIAction")) && request.getParameter("emailUIAction").equals("refreshKrawlerFolders")) { if (res.equals("Not a valid entry method")) { ArrayList filter_names = new ArrayList(); ArrayList filter_params = new ArrayList(); filter_names.add("u.userID"); filter_params.add(userid); HashMap<String, Object> requestParams = new HashMap<String, Object>(); KwlReturnObject kwlobject = profileHandlerDAOObj.getUserDetails(requestParams, filter_names, filter_params); List li = kwlobject.getEntityList(); if (li.size() >= 0) { if (li.iterator().hasNext()) { User user = (User) li.iterator().next(); String returnStr = addUserEntryForEmails( user.getCompany().getCreator().getUserID(), user, user.getUserLogin(), user.getUserLogin().getPassword(), false); JSONObject emailresult = new JSONObject(returnStr); if (Boolean.parseBoolean(emailresult.getString("success"))) { pw = new PrintWriter(uc.getOutputStream()); pw.println(str); pw.close(); in = new BufferedReader(new InputStreamReader(uc.getInputStream())); line = ""; while ((line = in.readLine()) != null) { res += line; } in.close(); } } } } } else if (res.equals("bool(false)")) { res = "false"; } } } if (!isFormSubmit) { JSONObject resjobj = new JSONObject(); resjobj.put("valid", true); resjobj.put("data", res); res = resjobj.toString(); } if (isDefaultModelView) mav = new ModelAndView("jsonView-ex", "model", res); else mav = new ModelAndView("jsonView", "model", res); } catch (SessionExpiredException e) { mav = new ModelAndView("jsonView-ex", "model", "{'valid':false}"); System.out.println(e.getMessage()); } catch (Exception e) { mav = new ModelAndView("jsonView-ex", "model", "{'valid':true,data:{success:false,errmsg:'" + e.getMessage() + "'}}"); System.out.println(e.getMessage()); } return mav; }
From source file:com.drevelopment.couponcodes.bukkit.updater.Updater.java
/** * Make a connection to the BukkitDev API and request the newest file's details. * * @return true if successful.//from w ww . ja va2 s.c om */ private boolean read() { try { final URLConnection conn = this.url.openConnection(); conn.setConnectTimeout(5000); if (this.apiKey != null) { conn.addRequestProperty("X-API-Key", this.apiKey); } conn.addRequestProperty("User-Agent", Updater.USER_AGENT); conn.setDoOutput(true); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); final String response = reader.readLine(); final JSONArray array = (JSONArray) JSONValue.parse(response); if (array.isEmpty()) { this.plugin.getLogger() .warning("The updater could not find any files for the project id " + this.id); this.result = UpdateResult.FAIL_BADID; return false; } JSONObject latestUpdate = (JSONObject) array.get(array.size() - 1); this.versionName = (String) latestUpdate.get(Updater.TITLE_VALUE); this.versionLink = (String) latestUpdate.get(Updater.LINK_VALUE); this.versionType = (String) latestUpdate.get(Updater.TYPE_VALUE); this.versionGameVersion = (String) latestUpdate.get(Updater.VERSION_VALUE); return true; } catch (final IOException e) { if (e.getMessage().contains("HTTP response code: 403")) { this.plugin.getLogger() .severe("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml"); this.plugin.getLogger().severe("Please double-check your configuration to ensure it is correct."); this.result = UpdateResult.FAIL_APIKEY; } else { this.plugin.getLogger().severe("The updater could not contact dev.bukkit.org for updating."); this.plugin.getLogger().severe( "If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime."); this.result = UpdateResult.FAIL_DBO; } this.plugin.getLogger().log(Level.SEVERE, null, e); return false; } }
From source file:org.xbmc.jsonrpc.Connection.java
/** * Executes a query./*from ww w . j a va 2s . co m*/ * @param command Name of the command to execute * @param parameters Parameters * @param manager Reference back to business layer * @return Parsed JSON object, empty object on error. */ public JsonNode query(String command, JsonNode parameters, INotifiableManager manager) { URLConnection uc = null; try { final ObjectMapper mapper = Client.MAPPER; if (mUrlSuffix == null) { throw new NoSettingsException(); } final URL url = new URL(mUrlSuffix + XBMC_JSONRPC_BOOTSTRAP); uc = url.openConnection(); uc.setConnectTimeout(SOCKET_CONNECTION_TIMEOUT); uc.setReadTimeout(mSocketReadTimeout); if (authEncoded != null) { uc.setRequestProperty("Authorization", "Basic " + authEncoded); } uc.setRequestProperty("Content-Type", "application/json"); uc.setDoOutput(true); final ObjectNode data = Client.obj().p("jsonrpc", "2.0").p("method", command).p("id", "1"); if (parameters != null) { data.put("params", parameters); } final JsonFactory jsonFactory = new JsonFactory(); final JsonGenerator jg = jsonFactory.createJsonGenerator(uc.getOutputStream(), JsonEncoding.UTF8); jg.setCodec(mapper); // POST data jg.writeTree(data); jg.flush(); final JsonParser jp = jsonFactory.createJsonParser(uc.getInputStream()); jp.setCodec(mapper); final JsonNode ret = jp.readValueAs(JsonNode.class); return ret; } catch (MalformedURLException e) { manager.onError(e); } catch (IOException e) { int responseCode = -1; try { responseCode = ((HttpURLConnection) uc).getResponseCode(); } catch (IOException e1) { } // do nothing, getResponse code failed so treat as default i/o exception. if (uc != null && responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) { manager.onError(new HttpException(Integer.toString(HttpURLConnection.HTTP_UNAUTHORIZED))); } else { manager.onError(e); } } catch (NoSettingsException e) { manager.onError(e); } return new ObjectNode(null); }
From source file:junk.gui.HazardDataSetCalcCondorApp.java
/** * this connects to the servlet on web server to check if dataset name already exists * or computation have already been for these parameter settings. * @return// ww w . j a va2 s. c o m */ private Object checkForHazardMapComputation() { try { if (D) System.out.println("starting to make connection with servlet"); URL hazardMapServlet = new URL(DATASET_CHECK_SERVLET_URL); URLConnection servletConnection = hazardMapServlet.openConnection(); if (D) System.out.println("connection established"); // inform the connection that we will send output and accept input servletConnection.setDoInput(true); servletConnection.setDoOutput(true); // Don't use a cached version of URL connection. servletConnection.setUseCaches(false); servletConnection.setDefaultUseCaches(false); // Specify the content type that we will send binary data servletConnection.setRequestProperty("Content-Type", "application/octet-stream"); ObjectOutputStream toServlet = new ObjectOutputStream(servletConnection.getOutputStream()); //sending the parameters info. to the servlet toServlet.writeObject(getParametersInfo()); //sending the dataset id to the servlet toServlet.writeObject(datasetIdText.getText()); toServlet.flush(); toServlet.close(); // Receive the datasetnumber from the servlet after it has received all the data ObjectInputStream fromServlet = new ObjectInputStream(servletConnection.getInputStream()); Object obj = fromServlet.readObject(); //if(D) System.out.println("Receiving the Input from the Servlet:"+success); fromServlet.close(); return obj; } catch (Exception e) { ExceptionWindow bugWindow = new ExceptionWindow(this, e, getParametersInfo()); bugWindow.setVisible(true); bugWindow.pack(); } return null; }