List of usage examples for java.net URLConnection setRequestProperty
public void setRequestProperty(String key, String value)
From source file:com.ibm.iotf.sample.devicemgmt.device.HTTPFirmwareDownload.java
public String downloadFirmware() { System.out.println(CLASS_NAME + ": Firmware Download start..."); boolean success = false; URL firmwareURL = null;//from ww w . ja va 2s .com URLConnection urlConnection = null; String downloadedFirmwareName = null; Properties props = new Properties(); try { props.load(HTTPFirmwareDownload.class.getResourceAsStream(PROPERTIES_FILE_NAME)); } catch (IOException e1) { System.err.println("Not able to read the properties file, exiting.."); System.exit(-1); } String username = trimedValue(props.getProperty("User-Name")); String password = trimedValue(props.getProperty("Password")); String dbName = trimedValue(props.getProperty("Repository-DB")); /** * start downloading the firmware image */ try { System.out.println(CLASS_NAME + ": Downloading Firmware from URL " + deviceFirmware.getUrl()); firmwareURL = new URL(deviceFirmware.getUrl()); urlConnection = firmwareURL.openConnection(); byte[] encoding = Base64.encodeBase64(new String(username + ":" + password).getBytes()); String encodedString = "Basic " + new String(encoding); urlConnection.setRequestProperty("Authorization", encodedString); int fileSize = urlConnection.getContentLength(); if (deviceFirmware.getName() != null && !"".equals(deviceFirmware.getName())) { downloadedFirmwareName = deviceFirmware.getName(); } else { // use the timestamp as the name downloadedFirmwareName = "firmware_" + new Date().getTime() + ".deb"; } File file = new File(downloadedFirmwareName); BufferedInputStream bis = new BufferedInputStream(urlConnection.getInputStream()); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file.getName())); // count the download size to send the progress report as DiagLog to Watson IoT Platform int downloadedSize = 0; int data = bis.read(); downloadedSize += 1; if (data != -1) { bos.write(data); byte[] block = new byte[1024 * 10]; int previousProgress = 0; while (true) { int len = bis.read(block, 0, block.length); downloadedSize = downloadedSize + len; if (len != -1) { // Send the progress update if (fileSize > 0) { int progress = (int) (((float) downloadedSize / fileSize) * 100); if (progress > previousProgress) { String message = "Firmware Download progress: " + progress + "%"; addDiagLog(message, new Date(), LogSeverity.informational); System.out.println(message); } } else { // If we can't retrieve the filesize, let us update how much we have download so far String message = "Downloaded : " + downloadedSize + " bytes so far"; addDiagLog(message, new Date(), LogSeverity.informational); System.out.println(message); } bos.write(block, 0, len); } else { break; } } bos.close(); bis.close(); success = true; } else { //There is no data to read, so throw an exception if (requirePlatformUpdate) { deviceFirmware.setUpdateStatus(FirmwareUpdateStatus.INVALID_URI); } } // Verify the firmware image if verifier is set if (deviceFirmware.getVerifier() != null && !deviceFirmware.getVerifier().equals("")) { success = verifyFirmware(file, deviceFirmware.getVerifier()); /** * As per the documentation, If a firmware verifier has been set, the device should * attempt to verify the firmware image. * * If the image verification fails, mgmt.firmware.state should be set to 0 (Idle) * and mgmt.firmware.updateStatus should be set to the error status value 4 (Verification Failed). */ if (success == false) { if (requirePlatformUpdate) { deviceFirmware.setUpdateStatus(FirmwareUpdateStatus.VERIFICATION_FAILED); } // the firmware state is updated to IDLE below } } } catch (MalformedURLException me) { // Invalid URL, so set the status to reflect the same, if (requirePlatformUpdate) { deviceFirmware.setUpdateStatus(FirmwareUpdateStatus.INVALID_URI); } me.printStackTrace(); } catch (IOException e) { if (requirePlatformUpdate) { deviceFirmware.setUpdateStatus(FirmwareUpdateStatus.CONNECTION_LOST); } e.printStackTrace(); } catch (OutOfMemoryError oom) { if (requirePlatformUpdate) { deviceFirmware.setUpdateStatus(FirmwareUpdateStatus.OUT_OF_MEMORY); } } /** * Set the firmware download and possibly the firmware update status * (will be sent later) accordingly */ if (success == true) { if (requirePlatformUpdate) { deviceFirmware.setUpdateStatus(FirmwareUpdateStatus.SUCCESS); deviceFirmware.setState(FirmwareState.DOWNLOADED); } } else { if (requirePlatformUpdate) { deviceFirmware.setState(FirmwareState.IDLE); } return null; } System.out.println(CLASS_NAME + ": Firmware Download END...(" + success + ")"); return downloadedFirmwareName; }
From source file:org.jab.docsearch.spider.LinkFinder.java
/** * Get all links from page/*from w w w .j av a 2 s . c o m*/ */ public void getAllLinks() { // writes links from a page out to a file String urlStr = pageName; String shortUrl = ""; numUnChanged = 0; numSkips = 0; int numSuccesses = 0; int numFailed = 0; int numNoRobots = 0; addLink(urlStr); domainUrl = Utils.getDomainURL(urlStr); if (logger.isDebugEnabled()) { logger.debug("getAllLinks() domain url='" + domainUrl + "'"); } SpiderUrl curl = new SpiderUrl(urlStr); baseUrlFolder = Utils.getBaseURLFolder(urlStr); int curLinkNo = 0; boolean completedSpider = false; boolean isDead = false; int curPread = 0; if (ds != null) { ds.setIsWorking(true); ds.setProgressMax(maxLinksToFind); ds.setCurProgressMSG("Spidering Files..."); } int numSpidered = 0; int curSuccessNo = 0; // start spider while (curLinkNo != -1) { BufferedInputStream urlStream = null; FileOutputStream fileOutStream = null; try { completedSpider = false; isDead = false; if (ds != null) { ds.setCurProgress(curPread); if (!ds.getIsWorking()) { break; } } curLinkNo = getNextUrlNo(); if (curLinkNo == -1) { logger.debug("getAllLinks() end of links reached."); break; } else { urlStr = getLinkNameByNo(curLinkNo); logger.info("getAllLinks() analyzing page='" + urlStr + "'"); curl = getSpiderUrl(curLinkNo); } shortUrl = Utils.concatEnd(urlStr, 33); setStatus(I18n.getString("connecting_to") + " " + shortUrl); // open url URL url = new URL(urlStr); URLConnection conn = url.openConnection(); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestProperty("User-Agent", "DocSearcher " + I18n.getString("ds.version")); conn.connect(); urlStream = new BufferedInputStream(conn.getInputStream()); // filesize int fileSize = conn.getContentLength(); if (fileSize > maxFileSizeToGet) { String ex = I18n.getString("skipping_file_too_big") + " (" + fileSize + " > " + maxFileSizeToGet + ") " + shortUrl; setStatus(ex); throw new Exception(ex); } setStatus(I18n.getString("downloading_uc") + "... " + shortUrl + " " + fileSize + " " + I18n.getString("bytes")); curl.setSize(fileSize); // last modified long curModified = conn.getLastModified(); // was .getDate(); curl.setLastModified(curModified); // content type String curContentType = netUtils.getContentType(conn); curl.setContentType(curContentType); // build the value for downloadFile String dnldTmpName = getDownloadFileName(curl.getContentType(), urlStr.toLowerCase()); String downloadFile = FileUtils.addFolder(downloadFileDir, dnldTmpName); // TODO it is better to use content type! boolean curIsWebPage = isHtml(urlStr.toLowerCase()) || (curContentType.toLowerCase().indexOf("html") != -1); logger.debug("getAllLinks() saving to " + downloadFile); fileOutStream = new FileOutputStream(downloadFile); int curSize = 0; int curI; int lastPercent = 0; StringBuilder tag = new StringBuilder(); String link = null; boolean inTag = false; boolean getFileSizeFromStream = false; if (fileSize == -1) { getFileSizeFromStream = true; } while ((curI = urlStream.read()) != -1) { fileOutStream.write(curI); curSize++; if (ds != null) { if (!ds.getIsWorking()) { break; } } // fix problem if filesize not in content length if (getFileSizeFromStream) { fileSize = curSize + urlStream.available(); } // notify of download progress if (curSize > 0 && (curSize % 10) == 0) { int curPercent = (curSize * 100) / fileSize; if (curPercent != lastPercent) { lastPercent = curPercent; setStatus(I18n.getString("downloading_uc") + "... : (" + shortUrl + ") --> " + curPercent + " %" + " ( " + (numSuccesses + numFailed + numNoRobots) + "/" + getNumLinksFound() + ")"); } } // end for percent updates else if (curSize % 40 == 0) { setStatus(I18n.getString("downloading_uc") + "... : (" + shortUrl + ") --> " + curSize + " " + I18n.getString("bytes")); } // handle links if (curIsWebPage) { char c = (char) curI; // LOOK AT THE TAGS // start tag if (c == '<') { inTag = true; tag = new StringBuilder(); } // end tag else if (c == '>') { inTag = false; tag.append(c); String realTag = tag.toString(); String lowerTag = realTag.toLowerCase(); // TODO fix problem with spaces before = // link if (lowerTag.startsWith("<a ")) { link = Utils.getTagString("href=", realTag); link = Utils.getNormalUrl(link); doPossibleAdd(urlStr, link); } // area else if (lowerTag.startsWith("<area")) { link = Utils.getTagString("href=", realTag); link = Utils.getNormalUrl(link); doPossibleAdd(urlStr, link); } // TODO is in param realy a link? else if (lowerTag.startsWith("<param")) { String appletParam = Utils.getTagString("name=", realTag); if (appletParam.toLowerCase().equals("url")) { link = Utils.getTagString("value=", realTag); link = Utils.getNormalUrl(link); doPossibleAdd(urlStr, link); } } } // in tag if (inTag) { tag.append(c); } } // filesize ok if (getFileSizeFromStream && fileSize > maxFileSizeToGet) { break; } } // end while downloading curPread++; fileOutStream.close(); urlStream.close(); curl.setMd5(FileUtils.getMD5Sum(downloadFile)); // now add out document if (ds != null) { curSuccessNo = ds.idx.addDocToIndex(downloadFile, iw, dsi, false, curl); switch (curSuccessNo) { case 0: // good numSuccesses++; break; case 1: // bad numFailed++; break; case 2: // meta robots - no index numNoRobots++; break; } } // delete temp file if (!FileUtils.deleteFile(downloadFile)) { logger.warn("getAllLinks() can't delete file '" + downloadFile + "'"); } numSpidered++; completedSpider = true; // max links found if (numSpidered > maxLinksToFind) { break; } } catch (Exception e) { logger.fatal("getAllLinks() failed", e); setStatus(I18n.getString("error") + " : " + e.toString()); isDead = true; } finally { // close resources IOUtils.closeQuietly(urlStream); IOUtils.closeQuietly(fileOutStream); curl.setSpidered(completedSpider); curl.setIsDeadLink(isDead); setStatus(I18n.getString("download_complete") + " " + shortUrl); } } // end for iterating over links if (ds != null) { ds.resetProgress(); } saveAllLinks(); logger.info("getAllLinks() " + numSpidered + " total web pages spidered for links."); showMessage(I18n.getString("spidering_complete") + " (" + Utils.concatStrToEnd(pageName, 28) + ") ", numSpidered + " " + I18n.getString("documents_indexed") + " " + getNumLinksFound() + " " + I18n.getString("links_found") + "\n\n" + numSuccesses + " " + I18n.getString("documents_spidered_successful") + "\n\n" + numFailed + " " + I18n.getString("documents_spidered_failed") + "\n\n" + numNoRobots + " " + I18n.getString("documents_not_spidered")); }
From source file:net.sf.taverna.t2.workbench.ui.impl.UserRegistrationForm.java
/** * Post registration data to our server. *//*from w ww . j a va2 s . c om*/ private boolean postUserRegistrationDataToServer(UserRegistrationData regData) { StringBuilder parameters = new StringBuilder(); /* * The 'submit' parameter - to let the server-side script know we are * submitting the user's registration form - all other requests will be * silently ignored */ try { // value does not matter enc(parameters, TAVERNA_REGISTRATION_POST_PARAMETER_NAME, "submit"); enc(parameters, TAVERNA_VERSION_POST_PARAMETER_NAME, regData.getTavernaVersion()); enc(parameters, FIRST_NAME_POST_PARAMETER_NAME, regData.getFirstName()); enc(parameters, LAST_NAME_POST_PARAMETER_NAME, regData.getLastName()); enc(parameters, EMAIL_ADDRESS_POST_PARAMETER_NAME, regData.getEmailAddress()); enc(parameters, KEEP_ME_INFORMED_POST_PARAMETER_PROPERTY_NAME, regData.getKeepMeInformed()); enc(parameters, INSTITUTION_OR_COMPANY_POST_PARAMETER_NAME, regData.getInstitutionOrCompanyName()); enc(parameters, INDUSTRY_TYPE_POST_PARAMETER_NAME, regData.getIndustry()); enc(parameters, FIELD_POST_PARAMETER_NAME, regData.getField()); enc(parameters, PURPOSE_POST_PARAMETER_NAME, regData.getPurposeOfUsingTaverna()); } catch (UnsupportedEncodingException ueex) { logger.error(FAILED + "Could not url encode post parameters", ueex); showMessageDialog(null, REGISTRATION_FAILED_MSG, "Error encoding registration data", ERROR_MESSAGE); return false; } String server = REGISTRATION_URL; logger.info("Posting user registartion to " + server + " with parameters: " + parameters); String response = ""; String failure; try { URL url = new URL(server); URLConnection conn = url.openConnection(); /* * Set timeout to e.g. 7 seconds, otherwise we might hang too long * if server is not responding and it will block Taverna */ conn.setConnectTimeout(7000); // Set connection parameters conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); // Make server believe we are HTML form data... conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // Write out the bytes of the content string to the stream. try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) { out.writeBytes(parameters.toString()); out.flush(); } // Read response from the input stream. try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) { String temp; while ((temp = in.readLine()) != null) response += temp + "\n"; // Remove the last \n character if (!response.isEmpty()) response = response.substring(0, response.length() - 1); } if (response.equals("Registration successful!")) return true; logger.error(FAILED + "Response form server was: " + response); failure = "Error saving registration data on the server"; } catch (ConnectException ceex) { /* * the connection was refused remotely (e.g. no process is listening * on the remote address/port). */ logger.error(FAILED + "Registration server is not listening of the specified url.", ceex); failure = "Registration server is not listening at the specified url"; } catch (SocketTimeoutException stex) { // timeout has occurred on a socket read or accept. logger.error(FAILED + "Socket timeout occurred.", stex); failure = "Registration server timeout"; } catch (MalformedURLException muex) { logger.error(FAILED + "Registartion server's url is malformed.", muex); failure = "Error with registration server's url"; } catch (IOException ioex) { logger.error( FAILED + "Failed to open url connection to registration server or writing/reading to/from it.", ioex); failure = "Error opening connection to the registration server"; } showMessageDialog(null, REGISTRATION_FAILED_MSG, failure, ERROR_MESSAGE); return false; }
From source file:org.apache.jsp.fileUploader_jsp.java
private String UpdateToShare(byte[] bytes, String mimeType, String title, String description, String prevId, Set<String> communities, boolean isJson, String type, boolean newShare, HttpServletRequest request, HttpServletResponse response) {//from w w w .ja va 2s . c o m String charset = "UTF-8"; String url = ""; try { if (isJson) { //first check if bytes are actually json try { new JsonParser().parse(new String(bytes)); } catch (Exception ex) { return "Failed, file was not valid JSON"; } if (newShare) url = API_ROOT + "social/share/add/json/" + URLEncoder.encode(type, charset) + "/" + URLEncoder.encode(title, charset) + "/" + URLEncoder.encode(description, charset) + "/"; else url = API_ROOT + "social/share/update/json/" + prevId + "/" + URLEncoder.encode(type, charset) + "/" + URLEncoder.encode(title, charset) + "/" + URLEncoder.encode(description, charset) + "/"; } else { if (newShare) url = API_ROOT + "social/share/add/binary/" + URLEncoder.encode(title, charset) + "/" + URLEncoder.encode(description, charset) + "/"; else url = API_ROOT + "social/share/update/binary/" + prevId + "/" + URLEncoder.encode(title, charset) + "/" + URLEncoder.encode(description, charset) + "/"; } if (localCookie) CookieHandler.setDefault(cm); URLConnection connection = new URL(url).openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Accept-Charset", charset); String cookieVal = getBrowserInfiniteCookie(request); if (cookieVal != null) { connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestProperty("Accept-Charset", "UTF-8"); } if (mimeType != null && mimeType.length() > 0) connection.setRequestProperty("Content-Type", mimeType + ";charset=" + charset); DataOutputStream output = new DataOutputStream(connection.getOutputStream()); output.write(bytes); DataInputStream responseStream = new DataInputStream(connection.getInputStream()); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; while ((nRead = responseStream.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } String json = buffer.toString(); String newCookie = getConnectionInfiniteCookie(connection); if (newCookie != null && response != null) { setBrowserInfiniteCookie(response, newCookie, request.getServerPort()); } buffer.flush(); buffer.close(); output.close(); responseStream.close(); if (isJson) { jsonResponse jr = new Gson().fromJson(json, jsonResponse.class); if (jr == null) { return "Failed: " + json; } if (jr.response.success == true) { if (jr.data != null && jr.data._id != null) { addRemoveCommunities(jr.data._id, communities, request, response); return jr.data._id; //When a new upload, mr.data contains the ShareID for the upload } } return "Upload Failed: " + jr.response.message; } else { modResponse mr = new Gson().fromJson(json, modResponse.class); if (mr == null) { return "Failed: " + json; } if (mr.response.success == true) { if (prevId != null && mr.data == null) { addRemoveCommunities(prevId, communities, request, response); return prevId; } else { addRemoveCommunities(mr.data, communities, request, response); return mr.data; //When a new upload, mr.data contains the ShareID for the upload } } else { return "Upload Failed: " + mr.response.message; } } } catch (IOException e) { e.printStackTrace(); return "Upload Failed: " + e.getMessage(); } }
From source file:org.sunnycode.zkws.socketio.impl.IOConnection.java
/** * Handshake.//from w w w. j a va2 s. c o m * */ private void handshake() { URL url; String response; URLConnection connection; try { setState(STATE_HANDSHAKE); url = new URL(IOConnection.this.url.toString() + SOCKET_IO_1); connection = url.openConnection(); if (connection instanceof HttpsURLConnection) { ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory()); } connection.setConnectTimeout(connectTimeout); connection.setReadTimeout(connectTimeout); /* Setting the request headers */ for (Entry<Object, Object> entry : headers.entrySet()) { connection.setRequestProperty((String) entry.getKey(), (String) entry.getValue()); } InputStream stream = connection.getInputStream(); Scanner in = new Scanner(stream); response = in.nextLine(); String[] data = response.split(":"); sessionId = data[0]; heartbeatTimeout = Long.parseLong(data[1]) * 1000; closingTimeout = Long.parseLong(data[2]) * 1000; protocols = Arrays.asList(data[3].split(",")); } catch (Exception e) { error(new SocketIOException("Error while handshaking", e)); } }
From source file:com.example.socketio.lib.IOConnection.java
/** * Handshake.// w ww. j a va2 s . c om * */ private void handshake() { URL url; String response; URLConnection connection; try { setState(STATE_HANDSHAKE); url = new URL(IOConnection.this.url.toString() + SOCKET_IO_1); connection = url.openConnection(); if (connection instanceof HttpsURLConnection) { ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory()); } connection.setConnectTimeout(connectTimeout); connection.setReadTimeout(connectTimeout); /* Setting the request headers */ for (Entry<Object, Object> entry : headers.entrySet()) { connection.setRequestProperty((String) entry.getKey(), (String) entry.getValue()); } InputStream stream = connection.getInputStream(); Scanner in = new Scanner(stream); response = in.nextLine(); String[] data = response.split(":"); sessionId = data[0]; heartbeatTimeout = Long.parseLong(data[1]) * 1000; closingTimeout = Long.parseLong(data[2]) * 1000; protocols = Arrays.asList(data[3].split(",")); } catch (Exception e) { error(new SocketIOException("Error while handshaking", e)); SendErrorMessageWithBroadcast(SocketIOAction.SOCKETIO_ERRORMESSAGE_ERRORHANDSHAKING); } }
From source file:com.freedomotic.plugins.devices.ipx800.Ipx800.java
private void sendToBoard(Board board, Command c) throws IOException { try {/*from w w w. j a va2s . co m*/ URL url = null; URLConnection urlConnection; String delimiter = configuration.getProperty("address-delimiter"); String[] address = c.getProperty("address").split(delimiter); Integer relayNumber = Integer.parseInt(address[1]) - 1; if (c.getProperty("command").equals("CHANGE-STATE-DIGITAL-INPUT")) { relayNumber = relayNumber + 100; } // if required set the authentication if (board.getAuthentication().equalsIgnoreCase("true")) { String authString = board.getUsername() + ":" + board.getPassword(); byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); String authStringEnc = new String(authEncBytes); //Create a URL for the desired page url = new URL( "http://" + board.getIpAddress() + ":" + board.getPort() + board.getPathAuthentication() + "/" + CHANGE_STATE_RELAY_URL + relayNumber + "=" + c.getProperty("state-value")); urlConnection = url.openConnection(); urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc); } else { //Create a URL for the desired page url = new URL("http://" + board.getIpAddress() + ":" + board.getPort() + "/" + CHANGE_STATE_RELAY_URL + relayNumber + "=" + c.getProperty("state-value")); urlConnection = url.openConnection(); } LOG.info("Freedomotic sends the command " + url); InputStream is = urlConnection.getInputStream(); InputStreamReader isr = new InputStreamReader(is); int numCharsRead; char[] charArray = new char[1024]; StringBuffer sb = new StringBuffer(); while ((numCharsRead = isr.read(charArray)) > 0) { sb.append(charArray, 0, numCharsRead); } String result = sb.toString(); } catch (MalformedURLException e) { LOG.error("Command malformed URL " + e.toString()); } catch (IOException e) { LOG.error("Command IOexception" + e.toString()); } }
From source file:com.freedomotic.plugins.devices.phwswethv2.ProgettiHwSwEthv2.java
private void toggleRelay(Board board, Command c) { try {/* www. j a v a 2 s .co m*/ URL url = null; URLConnection urlConnection; String delimiter = configuration.getProperty("address-delimiter"); String[] address = c.getProperty("address").split(delimiter); String relayNumber = address[1]; int time = Integer.parseInt(c.getProperty("time-in-ms")); int seconds = time / 1000; String relayLine = configuration.getProperty("TOGGLE" + seconds + "S" + relayNumber); // if required set the authentication if (board.getAuthentication().equalsIgnoreCase("true")) { String authString = board.getUsername() + ":" + board.getPassword(); byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); String authStringEnc = new String(authEncBytes); //Create a URL for the desired page url = new URL("http://" + board.getIpAddress() + ":" + board.getPort() + "/protect/" + TOGGLE_RELAY_URL + relayLine); urlConnection = url.openConnection(); urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc); } else { //Create a URL for the desired page url = new URL("http://" + board.getIpAddress() + ":" + board.getPort() + "/" + TOGGLE_RELAY_URL + relayLine); urlConnection = url.openConnection(); } LOG.info("Freedomotic sends the command " + url); InputStream is = urlConnection.getInputStream(); InputStreamReader isr = new InputStreamReader(is); int numCharsRead; char[] charArray = new char[1024]; StringBuffer sb = new StringBuffer(); while ((numCharsRead = isr.read(charArray)) > 0) { sb.append(charArray, 0, numCharsRead); } String result = sb.toString(); } catch (MalformedURLException e) { LOG.severe("Change relay status malformed URL " + e.toString()); } catch (IOException e) { LOG.severe("Change relay status IOexception" + e.toString()); } }
From source file:org.signserver.client.cli.defaultimpl.TimeStampCommand.java
@SuppressWarnings("SleepWhileInLoop") // We are just using the sleep for rate limiting private void tsaRequest() throws Exception { final Random rand = new Random(); final TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator(); boolean doRun = true; do {/*from ww w. j a v a 2s .co m*/ final int nonce = rand.nextInt(); byte[] digest = new byte[20]; if (instring != null) { final byte[] digestBytes = instring.getBytes("UTF-8"); final MessageDigest dig = MessageDigest.getInstance(TSPAlgorithms.SHA1.getId(), "BC"); dig.update(digestBytes); digest = dig.digest(); // When we have given input, we don't want to loop doRun = false; } if (infilestring != null) { // TSPAlgorithms constants changed from Strings to ASN1Encoded objects digest = digestFile(infilestring, TSPAlgorithms.SHA1.getId()); doRun = false; } final byte[] hexDigest = Hex.encode(digest); if (LOG.isDebugEnabled()) { LOG.debug("MessageDigest=" + new String(hexDigest)); } final TimeStampRequest timeStampRequest; if (inreqstring == null) { LOG.debug("Generating a new request"); timeStampRequestGenerator.setCertReq(certReq); if (reqPolicy != null) { timeStampRequestGenerator.setReqPolicy(new ASN1ObjectIdentifier(reqPolicy)); } timeStampRequest = timeStampRequestGenerator.generate(TSPAlgorithms.SHA1, digest, BigInteger.valueOf(nonce)); } else { LOG.debug("Reading request from file"); timeStampRequest = new TimeStampRequest(readFiletoBuffer(inreqstring)); } final byte[] requestBytes = timeStampRequest.getEncoded(); if (outreqstring != null) { // Store request byte[] outBytes; if (base64) { outBytes = Base64.encode(requestBytes); } else { outBytes = requestBytes; } FileOutputStream fos = null; try { fos = new FileOutputStream(outreqstring); fos.write(outBytes); } finally { if (fos != null) { fos.close(); } } } keyStoreOptions.setupHTTPS(); URL url; URLConnection urlConn; DataOutputStream printout; DataInputStream input; url = new URL(urlstring); // Take start time final long startMillis = System.currentTimeMillis(); final long startTime = System.nanoTime(); if (LOG.isDebugEnabled()) { LOG.debug("Sending request at: " + startMillis); } urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/timestamp-query"); // Send POST output. printout = new DataOutputStream(urlConn.getOutputStream()); printout.write(requestBytes); printout.flush(); printout.close(); // Get response data. input = new DataInputStream(urlConn.getInputStream()); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); int b; while ((b = input.read()) != -1) { baos.write(b); } // Take stop time final long estimatedTime = System.nanoTime() - startTime; LOG.info("Got reply after " + TimeUnit.NANOSECONDS.toMillis(estimatedTime) + " ms"); final byte[] replyBytes = baos.toByteArray(); if (outrepstring != null) { // Store request byte[] outBytes; if (base64) { outBytes = Base64.encode(replyBytes); } else { outBytes = replyBytes; } FileOutputStream fos = null; try { fos = new FileOutputStream(outrepstring); fos.write(outBytes); } finally { if (fos != null) { fos.close(); } } } final TimeStampResponse timeStampResponse = new TimeStampResponse(replyBytes); timeStampResponse.validate(timeStampRequest); LOG.info("TimeStampRequest validated"); if (LOG.isDebugEnabled()) { final Date genTime; if (timeStampResponse.getTimeStampToken() != null && timeStampResponse.getTimeStampToken().getTimeStampInfo() != null) { genTime = timeStampResponse.getTimeStampToken().getTimeStampInfo().getGenTime(); } else { genTime = null; } LOG.debug("(Status: " + timeStampResponse.getStatus() + ", " + timeStampResponse.getFailInfo() + "): " + timeStampResponse.getStatusString() + (genTime != null ? (", genTime: " + genTime.getTime()) : "") + "\n"); } if (doRun) { Thread.sleep(sleep); } } while (doRun); }
From source file:com.remobile.filetransfer.FileTransfer.java
private static void addHeadersToRequest(URLConnection connection, JSONObject headers) { try {//from ww w . j av a 2s . c o m for (Iterator<?> iter = headers.keys(); iter.hasNext();) { /* RFC 2616 says that non-ASCII characters and control * characters are not allowed in header names or values. * Additionally, spaces are not allowed in header names. * RFC 2046 Quoted-printable encoding may be used to encode * arbitrary characters, but we donon- not do that encoding here. */ String headerKey = iter.next().toString(); String cleanHeaderKey = headerKey.replaceAll("\\n", "").replaceAll("\\s+", "").replaceAll(":", "") .replaceAll("[^\\x20-\\x7E]+", ""); JSONArray headerValues = headers.optJSONArray(headerKey); if (headerValues == null) { headerValues = new JSONArray(); /* RFC 2616 also says that any amount of consecutive linear * whitespace within a header value can be replaced with a * single space character, without affecting the meaning of * that value. */ String headerValue = headers.getString(headerKey); String finalValue = headerValue.replaceAll("\\s+", " ").replaceAll("\\n", " ") .replaceAll("[^\\x20-\\x7E]+", " "); headerValues.put(finalValue); } //Use the clean header key, not the one that we passed in connection.setRequestProperty(cleanHeaderKey, headerValues.getString(0)); for (int i = 1; i < headerValues.length(); ++i) { connection.addRequestProperty(headerKey, headerValues.getString(i)); } } } catch (JSONException e1) { // No headers to be manipulated! } }