Java Code Examples for java.io.UnsupportedEncodingException

The following are top voted examples for showing how to use java.io.UnsupportedEncodingException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: iswc2012metadata   File: AgentSparql.java View source code Vote up 7 votes
private Object gerRet(Config.RDFSYNTAX rdfSyntax){
	Object ret = null;
	if (query.isDescribeType()){
		ret = qexec.execDescribe();
	}else if (query.isConstructType()){
		ret = qexec.execConstruct() ;
	}else if (query.isSelectType()){
		ResultSet results = qexec.execSelect() ;
	
		//System.out.println(ResultSetFormatter.asText(results));				

		ByteArrayOutputStream sw = new ByteArrayOutputStream();
		if (Config.RDFSYNTAX.SPARQL_XML.equals(rdfSyntax)){
			ResultSetFormatter.outputAsXML(sw, results);
		}else if (Config.RDFSYNTAX.SPARQL_JSON.equals(rdfSyntax)){
			ResultSetFormatter.outputAsJSON(sw, results);
		}else if (Config.RDFSYNTAX.CSV.equals(rdfSyntax)){
			ResultSetFormatter.outputAsCSV(sw, results);
		}else if (Config.RDFSYNTAX.TSV.equals(rdfSyntax)){
			ResultSetFormatter.outputAsTSV(sw, results);
		}else if (Config.RDFSYNTAX.SPARQL_TXT.equals(rdfSyntax)){
			return ResultSetFormatter.asText(results);
		}else{
			ResultSetFormatter.out(sw,results, query);				
		}

		try {

			ret = sw.toString("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
	}else if (query.isAskType()){
		ret = qexec.execAsk() ;
	}
	
	return ret;
}
 
Example 2
Project: dlna   File: DownloadProcess.java View source code Vote up 6 votes
public String decodeUri(String uri) {
	String newUri = "";
	try {
		newUri = URLDecoder.decode(uri, "utf-8");
	} catch (UnsupportedEncodingException e) {
		e.printStackTrace();
	}
	return newUri;
}
 
Example 3
Project: logback-flume   File: FlumeAppender.java View source code Vote up 6 votes
/**
   * Publish the event.
   * @param event The ILoggingEvent.
   */
  public void append(final ILoggingEvent event) {

      final FlumeEvent flumeEvent = 
      		new FlumeEvent(event, mdcIncludes, mdcExcludes, 
      				mdcRequired, mdcPrefix,
      				eventPrefix, compressBody);
      
      String str = this.layout.doLayout(flumeEvent.getEvent());
      byte[] bytes = null;
      
      try {
      	bytes = str.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
	e.printStackTrace();
}        
flumeEvent.setBody(bytes);
      manager.send(flumeEvent, reconnectDelay, retries);
  }
 
Example 4
Project: jena   File: ActionDataset.java View source code Vote up 6 votes
/**
 * This method returns true if the HttpServletRequest contains a valid
 * authorisation header
 * @param req The HttpServletRequest to test
 * @return true if the Authorisation header is valid
 */

private boolean authenticate(HttpServletRequest req)
{
    String authhead=req.getHeader("Authorization");

    if(authhead!=null)
    {
        byte[] up = Base64.decodeBase64(authhead.substring(6)) ;
        // Decode the authorisation String
        String usernpass ;
        try
        {
            usernpass = new String(up, "ascii") ;
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
            usernpass = null ;
        }
        // Split the username from the password
        String user=usernpass.substring(0,usernpass.indexOf(":"));
        String password=usernpass.substring(usernpass.indexOf(":")+1);

        if (user.equals("user") && password.equals("pass"))
            return true;
    }

    return false;
}
 
Example 5
Project: bitx-android   File: BitXClient.java View source code Vote up 6 votes
public BitXClient(String key, String secretKey) {
    try {
        mAuth = "Basic " + Base64.encodeToString((key + ":" + secretKey).getBytes("UTF-8"), Base64.DEFAULT);
    } catch (UnsupportedEncodingException e) {
        mAuth = "";
        //TODO: handle
        e.printStackTrace();
    }

    Gson gson = new GsonBuilder()
            .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .create();

    OkClient okClient = new OkClient() {

        @Override
        protected HttpURLConnection openConnection(Request request) throws IOException {
            HttpURLConnection connection = super.openConnection(request);
            connection.setReadTimeout(120000);
            connection.setConnectTimeout(120000);
            return connection;
        }
    };

    RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint(URL_BASE)
            .setClient(okClient)
            .setConverter(new GsonConverter(gson))
            .build();

    mRestService = restAdapter.create(BitXService.class);
}
 
Example 6
Project: nanobrowser   File: SentenceElement.java View source code Vote up 6 votes
public static SentenceElement withText(String text) throws AidaException {
	if (text == null) {
		throw new AidaException("Empty sentence.");
	}
	text = text.replaceAll("\\s+", " ").replaceAll("^ ", "").replaceAll(" $", "");
	if (text.isEmpty()) {
		throw new AidaException("Empty sentence.");
	} else if (text.matches(".*[a-z]+://.*")) {
		throw new AidaException("The sentence may not contain URIs.");
	} else if (text.indexOf(" ") == -1) {
		throw new AidaException("The sentence must consist of at least two words.");
	} else if (text.length() < 10) {
		throw new AidaException("The sentence is too short: it needs at least ten characters.");
	} else if (text.length() > 250) {
		throw new AidaException("The sentence is too long: at most 250 characters are allowed.");
	} else if (!text.substring(text.length()-1).equals(".")) {
		throw new AidaException("The sentence has to end with a full stop.");
	}
	try {
		return new SentenceElement(AIDA_URI_BASE + URLEncoder.encode(text, "UTF8"));
	} catch (UnsupportedEncodingException ex) {
		ex.printStackTrace();
	}
	return null;
}
 
Example 7
Project: xapi   File: StringBufferOutputStream.java View source code Vote up 6 votes
public String toString() {
  try {
    return new String(bout.toByteArray(), charset);
  } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    return new String(bout.toByteArray());
  }
}
 
Example 8
Project: RestLib   File: HttpsClient.java View source code Vote up 6 votes
private HttpEntity getHttpEntity(HttpUriRequest request, Map<String, String> params) {
	HttpEntity entity = null;
	
	if (params.containsKey("")) {
		try {
			entity = new StringEntity(params.get(""));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		request.setHeader("Accept", "application/json");
		request.setHeader("Content-type", "application/json");
	} else {
		entity = getUrlEncodedFormEntity(params);
		request.setHeader("Content-type", "application/x-www-form-urlencoded");
	}
	
	return entity;
}
 
Example 9
Project: java-fastdfs   File: StructBase.java View source code Vote up 6 votes
protected String stringValue(byte[] bs, int offset, FieldInfo filedInfo)
{
	try
	{
		return (new String(bs, offset + filedInfo.offset, filedInfo.size, ClientGlobal.g_charset)).trim();
	}
	catch(UnsupportedEncodingException ex)
	{
		ex.printStackTrace();
		return null;
	}
}
 
Example 10
Project: android-quick-library   File: QuickToolHelper.java View source code Vote up 6 votes
/**
 * convert byte data to String
 * 
 * @param data
 * @return
 */
public static String convertToString(byte[] data) {
	if (data == null)
		return null;
	try {
		return new String(data, UTF_CHARSET);
	} catch (UnsupportedEncodingException e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 11
Project: OrderNowAndroid   File: MyOrderActivity.java View source code Vote up 6 votes
public void doPositiveClick(String orderNote) {
	ApplicationState applicationContext = (ApplicationState)getApplicationContext();
	ArrayList<MyOrderItem> myOrderItemList = ApplicationState.getMyOrderItems(applicationContext);
	String restaurantId = OrderNowUtilities.getKeyFromSharedPreferences(applicationContext.getApplicationContext(), OrderNowConstants.KEY_ACTIVE_RESTAURANT_ID);
	Log.i("MyOrderActivity ", restaurantId);
	
	CustomerOrderWrapper customerOrderWrapper = new CustomerOrderWrapper(myOrderItemList, orderNote);
	ApplicationState.setCustomerOrderWrapper(applicationContext, customerOrderWrapper);

	Gson gs = new Gson();
	String order = gs.toJson(customerOrderWrapper.getCustomerOrder(applicationContext));
	String encoded = "";
       try {
           encoded = URLEncoder.encode(order,"UTF-8");
       } catch (UnsupportedEncodingException e1) {
           e1.printStackTrace();
       }
	String url = new URLBuilder().addPath(URLBuilder.Path.order)
			.addParam(URLBuilder.URLParam.order, encoded).build();

	new AsyncNetwork(this, null).execute(url);
	
	//start other activity
	Intent intent = new Intent(getApplicationContext(), MyParentOrderActivity.class);
	startActivity(intent);
	finish();
}
 
Example 12
Project: sslcertx   File: AbstractValueObject.java View source code Vote up 6 votes
public String getString() {
    if (rawBytes == null) {
        return null;
    }
    try {
       return new String(rawBytes, "UTF-8");
    } catch (UnsupportedEncodingException e) {
       throw new RuntimeException("Unsupported encoding: " + e.getMessage(), e);
   }
}
 
Example 13
Project: richfaces   File: FileUploadValueParam.java View source code Vote up 6 votes
public void complete() {
    byte[] bytes = getBufferBytes();
    buffer = null;

    try {
        value = (encoding != null) ? new String(bytes, encoding) : new String(bytes);
    } catch (UnsupportedEncodingException e) {
        throw new FacesException(e.getMessage(), e);
    }
}
 
Example 14
Project: OAuth2.0ProviderForJava   File: OAuth2.java View source code Vote up 6 votes
/** Construct a &-separated list of the given values, percentEncoded. */
//public static String percentEncode(Iterable values) {
//    StringBuilder p = new StringBuilder();
//    for (Object v : values) {
//        if (p.length() > 0) {
//            p.append("&");
//        }
//        p.append(OAuth2.percentEncode(toString(v)));
//    }
//    return p.toString();
//}

public static String percentEncode(String s) {
    if (s == null) {
        return "";
    }
    try {
        return URLEncoder.encode(s, ENCODING)
                // OAuth encodes some characters differently:
                .replace("+", "%20").replace("*", "%2A")
                .replace("%7E", "~");
        // This could be done faster with more hand-crafted code.
    } catch (UnsupportedEncodingException wow) {
        throw new RuntimeException(wow.getMessage(), wow);
    }
}
 
Example 15
Project: mycila   File: ExtendedAssert.java View source code Vote up 6 votes
public static String asString(String classPath, String encoding) {
    try {
        return new String(asBytes(classPath), encoding);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example 16
Project: SharkFW   File: UTF8SharkOutputStream.java View source code Vote up 6 votes
public void write(String utfString) throws IOException {
  try {
    
    // Translate the string to a byte array
    byte[] bytes = utfString.getBytes(KEPMessage.ENCODING);
    
    // Store the size of ths byte array
    int len = bytes.length;
    
    // Translate the long value into a byte[] for writing it on the stream
    byte[] lenBytes = Util.intToByteArray(len);
    
    // Write length info first
    this.os.write(lenBytes);
    
    // Write payload next (byte representation of string)
    Streamer.stream(new ByteArrayInputStream(bytes), this.os, STREAM_BUFFER_SIZE, len);
    
  } catch (UnsupportedEncodingException ex) {
    // Notify by IOException
    throw new IOException(ex.getMessage());
  }
}
 
Example 17
Project: RSQLServer   File: ParamInfo.java View source code Vote up 6 votes
/**
 * Get the string value of the parameter.
 *
 * @return The data value as a <code>String</code> or null.
 */
String getString(String charset) throws IOException {
    if (value == null || value instanceof String) {
        return (String) value;
    }

    if (value instanceof InputStream) {
        try {
            value = loadFromReader(new InputStreamReader((InputStream) value, charset), length);
            length = ((String) value).length();

            return (String) value;
        } catch (UnsupportedEncodingException e) {
            throw new IOException("I/O Error: UnsupportedEncodingException: "+ e.getMessage());
        }
    }

    if (value instanceof Reader) {
        value = loadFromReader((Reader)value, length);
        return (String)value;
    }

    return value.toString();
}
 
Example 18
Project: fedora-client   File: RelsExt.java View source code Vote up 6 votes
@Override
public String toString() {
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    model.write(bout);
    try {
        return bout.toString("UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example 19
Project: jaamsim   File: BlockWriter.java View source code Vote up 6 votes
private static long getBlockTotalSize(DataBlock b) {
	try {
		byte[] nameBytes = b.getName().getBytes("UTF-8");
		return 29 + nameBytes.length + getBlockDataSize(b);
	} catch (UnsupportedEncodingException e) {
		throw new DataBlock.Error(e.getMessage());
	}
}
 
Example 20
Project: jadira   File: PackagesClasspathUrlLocator.java View source code Vote up 6 votes
private String determineClasspathRootForResource(String nextResource, URL nextResourceMatchedUrl) {

        String nextResourceMatchedPathName = nextResourceMatchedUrl.getFile();
        try {
            nextResourceMatchedPathName = URLDecoder.decode(nextResourceMatchedPathName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // Never thrown for UTF-8
            throw new FileAccessException("Exception thrown for Encoding when not expected: " + e.getMessage(), e);
        }

        // Reformat file urls to remove file: prefix
        if (nextResourceMatchedPathName.startsWith("file:")) {
            nextResourceMatchedPathName = nextResourceMatchedPathName.substring(5);
        }

        // Chomp archive name if an archive
        if (nextResourceMatchedPathName.indexOf('!') > 0) {
            nextResourceMatchedPathName = nextResourceMatchedPathName.substring(0, nextResourceMatchedPathName.indexOf('!'));
        } else {
            File indicatedResource = new File(nextResourceMatchedPathName);

            // Traverse to classpath root relative to the original matching resource
            int pathDepth = nextResource.replaceAll("[^/]", "").length();
            for (int i = 0; i < pathDepth; i++) {
                indicatedResource = indicatedResource.getParentFile();
            }
            nextResourceMatchedPathName = indicatedResource.getParent();
        }

        return nextResourceMatchedPathName;
    }
 
Example 21
Project: CBReader2   File: HttpUtil.java View source code Vote up 6 votes
public static String encode(String s) {
    if (s == null) {
        return "";
    }
    try {
        return URLEncoder.encode(s, "UTF-8").replace("+", "%20").replace("*", "%2A")
                .replace("~", "%7E").replace("#", "%23");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example 22
Project: netlib   File: HttpUtil.java View source code Vote up 6 votes
/**
 * Execute a simple HTTP 1.1 request and read the response.
 * 
 * @param lowerLayer
 * @param httpServerNetAddress
 * @param pathOnHttpServer
 * @param timeoutInMs    do not wait longer the the specified milliseconds 
 * @return the response body
 * @throws IOException 
 */
public static byte[] get(
        NetSocket lowerLayerNetSocket,
        TcpipNetAddress httpServerNetAddress,
        String pathOnHttpServer,
        long timeoutInMs) throws IOException {
    try {
        String request =
            "GET "+pathOnHttpServer+" HTTP/1.1\n"+
            "Host: "+httpServerNetAddress.getHostnameOrIpaddress()+"\n"+
            // disable keep-alive
            "Connection: close\n"+
            "\n";
        byte[] requestBytes = request.getBytes(UTF8);

        // do the work
        return request(lowerLayerNetSocket, httpServerNetAddress, pathOnHttpServer, requestBytes, timeoutInMs);
    } catch (UnsupportedEncodingException e) {
        log.log(Level.SEVERE, "this exception may never occur", e);
        throw new IOException(e.toString());
    }
}
 
Example 23
Project: NemoVelo   File: Buffer.java View source code Vote up 6 votes
final void writeString(String s, String encoding, MySQLConnection conn) throws SQLException {
	ensureCapacity((s.length() * 2) + 1);
	try {
		writeStringNoNull(s, encoding, encoding, false, conn);
	} catch (UnsupportedEncodingException ue) {
		throw new SQLException(ue.toString(), SQLError.SQL_STATE_GENERAL_ERROR);
	}
	
	this.byteBuffer[this.position++] = 0;
}
 
Example 24
Project: Banc   File: Buffer.java View source code Vote up 6 votes
final void writeString(String s, String encoding, MySQLConnection conn) throws SQLException {
	ensureCapacity((s.length() * 3) + 1);
	try {
		writeStringNoNull(s, encoding, encoding, false, conn);
	} catch (UnsupportedEncodingException ue) {
		throw new SQLException(ue.toString(), SQLError.SQL_STATE_GENERAL_ERROR);
	}
	
	this.byteBuffer[this.position++] = 0;
}
 
Example 25
Project: SRS_CS_Project   File: Buffer.java View source code Vote up 6 votes
final void writeString(String s, String encoding, MySQLConnection conn) throws SQLException {
	ensureCapacity((s.length() * 2) + 1);
	try {
		writeStringNoNull(s, encoding, encoding, false, conn);
	} catch (UnsupportedEncodingException ue) {
		throw new SQLException(ue.toString(), SQLError.SQL_STATE_GENERAL_ERROR);
	}
	
	this.byteBuffer[this.position++] = 0;
}
 
Example 26
Project: Flock   File: LocalAddressbookStore.java View source code Vote up 6 votes
@Override
public Optional<LocalContactCollection> getCollection(String remotePath)
  throws RemoteException
{
  Optional<String> collectionPath = account.getCardDavCollectionPath(context);
  String           remotePathDecoded;

  try {

    remotePathDecoded = (URLDecoder.decode(remotePath, "UTF8"));

  } catch (UnsupportedEncodingException e) {
    Log.e(TAG, "caught exception while returning collection", e);
    throw new RemoteException(e.toString()); // HACK :(
  }

  if (collectionPath.isPresent() &&
      (collectionPath.get().equals(remotePath) || collectionPath.get().equals(remotePathDecoded)))
  {
    return Optional.of(new LocalContactCollection(context,
                                                  client,
                                                  account.getOsAccount(),
                                                  collectionPath.get()));
  }

  return Optional.absent();
}
 
Example 27
Project: pom   File: Buffer.java View source code Vote up 6 votes
final void writeString(String s, String encoding, Connection conn) throws SQLException {
	ensureCapacity((s.length() * 2) + 1);
	try {
		writeStringNoNull(s, encoding, encoding, false, conn);
	} catch (UnsupportedEncodingException ue) {
		throw new SQLException(ue.toString(), SQLError.SQL_STATE_GENERAL_ERROR);
	}
	
	this.byteBuffer[this.position++] = 0;
}
 
Example 28
Project: i-Prog   File: Buffer.java View source code Vote up 6 votes
final void writeString(String s, String encoding, MySQLConnection conn) throws SQLException {
	ensureCapacity((s.length() * 2) + 1);
	try {
		writeStringNoNull(s, encoding, encoding, false, conn);
	} catch (UnsupportedEncodingException ue) {
		throw new SQLException(ue.toString(), SQLError.SQL_STATE_GENERAL_ERROR);
	}
	
	this.byteBuffer[this.position++] = 0;
}
 
Example 29
Project: Netuno   File: Buffer.java View source code Vote up 6 votes
final void writeString(String s, String encoding, MySQLConnection conn) throws SQLException {
	ensureCapacity((s.length() * 2) + 1);
	try {
		writeStringNoNull(s, encoding, encoding, false, conn);
	} catch (UnsupportedEncodingException ue) {
		throw new SQLException(ue.toString(), SQLError.SQL_STATE_GENERAL_ERROR);
	}
	
	this.byteBuffer[this.position++] = 0;
}
 
Example 30
Project: oobd   File: CertificateHolderReference.java View source code Vote up 6 votes
CertificateHolderReference(byte[] contents)
{
    try
    {
        String concat = new String(contents, ReferenceEncoding);

        this.countryCode = concat.substring(0, 2);
        this.holderMnemonic = concat.substring(2, concat.length() - 5);

        this.sequenceNumber = concat.substring(concat.length() - 5);
    }
    catch (UnsupportedEncodingException e)
    {
        throw new IllegalStateException(e.toString());
    }
}
 
Example 31
Project: callback-blackberry   File: JSONArray.java View source code Vote up 6 votes
/**
 * Convert this object into a stream of JSON text.  Same as calling write(writer,false);
 * @param os The output stream to write data to.  Output stream characters will be serialized as UTF-8.
 * @param verbose Whether or not to write the JSON text in a verbose format.
 *
 * @throws JSONException Thrown on IO errors during serialization.
 */
public OutputStream write(OutputStream os, boolean verbose) throws JSONException {
    Writer writer = null;
    try {
    	//MSN reimplement BUFFERED
        writer = new OutputStreamWriter(os, "UTF-8");
    } catch (UnsupportedEncodingException uex) {
        JSONException jex = new JSONException(uex.toString());
        jex.setCause(uex);
        throw jex;
    }
    write(writer, verbose);
    return os;
}
 
Example 32
Project: PennMeet   File: Encoder.java View source code Vote up 6 votes
static void append8BitBytes(String content, BitArray bits, String encoding)
    throws WriterException {
  byte[] bytes;
  try {
    bytes = content.getBytes(encoding);
  } catch (UnsupportedEncodingException uee) {
    throw new WriterException(uee.toString());
  }
  for (int i = 0; i < bytes.length; ++i) {
    bits.appendBits(bytes[i], 8);
  }
}
 
Example 33
Project: wgen-iText   File: Encoder.java View source code Vote up 6 votes
static void append8BitBytes(String content, BitVector bits, String encoding)
    throws WriterException {
  byte[] bytes;
  try {
    bytes = content.getBytes(encoding);
  } catch (UnsupportedEncodingException uee) {
    throw new WriterException(uee.toString());
  }
  for (int i = 0; i < bytes.length; ++i) {
    bits.appendBits(bytes[i], 8);
  }
}
 
Example 34
Project: bitcoinj   File: DeterministicSeed.java View source code Vote up 6 votes
private static List<String> decodeMnemonicCode(byte[] mnemonicCode) throws UnreadableWalletException {
    try {
        return Splitter.on(" ").splitToList(new String(mnemonicCode, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        throw new UnreadableWalletException(e.toString());
    }
}
 
Example 35
Project: taller   File: Buffer.java View source code Vote up 6 votes
final void writeString(String s, String encoding, MySQLConnection conn) throws SQLException {
	ensureCapacity((s.length() * 2) + 1);
	try {
		writeStringNoNull(s, encoding, encoding, false, conn);
	} catch (UnsupportedEncodingException ue) {
		throw new SQLException(ue.toString(), SQLError.SQL_STATE_GENERAL_ERROR);
	}
	
	this.byteBuffer[this.position++] = 0;
}
 
Example 36
Project: uberpay-wallet   File: Wallet.java View source code Vote up 6 votes
private static List<String> decodeMnemonicCode(byte[] mnemonicCode) throws UnreadableWalletException {
    try {
        return Splitter.on(" ").splitToList(new String(mnemonicCode, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        throw new UnreadableWalletException(e.toString());
    }
}
 
Example 37
Project: SharkFW   File: SQLInformation.java View source code Vote up 6 votes
@Override
public String getContentAsString() throws SharkKBException {
    byte[] contentAsByte = this.getContentAsByte();
    
    try {
        return new String(contentAsByte, KEPMessage.ENCODING);
    } catch (UnsupportedEncodingException ex) {
        throw new SharkKBException("cannot convert content to string: " + ex.getLocalizedMessage());
    }
}
 
Example 38
Project: incubator-wave   File: AuthenticationServlet.java View source code Vote up 6 votes
@SuppressWarnings("unchecked")
private LoginContext login(BufferedReader body) throws IOException, LoginException {
  try {
    Subject subject = new Subject();

    String parametersLine = body.readLine();
    // Throws UnsupportedEncodingException.
    byte[] utf8Bytes = parametersLine.getBytes("UTF-8");

    CharsetDecoder utf8Decoder = Charset.forName("UTF-8").newDecoder();
    utf8Decoder.onMalformedInput(CodingErrorAction.IGNORE);
    utf8Decoder.onUnmappableCharacter(CodingErrorAction.IGNORE);

    // Throws CharacterCodingException.
    CharBuffer parsed = utf8Decoder.decode(ByteBuffer.wrap(utf8Bytes));
    parametersLine = parsed.toString();

    MultiMap<String> parameters = new UrlEncoded(parametersLine);
    CallbackHandler callbackHandler = new HttpRequestBasedCallbackHandler(parameters);

    LoginContext context = new LoginContext("Wave", subject, callbackHandler, configuration);

    // If authentication fails, login() will throw a LoginException.
    context.login();
    return context;
  } catch (CharacterCodingException cce) {
    throw new LoginException("Character coding exception (not utf-8): "
        + cce.getLocalizedMessage());
  } catch (UnsupportedEncodingException uee) {
    throw new LoginException("ad character encoding specification: " + uee.getLocalizedMessage());
  }
}
 
Example 39
Project: wave-protocol   File: AuthenticationServlet.java View source code Vote up 6 votes
@SuppressWarnings("unchecked")
private LoginContext login(BufferedReader body) throws IOException, LoginException {
  try {
    Subject subject = new Subject();

    String parametersLine = body.readLine();
    // Throws UnsupportedEncodingException.
    byte[] utf8Bytes = parametersLine.getBytes("UTF-8");

    CharsetDecoder utf8Decoder = Charset.forName("UTF-8").newDecoder();
    utf8Decoder.onMalformedInput(CodingErrorAction.IGNORE);
    utf8Decoder.onUnmappableCharacter(CodingErrorAction.IGNORE);

    // Throws CharacterCodingException.
    CharBuffer parsed = utf8Decoder.decode(ByteBuffer.wrap(utf8Bytes));
    parametersLine = parsed.toString();

    MultiMap<String> parameters = new UrlEncoded(parametersLine);
    CallbackHandler callbackHandler = new HttpRequestBasedCallbackHandler(parameters);

    LoginContext context = new LoginContext("Wave", subject, callbackHandler, configuration);

    // If authentication fails, login() will throw a LoginException.
    context.login();
    return context;
  } catch (CharacterCodingException cce) {
    throw new LoginException("Character coding exception (not utf-8): "
        + cce.getLocalizedMessage());
  } catch (UnsupportedEncodingException uee) {
    throw new LoginException("ad character encoding specification: " + uee.getLocalizedMessage());
  }
}
 
Example 40
Project: open-mika   File: Attributes.java View source code Vote up 6 votes
public String toString() {
    try {
        return new String(name, "ISO-8859-1");
    } catch (UnsupportedEncodingException iee) {
        throw new InternalError(iee.getLocalizedMessage());
    }
}
 
Example 41
Project: keyring-java   File: Ring.java View source code Vote up 6 votes
/**
 * Encrypt the given data with our key, prepending saltLength random
 * characters.

 * @return Base64 encoded representation of the encrypted data.
 */
String encrypt(String data, int saltLength) throws GeneralSecurityException {
	log("encrypt()");
	try {
		cipher.init(Cipher.ENCRYPT_MODE, key, iv);
	}
	catch (InvalidKeyException ike) {
		throw new GeneralSecurityException("InvalidKeyException: " +
				ike.getLocalizedMessage() + "\nYou (probably) need to " +
				"install the \"Java Cryptography Extension (JCE) " +
				"Unlimited Strength Jurisdiction Policy\" files.  Go to " +
				"http://java.sun.com/javase/downloads/index.jsp, download them, " +
		"and follow the instructions.");
	}
	String salted = saltString(saltLength, data);
	byte[] crypted;
	byte[] saltedBytes;
	try {
		saltedBytes = salted.getBytes("UTF-8");
	} catch (UnsupportedEncodingException e) {
		throw new GeneralSecurityException(e.getLocalizedMessage());
	}
	crypted = cipher.doFinal(saltedBytes);
	return Base64.encodeBytes(crypted);
}
 
Example 42
Project: platform-api   File: FactoryService.java View source code Vote up 6 votes
/**
 * Get factory information from storage by its id.
 *
 * @param id
 *         - id of factory
 * @param uriInfo
 *         - url context
 * @return - stored data, if id is correct.
 * @throws org.eclipse.che.api.core.ApiException
 *         - [email protected] org.eclipse.che.api.core.NotFoundException} when factory with given id doesn't exist
 */

@ApiOperation(value = "Get Factory information by its ID",
              notes = "Get JSON with Factory information. Factory ID is passed in a path parameter",
              response = Factory.class,
              position = 2)
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "OK"),
        @ApiResponse(code = 404, message = "Factory not found"),
        @ApiResponse(code = 409, message = "Failed to validate Factory URL"),
        @ApiResponse(code = 500, message = "Internal Server Error")})
@GET
@Path("/{id}")
@Produces({MediaType.APPLICATION_JSON})
public Factory getFactory(@ApiParam(value = "Factory ID", required = true)
                          @PathParam("id") String id,
                          @ApiParam(value = "Legacy. Whether or not to transform Factory into the most recent format",
                                    allowableValues = "true,false", defaultValue = "false")
                          @DefaultValue("false") @QueryParam("legacy") Boolean legacy,
                          @ApiParam(value = "Whether or not to validate values like it is done when accepting a Factory",
                                    allowableValues = "true,false", defaultValue = "false")
                          @DefaultValue("false") @QueryParam("validate") Boolean validate,
                          @Context UriInfo uriInfo) throws ApiException {
    Factory factoryUrl = factoryStore.getFactory(id);
    if (factoryUrl == null) {
        LOG.warn("Factory URL with id {} is not found.", id);
        throw new NotFoundException("Factory URL with id " + id + " is not found.");
    }

    if (legacy) {
        factoryUrl = factoryBuilder.convertToLatest(factoryUrl);
    }

    try {
        factoryUrl = factoryUrl.withLinks(linksHelper.createLinks(factoryUrl, factoryStore.getFactoryImages(id, null), uriInfo));
    } catch (UnsupportedEncodingException e) {
        throw new ServerException(e.getLocalizedMessage());
    }
    processDefaults(factoryUrl);
    if (validate) {
        acceptValidator.validateOnAccept(factoryUrl, true);
    }
    return factoryUrl;
}
 
Example 43
Project: wildfly-core   File: S3Util.java View source code Vote up 6 votes
static String urlencode(String unencoded) {
    try {
        return URLEncoder.encode(unencoded, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // should never happen
        throw new RuntimeException(e.getLocalizedMessage());
    }
}
 
Example 44
Project: gdata-client-java   File: CharacterParser.java View source code Vote up 6 votes
/**
 * The parse method will use the character encoding found in the output
 * properties instance to construct an appropriate [email protected] Reader} and then
 * delegate to the [email protected] #parse(Reader, InputProperties, Class)} method
 * to perform the parsing.
 */
public <R extends T> R parse(ParseSource parseSource, InputProperties inProps,
    Class<R> targetClass) throws IOException, ServiceException {
  Reader reader;
  reader = parseSource.getReader();
  if (reader == null) {
    InputStream inputStream = parseSource.getInputStream();
    if (inputStream != null) {
      try {
        String charset = getCharset(inProps);
        if (charset == null) {
          // case where charset has not been specified in the Content-Type.
          charset = "UTF-8";
        }
        if (charset.toLowerCase().startsWith("utf-")) {
          reader = new UnicodeReader(inputStream, charset);
        } else {
          reader = new InputStreamReader(inputStream, charset);
        }
      } catch (UnsupportedEncodingException e) {
        throw new ParseException("Unsupported encoding: " + 
            e.getLocalizedMessage(), e);
      }
    } else {
      // Means an XmlEventSource was passed in, should be handled at a higher
      // level by XmlInputParser
      throw new IllegalStateException("XML event source not supported");
    }
  }
  return parse(reader, inProps, targetClass);
}
 
Example 45
Project: databus   File: DbusEventKey.java View source code Vote up 6 votes
@Override
public String toString() {
  StringBuilder builder = new StringBuilder(  "DbusEventKey [_keyType=");
  builder.append(_keyType);
  builder.append(", _longKey=");
  builder.append(_longKey);
  builder.append(", _stringKey=");
  String stringKey;
  try {
    stringKey = _stringKey != null ? _stringKey : (_stringKeyInBytes == null ? "NULL" : new String(_stringKeyInBytes, "UTF-8"));
  } catch (UnsupportedEncodingException e) {
    stringKey = e.getLocalizedMessage();
  } 
  builder.append(stringKey);
  builder.append(", _schemaKey=" + _schemaKey);
  builder.append("]");
  return builder.toString();
}
 
Example 46
Project: WaveInCloud   File: AuthenticationServlet.java View source code Vote up 6 votes
@SuppressWarnings("unchecked")
private LoginContext login(BufferedReader body) throws IOException, LoginException {
  try {
    Subject subject = new Subject();

    String parametersLine = body.readLine();
    // Throws UnsupportedEncodingException.
    byte[] utf8Bytes = parametersLine.getBytes("UTF-8");

    CharsetDecoder utf8Decoder = Charset.forName("UTF-8").newDecoder();
    utf8Decoder.onMalformedInput(CodingErrorAction.IGNORE);
    utf8Decoder.onUnmappableCharacter(CodingErrorAction.IGNORE);

    // Throws CharacterCodingException.
    CharBuffer parsed = utf8Decoder.decode(ByteBuffer.wrap(utf8Bytes));
    parametersLine = parsed.toString();

    MultiMap<String> parameters = new UrlEncoded(parametersLine);
    CallbackHandler callbackHandler = new HttpRequestBasedCallbackHandler(parameters);

    LoginContext context = new LoginContext("Wave", subject, callbackHandler, configuration);

    // If authentication fails, login() will throw a LoginException.
    context.login();
    return context;
  } catch (CharacterCodingException cce) {
    throw new LoginException("Character coding exception (not utf-8): "
        + cce.getLocalizedMessage());
  } catch (UnsupportedEncodingException uee) {
    throw new LoginException("ad character encoding specification: " + uee.getLocalizedMessage());
  }
}
 
Example 47
Project: fog   File: Helper.java View source code Vote up 6 votes
/**
 * Method intended for GUI usage. It converts an object to a string, which can be shown to
 * a user. It is a longer version of data.toString(), since it tries to convert the
 * object. E.g. it tries to format byte arrays to text.
 * 
 * @return data as printable text (!= null)
 */
public static String toString(Object data)
{
	String res = null;
	
	if(data != null) {
		if(data instanceof byte[]) {
			try {
				res = new String((byte[]) data, "UTF-8");
			}
			catch(UnsupportedEncodingException exc) {
				res = data.toString() +" (" +exc.getLocalizedMessage() +")";
			}
		} else {
			res = data.toString();
		}
	} else {
		res = "null";
	}
	
	return res;
}
 
Example 48
Project: che-core   File: FactoryService.java View source code Vote up 6 votes
/**
 * Get factory information from storage by its id.
 *
 * @param id
 *         - id of factory
 * @param uriInfo
 *         - url context
 * @return - stored data, if id is correct.
 * @throws org.eclipse.che.api.core.ApiException
 *         - [email protected] org.eclipse.che.api.core.NotFoundException} when factory with given id doesn't exist
 */

@ApiOperation(value = "Get Factory information by its ID",
              notes = "Get JSON with Factory information. Factory ID is passed in a path parameter",
              response = Factory.class,
              position = 2)
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "OK"),
        @ApiResponse(code = 404, message = "Factory not found"),
        @ApiResponse(code = 409, message = "Failed to validate Factory URL"),
        @ApiResponse(code = 500, message = "Internal Server Error")})
@GET
@Path("/{id}")
@Produces({MediaType.APPLICATION_JSON})
public Factory getFactory(@ApiParam(value = "Factory ID", required = true)
                          @PathParam("id") String id,
                          @ApiParam(value = "Legacy. Whether or not to transform Factory into the most recent format",
                                    allowableValues = "true,false", defaultValue = "false")
                          @DefaultValue("false") @QueryParam("legacy") Boolean legacy,
                          @ApiParam(value = "Whether or not to validate values like it is done when accepting a Factory",
                                    allowableValues = "true,false", defaultValue = "false")
                          @DefaultValue("false") @QueryParam("validate") Boolean validate,
                          @Context UriInfo uriInfo) throws ApiException {
    Factory factoryUrl = factoryStore.getFactory(id);
    if (factoryUrl == null) {
        LOG.warn("Factory URL with id {} is not found.", id);
        throw new NotFoundException("Factory URL with id " + id + " is not found.");
    }

    if (legacy) {
        factoryUrl = factoryBuilder.convertToLatest(factoryUrl);
    }

    try {
        factoryUrl = factoryUrl.withLinks(linksHelper.createLinks(factoryUrl, factoryStore.getFactoryImages(id, null), uriInfo));
    } catch (UnsupportedEncodingException e) {
        throw new ServerException(e.getLocalizedMessage());
    }
    if (validate) {
        acceptValidator.validateOnAccept(factoryUrl, true);
    }
    return factoryUrl;
}
 
Example 49
Project: gcontact-excel-sync   File: CharacterParser.java View source code Vote up 6 votes
/**
 * The parse method will use the character encoding found in the output
 * properties instance to construct an appropriate [email protected] Reader} and then
 * delegate to the [email protected] #parse(Reader, InputProperties, Class)} method
 * to perform the parsing.
 */
public <R extends T> R parse(ParseSource parseSource, InputProperties inProps,
    Class<R> targetClass) throws IOException, ServiceException {
  Reader reader;
  reader = parseSource.getReader();
  if (reader == null) {
    InputStream inputStream = parseSource.getInputStream();
    if (inputStream != null) {
      try {
        String charset = getCharset(inProps);
        if (charset == null) {
          // case where charset has not been specified in the Content-Type.
          charset = "UTF-8";
        }
        if (charset.toLowerCase().startsWith("utf-")) {
          reader = new UnicodeReader(inputStream, charset);
        } else {
          reader = new InputStreamReader(inputStream, charset);
        }
      } catch (UnsupportedEncodingException e) {
        throw new ParseException("Unsupported encoding: " + 
            e.getLocalizedMessage(), e);
      }
    } else {
      // Means an XmlEventSource was passed in, should be handled at a higher
      // level by XmlInputParser
      throw new IllegalStateException("XML event source not supported");
    }
  }
  return parse(reader, inProps, targetClass);
}
 
Example 50
Project: Payara   File: RequestUtil.java View source code Vote up 6 votes
/**
 * This is a convenient API which wraps around the one in Grizzly and throws
 * checked java.io.UnsupportedEncodingException instead of
 * unchecked java.nio.charset.UnsupportedCharsetException.
 * cf. String.getBytes(String charset) throws UnsupportedEncodingException
 *
 * @exception UnsupportedEncodingException
 */
public static Charset lookupCharset(String enc) throws UnsupportedEncodingException {
    Charset charset = null;
    Throwable throwable = null;
    try {
        charset = Charsets.lookupCharset(enc);
    } catch(Throwable t) {
        throwable = t;
    }

    if (charset == null) {
        UnsupportedEncodingException uee = new UnsupportedEncodingException();
        if (throwable != null) {
            uee.initCause(throwable);
        }
        throw uee;
    }

    return charset;
}
 
Example 51
Project: j2objc   File: Charset.java View source code Vote up 6 votes
/**
 * Equivalent to [email protected] forName} but only throws [email protected] UnsupportedEncodingException},
 * which is all pre-nio code claims to throw.
 *
 * @hide internal use only
 */
public static Charset forNameUEE(String charsetName) throws UnsupportedEncodingException {
    try {
        return Charset.forName(charsetName);
    } catch (Exception cause) {
        UnsupportedEncodingException ex = new UnsupportedEncodingException(charsetName);
        ex.initCause(cause);
        throw ex;
    }
}
 
Example 52
Project: android_platform_libcore   File: Charset.java View source code Vote up 6 votes
/**
 * Equivalent to [email protected] forName} but only throws [email protected] UnsupportedEncodingException},
 * which is all pre-nio code claims to throw.
 *
 * @hide internal use only
 */
public static Charset forNameUEE(String charsetName) throws UnsupportedEncodingException {
    try {
        return Charset.forName(charsetName);
    } catch (Exception cause) {
        UnsupportedEncodingException ex = new UnsupportedEncodingException(charsetName);
        ex.initCause(cause);
        throw ex;
    }
}
 
Example 53
Project: android-15   File: Charset.java View source code Vote up 6 votes
/**
 * Equivalent to [email protected] forName} but only throws [email protected] UnsupportedEncodingException},
 * which is all pre-nio code claims to throw.
 *
 * @hide internal use only
 */
public static Charset forNameUEE(String charsetName) throws UnsupportedEncodingException {
    try {
        return Charset.forName(charsetName);
    } catch (Exception cause) {
        UnsupportedEncodingException ex = new UnsupportedEncodingException(charsetName);
        ex.initCause(cause);
        throw ex;
    }
}
 
Example 54
Project: android-libcore64   File: Charset.java View source code Vote up 6 votes
/**
 * Equivalent to [email protected] forName} but only throws [email protected] UnsupportedEncodingException},
 * which is all pre-nio code claims to throw.
 *
 * @hide internal use only
 */
public static Charset forNameUEE(String charsetName) throws UnsupportedEncodingException {
    try {
        return Charset.forName(charsetName);
    } catch (Exception cause) {
        UnsupportedEncodingException ex = new UnsupportedEncodingException(charsetName);
        ex.initCause(cause);
        throw ex;
    }
}
 
Example 55
Project: android-sdk-sources-for-api-level-23   File: Charset.java View source code Vote up 6 votes
/**
 * Equivalent to [email protected] forName} but only throws [email protected] UnsupportedEncodingException},
 * which is all pre-nio code claims to throw.
 *
 * @hide internal use only
 */
public static Charset forNameUEE(String charsetName) throws UnsupportedEncodingException {
    try {
        return Charset.forName(charsetName);
    } catch (Exception cause) {
        UnsupportedEncodingException ex = new UnsupportedEncodingException(charsetName);
        ex.initCause(cause);
        throw ex;
    }
}
 
Example 56
Project: ARTPart   File: Charset.java View source code Vote up 6 votes
/**
 * Equivalent to [email protected] forName} but only throws [email protected] UnsupportedEncodingException},
 * which is all pre-nio code claims to throw.
 *
 * @hide internal use only
 */
public static Charset forNameUEE(String charsetName) throws UnsupportedEncodingException {
    try {
        return Charset.forName(charsetName);
    } catch (Exception cause) {
        UnsupportedEncodingException ex = new UnsupportedEncodingException(charsetName);
        ex.initCause(cause);
        throw ex;
    }
}
 
Example 57
Project: glassfish-main   File: RequestUtil.java View source code Vote up 6 votes
/**
 * This is a convenient API which wraps around the one in Grizzly and throws
 * checked java.io.UnsupportedEncodingException instead of
 * unchecked java.nio.charset.UnsupportedCharsetException.
 * cf. String.getBytes(String charset) throws UnsupportedEncodingException
 *
 * @exception UnsupportedEncodingException
 */
public static Charset lookupCharset(String enc) throws UnsupportedEncodingException {
    Charset charset = null;
    Throwable throwable = null;
    try {
        charset = Charsets.lookupCharset(enc);
    } catch(Throwable t) {
        throwable = t;
    }

    if (charset == null) {
        UnsupportedEncodingException uee = new UnsupportedEncodingException();
        if (throwable != null) {
            uee.initCause(throwable);
        }
        throw uee;
    }

    return charset;
}
 
Example 58
Project: checkstyle   File: FileText.java View source code Vote up 5 votes
/**
 * Creates a new file text representation.
 *
 * The file will be read using the specified encoding, replacing
 * malformed input and unmappable characters with the default
 * replacement character.
 *
 * @param aFile the name of the file
 * @param aCharsetName the encoding to use when reading the file
 * @throws NullPointerException if the text is null
 * @throws IOException if the file could not be read
 */
public FileText(File aFile, String aCharsetName) throws IOException
{
    mFile = aFile;

    // We use our own decoder, to be sure we have complete control
    // about replacements.
    final CharsetDecoder decoder;
    try {
        mCharset = Charset.forName(aCharsetName);
        decoder = mCharset.newDecoder();
        decoder.onMalformedInput(CodingErrorAction.REPLACE);
        decoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
    }
    catch (final UnsupportedCharsetException ex) {
        final String message = "Unsuppored charset: " + aCharsetName;
        final UnsupportedEncodingException ex2;
        ex2 = new UnsupportedEncodingException(message);
        ex2.initCause(ex);
        throw ex2;
    }

    final char[] chars = new char[READ_BUFFER_SIZE];
    final StringBuilder buf = new StringBuilder();
    final FileInputStream stream = new FileInputStream(aFile);
    final Reader reader = new InputStreamReader(stream, decoder);
    try {
        while (true) {
            final int len = reader.read(chars);
            if (len < 0) {
                break;
            }
            buf.append(chars, 0, len);
        }
    }
    finally {
        Utils.closeQuietly(reader);
    }
    // buf.trimToSize(); // could be used instead of toString().
    mFullText = buf.toString();

    final String[] lines = LINE_TERMINATOR.split(mFullText, -1);
    if (lines.length > 0 && lines[lines.length - 1].length() == 0) {
        // drop empty line after last newline
        mLines = new String[lines.length - 1];
        System.arraycopy(lines, 0, mLines, 0, lines.length - 1);
    }
    else {
        // no newline at end, so we keep the last line as is
        mLines = lines;
    }
}