List of usage examples for java.io UnsupportedEncodingException toString
public String toString()
From source file:net.http.DemoService.java
public void getJobsTask() { List<Job> allJobs = new ArrayList<Job>(); boolean isLastPage = false; int pageCount = 1; // goes through pages and collects job and employers ids and links while (!isLastPage) { String urlParameters = null; try {/* w ww. ja v a 2 s . co m*/ urlParameters = "?published=" + URLEncoder.encode("1", "UTF-8") + "&page=" + URLEncoder.encode(String.valueOf(pageCount), "UTF-8"); } catch (UnsupportedEncodingException e) { log.error("UnsupportedEncodingException: " + e.toString() + ". Parameters: " + urlParameters); e.printStackTrace(); } // svi poslovi String response = null; try { response = HttpRequestHandling.sendGet("http://www.moj-posao.net/Pretraga-Poslova/", urlParameters); } catch (IOException e) { log.error("IOException: " + e.toString() + ". Parameters: " + urlParameters); e.printStackTrace(); } jp.setHtml(response); if (jp.featuredJobsExist()) { allJobs = jp.getFeaturedJobIdAndLink(allJobs); } isLastPage = jp.checkIfLastPage(); if (isLastPage) { if (jp.regionalJobFirst()) { break; } else { allJobs = jp.getJobIdAndLink(allJobs); } } else { allJobs = jp.getJobIdAndLink(allJobs); } pageCount++; } String response = null; // iterates through jobs and saves them into database if they don't // exist int count = 0; for (Job job : allJobs) { // if job doesn't exist in database if (jobDaoManager.getJobById(job.getId()) == null) { Employer employer = null; // if employer id is undefined on page if (job.getEmployer().getId() == 0 || job.getEmployer().getId() >= 10000000) { employer = employerDaoManager.getEmployerByName(job.getEmployer().getName()); // if employer exists in database if (employer != null) { job.setEmployer(employer); } else { // employer doesn't exist in database do { int employerId = Utils.generateRandomNumber(10000000, 99999999); employer = employerDaoManager.getEmployerById(employerId); if (employer == null) { job.getEmployer().setId(employerId); employerDaoManager.saveEmployer(job.getEmployer()); break; } } while (employer != null); } } else { employer = employerDaoManager.getEmployerById(job.getEmployer().getId()); // if employer exists in database if (employer != null) { job.setEmployer(employer); } else { try { response = HttpRequestHandling.sendGet(job.getEmployer().getLink(), ""); } catch (IOException e) { log.error("IOException: " + e.toString() + ". Employer link: " + job.getEmployer().getLink()); e.printStackTrace(); } jp.setHtml(response); String address = jp.getEmployerAddress(); job.getEmployer().setAddress(address); employerDaoManager.saveEmployer(job.getEmployer()); } } try { response = HttpRequestHandling.sendGet(job.getLink(), ""); } catch (IOException e) { log.error("IOException: " + e.toString() + ". Job link: " + job.getLink()); e.printStackTrace(); } jp.setHtml(response); String title = jp.getTitle(); if (title == null || title.equals("")) { log.error("Title error = no title, job_id: " + job.getId()); continue; } Date deadline = jp.getApplicationDeadline(); if (deadline == null) { log.error("Deadline error = no deadline, job_id: " + job.getId()); continue; } job.setTitle(title); job.setDeadline(jp.getApplicationDeadline()); job.setDescription(jp.getDescription()); job.setConditions(jp.getConditions()); job.setQualifications(jp.getQualification()); job.setYearsOfExperience(jp.getYearsOfExperience()); job.setLanguages(jp.getLanguages()); job.setSkills(jp.getSkills()); job.setDrivingLicence(jp.getDrivingLicense()); job.setEmployerOffer(jp.getEmployeeOffer()); job.setJobTypes(jp.getJobTypes()); job.setCategories(jp.getCategories()); job.setCounties(jp.getCounties()); jobDaoManager.saveJob(job); try { Thread.sleep(1000); } catch (InterruptedException e) { log.error("InterruptedException: " + e.toString()); e.printStackTrace(); } count++; } } System.out.println(); }
From source file:com.sonymobile.tools.gerrit.gerritevents.workers.rest.AbstractRestCommandJob.java
/** * Construct the post.// ww w . j a v a 2s . c o m * * @param reviewInput input * @param reviewEndpoint end point * @return the entity */ private HttpPost createHttpPostEntity(ReviewInput reviewInput, String reviewEndpoint) { HttpPost httpPost = new HttpPost(reviewEndpoint); String asJson = GSON.toJson(reviewInput); StringEntity entity = null; try { entity = new StringEntity(asJson); } catch (UnsupportedEncodingException e) { logger.error("Failed to create JSON for posting to Gerrit", e); if (altLogger != null) { altLogger.print("ERROR Failed to create JSON for posting to Gerrit: " + e.toString()); } return null; } entity.setContentType("application/json"); httpPost.setEntity(entity); return httpPost; }
From source file:sawtooth.examples.intkey.IntegerKeyHandler.java
@Override public void apply(TpProcessRequest transactionRequest, State state) throws InvalidTransactionException, InternalError { /*//from www.j a v a 2 s .c om * Integer Key state will be stored at an address of the name * with the key being the name and the value an Integer. so { "foo": 20, "bar": 26} * would be a possibility if the hashing algorithm hashes foo and bar to the * same address */ try { HashMap updateMap = this.mapper.readValue(transactionRequest.getPayload().toByteArray(), HashMap.class); String name = updateMap.get("Name").toString(); String address = null; try { address = this.intkeyNameSpace + Utils.hash512(name.getBytes("UTF-8")); } catch (UnsupportedEncodingException usee) { usee.printStackTrace(); throw new InternalError("Internal Error, " + usee.toString()); } if (name.length() == 0) { throw new InvalidTransactionException("Name is required"); } String verb = updateMap.get("Verb").toString(); if (verb.length() == 0) { throw new InvalidTransactionException("Verb is required"); } Integer value = Integer.decode(updateMap.get("Value").toString()); if (value == null) { throw new InvalidTransactionException("Value is required"); } if (!Arrays.asList("set", "dec", "inc").contains(verb)) { throw new InvalidTransactionException("Verb must be set, inc, dec not " + verb); } Collection<String> addresses = new ArrayList<String>(0); if (verb.equals("set")) { // The ByteString is cbor encoded dict/hashmap Map<String, ByteString> possibleAddressValues = state.get(Arrays.asList(address)); byte[] stateValueRep = possibleAddressValues.get(address).toByteArray(); Map<String, Integer> stateValue = null; if (stateValueRep.length > 0) { stateValue = this.mapper.readValue(stateValueRep, HashMap.class); if (stateValue.containsKey(name)) { throw new InvalidTransactionException("Verb is set but Name already in state, " + "Name: " + name + " Value: " + stateValue.get(name).toString()); } } if (value < 0) { throw new InvalidTransactionException("Verb is set but Value is less than 0"); } // 'set' passes checks so store it in the state if (stateValue == null) { stateValue = new HashMap<String, Integer>(); } Map<String, Integer> setValue = stateValue; setValue.put(name, value); Map.Entry<String, ByteString> entry = new AbstractMap.SimpleEntry<String, ByteString>(address, ByteString.copyFrom(this.mapper.writeValueAsBytes(setValue))); Collection<Map.Entry<String, ByteString>> addressValues = Arrays.asList(entry); addresses = state.set(addressValues); } if (verb.equals("inc")) { Map<String, ByteString> possibleValues = state.get(Arrays.asList(address)); byte[] stateValueRep = possibleValues.get(address).toByteArray(); if (stateValueRep.length == 0) { throw new InvalidTransactionException("Verb is inc but Name is not in state"); } Map<String, Integer> stateValue = this.mapper.readValue(stateValueRep, HashMap.class); if (!stateValue.containsKey(name)) { throw new InvalidTransactionException("Verb is inc but Name is not in state"); } // Increment the value in state by value Map<String, Integer> incValue = stateValue; incValue.put(name, stateValue.get(name) + value); Map.Entry<String, ByteString> entry = new AbstractMap.SimpleEntry<String, ByteString>(address, ByteString.copyFrom(this.mapper.writeValueAsBytes(incValue))); Collection<Map.Entry<String, ByteString>> addressValues = Arrays.asList(entry); addresses = state.set(addressValues); } if (verb.equals("dec")) { Map<String, ByteString> possibleAddressResult = state.get(Arrays.asList(address)); byte[] stateValueRep = possibleAddressResult.get(address).toByteArray(); if (stateValueRep.length == 0) { throw new InvalidTransactionException("Verb is dec but Name is not in state"); } Map<String, Integer> stateValue = this.mapper.readValue(stateValueRep, HashMap.class); if (!stateValue.containsKey(name)) { throw new InvalidTransactionException("Verb is dec but Name is not in state"); } if (stateValue.get(name) - value < 0) { throw new InvalidTransactionException("Dec would set Value to less than 0"); } Map<String, Integer> decValue = stateValue; // Decrement the value in state by value decValue.put(name, stateValue.get(name) - value); Map.Entry<String, ByteString> entry = new AbstractMap.SimpleEntry<String, ByteString>(address, ByteString.copyFrom(this.mapper.writeValueAsBytes(decValue))); Collection<Map.Entry<String, ByteString>> addressValues = Arrays.asList(entry); addresses = state.set(addressValues); } // if the 'set', 'inc', or 'dec' set to state didn't work if (addresses.size() == 0) { throw new InternalError("State error!."); } logger.info("Verb: " + verb + " Name: " + name + " value: " + value); } catch (IOException ioe) { ioe.printStackTrace(); throw new InternalError("State error" + ioe.toString()); } }
From source file:org.delta.crossplane.edifecs.dao.impl.EdifecsDaoImpl.java
/** * Get the result from the XE Stream.// ww w .j a va2 s .c o m * * @param strmFact * the stream factory * @param i * the index from which we would be getting the result from * * @return the EDI result * * @throws CrossPlaneTransportException */ private String getResult(XEMemOStreamFactory strmFact, int i) throws CrossPlaneTransportException { String result = null; XEMemOStreamFactory.StreamDetails details = strmFact.getDetails(i); if (logger.isTraceEnabled()) { logger.debug(" getting result details"); logger.debug(" Result name: " + details.getEngineName() + "_" + details.getResultType() + "_" + details.getDataName()); logger.debug(" Result size: " + strmFact.getContentSize(i)); } try { result = new String(strmFact.getContent(i), "UTF-8"); if (logger.isTraceEnabled()) { logger.debug(" result = " + result); } } catch (UnsupportedEncodingException e) { if (logger.isTraceEnabled()) { logger.error(" error getting results = " + e.toString()); } throw new CrossPlaneTransportException("Unable to tranform edi to xml: " + e); } if (logger.isTraceEnabled()) { logger.debug(" Result content: " + result); } return result; }
From source file:net.task.ParserTask.java
@Scheduled(fixedRate = 1000 * 60 * 60 * 24) public void getJobsTask() { List<Job> allJobs = new ArrayList<Job>(); boolean isLastPage = false; int pageCount = 1; // goes through pages and collects job and employer ids and links while (!isLastPage) { String urlParameters = null; try {/* ww w . j a v a 2s. c o m*/ urlParameters = "?published=" + URLEncoder.encode("2", "UTF-8") + "&page=" + URLEncoder.encode(String.valueOf(pageCount), "UTF-8"); } catch (UnsupportedEncodingException e) { log.error("UnsupportedEncodingException: " + e.toString() + ". Parameters: " + urlParameters); e.printStackTrace(); } // svi poslovi String response = null; try { response = HttpRequestHandling.sendGet("http://www.moj-posao.net/Pretraga-Poslova/", urlParameters); } catch (IOException e) { log.error("IOException: " + e.toString() + ". Parameters: " + urlParameters); e.printStackTrace(); } jp.setHtml(response); if (jp.featuredJobsExist()) { allJobs = jp.getFeaturedJobIdAndLink(allJobs); } isLastPage = jp.checkIfLastPage(); if (isLastPage) { if (jp.regionalJobFirst()) { break; } else { allJobs = jp.getJobIdAndLink(allJobs); } } else { allJobs = jp.getJobIdAndLink(allJobs); } pageCount++; } String response = null; // iterates through jobs and saves them into database if they don't exist int count = 0; for (Job job : allJobs) { // if job doesn't exist in database if (jobDaoManager.getJobById(job.getId()) == null) { Employer employer = null; // if employer id is undefined on page if (job.getEmployer().getId() == 0 || job.getEmployer().getId() >= 10000000) { employer = employerDaoManager.getEmployerByName(job.getEmployer().getName()); // if employer exists in database if (employer != null) { job.setEmployer(employer); } else { // employer doesn't exist in database do { int employerId = Utils.generateRandomNumber(10000000, 99999999); employer = employerDaoManager.getEmployerById(employerId); if (employer == null) { job.getEmployer().setId(employerId); employerDaoManager.saveEmployer(job.getEmployer()); break; } } while (employer != null); } } else { employer = employerDaoManager.getEmployerById(job.getEmployer().getId()); // if employer exists in database if (employer != null) { job.setEmployer(employer); } else { try { response = HttpRequestHandling.sendGet(job.getEmployer().getLink(), ""); } catch (IOException e) { log.error("IOException: " + e.toString() + ". Employer link: " + job.getEmployer().getLink()); e.printStackTrace(); } jp.setHtml(response); String address = jp.getEmployerAddress(); job.getEmployer().setAddress(address); employerDaoManager.saveEmployer(job.getEmployer()); } } try { response = HttpRequestHandling.sendGet(job.getLink(), ""); } catch (IOException e) { log.error("IOException: " + e.toString() + ". Job link: " + job.getLink()); e.printStackTrace(); } jp.setHtml(response); String title = jp.getTitle(); if (title == null || title.equals("")) { log.error("Title error = no title, job_id: " + job.getId()); continue; } Date deadline = jp.getApplicationDeadline(); if (deadline == null) { log.error("Deadline error = no deadline, job_id: " + job.getId()); continue; } job.setTitle(title); job.setDeadline(jp.getApplicationDeadline()); job.setDescription(jp.getDescription()); job.setConditions(jp.getConditions()); job.setQualifications(jp.getQualification()); job.setYearsOfExperience(jp.getYearsOfExperience()); job.setLanguages(jp.getLanguages()); job.setSkills(jp.getSkills()); job.setDrivingLicence(jp.getDrivingLicense()); job.setEmployerOffer(jp.getEmployeeOffer()); job.setJobTypes(jp.getJobTypes()); job.setCategories(jp.getCategories()); job.setCounties(jp.getCounties()); // traenje tehnologija - ovo se radi samo u slu?aju da je kategorija posla = IT if (job.getCategories() != null) { Iterator<Category> itr = job.getCategories().iterator(); while (itr.hasNext()) { Category cat = itr.next(); if (cat.getId() == 11) { job.setTechSkills(jp.getTechSkills()); } } } jobDaoManager.saveJob(job); try { Thread.sleep(1000); } catch (InterruptedException e) { log.error("InterruptedException: " + e.toString()); e.printStackTrace(); } count++; } } System.out.println(); System.out.println("Gotovo!"); }
From source file:org.bitbucket.mlopatkin.android.logviewer.Configuration.java
private String getSystemConfigDir() { if (SystemUtils.IS_OS_WINDOWS) { String appdata = System.getenv("APPDATA"); // dirty hack to get eclipse work properly with the environment // variables // when I start project in Debug under JDK 1.6_22 debug JRE it // receives environment variables in CP866 but thinks that they are // in CP1251. My login contains russian letters and APPDATA points // to nowhere :( if (DEBUG_MODE && !(new File(appdata).exists())) { logger.warn("DEBUG_MODE is ON"); logger.warn("Appdata value: " + Arrays.toString(appdata.getBytes())); try { appdata = new String(appdata.getBytes("WINDOWS-1251"), "CP866"); } catch (UnsupportedEncodingException e) { throw new AssertionError(e.toString()); }/*from w w w . j a v a 2 s. c o m*/ } return appdata; } else { return SystemUtils.USER_HOME; } }
From source file:biz.mosil.webtools.MosilWeb.java
/** * HTTP/* w ww . j av a 2s . c om*/ * @param _isSSL ? HTTPS * @param _type {@link biz.mosil.webtools.MosilWebConf.ContentType} * @param _postData POST ??? * @param _queryString GET ??(Query String) * */ private MosilWeb webInvoke(boolean _isSSL, ContentType _type, final String _postData, final String _queryString) { chkHostName(); try { String targetUrl = ((_isSSL) ? "https://" : "http://") + mHostName; if (!_queryString.equals("")) { targetUrl += "?" + _queryString; } HttpPost httpPost = new HttpPost(targetUrl); httpPost.setHeader("Accept", MosilWebConf.HEADER_ACCEPT); httpPost.setHeader("Content-Type", _type.toString()); StringEntity entity = null; try { entity = new StringEntity(_postData, "UTF-8"); } catch (UnsupportedEncodingException _ex) { throw new RuntimeException("" + _ex.toString()); } httpPost.setEntity(entity); mHttpResponse = (_isSSL) ? MosilSSLSocketFactory.getHttpClient(mHttpParams).execute(httpPost, mHttpContext) : new DefaultHttpClient(mHttpParams).execute(httpPost, mHttpContext); if (mHttpResponse != null) { mResponse = EntityUtils.toString(mHttpResponse.getEntity()); } } catch (ClientProtocolException _ex) { Log.e(TAG, "Client Protocol Exception: " + _ex.toString()); } catch (IOException _ex) { Log.e(TAG, "IO Exception: " + _ex.toString()); } return this; }
From source file:org.transdroid.daemon.BuffaloNas.BuffaloNasAdapter.java
private String makeRequest(Log log, String url, NameValuePair... params) throws DaemonException { try {/*from ww w . j a v a 2 s . c o m*/ // Initialise the HTTP client if (httpclient == null) { initialise(); } // Add the parameters to the query string boolean first = true; for (NameValuePair param : params) { if (first) { url += "?"; first = false; } else { url += "&"; } url += param.getName() + "=" + param.getValue(); } // Make the request HttpResponse response = httpclient.execute(new HttpGet(buildWebUIUrl(url))); HttpEntity entity = response.getEntity(); if (entity != null) { // Read JSON response java.io.InputStream instream = entity.getContent(); String result = HttpHelper.convertStreamToString(instream); instream.close(); // Return raw result return result; } log.d(LOG_NAME, "Error: No entity in HTTP response"); throw new DaemonException(ExceptionType.UnexpectedResponse, "No HTTP entity object in response."); } catch (UnsupportedEncodingException e) { throw new DaemonException(ExceptionType.ConnectionError, e.toString()); } catch (Exception e) { log.d(LOG_NAME, "Error: " + e.toString()); throw new DaemonException(ExceptionType.ConnectionError, e.toString()); } }
From source file:org.deviceconnect.message.http.impl.factory.AbstractHttpMessageFactory.java
/** * dConnect?HTTP??.// w w w . j a v a2 s . c om * @param dmessage dConnect * @return HTTP */ protected HttpEntity createHttpEntity(final DConnectMessage dmessage) { mLogger.entering(getClass().getName(), "createHttpEntity", dmessage); HttpEntity entity = null; try { DConnectMessage message = new BasicDConnectMessage(dmessage); message.remove(DConnectMessage.EXTRA_PROFILE); message.remove(DConnectMessage.EXTRA_INTERFACE); message.remove(DConnectMessage.EXTRA_ATTRIBUTE); message.remove(DConnectMessage.EXTRA_METHOD); entity = new ByteArrayEntity(message.toString(2).getBytes(HTTP.UTF_8)); } catch (UnsupportedEncodingException e) { mLogger.log(Level.FINE, e.toString(), e); mLogger.warning(e.toString()); } mLogger.exiting(getClass().getName(), "createHttpEntity", entity); return entity; }
From source file:eionet.cr.web.action.SpatialSearchActionBean.java
/** * * @return/* w w w . ja va2 s.c o m*/ * @throws DAOException */ public Resolution kmlLinks() throws DAOException { sources = factory.getDao(HelperDAO.class).getSpatialSources(); if (sources.isEmpty()) { addSystemMessage("No spatial objects currently found!"); return new ForwardResolution("/pages/googleEarthIntro.jsp"); } else { try { getContext().getRequest().setCharacterEncoding("UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.toString(), e); } getContext().getResponse().setHeader("Content-Disposition", "attachment; filename=kmllinks.kml"); return new ForwardResolution("/pages/kmllinks.jsp"); } }