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 generate more good examples.
Example 1
Project: s-store   File: TheHashinator.java   Source Code and License 8 votes vote down vote up
/**
 * Given an Object value, pick a partition to store the data. Currently only String objects can be hashed.
 *
 * @param value The value to hash.
 * @param partitionCount The number of partitions to choose from.
 * @return A value between 0 and partitionCount-1, hopefully pretty evenly
 * distributed.
 */
static int hashinate(Object value, int partitionCount) {
    if (value instanceof String) {
        String string = (String) value;
        try {
            byte bytes[] = string.getBytes("UTF-8");
            int hashCode = 0;
            int offset = 0;
            for (int ii = 0; ii < bytes.length; ii++) {
               hashCode = 31 * hashCode + bytes[offset++];
            }
            return java.lang.Math.abs(hashCode % partitionCount);
        } catch (UnsupportedEncodingException e) {
            hostLogger.l7dlog( Level.FATAL, LogKeys.host_TheHashinator_ExceptionHashingString.name(), new Object[] { string }, e);
            HStore.crashDB();
        }
    }
    hostLogger.l7dlog(Level.FATAL, LogKeys.host_TheHashinator_AttemptedToHashinateNonLongOrString.name(), new Object[] { value
            .getClass().getName() }, null);
    HStore.crashDB();
    return -1;
}
 
Example 2
Project: AgentWorkbench   File: OntologyInstanceViewer.java   Source Code and License 7 votes vote down vote up
/**
 * Sets the configuration in XML in a Base64 decode form.
 * @param configurationXML64 the new configuration xm l64
 */
public void setConfigurationXML64(String[] configurationXML64) {
	
	String[] configXML = new String[configurationXML64.length];
	for (int i = 0; i < configurationXML64.length; i++) {
		try {
			if (configurationXML64[i]==null || configurationXML64[i].equals("")) {
				configXML[i] = null;
			} else {
				configXML[i] = new String(Base64.decodeBase64(configurationXML64[i].getBytes()), "UTF8");	
			}
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	this.getDynForm().setOntoArgsXML(configXML);
	this.getDynTableJPanel().refreshTableModel();
	if (this.getSelectedIndex()==1) {
		this.setXMLText();
	}
	
}
 
Example 3
Project: boohee_v5.6   File: MQUtils.java   Source Code and License 6 votes vote down vote up
public static String stringToMD5(String string) {
    try {
        byte[] hash = MessageDigest.getInstance(Coder.KEY_MD5).digest(string.getBytes("UTF-8"));
        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 255) < 16) {
                hex.append("0");
            }
            hex.append(Integer.toHexString(b & 255));
        }
        return hex.toString();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    } catch (UnsupportedEncodingException e2) {
        e2.printStackTrace();
        return null;
    }
}
 
Example 4
Project: RDF2PT   File: DefaultIRIConverter.java   Source Code and License 6 votes vote down vote up
private String getLabelFromBuiltIn(String uri){
	try {
		IRI iri = IRI.create(URLDecoder.decode(uri, "UTF-8"));
		
		// if IRI is built-in entity
		if(iri.isReservedVocabulary()) {
			// use the short form
			String label = sfp.getShortForm(iri);
			
			 // if it is a XSD numeric data type, we attach "value"
            if(uri.equals(XSD.nonNegativeInteger.getURI()) || uri.equals(XSD.integer.getURI())
            		|| uri.equals(XSD.negativeInteger.getURI()) || uri.equals(XSD.decimal.getURI())
            		|| uri.equals(XSD.xdouble.getURI()) || uri.equals(XSD.xfloat.getURI())
            		|| uri.equals(XSD.xint.getURI()) || uri.equals(XSD.xshort.getURI())
            		|| uri.equals(XSD.xbyte.getURI()) || uri.equals(XSD.xlong.getURI())
            		){
            	label += " value";
            }
            
            return label;
		}
	} catch (UnsupportedEncodingException e) {
		logger.error("Getting short form of " + uri + "failed.", e);
	}
	return null;
}
 
Example 5
Project: SWDemo   File: ChatActivity.java   Source Code and License 6 votes vote down vote up
private void sendChannelMsg(String msgStr) {
    RtcEngine rtcEngine = rtcEngine();
    if (mDataStreamId <= 0) {
        mDataStreamId = rtcEngine.createDataStream(true, true); // boolean reliable, boolean ordered
    }

    if (mDataStreamId < 0) {
        String errorMsg = "Create data stream error happened " + mDataStreamId;
        log.warn(errorMsg);
        showLongToast(errorMsg);
        return;
    }

    byte[] encodedMsg;
    try {
        encodedMsg = msgStr.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        encodedMsg = msgStr.getBytes();
    }

    rtcEngine.sendStreamMessage(mDataStreamId, encodedMsg);
}
 
Example 6
Project: uavstack   File: HttpTestApphubManager.java   Source Code and License 6 votes vote down vote up
/**
 * 打包请求数据
 * 
 * @param type
 * @param paramPath
 * @return
 */
private static byte[] getRequestData(bussinessType type, String paramPath) {

    Map<String, String> dbInfo = getDBInfo(type);
    UAVHttpMessage request = new UAVHttpMessage();
    String dataStr = getFileData(paramPath);
    request.putRequest(DataStoreProtocol.MONGO_REQUEST_DATA, dataStr);
    request.putRequest(DataStoreProtocol.DATASTORE_NAME, dbInfo.get(k_dataStoreName));
    request.putRequest(DataStoreProtocol.MONGO_COLLECTION_NAME, dbInfo.get(k_conllectionName));
    String jsonStr = JSONHelper.toString(request);
    byte[] datab = null;
    try {
        datab = jsonStr.getBytes("utf-8");
    }
    catch (UnsupportedEncodingException e) {
        LOG.info("HttpTestApphub getRequestData \n" + e.getMessage());
    }

    return datab;
}
 
