List of usage examples for java.net MalformedURLException printStackTrace
public void printStackTrace()
From source file:com.smartbear.postman.PostmanImporter.java
private RestRequest addRestRequest(WsdlProject project, String serviceName, String method, String uri, String headers) {/*from w w w. j a va 2s. com*/ RestRequest currentRequest = null; PostmanRestServiceBuilder builder = new PostmanRestServiceBuilder(); try { currentRequest = builder.createRestServiceFromPostman(project, uri, RestRequestInterface.HttpMethod.valueOf(method), headers); } catch (MalformedURLException e) { e.printStackTrace(); } return currentRequest; }
From source file:com.gottibujiku.httpjsonexchange.main.HttpJSONExchange.java
/** * This method sends a POST request to the server. * // ww w.j a v a 2 s. c o m * @param fullDomainName a fully qualified domain name including the protocol * @param queryParams parameters to be sent in the query string * @param headers additional headers * @return a JSON object containing the response */ public JSONObject sendPOSTRequest(String fullDomainName, HashMap<String, String> queryParams, HashMap<String, String> headers) { /* 1. Form the query string by concatenating param names and their values * 2. Add HTTP headers to the request and set request method to POST, open output stream and write the query string * 3. Open input stream and read server response * */ if (fullDomainName == null) { throw new NullPointerException("No URL provided! Please provide one!");//No domain name was provided } JSONObject jsonResponse = null; URL url = null;//a url object to hold a complete URL try { url = new URL(fullDomainName);//a complete URL String queryString = getFormatedQueryString(queryParams); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection = addHeadersToRequest(headers, connection);//add headers to connection and get modified instance connection.setDoOutput(true);//enables writing over the open connection connection.setRequestProperty("Accept-Charset", UTF_CHARSET);//accept the given encoding connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + UTF_CHARSET); //a call to connection.connect() is superfluous since connect will be called //implicitly when the stream is opened connection.setRequestMethod("POST"); //open the connection and send the query string in the request body try (PrintWriter writer = new PrintWriter(connection.getOutputStream(), true)) { writer.print(queryString);//send the query string in the request body } String jsonString = getServerResponse(connection); connection.disconnect(); jsonResponse = new JSONObject(jsonString);//change the response into a json object } catch (MalformedURLException e) { e.printStackTrace(); return null;//return if the URL is malformed } catch (IOException e) { e.printStackTrace(); return null;//if failed to open a connection } catch (JSONException e) { e.printStackTrace(); return null;//invalid JSON response } return jsonResponse; }
From source file:com.gottibujiku.httpjsonexchange.main.HttpJSONExchange.java
/** * This method sends a POST request to the server. * /*from w ww .j av a2 s . c o m*/ * @return a JSON object containing the response */ public JSONObject sendPOSTRequest() { /* 1. Form the query string by concatenating param names and their values * 2. Add HTTP headers to the request and set request method to POST, open output stream and write the query string * 3. Open input stream and read server response * */ if (fullDomainName == null) { throw new NullPointerException("No URL provided! Please provide one!");//No domain name was provided } JSONObject jsonResponse = null; URL url = null;//a url object to hold a complete URL try { url = new URL(fullDomainName);//a complete URL String queryString = getFormatedQueryString(queryParams); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection = addHeadersToRequest(headers, connection);//add headers to connection and get modified instance connection.setDoOutput(true);//enables writing over the open connection connection.setRequestProperty("Accept-Charset", UTF_CHARSET);//accept the given encoding connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + UTF_CHARSET); //a call to connection.connect() is superfluous since connect will be called //implicitly when the stream is opened connection.setRequestMethod("POST"); //open the connection and send the query string in the request body try (PrintWriter writer = new PrintWriter(connection.getOutputStream(), true)) { writer.print(queryString);//send the query string in the request body } String jsonString = getServerResponse(connection); connection.disconnect(); jsonResponse = new JSONObject(jsonString);//change the response into a json object } catch (MalformedURLException e) { e.printStackTrace(); return null;//return if the URL is malformed } catch (IOException e) { e.printStackTrace(); return null;//if failed to open a connection } catch (JSONException e) { e.printStackTrace(); return null;//invalid JSON response } return jsonResponse; }
From source file:eu.codeplumbers.cosi.services.CosiFileService.java
private void getAllRemoteFolders() { //File.deleteAllFolders(); URL urlO = null;//from w w w . j a va 2 s .c om try { urlO = new URL(folderUrl); HttpURLConnection conn = (HttpURLConnection) urlO.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setRequestProperty("Authorization", authHeader); conn.setDoInput(true); conn.setRequestMethod("POST"); // read the response int status = conn.getResponseCode(); InputStream in = null; if (status >= HttpURLConnection.HTTP_BAD_REQUEST) { in = conn.getErrorStream(); } else { in = conn.getInputStream(); } StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); String result = writer.toString(); JSONArray jsonArray = new JSONArray(result); if (jsonArray != null) { for (int i = 0; i < jsonArray.length(); i++) { JSONObject folderJson = jsonArray.getJSONObject(i).getJSONObject("value"); File file = File.getByRemoteId(folderJson.get("_id").toString()); if (file == null) { file = new File(folderJson, true); } else { file.setName(folderJson.getString("name")); file.setPath(folderJson.getString("path")); file.setCreationDate(folderJson.getString("creationDate")); file.setLastModification(folderJson.getString("lastModification")); file.setTags(folderJson.getString("tags")); } mBuilder.setProgress(jsonArray.length(), i, false); mBuilder.setContentText("Indexing remote folder : " + file.getName()); mNotifyManager.notify(notification_id, mBuilder.build()); EventBus.getDefault() .post(new FileSyncEvent(SYNC_MESSAGE, "Indexing remote folder : " + file.getName())); file.save(); createFolder(file.getPath(), file.getName()); allFiles.add(file); } } else { EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, "Failed to parse API response")); stopSelf(); } in.close(); conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (ProtocolException e) { e.printStackTrace(); EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (IOException e) { e.printStackTrace(); EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (JSONException e) { e.printStackTrace(); EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } }
From source file:de.codecentric.jira.jenkins.plugin.servlet.OverviewServlet.java
/** * Creates a Jenkins Job List if authorization is required * @return Jenkins Job List//from w ww . j a va 2 s . c o m */ @SuppressWarnings("unchecked") private List<JenkinsJob> getJobListByServerAuth(String urlJenkinsServer, String view, I18nHelper i18nHelper) throws MalformedURLException, DocumentException { List<JenkinsJob> jobList = new ArrayList<JenkinsJob>(); String jobListUrl = urlJenkinsServer + (StringUtils.isNotEmpty(view) ? "view/" + view : "") + "/api/xml?depth=1"; PostMethod post = new PostMethod(jobListUrl); post.setDoAuthentication(true); Document jobsDocument = null; try { client.executeMethod(post); jobsDocument = new SAXReader().read(post.getResponseBodyAsStream()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (SSLException e) { if (e.getMessage().equals("Unrecognized SSL message, plaintext connection?")) { urlJenkinsServer = urlJenkinsServer.replaceFirst("s", ""); this.getJobListByServerAuth(urlJenkinsServer, view, i18nHelper); return jobList; } else { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } finally { post.releaseConnection(); } // if jenkinsUrl is invalid if (jobsDocument == null) { return jobList; } // get all jobs from xml and add them to list for (Element job : (List<Element>) jobsDocument.getRootElement().elements("job")) { // create a new job and set all params from xml JenkinsJob hJob = new JenkinsJob(); String jobName = job.elementText("name"); hJob.setName(jobName); hJob.setUrl(job.elementText("url")); hJob.setBuildTrigger(hJob.getUrl() + "/build"); hJob.setColor(job.elementText("color")); hJob.setLastSuccBuild(createBuildAuth(urlJenkinsServer, jobName, BuildType.LAST_SUCCESS, i18nHelper)); hJob.setLastFailBuild(createBuildAuth(urlJenkinsServer, jobName, BuildType.LAST_FAIL, i18nHelper)); jobList.add(hJob); } return jobList; }
From source file:com.bah.bahdit.main.plugins.imageindex.ImageIndex.java
/** * Search by using an image index table. The query can either be a url, file, * or just text. A url or file will be hashed and searched in the image hash table. * Text will be looked up in the tag table. * //from w ww . ja v a2s. c o m * In the event that a threshold specified in the properties file is in met, fuzzy query * will take over and try and find relevant tags and/or hashes. * * @param strQuery - query specified by the servlet * @param page - the page requested by the servlet (not implemented) * @param resultsPerPage - the number of results requested (not implemented) * * @return a SearchResults object, containing : * - a ArrayList of strings for each image -> loc + "[ ]" + URL * - The total number of results found (not necessarily returned) * - Total time needed to find the results */ @Override public SearchResults search(Object query, int page, int resultsPerPage) { String mainQuery = ""; this.doSimilar = page; long start = System.nanoTime(); HashSet<String> hashRanges; boolean isURL = (query instanceof String) && ((String) query).contains("http://"); // skip straight to hashing if (query instanceof File || isURL) { hashRanges = new HashSet<String>(); try { mainQuery = ImageHasher.hash(query); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } hashRanges.add(mainQuery); } // look through tags before hashing else { mainQuery = (String) query; // create scanner to get image hashes based on tags and IDs BatchScanner tagScanner = createImageTagScanner(); // get a set of the ranges to look through to find the hashes we want hashRanges = getTag(tagScanner, mainQuery); } if (hashRanges == null) return new SearchResults(null, "", 0); // create scanner to get image info based on hashes BatchScanner hashScanner = createHashScanner(); // get the image information and return HashSet<String> results = getHash(hashScanner, hashRanges); // create searchResults based on returned images ArrayList<String> r = new ArrayList<String>(results); int numResults = r.size(); String correction = ""; long elapsedTime = System.nanoTime() - start; SearchResults finalResults = new SearchResults(r, correction, numResults, elapsedTime); return finalResults; }
From source file:com.tinyhydra.botd.sql.SQLInterface.java
private void GetShopDataAndAdd(final String reference) { new Thread() { @Override//from www.j a v a2 s.c om public void run() { try { Properties creds = new Properties(); InputStream inputStream = this.getClass().getClassLoader() .getResourceAsStream("conf/credentials.properties"); creds.load(inputStream); URL url; HttpURLConnection conn; BufferedReader rd; String line; String result = ""; url = new URL("https://maps.googleapis.com/maps/api/place/details/json?reference=" + reference + "&sensor=true&key=" + creds.getProperty("placesapikey")); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = rd.readLine()) != null) { result += line; } rd.close(); JSONObject results = new JSONObject(result); String jstatus = results.getString("status"); if (jstatus.equals("OK")) { JSONObject resultObj = results.getJSONObject("result"); AddShop(resultObj.getString("id"), resultObj.getString("name"), resultObj.getString("url"), resultObj.getString("vicinity"), reference); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }.start(); }
From source file:net.andylizi.colormotd.Updater.java
private boolean checkUpdate() { if (file != null && file.exists()) { cancel();//from w w w .j a v a2 s . co m } URL url; try { url = new URL(UPDATE_URL); } catch (MalformedURLException ex) { if (DEBUG) { ex.printStackTrace(); } return false; } try { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setUseCaches(false); conn.setRequestMethod("GET"); conn.addRequestProperty("User-Agent", userAgent); if (etag != null) { conn.addRequestProperty("If-None-Match", etag); } conn.addRequestProperty("Accept", "application/json,text/plain,*/*;charset=utf-8"); conn.addRequestProperty("Accept-Encoding", "gzip"); conn.addRequestProperty("Cache-Control", "no-cache"); conn.addRequestProperty("Date", new Date().toString()); conn.addRequestProperty("Connection", "close"); conn.setDoInput(true); conn.setDoOutput(false); conn.setConnectTimeout(2000); conn.setReadTimeout(2000); conn.connect(); if (conn.getHeaderField("ETag") != null) { etag = conn.getHeaderField("ETag"); } if (DEBUG) { logger.log(Level.INFO, "DEBUG ResponseCode: {0}", conn.getResponseCode()); logger.log(Level.INFO, "DEBUG ETag: {0}", etag); } if (conn.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) { return false; } else if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { return false; } BufferedReader input = null; if (conn.getContentEncoding() != null && conn.getContentEncoding().contains("gzip")) { input = new BufferedReader( new InputStreamReader(new GZIPInputStream(conn.getInputStream()), "UTF-8"), 1); } else { input = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"), 1); } StringBuilder builder = new StringBuilder(); String buffer = null; while ((buffer = input.readLine()) != null) { builder.append(buffer); } try { JSONObject jsonObj = (JSONObject) new JSONParser().parse(builder.toString()); int build = ((Number) jsonObj.get("build")).intValue(); if (build <= ColorMOTD.buildVersion) { return false; } String version = (String) jsonObj.get("version"); String msg = (String) jsonObj.get("msg"); String download_url = (String) jsonObj.get("url"); newVersion = new NewVersion(version, build, msg, download_url); return true; } catch (ParseException ex) { if (DEBUG) { ex.printStackTrace(); } exception = ex; return false; } } catch (SocketTimeoutException ex) { return false; } catch (IOException ex) { if (DEBUG) { ex.printStackTrace(); } exception = ex; return false; } }
From source file:edu.cmu.cs.in.hoop.hoops.load.HoopFTPReader.java
/** * //from ww w.ja v a 2s. c o m */ private String retrieveFTP(String aURL) { debug("retrieveFTP (" + aURL + ")"); URL urlObject = null; try { urlObject = new URL(aURL); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } String downloadPath = this.projectToFullPath("<PROJECTPATH>/tmp/download/"); HoopLink.fManager.createDirectory(downloadPath); File translator = new File(urlObject.getFile()); String localFileName = "<PROJECTPATH>/tmp/download/" + translator.getName(); OutputStream fileStream = null; if (HoopLink.fManager.openStreamBinary(this.projectToFullPath(localFileName)) == false) { this.setErrorString("Error opening temporary output file"); return (null); } fileStream = HoopLink.fManager.getOutputStreamBinary(); if (fileStream == null) { this.setErrorString("Error opening temporary output file"); return (null); } debug("Starting FTP client ..."); FTPClient ftp = new FTPClient(); try { int reply; debug("Connecting ..."); ftp.connect(urlObject.getHost()); debug("Connected to " + urlObject.getHost() + "."); debug(ftp.getReplyString()); // After connection attempt, you should check the reply code to verify // success. reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); debug("FTP server refused connection."); return (null); } else { ftp.login("anonymous", "hoop-dev@gmail.com"); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); debug("Unable to login to FTP server"); return (null); } debug("Logged in"); boolean rep = true; String pathFixed = translator.getParent().replace("\\", "/"); rep = ftp.changeWorkingDirectory(pathFixed); if (rep == false) { debug("Unable to change working directory to: " + pathFixed); return (null); } else { debug("Current working directory: " + pathFixed); debug("Retrieving file " + urlObject.getFile() + " ..."); try { rep = ftp.retrieveFile(urlObject.getFile(), fileStream); } catch (FTPConnectionClosedException connEx) { debug("Caught: FTPConnectionClosedException"); connEx.printStackTrace(); return (null); } catch (CopyStreamException strEx) { debug("Caught: CopyStreamException"); strEx.printStackTrace(); return (null); } catch (IOException ioEx) { debug("Caught: IOException"); ioEx.printStackTrace(); return (null); } debug("File retrieved"); } ftp.logout(); } } catch (IOException e) { debug("Error retrieving FTP file"); e.printStackTrace(); return (null); } finally { if (ftp.isConnected()) { debug("Closing ftp connection ..."); try { ftp.disconnect(); } catch (IOException ioe) { debug("Exception closing ftp connection"); } } } debug("Closing local file stream ..."); try { fileStream.close(); } catch (IOException e) { e.printStackTrace(); } String result = HoopLink.fManager.loadContents(this.projectToFullPath(localFileName)); return (result); }
From source file:com.sourcesense.alfresco.opensso.integration.WebClientSSOIntegrationTest.java
private String callLoginWebScript(String encodedToken) { String loginWebScript = "http://localhost:8080/alfresco/s/api/login?u=admin&pw=".concat(encodedToken); WebConversation wc = new WebConversation(); WebRequest req = new GetMethodWebRequest(loginWebScript); WebResponse resp;/* ww w. jav a 2s. c om*/ try { resp = wc.getResponse(req); return resp.getText(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } return loginWebScript; }