List of usage examples for java.io UnsupportedEncodingException toString
public String toString()
From source file:eionet.util.SecurityUtil.java
/** * * @param request// w ww . j ava2 s . co m * @return */ public static String getLogoutURL(HttpServletRequest request) { // The default result used when the application is configured to not use Central Authentication Service (CAS). String result = "index.jsp"; if (Props.isUseCentralAuthenticationService()) { CASFilterConfig casFilterConfig = CASFilterConfig.getInstance(); if (casFilterConfig != null) { String casLoginUrl = casFilterConfig.getInitParameter(CASFilter.LOGIN_INIT_PARAM); if (casLoginUrl != null) { String casServerName = casFilterConfig.getInitParameter(CASFilter.SERVERNAME_INIT_PARAM); if (casServerName == null) { throw new DDRuntimeException("If " + CASFilter.LOGIN_INIT_PARAM + " context parameter has been specified, so must be " + CASFilter.SERVERNAME_INIT_PARAM); } try { result = casLoginUrl.replaceFirst("/login", "/logout") + "?url=" + URLEncoder.encode( request.getScheme() + "://" + casServerName + request.getContextPath(), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new DDRuntimeException(e.toString(), e); } } } } return result; }
From source file:io.github.retz.mesosc.MesosHTTPFetcher.java
public static Optional<String> sandboxUri(String t, String master, String slaveId, String frameworkId, String executorId, String containerId) { Optional<String> slaveAddr = fetchSlaveAddr(master, slaveId); // get master:5050/slaves with slaves/pid, cut with '@' LOG.debug("Agent address of executor {}: {}", executorId, slaveAddr); if (!slaveAddr.isPresent()) { return Optional.empty(); }/*from w ww.ja v a 2s .c o m*/ Optional<String> dir = fetchDirectory(slaveAddr.get(), frameworkId, executorId, containerId); if (!dir.isPresent()) { return Optional.empty(); } try { return Optional .of(String.format("http://%s/files/%s?path=%s", slaveAddr.get(), t, URLEncoder.encode(dir.get(), //builder.toString(), UTF_8.toString()))); } catch (UnsupportedEncodingException e) { LOG.error(e.toString(), e); return Optional.empty(); } }
From source file:eionet.util.SecurityUtil.java
/** * * @param request/*from w ww . j av a2 s.com*/ * @return */ public static String getLoginURL(HttpServletRequest request) { // Legacy login mechanism. Used if the application is configured to not use Central Authentication Service (CAS). //String result = "javascript:login('" + request.getContextPath() + "')"; String result = request.getContextPath() + "/" + LoginServlet.LOGIN_JSP; boolean rememberAfterLoginUrl = false; if (Props.isUseCentralAuthenticationService()) { CASFilterConfig casFilterConfig = CASFilterConfig.getInstance(); if (casFilterConfig != null) { String casLoginUrl = casFilterConfig.getInitParameter(CASFilter.LOGIN_INIT_PARAM); if (casLoginUrl != null) { String casServerName = casFilterConfig.getInitParameter(CASFilter.SERVERNAME_INIT_PARAM); if (casServerName == null) { throw new DDRuntimeException("If " + CASFilter.LOGIN_INIT_PARAM + " context parameter has been specified, so must be " + CASFilter.SERVERNAME_INIT_PARAM); } rememberAfterLoginUrl = true; try { result = casLoginUrl + "?service=" + URLEncoder.encode( request.getScheme() + "://" + casServerName + request.getContextPath() + "/login", "UTF-8"); } catch (UnsupportedEncodingException e) { throw new DDRuntimeException(e.toString(), e); } } } } else { String servletPath = request.getServletPath(); if (servletPath == null || !servletPath.endsWith(LoginServlet.LOGIN_JSP)) { rememberAfterLoginUrl = true; } } if (rememberAfterLoginUrl) { String requestURL = request.getRequestURL().toString(); if (requestURL != null && !AfterCASLoginServlet.isSkipUrl(requestURL)) { request.getSession().setAttribute(AfterCASLoginServlet.AFTER_LOGIN_ATTR_NAME, buildAfterLoginURL(request)); } } return result; }
From source file:com.meterware.httpunit.HttpUnitUtils.java
/** * Decodes a URL safe string into its original form using the * specified character set. Escaped characters are converted back * to their original representation.//from w w w . j a v a 2s .co m * * This method is copied from the <b>Jakarta Commons Codec</b>; * <code>org.apache.commons.codec.net.URLCodec</code> class. * * @param string URL safe string to convert into its original form * @return original string * @throws IllegalArgumentException thrown if URL decoding is unsuccessful, */ public static String decode(String string, String charset) { try { if (string == null) return null; return new String(decodeUrl(string.getBytes("US-ASCII")), charset); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.toString()); } }
From source file:eu.crowdrec.contest.sender.RequestSender.java
/** * Send a line from a logFile to an HTTP server. * /*from ww w.j a v a 2 s. co m*/ * @param logline the line that should by sent * * @param connection the connection to the http server, must not be null * * @return the response or null (if an error has been detected) */ static private String excutePostWithHttpClient(final String logline, final String serverURL) { // split the logLine into several token String[] token = logline.split("\t"); // define the URL parameter String urlParameters = ""; boolean oldMethod = token.length < 4; if (oldMethod) { try { String type = logline.contains("\"event_type\": \"recommendation_request\"") ? "recommendation_request" : "event_notification"; String newLine = logline.substring(0, logline.length() - 1) + ", \"limit\":6, \"type\":\"impression\"}"; urlParameters = String.format("type=%s&body=%s", URLEncoder.encode(type, "UTF-8"), URLEncoder.encode(newLine, "UTF-8")); } catch (UnsupportedEncodingException e1) { logger.warn(e1.toString()); } } else { String type = token[0]; String property = token[3]; String entity = token[4]; // encode the content as URL parameters. try { urlParameters = String.format("type=%s&properties=%s&entities=%s", URLEncoder.encode(type, "UTF-8"), URLEncoder.encode(property, "UTF-8"), URLEncoder.encode(entity, "UTF-8")); } catch (UnsupportedEncodingException e1) { logger.warn(e1.toString()); } } PostMethod postMethod = null; try { StringRequestEntity requestEntity = new StringRequestEntity(urlParameters, "application/x-www-form-urlencoded", "UTF-8"); postMethod = new PostMethod(serverURL); postMethod.setParameter("useCache", "false"); postMethod.setRequestEntity(requestEntity); int statusCode = httpClient.executeMethod(postMethod); String response = statusCode == 200 ? postMethod.getResponseBodyAsString() : "statusCode:" + statusCode; return response.trim(); } catch (IOException e) { logger.warn("receivind response failed, ignored."); } finally { if (postMethod != null) { postMethod.releaseConnection(); } } return null; }
From source file:org.ireland.jnetty.util.http.URIDecoder.java
/** * Converts the escaped URI to a string. * /* w w w.j a v a2 s . co m*/ * @param rawUri * the escaped URI * @param i * index into the URI * @param len * the length of the uri * @param encoding * the character encoding to handle %xx * * @return the converted URI */ private static String normalizeUriEscape(byte[] rawUri, int i, int len, String encoding) throws IOException { ByteToChar converter = allocateConverter(); // XXX: make this configurable if (encoding == null) encoding = "utf-8"; try { converter.setEncoding(encoding); } catch (UnsupportedEncodingException e) { log.debug(e.toString(), e); } try { while (i < len) { int ch = rawUri[i++] & 0xff; if (ch == '%') i = scanUriEscape(converter, rawUri, i, len); else converter.addByte(ch); } String result = converter.getConvertedString(); freeConverter(converter); return result; } catch (Exception e) { throw new IllegalArgumentException( "The URL contains escaped bytes unsupported by the '" + encoding + "' encoding."); } }
From source file:eu.crowdrec.contest.sender.RequestSender.java
/** * Send a line from a logFile to an HTTP server (single-threaded). * /*from w w w . jav a 2 s . co m*/ * @param logline the line that should by sent * * @param connection the connection to the http server, must not be null * * @return the response or null (if an error has been detected) */ static private String excutePost(final String logline, final String serverURL) { // split the logLine into several token String[] token = logline.split("\t"); String type = token[0]; String property = token[3]; String entity = token[4]; // encode the content as URL parameters. String urlParameters = ""; try { urlParameters = String.format("type=%s&properties=%s&entities=%s", URLEncoder.encode(type, "UTF-8"), URLEncoder.encode(property, "UTF-8"), URLEncoder.encode(entity, "UTF-8")); } catch (UnsupportedEncodingException e1) { logger.warn(e1.toString()); } // initialize a HTTP connection to the server // reuse of connection objects is delegated to the JVM HttpURLConnection connection = null; try { final URL url = new URL(serverURL); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); // Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); // Get Response BufferedReader rd = null; InputStream is = null; try { is = connection.getInputStream(); rd = new BufferedReader(new InputStreamReader(is)); StringBuffer response = new StringBuffer(); for (String line = rd.readLine(); line != null; line = rd.readLine()) { response.append(line); response.append(" "); } return response.toString(); } catch (IOException e) { logger.warn("receivind response failed, ignored."); } finally { if (is != null) { is.close(); } if (rd != null) { rd.close(); } } } catch (MalformedURLException e) { System.err.println("invalid server URL, program stopped."); System.exit(-1); } catch (IOException e) { System.err.println("i/o error connecting the http server, program stopped. e=" + e); System.exit(-1); } catch (Exception e) { System.err.println("general error connecting the http server, program stopped. e:" + e); e.printStackTrace(); System.exit(-1); } finally { // close the connection if (connection != null) { connection.disconnect(); } } return null; }
From source file:com.moz.fiji.schema.FormattedEntityId.java
/** * Create an hbase row key, which is a byte array from the given formatted fijiRowKey. * This method requires that the fijiRowKey argument is the correct length for the specified * format./* w w w . j a v a 2 s. c o m*/ * The following encoding will be used to ensure correct ordering: * Strings are UTF-8 encoded and terminated by a null byte. Strings cannot contain "\u0000". * Integers are exactly 4 bytes long. * Longs are exactly 8 bytes long. * Both integers and longs have the sign bit flipped so that their values are wrapped around to * create the correct lexicographic ordering. (i.e. after converting to byte array, * MIN_INT < 0 < MAX_INT). * Hashed components are exactly hash_size bytes long and are the first component of * the hbase key. * Except for the first, all components of a fijiRowKey can be null. However, to maintain * ordering, all components to the right of a null component must also be null. Nullable index * in the row key format specifies which component (and hence following components) are nullable. * By default, the hash only uses the first component, but this can be changed using the Range * Scan index. * * @param format The formatted row key format for this table. * @param fijiRowKey An ordered list of Objects of the key components. * @return A byte array representing the encoded Hbase row key. */ private static byte[] makeHbaseRowKey(RowKeyFormat2 format, List<Object> fijiRowKey) { ArrayList<byte[]> hbaseKey = new ArrayList<byte[]>(); final byte zeroDelim = 0; int pos; for (pos = 0; pos < fijiRowKey.size(); pos++) { // we have already done the validation check for null cascades. if (null == fijiRowKey.get(pos)) { continue; } byte[] tempBytes; switch (getType(fijiRowKey.get(pos))) { case STRING: if (((String) fijiRowKey.get(pos)).contains("\u0000")) { throw new EntityIdException("String component cannot contain \u0000"); } try { hbaseKey.add(((String) fijiRowKey.get(pos)).getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { LOG.error(e.toString()); throw new EntityIdException(String.format("UnsupportedEncoding for component %d", pos)); } break; case INTEGER: int temp = (Integer) fijiRowKey.get(pos); tempBytes = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE).putInt(temp).array(); tempBytes[0] = (byte) ((int) tempBytes[0] ^ (int) Byte.MIN_VALUE); hbaseKey.add(tempBytes); break; case LONG: long templong = (Long) fijiRowKey.get(pos); tempBytes = ByteBuffer.allocate(Long.SIZE / Byte.SIZE).putLong(templong).array(); tempBytes[0] = (byte) ((int) tempBytes[0] ^ (int) Byte.MIN_VALUE); hbaseKey.add(tempBytes); break; default: throw new RuntimeException("Invalid code path"); } } // hash stuff int hashUpto = format.getRangeScanStartIndex() - 1; ByteArrayOutputStream tohash = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); for (pos = 0; pos <= hashUpto && pos < hbaseKey.size(); pos++) { tohash.write(hbaseKey.get(pos), 0, hbaseKey.get(pos).length); } byte[] hashed = Arrays.copyOfRange(Hasher.hash(tohash.toByteArray()), 0, format.getSalt().getHashSize()); baos.write(hashed, 0, hashed.length); // to materialize or not to materialize that is the question if (format.getSalt().getSuppressKeyMaterialization()) { return baos.toByteArray(); } else { for (pos = 0; pos < hbaseKey.size(); pos++) { baos.write(hbaseKey.get(pos), 0, hbaseKey.get(pos).length); if (format.getComponents().get(pos).getType() == ComponentType.STRING || format.getComponents().get(pos) == null) { // empty strings will be encoded as null, hence we need to delimit them too baos.write(zeroDelim); } } return baos.toByteArray(); } }
From source file:org.kiji.schema.FormattedEntityId.java
/** * Create an hbase row key, which is a byte array from the given formatted kijiRowKey. * This method requires that the kijiRowKey argument is the correct length for the specified * format.//from w w w .ja va 2 s .c o m * The following encoding will be used to ensure correct ordering: * Strings are UTF-8 encoded and terminated by a null byte. Strings cannot contain "\u0000". * Integers are exactly 4 bytes long. * Longs are exactly 8 bytes long. * Both integers and longs have the sign bit flipped so that their values are wrapped around to * create the correct lexicographic ordering. (i.e. after converting to byte array, * MIN_INT < 0 < MAX_INT). * Hashed components are exactly hash_size bytes long and are the first component of * the hbase key. * Except for the first, all components of a kijiRowKey can be null. However, to maintain * ordering, all components to the right of a null component must also be null. Nullable index * in the row key format specifies which component (and hence following components) are nullable. * By default, the hash only uses the first component, but this can be changed using the Range * Scan index. * * @param format The formatted row key format for this table. * @param kijiRowKey An ordered list of Objects of the key components. * @return A byte array representing the encoded Hbase row key. */ private static byte[] makeHbaseRowKey(RowKeyFormat2 format, List<Object> kijiRowKey) { ArrayList<byte[]> hbaseKey = new ArrayList<byte[]>(); final byte zeroDelim = 0; int pos; for (pos = 0; pos < kijiRowKey.size(); pos++) { // we have already done the validation check for null cascades. if (null == kijiRowKey.get(pos)) { continue; } byte[] tempBytes; switch (getType(kijiRowKey.get(pos))) { case STRING: if (((String) kijiRowKey.get(pos)).contains("\u0000")) { throw new EntityIdException("String component cannot contain \u0000"); } try { hbaseKey.add(((String) kijiRowKey.get(pos)).getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { LOG.error(e.toString()); throw new EntityIdException(String.format("UnsupportedEncoding for component %d", pos)); } break; case INTEGER: int temp = (Integer) kijiRowKey.get(pos); tempBytes = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE).putInt(temp).array(); tempBytes[0] = (byte) ((int) tempBytes[0] ^ (int) Byte.MIN_VALUE); hbaseKey.add(tempBytes); break; case LONG: long templong = (Long) kijiRowKey.get(pos); tempBytes = ByteBuffer.allocate(Long.SIZE / Byte.SIZE).putLong(templong).array(); tempBytes[0] = (byte) ((int) tempBytes[0] ^ (int) Byte.MIN_VALUE); hbaseKey.add(tempBytes); break; default: throw new RuntimeException("Invalid code path"); } } // hash stuff int hashUpto = format.getRangeScanStartIndex() - 1; ByteArrayOutputStream tohash = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); for (pos = 0; pos <= hashUpto && pos < hbaseKey.size(); pos++) { tohash.write(hbaseKey.get(pos), 0, hbaseKey.get(pos).length); } byte[] hashed = Arrays.copyOfRange(Hasher.hash(tohash.toByteArray()), 0, format.getSalt().getHashSize()); baos.write(hashed, 0, hashed.length); // to materialize or not to materialize that is the question if (format.getSalt().getSuppressKeyMaterialization()) { return baos.toByteArray(); } else { for (pos = 0; pos < hbaseKey.size(); pos++) { baos.write(hbaseKey.get(pos), 0, hbaseKey.get(pos).length); if (format.getComponents().get(pos).getType() == ComponentType.STRING || format.getComponents().get(pos) == null) { // empty strings will be encoded as null, hence we need to delimit them too baos.write(zeroDelim); } } return baos.toByteArray(); } }
From source file:com.moz.fiji.schema.FormattedEntityId.java
/** * Decode a byte array containing an hbase row key into an ordered list corresponding to * the key format in the layout file.//w w w.j av a2 s . co m * * @param format The row key format as specified in the layout file. * @param hbaseRowKey A byte array containing the hbase row key. * @return An ordered list of component values in the key. */ private static List<Object> makeFijiRowKey(RowKeyFormat2 format, byte[] hbaseRowKey) { if (hbaseRowKey.length == 0) { throw new EntityIdException("Invalid hbase row key"); } List<Object> fijiRowKey = new ArrayList<Object>(); // skip over the hash int pos = format.getSalt().getHashSize(); // we are suppressing materialization, so the components cannot be retrieved. int fijiRowElem = 0; if (format.getSalt().getSuppressKeyMaterialization()) { if (pos < hbaseRowKey.length) { throw new EntityIdException("Extra bytes in key after hash when materialization is" + "suppressed"); } return null; } ByteBuffer buf; while (fijiRowElem < format.getComponents().size() && pos < hbaseRowKey.length) { switch (format.getComponents().get(fijiRowElem).getType()) { case STRING: // Read the row key until we encounter a Null (0) byte or end. int endpos = pos; while (endpos < hbaseRowKey.length && (hbaseRowKey[endpos] != (byte) 0)) { endpos += 1; } String str = null; try { str = new String(hbaseRowKey, pos, endpos - pos, "UTF-8"); } catch (UnsupportedEncodingException e) { LOG.error(e.toString()); throw new EntityIdException(String.format("UnsupportedEncoding for component %d", fijiRowElem)); } fijiRowKey.add(str); pos = endpos + 1; break; case INTEGER: // Toggle highest order bit to return to original 2's complement. hbaseRowKey[pos] = (byte) ((int) hbaseRowKey[pos] ^ (int) Byte.MIN_VALUE); try { buf = ByteBuffer.wrap(hbaseRowKey, pos, Integer.SIZE / Byte.SIZE); } catch (IndexOutOfBoundsException e) { throw new EntityIdException("Malformed hbase Row Key"); } fijiRowKey.add(Integer.valueOf(buf.getInt())); pos = pos + Integer.SIZE / Byte.SIZE; break; case LONG: // Toggle highest order bit to return to original 2's complement. hbaseRowKey[pos] = (byte) ((int) hbaseRowKey[pos] ^ (int) Byte.MIN_VALUE); try { buf = ByteBuffer.wrap(hbaseRowKey, pos, Long.SIZE / Byte.SIZE); } catch (IndexOutOfBoundsException e) { throw new EntityIdException("Malformed hbase Row Key"); } fijiRowKey.add(Long.valueOf(buf.getLong())); pos = pos + Long.SIZE / Byte.SIZE; break; default: throw new RuntimeException("Invalid code path"); } fijiRowElem += 1; } // Fail if there are extra bytes in hbase row key. if (pos < hbaseRowKey.length) { throw new EntityIdException("Extra bytes in hbase row key cannot be mapped to any " + "component"); } // Fail if we encounter nulls before it is legal to do so. if (fijiRowElem < format.getNullableStartIndex()) { throw new EntityIdException("Too few components decoded from hbase row key. Component " + "number " + fijiRowElem + " cannot be null"); } // finish up with nulls for everything that wasn't in the key for (; fijiRowElem < format.getComponents().size(); fijiRowElem++) { fijiRowKey.add(null); } return fijiRowKey; }