Example usage for java.io InputStream available

List of usage examples for java.io InputStream available

Introduction

In this page you can find the example usage for java.io InputStream available.

Prototype

public int available() throws IOException 

Source Link

Document

Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking, which may be 0, or 0 when end of stream is detected.

Usage

From source file:com.ieasy.basic.util.file.FileUtils.java

/**
 * ?//  w w  w  .j av  a  2s .  c o  m
 * 
 * @param in
 */
private static void showAvailableBytes(InputStream in) {
    try {
        System.out.println("??:" + in.available());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.amazonaws.services.kinesis.aggregators.configuration.ExternalConfigurationModel.java

public static List<ExternalConfigurationModel> buildFromConfig(String configFilePath) throws Exception {
    List<ExternalConfigurationModel> response = new ArrayList<>();

    // reference the config file as a full path
    File configFile = new File(configFilePath);
    if (!configFile.exists()) {

        // try to load the file from the classpath
        InputStream classpathConfig = ExternalConfigurationModel.class.getClassLoader()
                .getResourceAsStream(configFilePath);
        if (classpathConfig != null && classpathConfig.available() > 0) {
            configFile = new File(ExternalConfigurationModel.class
                    .getResource((configFilePath.startsWith("/") ? "" : "/") + configFilePath).toURI());

            LOG.info(String.format("Loaded Configuration %s from Classpath", configFilePath));
        } else {// w w w. j a v  a2s.co  m
            if (configFilePath.startsWith("s3://")) {
                AmazonS3 s3Client = new AmazonS3Client(new DefaultAWSCredentialsProviderChain());
                TransferManager tm = new TransferManager(s3Client);

                // parse the config path to get the bucket name and prefix
                final String s3ProtoRegex = "s3:\\/\\/";
                String bucket = configFilePath.replaceAll(s3ProtoRegex, "").split("/")[0];
                String prefix = configFilePath.replaceAll(String.format("%s%s\\/", s3ProtoRegex, bucket), "");

                // download the file using TransferManager
                configFile = File.createTempFile(configFilePath, null);
                Download download = tm.download(bucket, prefix, configFile);
                download.waitForCompletion();

                // shut down the transfer manager
                tm.shutdownNow();

                LOG.info(String.format("Loaded Configuration from Amazon S3 %s/%s to %s", bucket, prefix,
                        configFile.getAbsolutePath()));
            } else {
                // load the file from external URL
                try {
                    configFile = File.createTempFile(configFilePath, null);
                    FileUtils.copyURLToFile(new URL(configFilePath), configFile, 1000, 1000);
                    LOG.info(String.format("Loaded Configuration from %s to %s", configFilePath,
                            configFile.getAbsolutePath()));
                } catch (IOException e) {
                    // handle the timeouts and so on with a generalised
                    // config
                    // file not found handler later
                }
            }
        }
    } else {
        LOG.info(String.format("Loaded Configuration from Filesystem %s", configFilePath));
    }

    // if we haven't been able to load a config file, then bail
    if (configFile == null || !configFile.exists()) {
        throw new InvalidConfigurationException(
                String.format("Unable to Load Config File from %s", configFilePath));
    }

    JsonNode document = StreamAggregatorUtils.asJsonNode(configFile);

    ExternalConfigurationModel config = null;

    Iterator<JsonNode> i = document.elements();
    while (i.hasNext()) {
        config = new ExternalConfigurationModel();

        JsonNode section = i.next();

        // set generic properties
        config.setNamespace(StreamAggregatorUtils.readValueAsString(section, "namespace"));
        config.setDateFormat(StreamAggregatorUtils.readValueAsString(section, "dateFormat"));
        addTimeHorizons(section, config);
        setAggregatorType(section, config);

        // set the label items
        JsonNode labelItems = StreamAggregatorUtils.readJsonValue(section, "labelItems");
        if (labelItems != null && labelItems.size() > 0) {
            Iterator<JsonNode> iterator = labelItems.elements();
            while (iterator.hasNext()) {
                JsonNode n = iterator.next();
                config.addLabelItems(n.asText());
            }
        }
        config.setLabelAttributeAlias(StreamAggregatorUtils.readValueAsString(section, "labelAttributeAlias"));

        config.setDateItem(StreamAggregatorUtils.readValueAsString(section, "dateItem"));
        config.setDateAttributeAlias(StreamAggregatorUtils.readValueAsString(section, "dateAttributeAlias"));
        JsonNode summaryItems = StreamAggregatorUtils.readJsonValue(section, "summaryItems");
        if (summaryItems != null && summaryItems.size() > 0) {
            Iterator<JsonNode> iterator = summaryItems.elements();
            while (iterator.hasNext()) {
                JsonNode n = iterator.next();
                config.addSummaryItem(n.asText());
            }
        }

        config.setTableName(StreamAggregatorUtils.readValueAsString(section, "tableName"));

        String readIO = StreamAggregatorUtils.readValueAsString(section, "readIOPS");
        if (readIO != null)
            config.setReadIOPs(Long.parseLong(readIO));
        String writeIO = StreamAggregatorUtils.readValueAsString(section, "writeIOPS");
        if (writeIO != null)
            config.setWriteIOPs(Long.parseLong(writeIO));

        // configure tolerance of data extraction problems
        String failOnDataExtraction = StreamAggregatorUtils.readValueAsString(section, "failOnDataExtraction");
        if (failOnDataExtraction != null)
            config.setFailOnDataExtraction(Boolean.parseBoolean(failOnDataExtraction));

        // configure whether metrics should be emitted
        String emitMetrics = StreamAggregatorUtils.readValueAsString(section, "emitMetrics");
        String metricsEmitterClassname = StreamAggregatorUtils.readValueAsString(section,
                "metricsEmitterClass");
        if (emitMetrics != null || metricsEmitterClassname != null) {
            if (metricsEmitterClassname != null) {
                config.setMetricsEmitter((Class<IMetricsEmitter>) ClassLoader.getSystemClassLoader()
                        .loadClass(metricsEmitterClassname));
            } else {
                config.setEmitMetrics(Boolean.parseBoolean(emitMetrics));
            }
        }

        // configure the data store class
        String dataStoreClass = StreamAggregatorUtils.readValueAsString(section, "IDataStore");
        if (dataStoreClass != null) {
            Class<IDataStore> dataStore = (Class<IDataStore>) ClassLoader.getSystemClassLoader()
                    .loadClass(dataStoreClass);
            config.setDataStore(dataStore);
        }

        // get the data extractor configuration, so we know what other json
        // elements to retrieve from the configuration document
        String useExtractor = null;
        try {
            useExtractor = StreamAggregatorUtils.readValueAsString(section, "dataExtractor");
            config.setDataExtractor(DataExtractor.valueOf(useExtractor));
        } catch (Exception e) {
            throw new Exception(
                    String.format("Unable to configure aggregator with Data Extractor %s", useExtractor));
        }

        switch (config.getDataExtractor()) {
        case CSV:
            configureStringCommon(section, config);
            configureCsv(section, config);
            break;
        case JSON:
            configureStringCommon(section, config);
            break;
        case OBJECT:
            configureObject(section, config);
            break;
        case REGEX:
            configureRegex(section, config);
        }

        response.add(config);
    }
    return response;
}

From source file:com.openkm.module.jcr.base.BaseDocumentModule.java

/**
 * Create a new document/*w  ww.  j  a v a  2s .  c  om*/
 * 
 * TODO Parameter title to be used in OpenKM 6
 */
public static Node create(Session session, Node parentNode, String name, String title, String mimeType,
        String[] keywords, InputStream is)
        throws javax.jcr.ItemExistsException, javax.jcr.PathNotFoundException, javax.jcr.AccessDeniedException,
        javax.jcr.RepositoryException, IOException, DatabaseException, UserQuotaExceededException {
    log.debug("create({}, {}, {}, {}, {}, {}, {})",
            new Object[] { session, parentNode, name, title, mimeType, keywords, is });
    long size = is.available();

    // Check user quota
    UserConfig uc = UserConfigDAO.findByPk(session, session.getUserID());
    ProfileMisc pm = uc.getProfile().getPrfMisc();

    // System user don't care quotas
    if (!Config.SYSTEM_USER.equals(session.getUserID()) && pm.getUserQuota() > 0) {
        long currentQuota = JCRUtils.calculateQuota(session);

        if (currentQuota + size > pm.getUserQuota() * 1024 * 1024) {
            throw new UserQuotaExceededException(Long.toString(currentQuota + size));
        }
    }

    // Create and add a new file node
    Node documentNode = parentNode.addNode(name, Document.TYPE);
    documentNode.setProperty(Property.KEYWORDS, keywords);
    documentNode.setProperty(Property.CATEGORIES, new String[] {}, PropertyType.REFERENCE);
    documentNode.setProperty(Document.AUTHOR, session.getUserID());
    documentNode.setProperty(Document.NAME, name);
    documentNode.setProperty(Document.TITLE, title);

    // Get parent node auth info
    Value[] usersReadParent = parentNode.getProperty(Permission.USERS_READ).getValues();
    String[] usersRead = JCRUtils.usrValue2String(usersReadParent, session.getUserID());
    Value[] usersWriteParent = parentNode.getProperty(Permission.USERS_WRITE).getValues();
    String[] usersWrite = JCRUtils.usrValue2String(usersWriteParent, session.getUserID());
    Value[] usersDeleteParent = parentNode.getProperty(Permission.USERS_DELETE).getValues();
    String[] usersDelete = JCRUtils.usrValue2String(usersDeleteParent, session.getUserID());
    Value[] usersSecurityParent = parentNode.getProperty(Permission.USERS_SECURITY).getValues();
    String[] usersSecurity = JCRUtils.usrValue2String(usersSecurityParent, session.getUserID());

    Value[] rolesReadParent = parentNode.getProperty(Permission.ROLES_READ).getValues();
    String[] rolesRead = JCRUtils.rolValue2String(rolesReadParent);
    Value[] rolesWriteParent = parentNode.getProperty(Permission.ROLES_WRITE).getValues();
    String[] rolesWrite = JCRUtils.rolValue2String(rolesWriteParent);
    Value[] rolesDeleteParent = parentNode.getProperty(Permission.ROLES_DELETE).getValues();
    String[] rolesDelete = JCRUtils.rolValue2String(rolesDeleteParent);
    Value[] rolesSecurityParent = parentNode.getProperty(Permission.ROLES_SECURITY).getValues();
    String[] rolesSecurity = JCRUtils.rolValue2String(rolesSecurityParent);

    // Set auth info
    documentNode.setProperty(Permission.USERS_READ, usersRead);
    documentNode.setProperty(Permission.USERS_WRITE, usersWrite);
    documentNode.setProperty(Permission.USERS_DELETE, usersDelete);
    documentNode.setProperty(Permission.USERS_SECURITY, usersSecurity);
    documentNode.setProperty(Permission.ROLES_READ, rolesRead);
    documentNode.setProperty(Permission.ROLES_WRITE, rolesWrite);
    documentNode.setProperty(Permission.ROLES_DELETE, rolesDelete);
    documentNode.setProperty(Permission.ROLES_SECURITY, rolesSecurity);

    Node contentNode = documentNode.addNode(Document.CONTENT, Document.CONTENT_TYPE);
    contentNode.setProperty(Document.SIZE, size);
    contentNode.setProperty(Document.AUTHOR, session.getUserID());
    contentNode.setProperty(Document.VERSION_COMMENT, "");
    contentNode.setProperty(JcrConstants.JCR_MIMETYPE, mimeType);
    contentNode.setProperty(JcrConstants.JCR_DATA, is);

    // jcr:encoding only have sense for text/* MIME
    if (mimeType.startsWith("text/")) {
        contentNode.setProperty(JcrConstants.JCR_ENCODING, "UTF-8");
    }

    if (Config.MANAGED_TEXT_EXTRACTION) {
        RegisteredExtractors.index(documentNode, contentNode, mimeType);
    }

    contentNode.setProperty(JcrConstants.JCR_LASTMODIFIED, Calendar.getInstance());
    parentNode.save();

    // Esta lnea vale millones!! Resuelve la incidencia del isCkechedOut.
    // Por lo visto un nuevo nodo se aade con el isCheckedOut a true :/
    contentNode.checkin();

    return documentNode;
}

From source file:com.nextgis.mobile.map.LocalGeoJsonLayer.java

/**
 * Create a LocalGeoJsonLayer from the GeoJson data submitted by uri.
 *//*  www . ja  v a2s .  c om*/
protected static void create(final MapBase map, String layerName, Uri uri) {

    String sErr = map.getContext().getString(R.string.error_occurred);
    ProgressDialog progressDialog = new ProgressDialog(map.getContext());

    try {
        InputStream inputStream = map.getContext().getContentResolver().openInputStream(uri);
        if (inputStream != null) {

            progressDialog.setMessage(map.getContext().getString(R.string.message_loading_progress));
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.setCancelable(true);
            progressDialog.show();

            int nSize = inputStream.available();
            int nIncrement = 0;
            progressDialog.setMax(nSize);

            //read all geojson
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

            StringBuilder responseStrBuilder = new StringBuilder();

            String inputStr;
            while ((inputStr = streamReader.readLine()) != null) {
                nIncrement += inputStr.length();
                progressDialog.setProgress(nIncrement);
                responseStrBuilder.append(inputStr);
            }

            progressDialog.setMessage(map.getContext().getString(R.string.message_opening_progress));

            JSONObject geoJSONObject = new JSONObject(responseStrBuilder.toString());

            if (!geoJSONObject.has(GEOJSON_TYPE)) {
                sErr += ": " + map.getContext().getString(R.string.error_geojson_unsupported);
                Toast.makeText(map.getContext(), sErr, Toast.LENGTH_SHORT).show();
                progressDialog.hide();
                return;
            }

            //check crs
            boolean isWGS84 = true; //if no crs tag - WGS84 CRS

            if (geoJSONObject.has(GEOJSON_CRS)) {
                JSONObject crsJSONObject = geoJSONObject.getJSONObject(GEOJSON_CRS);

                //the link is unsupported yet.
                if (!crsJSONObject.getString(GEOJSON_TYPE).equals(GEOJSON_NAME)) {
                    sErr += ": " + map.getContext().getString(R.string.error_geojson_crs_unsupported);
                    Toast.makeText(map.getContext(), sErr, Toast.LENGTH_SHORT).show();
                    progressDialog.hide();
                    return;
                }

                JSONObject crsPropertiesJSONObject = crsJSONObject.getJSONObject(GEOJSON_PROPERTIES);
                String crsName = crsPropertiesJSONObject.getString(GEOJSON_NAME);

                if (crsName.equals("urn:ogc:def:crs:OGC:1.3:CRS84")) { // WGS84
                    isWGS84 = true;
                } else if (crsName.equals("urn:ogc:def:crs:EPSG::3857")) { //Web Mercator
                    isWGS84 = false;
                } else {
                    sErr += ": " + map.getContext().getString(R.string.error_geojson_crs_unsupported);
                    Toast.makeText(map.getContext(), sErr, Toast.LENGTH_SHORT).show();
                    progressDialog.hide();
                    return;
                }
            }

            //load contents to memory and reproject if needed
            JSONArray geoJSONFeatures = geoJSONObject.getJSONArray(GEOJSON_TYPE_FEATURES);

            if (0 == geoJSONFeatures.length()) {
                sErr += ": " + map.getContext().getString(R.string.error_geojson_crs_unsupported);
                Toast.makeText(map.getContext(), sErr, Toast.LENGTH_SHORT).show();
                progressDialog.hide();
                return;
            }

            List<Feature> features = geoJSONFeaturesToFeatures(geoJSONFeatures, isWGS84, map.getContext(),
                    progressDialog);

            create(map, layerName, features);
        }

    } catch (UnsupportedEncodingException e) {
        Log.d(TAG, "Exception: " + e.getLocalizedMessage());
        sErr += ": " + e.getLocalizedMessage();
    } catch (FileNotFoundException e) {
        Log.d(TAG, "Exception: " + e.getLocalizedMessage());
        sErr += ": " + e.getLocalizedMessage();
    } catch (IOException e) {
        Log.d(TAG, "Exception: " + e.getLocalizedMessage());
        sErr += ": " + e.getLocalizedMessage();
    } catch (JSONException e) {
        Log.d(TAG, "Exception: " + e.getLocalizedMessage());
        sErr += ": " + e.getLocalizedMessage();
    }

    progressDialog.hide();
    //if we here something wrong occurred
    Toast.makeText(map.getContext(), sErr, Toast.LENGTH_SHORT).show();
}

From source file:com.clustercontrol.infra.util.JschUtil.java

private static byte[] getByteArray(ChannelExec channel, InputStream in, int maxSize, int timeout)
        throws IOException, HinemosUnknown {
    int pos = 0;// www. j a  v a 2  s .c  o m
    byte[] buffer = new byte[maxSize];
    boolean loop = true;

    long start = HinemosTime.currentTimeMillis();
    while (loop) {
        while (in.available() > 0 && pos < maxSize) {
            int len = in.read(buffer, pos, maxSize - pos);
            if (len < 0) {
                loop = false;
                break;
            }
            pos += len;
            start = HinemosTime.currentTimeMillis();
        }

        if (pos >= maxSize) {
            loop = false;
        } else if (channel.isClosed()) {
            if (in.available() <= 0) {
                loop = false;
            }
        } else {
            if ((HinemosTime.currentTimeMillis() - start) > timeout)
                throw new HinemosUnknown("Jsch command is spent too much time.");

            try {
                Thread.sleep(500);
            } catch (Exception ee) {
            }
        }
    }
    return pos >= maxSize ? buffer : Arrays.copyOfRange(buffer, 0, pos);
}

From source file:com.ikon.module.jcr.base.BaseDocumentModule.java

/**
 * Create a new document/*from  w  ww  . jav  a  2s.  c om*/
 * 
 * TODO Parameter title to be used in openkm 6
 */
public static Node create(Session session, Node parentNode, String name, String title, String mimeType,
        String[] keywords, InputStream is)
        throws javax.jcr.ItemExistsException, javax.jcr.PathNotFoundException, javax.jcr.AccessDeniedException,
        javax.jcr.RepositoryException, IOException, DatabaseException, UserQuotaExceededException {
    log.debug("create({}, {}, {}, {}, {}, {}, {})",
            new Object[] { session, parentNode, name, title, mimeType, keywords, is });
    long size = is.available();

    // Check user quota
    UserConfig uc = UserConfigDAO.findByPk(session, session.getUserID());
    ProfileMisc pm = uc.getProfile().getPrfMisc();

    // System user don't care quotas
    if (!Config.SYSTEM_USER.equals(session.getUserID()) && pm.getUserQuota() > 0) {
        long currentQuota = 0;

        if (Config.USER_ITEM_CACHE) {
            UserItems ui = UserItemsManager.get(session.getUserID());
            currentQuota = ui.getSize();
        } else {
            currentQuota = JCRUtils.calculateQuota(session);
        }

        if (currentQuota + size > pm.getUserQuota() * 1024 * 1024) {
            throw new UserQuotaExceededException(Long.toString(currentQuota + size));
        }
    }

    // Create and add a new file node
    Node documentNode = parentNode.addNode(name, Document.TYPE);
    documentNode.setProperty(Property.KEYWORDS, keywords);
    documentNode.setProperty(Property.CATEGORIES, new String[] {}, PropertyType.REFERENCE);
    documentNode.setProperty(Document.AUTHOR, session.getUserID());
    documentNode.setProperty(Document.NAME, name);
    documentNode.setProperty(Document.TITLE, title);

    // Get parent node auth info
    Value[] usersReadParent = parentNode.getProperty(Permission.USERS_READ).getValues();
    String[] usersRead = JCRUtils.usrValue2String(usersReadParent, session.getUserID());
    Value[] usersWriteParent = parentNode.getProperty(Permission.USERS_WRITE).getValues();
    String[] usersWrite = JCRUtils.usrValue2String(usersWriteParent, session.getUserID());
    Value[] usersDeleteParent = parentNode.getProperty(Permission.USERS_DELETE).getValues();
    String[] usersDelete = JCRUtils.usrValue2String(usersDeleteParent, session.getUserID());
    Value[] usersSecurityParent = parentNode.getProperty(Permission.USERS_SECURITY).getValues();
    String[] usersSecurity = JCRUtils.usrValue2String(usersSecurityParent, session.getUserID());

    Value[] rolesReadParent = parentNode.getProperty(Permission.ROLES_READ).getValues();
    String[] rolesRead = JCRUtils.rolValue2String(rolesReadParent);
    Value[] rolesWriteParent = parentNode.getProperty(Permission.ROLES_WRITE).getValues();
    String[] rolesWrite = JCRUtils.rolValue2String(rolesWriteParent);
    Value[] rolesDeleteParent = parentNode.getProperty(Permission.ROLES_DELETE).getValues();
    String[] rolesDelete = JCRUtils.rolValue2String(rolesDeleteParent);
    Value[] rolesSecurityParent = parentNode.getProperty(Permission.ROLES_SECURITY).getValues();
    String[] rolesSecurity = JCRUtils.rolValue2String(rolesSecurityParent);

    // Set auth info
    documentNode.setProperty(Permission.USERS_READ, usersRead);
    documentNode.setProperty(Permission.USERS_WRITE, usersWrite);
    documentNode.setProperty(Permission.USERS_DELETE, usersDelete);
    documentNode.setProperty(Permission.USERS_SECURITY, usersSecurity);
    documentNode.setProperty(Permission.ROLES_READ, rolesRead);
    documentNode.setProperty(Permission.ROLES_WRITE, rolesWrite);
    documentNode.setProperty(Permission.ROLES_DELETE, rolesDelete);
    documentNode.setProperty(Permission.ROLES_SECURITY, rolesSecurity);

    Node contentNode = documentNode.addNode(Document.CONTENT, Document.CONTENT_TYPE);
    contentNode.setProperty(Document.SIZE, size);
    contentNode.setProperty(Document.AUTHOR, session.getUserID());
    contentNode.setProperty(Document.VERSION_COMMENT, "");
    contentNode.setProperty(JcrConstants.JCR_MIMETYPE, mimeType);
    contentNode.setProperty(JcrConstants.JCR_DATA, is);

    // jcr:encoding only have sense for text/* MIME
    if (mimeType.startsWith("text/")) {
        contentNode.setProperty(JcrConstants.JCR_ENCODING, "UTF-8");
    }

    if (Config.MANAGED_TEXT_EXTRACTION) {
        RegisteredExtractors.index(documentNode, contentNode, mimeType);
    }

    contentNode.setProperty(JcrConstants.JCR_LASTMODIFIED, Calendar.getInstance());
    parentNode.save();

    // Esta lnea vale millones!! Resuelve la incidencia del isCkechedOut.
    // Por lo visto un nuevo nodo se aade con el isCheckedOut a true :/
    contentNode.checkin();

    // Update user items size
    if (Config.USER_ITEM_CACHE) {
        UserItemsManager.incSize(session.getUserID(), size);
        UserItemsManager.incDocuments(session.getUserID(), 1);
    }

    return documentNode;
}

From source file:com.nary.Debug.java

public static Object loadClass(InputStream _inStream, boolean _uncompress) {
    ObjectInputStream ois;//from ww w.  j  a v a 2 s  .c  om
    try {
        if (_uncompress) {
            // we need to get the input as a byte [] so we can decompress (inflate) it.  
            Inflater inflater = new Inflater();
            ByteArrayOutputStream bos;
            int bytesAvail = _inStream.available();
            if (bytesAvail > 0) {
                bos = new ByteArrayOutputStream(bytesAvail);
            } else {
                bos = new ByteArrayOutputStream();
            }

            byte[] buffer = new byte[1024];
            int read = _inStream.read(buffer);
            while (read > 0) {
                bos.write(buffer, 0, read);
                read = _inStream.read(buffer);
            }
            bos.flush();
            inflater.setInput(bos.toByteArray());

            bos.reset();
            buffer = new byte[1024];
            int inflated = inflater.inflate(buffer);
            while (inflated > 0) {
                bos.write(buffer, 0, inflated);
                inflated = inflater.inflate(buffer);
            }

            bos.flush();
            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());

            ois = new ObjectInputStream(bis);

        } else {
            ois = new ObjectInputStream(_inStream);
        }

        return ois.readObject();
    } catch (Exception E) {
        return null;
    } finally {
        try {
            _inStream.close();
        } catch (Exception ioe) {
        }
    }
}

From source file:it.crs4.most.ehrlib.WidgetProvider.java

/**
 * Parses the file to string./*from w  w w . j a va  2s  . c om*/
 *
 * @param context the context
 * @param filename the filename
 * @return the string
 */
public static String parseFileToString(Context context, String filename) {
    try {
        InputStream stream = context.getAssets().open(filename);
        int size = stream.available();

        byte[] bytes = new byte[size];
        stream.read(bytes);
        stream.close();

        return new String(bytes);

    } catch (IOException e) {
        Log.i(TAG, "IOException: " + e.getMessage());
    }
    return null;
}

From source file:com.ai.runner.center.pay.web.business.payment.util.third.unionpay.sdk.SDKUtil.java

/**
 * ?DEFLATEBase64??/* ww w . j a v a 2s.co  m*/
 * ???
 * @param filePath ?
 * @return
 */
public static String enCodeFileContent(String filePath) {
    String baseFileContent = "";

    File file = new File(filePath);
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    InputStream in = null;
    try {
        in = new FileInputStream(file);
        int fl = in.available();
        if (null != in) {
            byte[] s = new byte[fl];
            in.read(s, 0, fl);
            // ?.
            baseFileContent = new String(SecureUtil.base64Encode(SecureUtil.deflater(s)));
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (null != in) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return baseFileContent;
}

From source file:Gen.java

public static void genWeb() throws Exception {

    String GEN_WEBINF = GEN_ROOT + FILE_SEPARATOR + "war" + FILE_SEPARATOR + "WEB-INF";

    String WAR_NAME = System.getProperty("warname") != null && !System.getProperty("warname").equals("")
            ? System.getProperty("warname")
            : MAPPING_JAR_NAME.substring(0, MAPPING_JAR_NAME.length() - "jar".length()) + "war";
    if (!WAR_NAME.endsWith(".war"))
        WAR_NAME += ".war";

    String PROPS_EMBED = System.getProperty("propsembed") != null
            && !System.getProperty("propsembed").equals("") ? System.getProperty("propsembed") : null;

    deleteDir(GEN_ROOT + FILE_SEPARATOR + "war");

    regenerateDir(GEN_WEBINF + FILE_SEPARATOR + "classes");
    regenerateDir(GEN_WEBINF + FILE_SEPARATOR + "lib");

    Vector<String> warJars = new Vector<String>();
    warJars.add(GEN_ROOT_LIB + FILE_SEPARATOR + MAPPING_JAR_NAME);

    InputStream inputStreamCore = Gen.class.getResourceAsStream("/biocep-core-tomcat.jar");
    if (inputStreamCore != null) {
        try {//from  w  w  w.j a  va2  s.c om
            byte data[] = new byte[BUFFER_SIZE];
            FileOutputStream fos = new FileOutputStream(
                    GEN_WEBINF + FILE_SEPARATOR + "lib" + "/biocep-core.jar");
            int count = 0;
            while ((count = inputStreamCore.read(data, 0, BUFFER_SIZE)) != -1) {
                fos.write(data, 0, count);
            }
            fos.flush();
            fos.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {

        warJars.add("RJB.jar");

        warJars.add("lib/desktop/JRI.jar");

        FilenameFilter jarsFilter = new FilenameFilter() {
            public boolean accept(File arg0, String arg1) {
                return arg1.endsWith(".jar");
            }
        };

        {
            String[] derby_jdbc_jars = new File("lib/jdbc").list(jarsFilter);
            for (int i = 0; i < derby_jdbc_jars.length; ++i) {
                warJars.add("lib/jdbc" + FILE_SEPARATOR + derby_jdbc_jars[i]);
            }
        }

        {
            String[] pool_jars = new File("lib/pool").list(jarsFilter);
            for (int i = 0; i < pool_jars.length; ++i) {
                warJars.add("lib/pool" + FILE_SEPARATOR + pool_jars[i]);
            }
        }

        {
            String[] httpclient_jars = new File("lib/j2ee").list(jarsFilter);
            for (int i = 0; i < httpclient_jars.length; ++i) {
                warJars.add("lib/j2ee" + FILE_SEPARATOR + httpclient_jars[i]);
            }
        }
    }

    log.info(warJars);
    for (int i = 0; i < warJars.size(); ++i) {
        Copy copyTask = new Copy();
        copyTask.setProject(_project);
        copyTask.setTaskName("copy to war");
        copyTask.setTodir(new File(GEN_WEBINF + FILE_SEPARATOR + "lib"));
        copyTask.setFile(new File(warJars.elementAt(i)));
        copyTask.init();
        copyTask.execute();
    }

    unzip(Gen.class.getResourceAsStream("/jaxws.zip"), GEN_WEBINF + FILE_SEPARATOR + "lib",
            new EqualNameFilter("activation.jar", "jaxb-api.jar", "jaxb-impl.jar", "jaxb-xjc.jar",
                    "jaxws-api.jar", "jaxws-libs.jar", "jaxws-rt.jar", "jaxws-tools.jar", "jsr173_api.jar",
                    "jsr181-api.jar", "jsr250-api.jar", "saaj-api.jar", "saaj-impl.jar", "sjsxp.jar",
                    "FastInfoset.jar", "http.jar", "mysql-connector-java-5.1.0-bin.jar", "ojdbc-14.jar"),
            BUFFER_SIZE, false, "Unzipping psTools..", 17);

    PrintWriter pw_web_xml = new PrintWriter(GEN_WEBINF + FILE_SEPARATOR + "web.xml");
    pw_web_xml.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    pw_web_xml.println(
            "<web-app version=\"2.4\" xmlns=\"http://java.sun.com/xml/ns/j2ee\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd\">");
    pw_web_xml.println(
            "<listener><listener-class>com.sun.xml.ws.transport.http.servlet.WSServletContextListener</listener-class></listener>");

    for (String className : DirectJNI._rPackageInterfacesHash.keySet()) {
        String shortClassName = className.substring(className.lastIndexOf('.') + 1);
        pw_web_xml.println("<servlet><servlet-name>" + shortClassName
                + "_servlet</servlet-name><servlet-class>org.kchine.r.server.http.frontend.InterceptorServlet</servlet-class><load-on-startup>1</load-on-startup></servlet>");
    }

    pw_web_xml.println("<servlet><servlet-name>" + "WSServlet"
            + "</servlet-name><servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class><load-on-startup>1</load-on-startup></servlet>");

    pw_web_xml.println("<servlet><servlet-name>" + "MappingClassServlet"
            + "</servlet-name><servlet-class>org.kchine.r.server.http.frontend.MappingClassServlet</servlet-class><load-on-startup>1</load-on-startup></servlet>");

    for (String className : DirectJNI._rPackageInterfacesHash.keySet()) {
        String shortClassName = className.substring(className.lastIndexOf('.') + 1);
        pw_web_xml.println(
                "<servlet-mapping><servlet-name>" + shortClassName + "_servlet</servlet-name><url-pattern>/"
                        + shortClassName + "</url-pattern></servlet-mapping>");
    }

    pw_web_xml.println("<servlet-mapping><servlet-name>" + "MappingClassServlet"
            + "</servlet-name><url-pattern>" + "/mapping/classes/*" + "</url-pattern></servlet-mapping>");

    pw_web_xml.println("<session-config><session-timeout>30</session-timeout></session-config>");
    pw_web_xml.println("</web-app>");
    pw_web_xml.flush();
    pw_web_xml.close();

    PrintWriter pw_sun_jaxws_xml = new PrintWriter(GEN_WEBINF + FILE_SEPARATOR + "sun-jaxws.xml");
    pw_sun_jaxws_xml.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    pw_sun_jaxws_xml.println("<endpoints xmlns='http://java.sun.com/xml/ns/jax-ws/ri/runtime' version='2.0'>");

    for (String className : DirectJNI._rPackageInterfacesHash.keySet()) {
        String shortClassName = className.substring(className.lastIndexOf('.') + 1);
        pw_sun_jaxws_xml.println("   <endpoint    name='name_" + shortClassName + "'   implementation='"
                + className + "Web" + "' url-pattern='/" + shortClassName + "'/>");
    }

    pw_sun_jaxws_xml.println("</endpoints>");
    pw_sun_jaxws_xml.flush();
    pw_sun_jaxws_xml.close();

    if (PROPS_EMBED != null) {
        InputStream is = new FileInputStream(PROPS_EMBED);
        byte[] buffer = new byte[is.available()];
        is.read(buffer);
        RandomAccessFile raf = new RandomAccessFile(
                GEN_WEBINF + FILE_SEPARATOR + "classes" + FILE_SEPARATOR + "globals.properties", "rw");
        raf.setLength(0);
        raf.write(buffer);
        raf.close();
    }

    War warTask = new War();
    warTask.setProject(_project);
    warTask.setTaskName("war");
    warTask.setBasedir(new File(GEN_ROOT + FILE_SEPARATOR + "war"));
    warTask.setDestFile(new File(GEN_ROOT + FILE_SEPARATOR + WAR_NAME));
    warTask.setIncludes("**/*");
    warTask.init();
    warTask.execute();

}