Example 7
Project: SpringWebAnuncio   File: Usuarios.java   Source Code and License 6 votes vote down vote up
public static String sha256(String base) {
try {
    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    byte[] hash = digest.digest(base.getBytes("UTF-8"));
    StringBuffer hexString = new StringBuffer();

    for (int i = 0; i < hash.length; i++) {
	String hex = Integer.toHexString(0xff & hash[i]);
	if (hex.length() == 1) {
	    hexString.append('0');
	}
	hexString.append(hex);
    }

    return hexString.toString();
} catch (UnsupportedEncodingException | NoSuchAlgorithmException ex) {
    throw new RuntimeException(ex);
}
   }
 
Example 8
Project: romanov   File: MpegAudioFileReader.java   Source Code and License 6 votes vote down vote up
/**
 * Parse Text Frames.
 * 
 * @param bframes
 * @param offset
 * @param size
 * @param skip
 * @return
 */
protected String parseText(byte[] bframes, int offset, int size, int skip)
{
	String value = null;
	try
	{
		String enc = ENC_TYPES[0];
		if ( bframes[offset] >= 0 && bframes[offset] < 4 )
		{
			enc = ENC_TYPES[bframes[offset]];
		}
		value = new String(bframes, offset + skip, size - skip, enc);
		value = chopSubstring(value, 0, value.length());
	}
	catch (UnsupportedEncodingException e)
	{
		system.error("ID3v2 Encoding error: " + e.getMessage());
	}
	return value;
}
 
Example 9
Project: openaudible   File: OggVorbisCommentTagCreator.java   Source Code and License 6 votes vote down vote up
public ByteBuffer convert(Tag tag) throws UnsupportedEncodingException {
    ByteBuffer ogg = creator.convert(tag);
    int tagLength = ogg.capacity() + VorbisHeader.FIELD_PACKET_TYPE_LENGTH + VorbisHeader.FIELD_CAPTURE_PATTERN_LENGTH + OggVorbisCommentTagCreator.FIELD_FRAMING_BIT_LENGTH;

    ByteBuffer buf = ByteBuffer.allocate(tagLength);

    //[packet type=comment0x03]['vorbis']
    buf.put((byte) VorbisPacketType.COMMENT_HEADER.getType());
    buf.put(VorbisHeader.CAPTURE_PATTERN_AS_BYTES);

    //The actual tag
    buf.put(ogg);

    //Framing bit = 1
    buf.put(FRAMING_BIT_VALID_VALUE);

    buf.rewind();
    return buf;
}
 
Example 10
Project: awe-awesomesky   File: PasswdEncode.java   Source Code and License 6 votes vote down vote up
/**
 *  可逆加密
 * @param secret
 * @param key
 * @return
 */
public static String aesEncode(String secret,String key){
    if (StringUtils.isEmpty(secret) || StringUtils.isEmpty(key)){
        return null;
    }

    byte[] retByte = new byte[0];
    try {
        retByte = AESEncode(secret.getBytes(chart_set_utf8),key);
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage(),e);
    }
    if (retByte != null) {
        return bytesToHexString(retByte);
    }

    return null;
}
 
Example 11
Project: lambdora   File: TripleUtil.java   Source Code and License 6 votes vote down vote up
/**
 * This method converts a string (in n-triples format) into a Jena triple
 *
 * @param string containing single n-triples triple
 * @return Triple
 */
public static Triple toTriple(final String string) {
    // Create Jena model
    Model inputModel = createDefaultModel();
    try {
        // Load model with arg string (expecting n-triples)
        inputModel = inputModel.read(new StringInputStream(string), null, strLangNTriples);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }

    // Since there is only one statement, get it
    final Statement stmt = inputModel.listStatements().nextStatement();

    // Return the Jena triple which the statement represents
    return stmt.asTriple();
}
 
Example 12
Project: JWT4B   File: AlgorithmLinker.java   Source Code and License 6 votes vote down vote up
private static Algorithm getAlgorithm(String algo, String key, boolean IsKeyASignerKey)
		throws IllegalArgumentException, UnsupportedEncodingException {
	if (algo.equals(HS256.getAlgorithm())) {
		return Algorithm.HMAC256(key);
	}
	if (algo.equals(HS384.getAlgorithm())) {
		return Algorithm.HMAC384(key);
	}
	if (algo.equals(HS512.getAlgorithm())) {
		return Algorithm.HMAC512(key);
	}
	if (algo.equals(ES256.getAlgorithm())) {
		return Algorithm.ECDSA256((ECKey) getKeyInstance(key, "EC", IsKeyASignerKey));
	}
	if (algo.equals(ES384.getAlgorithm())) {
		return Algorithm.ECDSA384((ECKey) getKeyInstance(key, "EC", IsKeyASignerKey));
	}
	if (algo.equals(ES512.getAlgorithm())) {
		return Algorithm.ECDSA512((ECKey) getKeyInstance(key, "EC",IsKeyASignerKey));
	}
	if (algo.equals(RS256.getAlgorithm())) {
		return Algorithm.RSA256((RSAKey) getKeyInstance(key, "RSA", IsKeyASignerKey));
	}
	if (algo.equals(RS384.getAlgorithm())) {
		return Algorithm.RSA384((RSAKey) getKeyInstance(key, "RSA", IsKeyASignerKey));
	}
	if (algo.equals(RS512.getAlgorithm())) {
		return Algorithm.RSA512((RSAKey) getKeyInstance(key, "RSA", IsKeyASignerKey));
	}

	return Algorithm.none();
}
 
