Java 类java.io.UnsupportedEncodingException 实例源码

项目:AgentWorkbench    文件:OntologyInstanceViewer.java   
/**
 * 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();
    }

}
项目:s-store    文件:TheHashinator.java   
/**
 * 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;
}
项目:boohee_v5.6    文件:MQUtils.java   
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;
    }
}
项目:RDF2PT    文件:DefaultIRIConverter.java   
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;
}
项目:SWDemo    文件:ChatActivity.java   
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);
}
项目:uavstack    文件:HttpTestApphubManager.java   
/**
 * 打包请求数据
 * 
 * @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;
}
项目:SpringWebAnuncio    文件:Usuarios.java   
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);
}
   }
项目:romanov    文件:MpegAudioFileReader.java   
/**
 * 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;
}
项目:openaudible    文件:OggVorbisCommentTagCreator.java   
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;
}
项目:awe-awesomesky    文件:PasswdEncode.java   
/**
 *  可逆加密
 * @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;
}
项目:lambdora    文件:TripleUtil.java   
/**
 * 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();
}
项目:ProyectoPacientes    文件:Buffer.java   
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;
}
项目:outcomes    文件:Main.java   
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));

    }
项目:Pet-Supply-Store    文件:SHASecurityProvider.java   
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;
}
项目:3DSFE-Randomizer    文件:FatesJobs.java   
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;
}
项目:uri-toolkit    文件:FormEncoded.java   
@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();
}
项目:incubator-netbeans    文件:DispatchingHandlerTest.java   
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);
}
项目:Fetax-AI    文件:PasswdEncode.java   
/**
 * 可逆解密
 * @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;
}
项目:OpenDiabetes    文件:RowOutputText.java   
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);
        }
    }
项目:picocli    文件:CommandLineHelpTest.java   
@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));
}
项目:incubator-netbeans    文件:URLMapper.java   
/** 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;
            }
        }
    }
}
项目:the-vigilantes    文件:SingleByteCharsetConverter.java   
/**
 * 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;
}
项目:xlight_android_native    文件:WebSocketDelegateImpl.java   
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;
}
项目:Relay    文件:MessageDigestUtil.java   
/**
 * 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);
    }
}
项目:lams    文件:ResponseCachingSender.java   
@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);
}
项目:exciting-app    文件:StickerService.java   
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();
}
项目:ditb    文件:ZKSplitLog.java   
static String encode(String s) {
  try {
    return URLEncoder.encode(s, "UTF-8");
  } catch (UnsupportedEncodingException e) {
    throw new RuntimeException("URLENCODER doesn't support UTF-8");
  }
}
项目:Tesseract-OCR-Scanner    文件:Encoder.java   
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);
  }
}
项目:dice    文件:ColumnRendererTest.java   
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();
}
项目:logistimo-web-service    文件:HDFSStorageUtil.java   
@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());
  }
}
项目:NanoMaven    文件:DirectoryUtils.java   
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;
}
项目:util4j    文件:DataTools.java   
/**
 * 使用文本截取数据的中间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);
}
项目:EasyHttp    文件:EasyHttpUtils.java   
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;
}
项目:bubichain-sdk-java    文件:HttpKit.java   
/**
 * 鏋勯�爑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();
}
项目:mumu    文件:ProtoCommon.java   
/**
* 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);
 }
项目:coner-core-client-java    文件:ApiClient.java   
/**
 * 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;
    }
}
项目:Snow-Globe    文件:CallUtilityTest.java   
@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()));
}
项目:metanome-algorithms    文件:PartialUniqueTest.java   
@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();
}
项目:alfresco-repository    文件:CommentServiceImpl.java   
@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;
       }
   }
项目:keemob    文件:CordovaResourceApi.java   
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);
}