List of usage examples for org.apache.commons.io Charsets UTF_8
Charset UTF_8
To view the source code for org.apache.commons.io Charsets UTF_8.
Click Source Link
Eight-bit Unicode Transformation Format.
From source file:org.springframework.security.kerberos.test.MiniKdc.java
public static void main(String[] args) throws Exception { if (args.length < 4) { System.out.println("Arguments: <WORKDIR> <MINIKDCPROPERTIES> " + "<KEYTABFILE> [<PRINCIPALS>]+"); System.exit(1);//from w ww. j av a 2s. com } File workDir = new File(args[0]); if (!workDir.exists()) { throw new RuntimeException("Specified work directory does not exists: " + workDir.getAbsolutePath()); } Properties conf = createConf(); File file = new File(args[1]); if (!file.exists()) { throw new RuntimeException("Specified configuration does not exists: " + file.getAbsolutePath()); } Properties userConf = new Properties(); InputStreamReader r = null; try { r = new InputStreamReader(new FileInputStream(file), Charsets.UTF_8); userConf.load(r); } finally { if (r != null) { r.close(); } } for (Map.Entry<?, ?> entry : userConf.entrySet()) { conf.put(entry.getKey(), entry.getValue()); } final MiniKdc miniKdc = new MiniKdc(conf, workDir); miniKdc.start(); File krb5conf = new File(workDir, "krb5.conf"); if (miniKdc.getKrb5conf().renameTo(krb5conf)) { File keytabFile = new File(args[2]).getAbsoluteFile(); String[] principals = new String[args.length - 3]; System.arraycopy(args, 3, principals, 0, args.length - 3); miniKdc.createPrincipal(keytabFile, principals); System.out.println(); System.out.println("Standalone MiniKdc Running"); System.out.println("---------------------------------------------------"); System.out.println(" Realm : " + miniKdc.getRealm()); System.out.println(" Running at : " + miniKdc.getHost() + ":" + miniKdc.getHost()); System.out.println(" krb5conf : " + krb5conf); System.out.println(); System.out.println(" created keytab : " + keytabFile); System.out.println(" with principals : " + Arrays.asList(principals)); System.out.println(); System.out.println(" Do <CTRL-C> or kill <PID> to stop it"); System.out.println("---------------------------------------------------"); System.out.println(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { miniKdc.stop(); } }); } else { throw new RuntimeException("Cannot rename KDC's krb5conf to " + krb5conf.getAbsolutePath()); } }
From source file:org.springframework.security.kerberos.test.MiniKdc.java
private void initKDCServer() throws Exception { String orgName = conf.getProperty(ORG_NAME); String orgDomain = conf.getProperty(ORG_DOMAIN); String bindAddress = conf.getProperty(KDC_BIND_ADDRESS); final Map<String, String> map = new HashMap<String, String>(); map.put("0", orgName.toLowerCase()); map.put("1", orgDomain.toLowerCase()); map.put("2", orgName.toUpperCase()); map.put("3", orgDomain.toUpperCase()); map.put("4", bindAddress); ClassLoader cl = Thread.currentThread().getContextClassLoader(); InputStream is1 = cl.getResourceAsStream("minikdc.ldiff"); SchemaManager schemaManager = ds.getSchemaManager(); LdifReader reader = null;/* w w w . ja v a 2 s .c o m*/ try { final String content = StrSubstitutor.replace(IOUtils.toString(is1), map); reader = new LdifReader(new StringReader(content)); for (LdifEntry ldifEntry : reader) { ds.getAdminSession().add(new DefaultEntry(schemaManager, ldifEntry.getEntry())); } } finally { IOUtils.closeQuietly(reader); IOUtils.closeQuietly(is1); } kdc = new KdcServer(); kdc.setDirectoryService(ds); // transport String transport = conf.getProperty(TRANSPORT); if (transport.trim().equals("TCP")) { kdc.addTransports(new TcpTransport(bindAddress, port, 3, 50)); } else if (transport.trim().equals("UDP")) { kdc.addTransports(new UdpTransport(port)); } else { throw new IllegalArgumentException("Invalid transport: " + transport); } kdc.setServiceName(conf.getProperty(INSTANCE)); kdc.getConfig().setMaximumRenewableLifetime(Long.parseLong(conf.getProperty(MAX_RENEWABLE_LIFETIME))); kdc.getConfig().setMaximumTicketLifetime(Long.parseLong(conf.getProperty(MAX_TICKET_LIFETIME))); kdc.getConfig().setPaEncTimestampRequired(false); kdc.start(); StringBuilder sb = new StringBuilder(); InputStream is2 = cl.getResourceAsStream("minikdc-krb5.conf"); BufferedReader r = null; try { r = new BufferedReader(new InputStreamReader(is2, Charsets.UTF_8)); String line = r.readLine(); while (line != null) { sb.append(line).append("{3}"); line = r.readLine(); } } finally { IOUtils.closeQuietly(r); IOUtils.closeQuietly(is2); } krb5conf = new File(workDir, "krb5.conf").getAbsoluteFile(); FileUtils.writeStringToFile(krb5conf, MessageFormat.format(sb.toString(), getRealm(), getHost(), Integer.toString(getPort()), System.getProperty("line.separator"))); System.setProperty("java.security.krb5.conf", krb5conf.getAbsolutePath()); System.setProperty("sun.security.krb5.debug", conf.getProperty(DEBUG, "false")); // refresh the config Class<?> classRef; if (System.getProperty("java.vendor").contains("IBM")) { classRef = Class.forName("com.ibm.security.krb5.internal.Config"); } else { classRef = Class.forName("sun.security.krb5.Config"); } Method refreshMethod = classRef.getMethod("refresh", new Class[0]); refreshMethod.invoke(classRef, new Object[0]); LOG.info("MiniKdc listening at port: {}", getPort()); LOG.info("MiniKdc setting JVM krb5.conf to: {}", krb5conf.getAbsolutePath()); }
From source file:org.tomahawk.libtomahawk.resolver.ScriptAccount.java
public ScriptAccount(String path, boolean manuallyInstalled) { String prefix = manuallyInstalled ? "file://" : "file:///android_asset"; mPath = prefix + path;/* w w w.j a va 2 s.c o m*/ mManuallyInstalled = manuallyInstalled; String[] parts = mPath.split("/"); mName = parts[parts.length - 1]; try { InputStream inputStream; if (mManuallyInstalled) { File metadataFile = new File(path + File.separator + "content" + File.separator + "metadata.json"); inputStream = new FileInputStream(metadataFile); } else { inputStream = TomahawkApp.getContext().getAssets() .open(path.substring(1) + "/content/metadata.json"); } String metadataString = IOUtils.toString(inputStream, Charsets.UTF_8); mMetaData = GsonHelper.get().fromJson(metadataString, ScriptResolverMetaData.class); if (mMetaData == null) { Log.e(TAG, "Couldn't read metadata.json. Cannot instantiate ScriptAccount."); return; } } catch (IOException e) { Log.e(TAG, "ScriptAccount: " + e.getClass() + ": " + e.getLocalizedMessage()); Log.e(TAG, "Couldn't read metadata.json. Cannot instantiate ScriptAccount."); return; } mWebView = new WebView(TomahawkApp.getContext()); WebSettings settings = mWebView.getSettings(); settings.setJavaScriptEnabled(true); settings.setDatabaseEnabled(true); if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN_MR2) { //noinspection deprecation settings.setDatabasePath(TomahawkApp.getContext().getDir("databases", Context.MODE_PRIVATE).getPath()); } settings.setDomStorageEnabled(true); mWebView.setWebChromeClient(new TomahawkWebChromeClient()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { mWebView.getSettings().setAllowUniversalAccessFromFileURLs(true); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { WebView.setWebContentsDebuggingEnabled(true); } new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { //initalize WebView String data = "<!DOCTYPE html>" + "<html>" + "<head><title>" + mName + "</title></head>" + "<body>" + "<script src=\"file:///android_asset/js/rsvp-latest.min.js" + "\" type=\"text/javascript\"></script>" + "<script src=\"file:///android_asset/js/cryptojs-core.js" + "\" type=\"text/javascript\"></script>"; if (mMetaData.manifest.scripts != null) { for (String scriptPath : mMetaData.manifest.scripts) { data += "<script src=\"" + mPath + "/content/" + scriptPath + "\" type=\"text/javascript\"></script>"; } } try { String[] cryptoJsScripts = TomahawkApp.getContext().getAssets().list("js/cryptojs"); for (String scriptPath : cryptoJsScripts) { data += "<script src=\"file:///android_asset/js/cryptojs/" + scriptPath + "\" type=\"text/javascript\"></script>"; } } catch (IOException e) { Log.e(TAG, "ScriptResolver: " + e.getClass() + ": " + e.getLocalizedMessage()); } data += "<script src=\"file:///android_asset/js/tomahawk_android_pre.js" + "\" type=\"text/javascript\"></script>" + "<script src=\"file:///android_asset/js/tomahawk.js" + "\" type=\"text/javascript\"></script>" + "<script src=\"file:///android_asset/js/tomahawk-infosystem.js" + "\" type=\"text/javascript\"></script>" + "<script src=\"file:///android_asset/js/tomahawk_android_post.js" + "\" type=\"text/javascript\"></script>" + "<script src=\"" + mPath + "/content/" + mMetaData.manifest.main + "\" type=\"text/javascript\"></script>" + "</body></html>"; mWebView.setWebViewClient(new ScriptWebViewClient(ScriptAccount.this)); mWebView.addJavascriptInterface(new ScriptInterface(ScriptAccount.this), SCRIPT_INTERFACE_NAME); mWebView.loadDataWithBaseURL("file:///android_asset/test.html", data, "text/html", null, null); } }); }
From source file:org.tomahawk.tomahawk_android.dialogs.InstallPluginConfigDialog.java
@Override protected void onPositiveAction() { new Thread(new Runnable() { @Override/*from ww w . j av a 2s. co m*/ public void run() { String destDirPath = TomahawkApp.getContext().getFilesDir().getAbsolutePath() + File.separator + "manualresolvers" + File.separator + ".temp"; File destDir = new File(destDirPath); try { VariousUtils.deleteRecursive(destDir); } catch (FileNotFoundException e) { Log.d(TAG, "onPositiveAction: " + e.getClass() + ": " + e.getLocalizedMessage()); } try { if (UnzipUtility.unzip(mPathToAxe, destDirPath)) { File metadataFile = new File( destDirPath + File.separator + "content" + File.separator + "metadata.json"); String metadataString = FileUtils.readFileToString(metadataFile, Charsets.UTF_8); ScriptResolverMetaData metaData = GsonHelper.get().fromJson(metadataString, ScriptResolverMetaData.class); final File renamedFile = new File(destDir.getParent() + File.separator + metaData.pluginName + "_" + System.currentTimeMillis()); destDir.renameTo(renamedFile); new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { PipeLine.get().addScriptAccount(new ScriptAccount(renamedFile.getPath(), true)); } }); } } catch (IOException e) { Log.e(TAG, "onPositiveAction: " + e.getClass() + ": " + e.getLocalizedMessage()); } } }).start(); dismiss(); }
From source file:org.wisdom.content.bodyparsers.BodyParserXML.java
/** * Invoke the parser and get back a Java object populated * with the content of this request./*from w w w .j ava 2s. c o m*/ * <p> * MUST BE THREAD SAFE TO CALL! * * @param context The context * @param classOfT The class we expect * @param genericType the generic type * @return The object instance populated with all values from raw request */ @Override public <T> T invoke(Context context, Class<T> classOfT, Type genericType) { T t = null; try { final String content = context.body(); if (content == null || content.length() == 0) { return null; } if (classOfT.equals(Document.class)) { return (T) parseXMLDocument(content.getBytes(Charsets.UTF_8)); } if (genericType != null) { t = xml.xmlMapper().readValue(content, xml.xmlMapper().constructType(genericType)); } else { t = xml.xmlMapper().readValue(content, classOfT); } } catch (IOException e) { LOGGER.error(ERROR, e); } return t; }
From source file:org.wisdom.content.bodyparsers.BodyParserXML.java
private Document parseXMLDocument(byte[] bytes) { ByteArrayInputStream stream = null; try {// w w w .j av a 2 s .co m stream = new ByteArrayInputStream(bytes); return xml.fromInputStream(stream, Charsets.UTF_8); } catch (IOException e) { LOGGER.error(ERROR, e); return null; } finally { IOUtils.closeQuietly(stream); } }
From source file:org.wso2.carbon.apimgt.authenticator.LogInServiceTest.java
@Test public void testLogin() throws IOException { HttpURLConnection urlConn = request("/login/token", HttpMethod.POST, true); String postParams = "username=admin&password=admin&grant_type=password" + "&validity_period=3600&scopes=apim:api_view"; urlConn.getOutputStream().write((postParams).getBytes(Charsets.UTF_8)); assertEquals(200, urlConn.getResponseCode()); String content = new String(IOUtils.toByteArray(urlConn.getInputStream()), Charsets.UTF_8); JsonParser parser = new JsonParser(); JsonObject obj = parser.parse(content).getAsJsonObject(); assertTrue(obj.has("isTokenValid")); assertTrue(obj.get("isTokenValid").getAsBoolean()); urlConn.disconnect();//w w w . j a v a2 s . c o m }
From source file:org.wso2.carbon.apimgt.authenticator.LogInServiceTest.java
@Test public void testRefresh() throws IOException { HttpURLConnection urlConn = request("/login/token", HttpMethod.POST, true); String postParams = "grant_type=refresh_token&validity_period=3600&scopes=apim:api_view"; urlConn.setRequestProperty("Authorization", "Bearer 1234"); urlConn.setRequestProperty("Cookie", "WSO2_AM_REFRESH_TOKEN_2=2345"); urlConn.getOutputStream().write((postParams).getBytes(Charsets.UTF_8)); assertEquals(200, urlConn.getResponseCode()); String content = new String(IOUtils.toByteArray(urlConn.getInputStream()), Charsets.UTF_8); JsonParser parser = new JsonParser(); JsonObject obj = parser.parse(content).getAsJsonObject(); assertTrue(obj.has("isTokenValid")); assertTrue(obj.get("isTokenValid").getAsBoolean()); urlConn.disconnect();/*from ww w .j a v a 2 s . c om*/ }
From source file:org.wso2.carbon.identity.application.authenticator.totp.util.TOTPUtil.java
/** * Encrypt the given plain text.//w w w .j a v a 2 s. c o m * * @param plainText The plaintext value to be encrypted and base64 encoded * @return Base64 encoded string * @throws CryptoException On error during encryption */ public static String encrypt(String plainText) throws CryptoException { return CryptoUtil.getDefaultCryptoUtil().encryptAndBase64Encode(plainText.getBytes(Charsets.UTF_8)); }
From source file:org.wso2.carbon.identity.application.authenticator.totp.util.TOTPUtil.java
/** * Decrypt the given cipher text.//ww w . jav a 2 s . c o m * * @param cipherText The string which needs to be decrypted * @return Base64 decoded string * @throws CryptoException On an error during decryption */ public static String decrypt(String cipherText) throws CryptoException { return new String(CryptoUtil.getDefaultCryptoUtil().base64DecodeAndDecrypt(cipherText), Charsets.UTF_8); }