Example 13
Project: ProyectoPacientes   File: Buffer.java   Source Code and License 6 votes vote down vote up
final void writeLenString(String s, String encoding, String serverEncoding, SingleByteCharsetConverter converter, boolean parserKnowsUnicode,
        MySQLConnection conn) throws UnsupportedEncodingException, SQLException {
    byte[] b = null;

    if (converter != null) {
        b = converter.toBytes(s);
    } else {
        b = StringUtils.getBytes(s, encoding, serverEncoding, parserKnowsUnicode, conn, conn.getExceptionInterceptor());
    }

    int len = b.length;
    ensureCapacity(len + 9);
    writeFieldLength(len);
    System.arraycopy(b, 0, this.byteBuffer, this.position, len);
    this.position += len;
}
 
Example 14
Project: outcomes   File: Main.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws GeneralSecurityException, UnsupportedEncodingException {

        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(1024);
        KeyPair kp = kpg.genKeyPair();

        KeyFactory fact = KeyFactory.getInstance("RSA");
        RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(),
                RSAPublicKeySpec.class);
        RSAPrivateKeySpec priv = fact.getKeySpec(kp.getPrivate(),
                RSAPrivateKeySpec.class);

        publicKey = fact.generatePublic(pub);
        privateKey = fact.generatePrivate(priv);

        String foo = rsaEncrypt("foo");

        byte[] decode = Base64.getDecoder().decode("foo");
        System.out.println(Base64.getEncoder().encodeToString(decode));

        System.out.println(rsaDecrypt(foo));

    }
 
Example 15
Project: Pet-Supply-Store   File: SHASecurityProvider.java   Source Code and License 6 votes vote down vote up
private String getSHA512(String passwordToHash) {
	String generatedPassword = null;
    try {
    	String salt = getKeyProvider().getKey(null);
        MessageDigest md = MessageDigest.getInstance("SHA-512");
        md.update(salt.getBytes("UTF-8"));
        byte[] bytes = md.digest(passwordToHash.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
           sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
        }
        generatedPassword = sb.toString();
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
       	 e.printStackTrace();
        }
	    return generatedPassword;
}
 
Example 16
Project: 3DSFE-Randomizer   File: FatesJobs.java   Source Code and License 6 votes vote down vote up
public List<Job> getEligibleJobs(boolean male, int maxLength) {
    if(maxLength < 1)
        throw new IllegalArgumentException("Violation of precondidition: " +
                "getEligibleJobs. maxLength must be greater than 0.");

    List<Job> eligible = new ArrayList<>();
    List<Job> pool;
    if(male)
        pool = getMaleBaseClasses();
    else
        pool = getFemaleBaseClasses();
    try {
        for(Job j : pool) {
            if(j.getJid().getBytes("shift-jis").length <= maxLength && j.getItemType()
                    != ItemType.Staves && j.getItemType() != ItemType.Beaststone)
                eligible.add(j);
        }
    } catch(UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return eligible;
}
 
Example 17
Project: uri-toolkit   File: FormEncoded.java   Source Code and License 6 votes vote down vote up
@Override
public String toString()
{
    if (mEncoded == null)
    {
        try
        {
            mEncoded = encoded(mPlain, mCharSet);
        }
        catch (UnsupportedEncodingException e)
        {
            throw new IllegalArgumentException(String.format("Charset %s not supported by Runtime", mCharSet));
        }
    }
    return mEncoded.toString();
}
 
Example 18
Project: incubator-netbeans   File: DispatchingHandlerTest.java   Source Code and License 6 votes vote down vote up
public void testOwnFormatter() throws UnsupportedEncodingException {
    class MyFrmtr extends Formatter {
        private int cnt;
        @Override
        public String format(LogRecord record) {
            cnt++;
            return record.getMessage();
        }
    }
    MyFrmtr my = new MyFrmtr();
    
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    StreamHandler sh = new StreamHandler(os, NbFormatter.FORMATTER);
    DispatchingHandler dh = new DispatchingHandler(sh, 10);
    dh.setFormatter(my);
    dh.publish(new LogRecord(Level.WARNING, "Ahoj"));
    dh.flush();
    String res = new String(os.toByteArray(), "UTF-8");
    assertEquals("Only the message is written", "Ahoj", res);
    assertEquals("Called once", 1, my.cnt);
}
 
Example 19
Project: Fetax-AI   File: PasswdEncode.java   Source Code and License 6 votes vote down vote up
/**
 * 可逆解密
 * @param secret
 * @param key
 * @return
 */
public static String aesDecode(String secret,String key){
    if (StringUtils.isEmpty(secret)){
        return null;
    }
    byte[] encodeBytes = hexStringToBytes(secret);
    byte[] retByte = AESDecode(encodeBytes,key);
    if (retByte != null) {
        try {
            return new String(retByte,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    return null;
}
 
Example 20
Project: OpenDiabetes   File: RowOutputText.java   Source Code and License 6 votes vote down vote up
public void writeBytes(String s) {

        if (textFileSettings.isUTF16) {
            try {
                if (s.length() > 0) {
                    byte[] bytes = s.getBytes(textFileSettings.charEncoding);

                    super.write(bytes);
                }
            } catch (UnsupportedEncodingException e) {
                throw Error.error(ErrorCode.TEXT_FILE_IO, e);
            }
        } else {
            super.writeBytes(s);
        }
    }
 
Example 21
Project: picocli   File: CommandLineHelpTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testUsageVariableArityParametersArray() throws UnsupportedEncodingException {
    // if option is required at least once and can be specified multiple times:
    // -f=ARG [-f=ARG]...
    class Args {
        @Parameters(paramLabel = "APARAM", description = "APARAM description")
        String[] a;
        @Parameters(arity = "0..*", description = "b description")
        List<String> b;
        @Parameters(arity = "1..*", description = "c description")
        String[] c;
        @Parameters(arity = "2..*", description = "d description")
        List<String> d;
    }
    String expected = String.format("" +
            "Usage: <main class> [APARAM]... [<b>]... <c>... <d> <d>...%n" +
            "      [APARAM]...             APARAM description%n" +
            "      [<b>]...                b description%n" +
            "      <c>...                  c description%n" +
            "      <d> <d>...              d description%n");
    //CommandLine.usage(new Args(), System.out);
    assertEquals(expected, usageString(new Args(), Help.Ansi.OFF));
}
 
Example 22
Project: incubator-netbeans   File: URLMapper.java   Source Code and License 6 votes vote down vote up
/** copy & pasted from JarURLConnection.parse*/
void parse(URL originalURL) {
    String spec = originalURL.getFile();

    int separator = spec.indexOf('!');

    if (separator != -1) {
        try {
            jarFile = toFile(new URL(spec.substring(0, separator++)));
            entryName = null;
        } catch (MalformedURLException e) {
            return;
        }

        /* if ! is the last letter of the innerURL, entryName is null */
        if (++separator != spec.length()) {
            try {
                // XXX new URI("substring").getPath() might be better?
                entryName = URLDecoder.decode(spec.substring(separator, spec.length()),"UTF-8");
            } catch (UnsupportedEncodingException ex) {
                return;
            }
        }
    }
}
 
Example 23
Project: the-vigilantes   File: SingleByteCharsetConverter.java   Source Code and License 6 votes vote down vote up
/**
 * Initialize the shared instance of a converter for the given character
 * encoding.
 * 
 * @param javaEncodingName
 *            the Java name for the character set to initialize
 * @return a converter for the given character set
 * @throws UnsupportedEncodingException
 *             if the character encoding is not supported
 */
public static SingleByteCharsetConverter initCharset(String javaEncodingName) throws UnsupportedEncodingException, SQLException {
    try {
        if (CharsetMapping.isMultibyteCharset(javaEncodingName)) {
            return null;
        }
    } catch (RuntimeException ex) {
        SQLException sqlEx = SQLError.createSQLException(ex.toString(), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, null);
        sqlEx.initCause(ex);
        throw sqlEx;
    }

    SingleByteCharsetConverter converter = new SingleByteCharsetConverter(javaEncodingName);

    CONVERTER_MAP.put(javaEncodingName, converter);

    return converter;
}
 
Example 24
Project: xlight_android_native   File: WebSocketDelegateImpl.java   Source Code and License 5 votes vote down vote up
private static String[] getLines(ByteBuffer buf) {
    List<String> lineList = new ArrayList<String>();
    while (buf.hasRemaining()) {
        byte next = buf.get();
        List<Byte> lineText = new ArrayList<Byte>();
        while (next != 13) { // CR
            lineText.add(next);
            if (buf.hasRemaining()) {
                next = buf.get();
            }
            else {
                break;
            }
        }
        if (buf.hasRemaining()) {
            next = buf.get(); // should be LF
        }
        byte[] lineTextBytes = new byte[lineText.size()];
        int i = 0;
        for (Byte text : lineText) {
            lineTextBytes[i] = text;
            i++;
        }
        try {
            lineList.add(new String(lineTextBytes, "UTF-8"));
        }
        catch (UnsupportedEncodingException e) {
            throw new IllegalStateException("Unrecognized Encoding from the server", e);
        }
    }
    String[] lines = new String[lineList.size()];
    lineList.toArray(lines);
    return lines;
}
 
Example 25
Project: Relay   File: MessageDigestUtil.java   Source Code and License 5 votes vote down vote up
/**
 * UTF-8编码转换为ISO-9959-1
 *
 * @param str
 * @return
 */
public static String utf8ToIso88591(String str) {
    if (str == null) {
        return str;
    }

    try {
        return new String(str.getBytes("UTF-8"), "ISO-8859-1");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example 26
Project: lams   File: ResponseCachingSender.java   Source Code and License 5 votes vote down vote up
@Override
public void send(final String data, final IoCallback callback) {
    try {
        handleUpdate(ByteBuffer.wrap(data.getBytes("UTF-8")));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    delegate.send(data, callback);
}
 
Example 27
Project: exciting-app   File: StickerService.java   Source Code and License 5 votes vote down vote up
public static void saveStickerToJson(String key, String value) {
    SharedPreferences.Editor editor = App.getDefault().getSharedPreferences(Constants.STICKERPREFER, Context.MODE_PRIVATE).edit();
    try {
        value = URLEncoder.encode(value, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    editor.putString(key, value);
    editor.apply();
}
 
Example 28
Project: ditb   File: ZKSplitLog.java   Source Code and License 5 votes vote down vote up
static String encode(String s) {
  try {
    return URLEncoder.encode(s, "UTF-8");
  } catch (UnsupportedEncodingException e) {
    throw new RuntimeException("URLENCODER doesn't support UTF-8");
  }
}
 
Example 29
Project: Tesseract-OCR-Scanner   File: Encoder.java   Source Code and License 5 votes vote down vote up
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);
  }
  for (byte b : bytes) {
    bits.appendBits(b, 8);
  }
}
 
Example 30
Project: dice   File: ColumnRendererTest.java   Source Code and License 5 votes vote down vote up
private void testRender(ColumnRenderer.RandomGenerator randomGenerator, EncoderFormat encoderFormat, int count, boolean auto, boolean isFile) throws UnsupportedEncodingException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    if (auto) {
        new ColumnRenderer(encoderFormat, randomGenerator).renderAutoColumn(count, new PrintStream(baos), isFile);
    } else {
        new ColumnRenderer(encoderFormat, randomGenerator).render(count, new PrintStream(baos), isFile);
    }

    String out = baos.toString("UTF-8");
    assertNotNull(out);
    assertTrue(out.length() > 10);
    System.out.println(out);
    System.out.println();
}
 
Example 31
Project: logistimo-web-service   File: HDFSStorageUtil.java   Source Code and License 5 votes vote down vote up
@Override
public void write(String bucketName, String filename, String data, String mimeType)
    throws IOException {
  try {
    write(bucketName, filename, data.getBytes("UTF-8"), mimeType);
  } catch (UnsupportedEncodingException e) {
    LOGGER.severe("{0} while getting bytes from data. Message: {1}", e.getClass().getName(),
        e.getMessage());
  }
}
 
Example 32
Project: NanoMaven   File: DirectoryUtils.java   Source Code and License 5 votes vote down vote up
public static String getDataFolder(Class clazz) {
    String path = clazz.getProtectionDomain().getCodeSource().getLocation().getPath();
    String decodedPath = null;

    try {
        decodedPath = URLDecoder.decode(path, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    return decodedPath;
}
 
Example 33
Project: util4j   File: DataTools.java   Source Code and License 5 votes vote down vote up
/**
 * 使用文本截取数据的中间hex数据,文本默认使用utf-8编码
 * @param data
 * @param startHexStr "username"
 * @param endHexStr	 "id"
 * @return
 * @throws UnsupportedEncodingException 
 */
public String[] SubHexArrays(byte[] data,String startStr,String endStr) throws UnsupportedEncodingException
{
	if(data==null||data.length<=0)
	{
		System.out.println("data参数无效!");
		return null;
	}
	byte[] s=startStr.getBytes("utf-8");
	byte[] e=endStr.getBytes("utf-8");
	return SubHexArrays(data, s, e);
}
 
Example 34
Project: EasyHttp   File: EasyHttpUtils.java   Source Code and License 5 votes vote down vote up
public static String createUrlFromParams(String url, Map<String, String> params) {
	if (params == null || params.size() == 0) {
		return url;
	}

	try {
		StringBuilder sb = new StringBuilder();
		sb.append(url);
		if (url.indexOf('&') > 0 || url.indexOf('?') > 0) {
			sb.append("&");
		} else {
			sb.append("?");
		}
		for (Map.Entry<String, String> urlParam : params.entrySet()) {
			//对参数进行 utf-8 编码,防止头信息传中文
			String urlValue = URLEncoder.encode(urlParam.getValue(), "UTF-8");
			sb.append(urlParam.getKey())
					.append("=")
					.append(urlValue)
					.append("&");
		}
		sb.deleteCharAt(sb.length() - 1);
		return sb.toString();
	} catch (UnsupportedEncodingException e) {
		e.printStackTrace();
	}
	return url;
}
 
Example 35
Project: bubichain-sdk-java   File: HttpKit.java   Source Code and License 5 votes vote down vote up
/**
 * 鏋勯�爑rl
 * @param url
 * @param params
 * @return
 */
private static String initParams(String url, Map<String, String> params){
    if (null == params || params.isEmpty()) {
        return url;
    }
    StringBuilder sb = new StringBuilder(url);
    if (url.indexOf("?") == -1) {
        sb.append("?");
    } else {
        sb.append("&");
    }
    boolean first = true;
    for (Entry<String, String> entry : params.entrySet()) {
        if (first) {
            first = false;
        } else {
            sb.append("&");
        }
        String key = entry.getKey();
        String value = entry.getValue();
        sb.append(key).append("=");
        try {
            sb.append(URLEncoder.encode(value, DEFAULT_CHARSET));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}
 
Example 36
Project: mumu   File: ProtoCommon.java   Source Code and License 5 votes vote down vote up
/**
* get token for file URL
* @param remote_filename the filename return by FastDFS server
* @param ts unix timestamp, unit: second
* @param secret_key the secret key
* @return token string
*/
 public static String getToken(String remote_filename, int ts, String secret_key) throws UnsupportedEncodingException, NoSuchAlgorithmException, MyException
 {
 	byte[] bsFilename = remote_filename.getBytes(ClientGlobal.g_charset);
 	byte[] bsKey = secret_key.getBytes(ClientGlobal.g_charset);
 	byte[] bsTimestamp = (new Integer(ts)).toString().getBytes(ClientGlobal.g_charset);
 	
 	byte[] buff = new byte[bsFilename.length + bsKey.length + bsTimestamp.length];
 	System.arraycopy(bsFilename, 0, buff, 0, bsFilename.length);
 	System.arraycopy(bsKey, 0, buff, bsFilename.length, bsKey.length);
 	System.arraycopy(bsTimestamp, 0, buff, bsFilename.length + bsKey.length, bsTimestamp.length);
 	
 	return md5(buff);
 }
 
Example 37
Project: coner-core-client-java   File: ApiClient.java   Source Code and License 5 votes vote down vote up
/**
 * Escape the given string to be used as URL query value.
 *
 * @param str String to be escaped
 * @return Escaped string
 */
public String escapeString(String str) {
    try {
        return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20");
    } catch (UnsupportedEncodingException e) {
        return str;
    }
}
 
Example 38
Project: Snow-Globe   File: CallUtilityTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldGetHttpEntity() throws UnsupportedEncodingException {
    TestRequest request = mock(TestRequest.class);
    String body = "{ thing: \"yes\"}";
    when(request.getBody()).thenReturn(body);
    HttpEntity expectedEntity = new ByteArrayEntity(body.getBytes("UTF-8"));
    HttpEntity actualResult = CallUtility.getHttpEntity(request);
    assertThat(expectedEntity.toString(), is(actualResult.toString()));
}
 
Example 39
Project: metanome-algorithms   File: PartialUniqueTest.java   Source Code and License 5 votes vote down vote up
@Test
public void partialUniqueTest()
    throws AlgorithmExecutionException, FileNotFoundException, UnsupportedEncodingException {
  HepatitisFixture fixture = new HepatitisFixture();
  RelationalInput input = fixture.getInputGenerator().generateNewCopy();
  DuccAlgorithm
      ducc =
      new DuccAlgorithm(input.relationName(), input.columnNames(),
                        fixture.getUCCResultReceiver());
  ducc.setRawKeyError(152);
  PLIBuilder builder = new PLIBuilder(input);
  ducc.run(builder.getPLIList());

  fixture.verifyConditionalUniqueColumnCombination();
}
 
Example 40
Project: alfresco-repository   File: CommentServiceImpl.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private JSONObject getActivityData(String siteId, final NodeRef nodeRef)
   {
       if(siteId != null)
       {
        // create an activity (with some Share-specific parts)
        JSONObject json = new JSONObject();
        json.put("title", nodeService.getProperty(nodeRef, ContentModel.PROP_NAME));
		try
		{
			StringBuilder sb = new StringBuilder("document-details?nodeRef=");
			sb.append(URLEncoder.encode(nodeRef.toString(), "UTF-8"));
			json.put("page", sb.toString());
			// MNT-11667 "createComment" method creates activity for users who are not supposed to see the file
			json.put("nodeRef", nodeRef.toString());
		}
		catch (UnsupportedEncodingException e)
		{
			logger.warn("Unable to urlencode page for create comment activity");
		}

		return json;
       }
       else
       {
       	logger.warn("Unable to determine site in which node " + nodeRef + " resides.");
       	return null;
       }
   }
 
Example 41
Project: keemob   File: CordovaResourceApi.java   Source Code and License 5 votes vote down vote up
private OpenForReadResult readDataUri(Uri uri) {
    String uriAsString = uri.getSchemeSpecificPart();
    int commaPos = uriAsString.indexOf(',');
    if (commaPos == -1) {
        return null;
    }
    String[] mimeParts = uriAsString.substring(0, commaPos).split(";");
    String contentType = null;
    boolean base64 = false;
    if (mimeParts.length > 0) {
        contentType = mimeParts[0];
    }
    for (int i = 1; i < mimeParts.length; ++i) {
        if ("base64".equalsIgnoreCase(mimeParts[i])) {
            base64 = true;
        }
    }
    String dataPartAsString = uriAsString.substring(commaPos + 1);
    byte[] data;
    if (base64) {
        data = Base64.decode(dataPartAsString, Base64.DEFAULT);
    } else {
        try {
            data = dataPartAsString.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            data = dataPartAsString.getBytes();
        }
    }
    InputStream inputStream = new ByteArrayInputStream(data);
    return new OpenForReadResult(uri, inputStream, contentType, data.length, null);
}
 
Example 42
Project: EatDubbo   File: URL.java   Source Code and License 5 votes vote down vote up
public static String encode(String value) {
    if (value == null || value.length() == 0) { 
        return "";
    }
    try {
        return URLEncoder.encode(value, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example 43
Project: openjdk-jdk10   File: Util.java   Source Code and License 5 votes vote down vote up
static boolean compare(ByteBuffer bb, String str) {
    try{
        return Util.compare(bb, str.getBytes("ISO-8859-1"));
    } catch (UnsupportedEncodingException unsupported) {
        throw new AssertionError(unsupported);
    }
}
 
Example 44
Project: Cryptocurrency-Java-Wrappers   File: Poloniex.java   Source Code and License 5 votes vote down vote up
/**
 * Returns all of your available balances
 */
public void balances() {

	String nonce = String.valueOf(System.currentTimeMillis());
	String queryArgs = "command=returnBalances&nonce=" + nonce;

	String sign = sign(secretKey, queryArgs);

	HttpPost post = new HttpPost(TRADING_URL);
	try {
		post.addHeader("Key", key);
		post.addHeader("Sign", sign);
		post.setEntity(new ByteArrayEntity(queryArgs.getBytes("UTF-8")));

		List<NameValuePair> params = new ArrayList<>();
		params.add(new BasicNameValuePair("command", "returnBalances"));
		params.add(new BasicNameValuePair("nonce", nonce));
		post.setEntity(new UrlEncodedFormEntity(params));
	} catch (UnsupportedEncodingException uee) {
		uee.printStackTrace();
	}

	String response = null;

	try(CloseableHttpResponse httpResponse = httpClient.execute(post)) {
		response = EntityUtils.toString(httpResponse.getEntity());
	} catch (IOException ioe) {
		ioe.printStackTrace();
	}

	Utility.evaluateExpression(response);

}
 
Example 45
Project: redpacketui-open   File: RandomDetailDialogFragment.java   Source Code and License 5 votes vote down vote up
private String calculateNameByte(String str) {
    try {
        byte[] strByte = str.getBytes("UTF-8");
        if (strByte.length > 30) {
            str = str.substring(0, str.length() - 1);
            return calculateNameByte(str);
        } else {
            return str;
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return str;
    }
}
 
Example 46
Project: ctsms   File: diff_match_patch.java   Source Code and License 5 votes vote down vote up
/**
 * Crush the diff into an encoded string which describes the operations
 * required to transform text1 into text2.
 * E.g. =3\t-2\t+ing  -> Keep 3 chars, delete 2 chars, insert 'ing'.
 * Operations are tab-separated.  Inserted text is escaped using %xx notation.
 * @param diffs Array of Diff objects.
 * @return Delta text.
 */
public String diff_toDelta(LinkedList<Diff> diffs) {
	StringBuilder text = new StringBuilder();
	for (Diff aDiff : diffs) {
		switch (aDiff.operation) {
			case INSERT:
				try {
					text.append("+").append(URLEncoder.encode(aDiff.text, "UTF-8")
							.replace('+', ' ')).append("\t");
				} catch (UnsupportedEncodingException e) {
					// Not likely on modern system.
					throw new Error("This system does not support UTF-8.", e);
				}
				break;
			case DELETE:
				text.append("-").append(aDiff.text.length()).append("\t");
				break;
			case EQUAL:
				text.append("=").append(aDiff.text.length()).append("\t");
				break;
		}
	}
	String delta = text.toString();
	if (delta.length() != 0) {
		// Strip off trailing tab character.
		delta = delta.substring(0, delta.length() - 1);
		delta = unescapeForEncodeUriCompatability(delta);
	}
	return delta;
}
 
Example 47
Project: personium-core   File: ExtCellLinkTest.java   Source Code and License 5 votes vote down vote up
/**
 * ExtCellとIdなしRoleのlinkを更新するとresponseが400であること.
 */
@Test
public final void ExtCellとIdなしRoleのlinkを更新するとresponseが400であること() {
    String extCellUrl = UrlUtils.cellRoot(EXTCELL_NAME);
    String extCellUrlEncoded = null;
    try {
        extCellUrlEncoded = URLEncoder.encode(UrlUtils.cellRoot(EXTCELL_NAME), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        extCellUrlEncoded = extCellUrl;
    }
    String linkPath = "__ctl/" + ENTITY_SET_EXTCELL + "\\('" + extCellUrlEncoded + "'\\)/\\$links/" + NAV_PROP_ROLE;

    try {
        ExtCellUtils.create(TOKEN, CELL_NAME, extCellUrl, -1);

        // IdなしRoleへの$link更新
        Http.request("link-update-with-body.txt")
                .with("cellPath", CELL_NAME)
                .with("linkPath", linkPath)
                .with("token", AbstractCase.MASTER_TOKEN_NAME)
                .with("body", "\\{\\\"uri\\\":\\\"" + roleUri + "\\\"")
                .returns()
                .statusCode(HttpStatus.SC_BAD_REQUEST);
    } finally {
        ExtCellUtils.delete(TOKEN, CELL_NAME, extCellUrl, -1);
    }
}
 
Example 48
Project: jdk8u-jdk   File: UrlUtil.java   Source Code and License 5 votes vote down vote up
/**
 * Encode a string for inclusion in a URI (according to RFC 2396).
 *
 * Unsafe characters are escaped by encoding them in three-character
 * sequences '%xy', where 'xy' is the two-digit hexadecimal representation
 * of the lower 8-bits of the character.
 *
 * The question mark '?' character is also escaped, as required by RFC 2255.
 *
 * The string is first converted to the specified encoding.
 * For LDAP (2255), the encoding must be UTF-8.
 */
public static final String encode(String s, String enc)
    throws UnsupportedEncodingException {

    byte[] bytes = s.getBytes(enc);
    int count = bytes.length;

    /*
     * From RFC 2396:
     *
     *     mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
     * reserved = ";" | "/" | ":" | "?" | "@" | "&" | "=" | "+" | "$" | ","
     */
    final String allowed = "=,+;.'[email protected]&/$_()!~*:"; // '?' is omitted
    char[] buf = new char[3 * count];
    int j = 0;

    for (int i = 0; i < count; i++) {
        if ((bytes[i] >= 0x61 && bytes[i] <= 0x7A) || // a..z
            (bytes[i] >= 0x41 && bytes[i] <= 0x5A) || // A..Z
            (bytes[i] >= 0x30 && bytes[i] <= 0x39) || // 0..9
            (allowed.indexOf(bytes[i]) >= 0)) {
            buf[j++] = (char) bytes[i];
        } else {
            buf[j++] = '%';
            buf[j++] = Character.forDigit(0xF & (bytes[i] >>> 4), 16);
            buf[j++] = Character.forDigit(0xF & bytes[i], 16);
        }
    }
    return new String(buf, 0, j);
}
 
Example 49
Project: pub-service   File: StringUtil.java   Source Code and License 5 votes vote down vote up
public static String decode(String keyword) {
	try {
		keyword = URLDecoder.decode(keyword, "UTF-8");
	} catch (UnsupportedEncodingException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	return keyword;
}
 
Example 50
Project: fitnotifications   File: ResourceReader.java   Source Code and License 5 votes vote down vote up
/**
 * Reset this reader so that the next call to
 * <code>readLine()</code> returns the first line of the file
 * again.  This is a somewhat expensive call, however, calling
 * <code>reset()</code> after calling it the first time does
 * nothing if <code>readLine()</code> has not been called in
 * between.
 */
public void reset() {
    try {
        _reset();
    } catch (UnsupportedEncodingException e) {}
    // We swallow this exception, if there is one.  If the encoding is
    // invalid, the constructor will have thrown this exception already and
    // the caller shouldn't use the object afterwards.
}
 
Example 51
Project: AgentWorkbench   File: GlobalInfo.java   Source Code and License 5 votes vote down vote up
/**
 * This method is used to encrypt password.
 * @param pswd the password
 * @return the password encrypted
 */
public String pwEncrypt(String pswd) {
	String encryptedPSWD = null;
	if (pswd!=null && pswd.trim().equals("")==false) {
		try {
			encryptedPSWD = new String(Base64.encodeBase64(pswd.getBytes("UTF8")));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	return encryptedPSWD;
}
 
Example 52
Project: hibernateMaster   File: StringUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 按系统编码获取str的字节数组
 * @param str
 * @return
 */
public static byte[] getSystemCharacterSetBytes(String str){
	try {
		return str.getBytes(getCharacterSet());
	} catch (UnsupportedEncodingException e) {
		e.printStackTrace();
		throw new RuntimeException(String.format("不支持%s编码!!", getCharacterSet()));
	}
}
 
Example 53
Project: openjdk-jdk10   File: InternationalBAT.java   Source Code and License 5 votes vote down vote up
private static boolean testRequiredEncodings() {
    boolean pass = true;

    for (int i = 0; i < requiredEncodings.length; i++) {
        String encoding = requiredEncodings[i];
        Locale sampleLocale = sampleLocales[i];
        try {
            int index = 0;
            while (!sampleLocale.equals(requiredLocales[index])) {
                index++;
            }
            byte[] out = requiredLocaleDates[index].getBytes(encoding);
            byte[] expected = expectedBytes[i];
            if (out.length != expected.length) {
                reportConversionError(encoding, expected, out);
                pass = false;
            } else {
                for (int j = 0; j < out.length; j++) {
                    if (out[j] != expected[j]) {
                        reportConversionError(encoding, expected, out);
                        pass = false;
                        break;
                    }
                }
            }
        } catch (UnsupportedEncodingException e) {
            System.out.println("Encoding not available: " + encoding);
            pass = false;
        }
    }
    return pass;
}
 
Example 54
Project: GitHub   File: EventQueueTests.java   Source Code and License 5 votes vote down vote up
public void testEvents_emptyList() throws UnsupportedEncodingException {
    final List<Event> eventsList = new ArrayList<Event>();
    when(mMockCountlyStore.eventsList()).thenReturn(eventsList);

    final String expected = URLEncoder.encode("[]", "UTF-8");
    assertEquals(expected, mEventQueue.events());
    verify(mMockCountlyStore).eventsList();
    verify(mMockCountlyStore).removeEvents(eventsList);
}
 
Example 55
Project: neoscada   File: URLImageLabel.java   Source Code and License 5 votes vote down vote up
private String format ( final String imageUrl, final String string ) throws UnsupportedEncodingException
{
    final Map<String, Object> properties = new HashMap<String, Object> ();
    properties.put ( "value", URLEncoder.encode ( string, "UTF-8" ) );
    properties.put ( "properties", getProperties () );

    final String result = StringReplacer.replace ( imageUrl, StringReplacer.newSource ( properties ), Constants.DEFAULT_PATTERN );

    logger.debug ( "Formatted URL - '{}' -> '{}'", imageUrl, result );

    return result;
}
 
Example 56
Project: tasfe-framework   File: EncryptUtils.java   Source Code and License 5 votes vote down vote up
public static String decryptMode(String secretValue, String encryptKey) {
    String value = null;

    try {
        value = new String(decryptMode(hexStringToByte(secretValue), encryptKey), "UTF-8");
    } catch (UnsupportedEncodingException var4) {
        LOGGER.warn("找不到编码表!", var4);
    }

    return value;
}
 
Example 57
Project: attendance   File: FileAction.java   Source Code and License 5 votes vote down vote up
@RequestMapping("download.do")
public void updown(HttpServletRequest request,HttpServletResponse response,HttpSession session) throws UnsupportedEncodingException {
     String fileName=request.getParameter("fileName");
     String month=request.getParameter("month");
     //��Ҫ�޸�
     //String submonth=month.substring(5, 6);
     String headfilename="���࿼��"+month+"�·�.xls";
     try {
	fileName= new String(fileName.getBytes("ISO-8859-1"),"UTF-8");
} catch (UnsupportedEncodingException e1) {
	// TODO Auto-generated catch block
	e1.printStackTrace();
} 
   response.setCharacterEncoding("utf-8");
   response.setContentType("multipart/form-data");
   response.setHeader("Content-Disposition", "attachment;filename="+new String(headfilename.getBytes("utf-8"),"iso-8859-1"));
   String leftPath= session.getServletContext().getRealPath("file");
   File file=new File(leftPath,fileName); 
   FileUpLoad.writeExcel(leftPath, month);

  try {
	InputStream input=new FileInputStream(file);
	OutputStream os=response.getOutputStream();
	byte[] b=new byte[2048];
	int length;
	while((length=input.read(b))>0){
		os.write(b, 0, length);
	}
	os.close();//�ر���
	input.close();
} catch (Exception e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}

}
 
Example 58
Project: Accessibility   File: DeviceUtils.java   Source Code and License 5 votes vote down vote up
public static String getABI2() {
    if (TextUtils.isEmpty(sAbi2)) {
        try {
            sAbi2 = URLEncoder.encode(Build.CPU_ABI2, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    return sAbi2;
}
 
Example 59
Project: apache-tomcat-7.0.73-with-comment   File: AccessLogValve.java   Source Code and License 5 votes vote down vote up
/**
 * Open the new log file for the date specified by <code>dateStamp</code>.
 */
protected synchronized void open() {
    // Open the current log file
    // If no rotate - no need for dateStamp in fileName
    File pathname = getLogFile(rotatable && !renameOnRotate);

    Charset charset = null;
    if (encoding != null) {
        try {
            charset = B2CConverter.getCharset(encoding);
        } catch (UnsupportedEncodingException ex) {
            log.error(sm.getString(
                    "accessLogValve.unsupportedEncoding", encoding), ex);
        }
    }
    if (charset == null) {
        charset = Charset.defaultCharset();
    }

    try {
        writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(pathname, true), charset), 128000),
                false);

        currentLogFile = pathname;
    } catch (IOException e) {
        writer = null;
        currentLogFile = null;
        log.error(sm.getString("accessLogValve.openFail", pathname), e);
    }
}
 
Example 60
Project: QrCode   File: Encoder.java   Source Code and License 5 votes vote down vote up
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);
  }
  for (byte b : bytes) {
    bits.appendBits(b, 8);
  }
}