Example usage for java.io InputStreamReader close

List of usage examples for java.io InputStreamReader close

Introduction

In this page you can find the example usage for java.io InputStreamReader close.

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:com.izforge.izpack.compiler.CompilerConfig.java

/**
 * Adds the resources./* ww w .j a v  a 2 s  . c  om*/
 *
 * @param data The XML data.
 * @throws CompilerException Description of the Exception
 */
protected void addResources(IXMLElement data) throws CompilerException {
    notifyCompilerListener("addResources", CompilerListener.BEGIN, data);
    IXMLElement root = data.getFirstChildNamed("resources");
    if (root == null) {
        return;
    }

    // We process each res markup
    for (IXMLElement resNode : root.getChildrenNamed("res")) {
        String id = xmlCompilerHelper.requireAttribute(resNode, "id");
        String src = xmlCompilerHelper.requireAttribute(resNode, "src");
        // the parse attribute causes substitution to occur
        boolean substitute = xmlCompilerHelper.validateYesNoAttribute(resNode, "parse", NO);
        // the parsexml attribute causes the xml document to be parsed
        boolean parsexml = xmlCompilerHelper.validateYesNoAttribute(resNode, "parsexml", NO);

        String encoding = resNode.getAttribute("encoding");
        if (encoding == null) {
            encoding = "";
        }

        // basedir is not prepended if src is already an absolute path
        URL originalUrl = resourceFinder.findProjectResource(src, "Resource", resNode);
        URL url = originalUrl;

        InputStream is = null;
        OutputStream os = null;
        try {
            if (parsexml || (!"".equals(encoding)) || (substitute && !packager.getVariables().isEmpty())) {
                // make the substitutions into a temp file
                File parsedFile = FileUtils.createTempFile("izpp", null);
                parsedFile.deleteOnExit();
                FileOutputStream outFile = new FileOutputStream(parsedFile);
                os = new BufferedOutputStream(outFile);
                // and specify the substituted file to be added to the
                // packager
                url = parsedFile.toURI().toURL();
            }

            if (!"".equals(encoding)) {
                File recodedFile = FileUtils.createTempFile("izenc", null);
                recodedFile.deleteOnExit();

                InputStreamReader reader = new InputStreamReader(originalUrl.openStream(), encoding);
                OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(recodedFile), "UTF-8");

                char[] buffer = new char[1024];
                int read;
                while ((read = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, read);
                }
                reader.close();
                writer.close();
                if (parsexml) {
                    originalUrl = recodedFile.toURI().toURL();
                } else {
                    url = recodedFile.toURI().toURL();
                }
            }

            if (parsexml) {
                IXMLParser parser = new XMLParser();
                // this constructor will open the specified url (this is
                // why the InputStream is not handled in a similar manner
                // to the OutputStream)

                IXMLElement xml = parser.parse(originalUrl);
                IXMLWriter writer = new XMLWriter();
                if (substitute && !packager.getVariables().isEmpty()) {
                    // if we are also performing substitutions on the file
                    // then create an in-memory copy to pass to the
                    // substitutor
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    writer.setOutput(baos);
                    is = new ByteArrayInputStream(baos.toByteArray());
                } else {
                    // otherwise write direct to the temp file
                    writer.setOutput(os);
                }
                writer.write(xml);
            }

            // substitute variable values in the resource if parsed
            if (substitute) {
                if (packager.getVariables().isEmpty()) {
                    // reset url to original.
                    url = originalUrl;
                    assertionHelper.parseWarn(resNode,
                            "No variables defined. " + url.getPath() + " not parsed.");
                } else {
                    SubstitutionType type = SubstitutionType.lookup(resNode.getAttribute("type"));

                    // if the xml parser did not open the url
                    // ('parsexml' was not enabled)
                    if (null == is) {
                        is = new BufferedInputStream(originalUrl.openStream());
                    }
                    // VariableSubstitutor vs = new
                    // VariableSubstitutorImpl(compiler.getVariables());
                    variableSubstitutor.substitute(is, os, type, "UTF-8");
                }
            }

        } catch (Exception e) {
            assertionHelper.parseError(resNode, e.getMessage(), e);
        } finally {
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    // ignore as there is nothing we can realistically do
                    // so lets at least try to close the input stream
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    // ignore as there is nothing we can realistically do
                }
            }
        }

        packager.addResource(id, url);

        // remembering references to all added packsLang.xml files
        if (id.startsWith("packsLang.xml")) {
            List<URL> packsLangURLs;
            if (packsLangUrlMap.containsKey(id)) {
                packsLangURLs = packsLangUrlMap.get(id);
            } else {
                packsLangURLs = new ArrayList<URL>();
                packsLangUrlMap.put(id, packsLangURLs);
            }
            packsLangURLs.add(url);
        } else if (id.startsWith(UserInputPanel.SPEC_FILE_NAME)) {
            // Check user input panel definitions
            IXMLElement xml = new XMLParser().parse(url);
            for (IXMLElement userPanelDef : xml.getChildrenNamed(UserInputPanel.NODE_ID)) {
                String userPanelId = xmlCompilerHelper.requireAttribute(userPanelDef, "id");
                if (userInputPanelIds == null) {
                    userInputPanelIds = new HashSet<String>();
                }
                if (!userInputPanelIds.add(userPanelId)) {
                    assertionHelper.parseError(xml, "Resource " + UserInputPanel.SPEC_FILE_NAME
                            + ": Duplicate user input panel identifier '" + userPanelId + "'");
                }
            }
        }
    }
    notifyCompilerListener("addResources", CompilerListener.END, data);
}

From source file:com.mobiperf.MeasurementScheduler.java

/**
 * Load the schedule from the schedule file, if it exists.
 * /*from   w w  w. j  a  v a2 s . c  o m*/
 * This is to be run when the app first starts up, so scheduled items
 * are not lost.
 */
private void loadSchedulerState() {
    Vector<MeasurementTask> tasksToAdd = new Vector<MeasurementTask>();
    synchronized (currentSchedule) {
        try {
            Logger.i("Restoring schedule from disk...");
            FileInputStream inputstream = openFileInput("schedule");
            InputStreamReader streamreader = new InputStreamReader(inputstream);
            BufferedReader bufferedreader = new BufferedReader(streamreader);

            String line;
            while ((line = bufferedreader.readLine()) != null) {
                JSONObject jsonTask;
                try {
                    jsonTask = new JSONObject(line);
                    MeasurementTask newTask = MeasurementJsonConvertor.makeMeasurementTaskFromJson(jsonTask,
                            getApplicationContext());

                    // If the task is scheduled in the past, re-schedule it in the future
                    // We assume tasks in the past have run, otherwise we can wind up getting
                    // stuck trying to run a large backlog of tasks

                    long curtime = System.currentTimeMillis();
                    if (curtime > newTask.getDescription().startTime.getTime()) {
                        long timediff = curtime - newTask.getDescription().startTime.getTime();

                        timediff = (long) (timediff % (newTask.getDescription().intervalSec * 1000));
                        Calendar now = Calendar.getInstance();
                        now.add(Calendar.SECOND, (int) timediff / 1000);
                        newTask.getDescription().startTime.setTime(now.getTimeInMillis());
                        Logger.i("Rescheduled task " + newTask.getDescription().key + " at time "
                                + now.getTimeInMillis());
                    }

                    tasksToAdd.add(newTask);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            bufferedreader.close();
            streamreader.close();
            inputstream.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    updateSchedule(tasksToAdd, true);
}

From source file:com.mobilyzer.MeasurementScheduler.java

/**
 * Load the schedule from the schedule file, if it exists.
 * /*from  w  ww  . j  a v  a2s . c  om*/
 * This is to be run when the app first starts up, so scheduled items are not lost.
 */
private void loadSchedulerState() {
    // Vector<MeasurementTask> tasksToAdd = new Vector<MeasurementTask>();
    synchronized (mainQueue) {
        try {
            Logger.i("Restoring schedule from disk...");
            FileInputStream inputstream = openFileInput("schedule");
            InputStreamReader streamreader = new InputStreamReader(inputstream);
            BufferedReader bufferedreader = new BufferedReader(streamreader);

            String line;
            while ((line = bufferedreader.readLine()) != null) {
                JSONObject jsonTask;
                try {
                    jsonTask = new JSONObject(line);
                    MeasurementTask newTask = MeasurementJsonConvertor.makeMeasurementTaskFromJson(jsonTask);

                    // If the task is scheduled in the past, re-schedule it in the future
                    // We assume tasks in the past have run, otherwise we can wind up getting
                    // stuck trying to run a large backlog of tasks

                    long curtime = System.currentTimeMillis();

                    if (curtime > newTask.getDescription().endTime.getTime()) {
                        continue;
                    }

                    if (curtime > newTask.getDescription().startTime.getTime()) {
                        long timediff = curtime - newTask.getDescription().startTime.getTime();

                        timediff = (long) (timediff % (newTask.getDescription().intervalSec * 1000));
                        Calendar now = Calendar.getInstance();
                        now.add(Calendar.SECOND, (int) timediff / 1000);
                        newTask.getDescription().startTime.setTime(now.getTimeInMillis());
                        Logger.i("Rescheduled task " + newTask.getDescription().key + " at time "
                                + now.getTimeInMillis());
                    }

                    mainQueue.add(newTask);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            handleMeasurement();
            bufferedreader.close();
            streamreader.close();
            inputstream.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

From source file:com.cemso.action.FileUploadAction.java

public String execute() {
    try {/* w w w  . j a va2s .c  om*/
        if (log.isDebugEnabled()) {
            log.debug("start to upload file...");
        }

        ActionContext context = ActionContext.getContext();
        HttpServletRequest request = (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST);
        HttpServletResponse response = ServletActionContext.getResponse();
        Map<String, Object> session = context.getSession();
        response.setCharacterEncoding("GBK"); // 
        String type = request.getParameter("type");
        if (type != null && type.equals("register")) {
            log.debug("upload license");
            SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
            String datetime = tempDate.format(new java.util.Date());
            String desFilePath = XmlOperationTool.CONFIG_FOLDER + datetime + "_LICENSE.TXT";
            boolean bool = false;
            if (uploadify != null) {
                FileOperationTool.ChannelCopy(uploadify, new File(desFilePath));
                InputStreamReader isr = new InputStreamReader(new FileInputStream(desFilePath), "GBK");
                BufferedReader br = new BufferedReader(isr);
                long current = System.currentTimeMillis();
                String firstLine = br.readLine();
                String data = "";
                int months = 1;
                if (firstLine.startsWith("1")) {
                    data = firstLine.substring(2);
                    months = Integer.parseInt(firstLine.substring(1, 2));
                }
                if (firstLine.startsWith("2")) {
                    data = firstLine.substring(3);
                    months = Integer.parseInt(firstLine.substring(1, 3));
                }
                if (firstLine.startsWith("3")) {
                    data = firstLine.substring(4);
                    months = Integer.parseInt(firstLine.substring(1, 4));
                }
                String startdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(current));
                String expdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                        .format(new Date(current + 30l * months * 24 * 3600 * 1000));
                String key = "";
                List<RegisterDTO> registers = new ArrayList<RegisterDTO>();
                if (data != null && !data.trim().isEmpty()) {
                    if (Long.parseLong(data) >= current) {
                        log.warn("Invalid License file");
                        registerService.addChecklog(ConstantUtil.CheckLogs.INVALID,
                                ConstantUtil.CheckLogs.TYPE_INVALID);
                        response.getWriter().print("License");
                        return null;
                    }
                    key = data;
                    data = br.readLine();
                } else {
                    log.warn("Invalid License file");
                    registerService.addChecklog(ConstantUtil.CheckLogs.INVALID,
                            ConstantUtil.CheckLogs.TYPE_INVALID);
                    response.getWriter().print("License");
                    return null;
                }
                while (data != null && !data.trim().isEmpty()) {
                    int indexid = SequenceUtil.getInstance()
                            .getNextKeyValue(ConstantUtil.SequenceName.REGISTER_SEQUENCE);
                    String device = data.trim();
                    RegisterDTO rd = new RegisterDTO(indexid, startdate, expdate, key, device,
                            ConstantUtil.Register.NO);
                    registers.add(rd);
                    data = br.readLine();
                }
                br.close();
                isr.close();
                //registerService.updateToDelete();
                // delete the old devices
                /*
                boolean f = deviceService.deleteAllDevices();
                if(log.isDebugEnabled()){
                   log.debug("Delete all devices result is : " + f);
                }
                */
                bool = registerService.add(registers);
                if (log.isDebugEnabled()) {
                    log.debug("Add register devices result is : " + bool);
                }
            }

            try {
                if (bool) {
                    // return response
                    response.getWriter().print(uploadifyFileName + " ");
                    registerService.addChecklog(ConstantUtil.CheckLogs.VALID,
                            ConstantUtil.CheckLogs.TYPE_VALID);
                    if (log.isDebugEnabled()) {
                        log.debug("upload file successfully");
                    }
                } else {
                    if (log.isErrorEnabled()) {
                        log.error("Add License failed !");
                    }
                }
            } catch (IOException e) {
                if (log.isErrorEnabled()) {
                    log.error("upload file failed !!!");
                    log.error(e.getMessage());
                }
            }
            return null;
        }

        String desFilePath = null;
        String currentMillins = Long.toString(System.currentTimeMillis());
        String resourceId = "resource_" + currentMillins;
        if (FileOperationTool.getResourceType(uploadifyFileName).equals(FileOperationTool.IMAGETYPE)) {
            resource.setResourceType("image");
            desFilePath = FileOperationTool.DEFAULT_IMG_DES_PATH + currentMillins + "_" + uploadifyFileName;
        }
        if (FileOperationTool.getResourceType(uploadifyFileName).equals(FileOperationTool.AUDIOTYPE)) {
            resource.setResourceType("audio");
            desFilePath = FileOperationTool.DEFAULT_AUDIO_DES_PATH + currentMillins + "_" + uploadifyFileName;
        }
        if (FileOperationTool.getResourceType(uploadifyFileName).equals(FileOperationTool.TEXTTYPE)) {
            resource.setResourceType("text");
            desFilePath = FileOperationTool.DEFAULT_TEXT_DES_PATH + currentMillins + "_" + uploadifyFileName;
        }
        if (FileOperationTool.getResourceType(uploadifyFileName).equals(FileOperationTool.VIDEOTYPE)) {
            resource.setResourceType("video");
            desFilePath = FileOperationTool.DEFAULT_VIDEO_DES_PATH + currentMillins + "_" + uploadifyFileName;
        }

        FileOperationTool.ChannelCopy(uploadify, new File(desFilePath));

        // if resource type is video, convert it to flv format
        if (resource.getResourceType().equals("video") && XmlOperationTool.isWindos) {
            VideoConverter.convert(currentMillins + "_" + uploadifyFileName);
        }

        if (uploadify != null) {
            resource.setId(resourceId);
            resource.setResourceName(currentMillins + "_" + uploadifyFileName);
            if (!resource.getResourceType().equals("text")) {
                resource.setParamRemark(uploadifyFileName);
            } else {
                String txtContent = FileOperationTool.getContentOfTxt(desFilePath);
                resource.setParamRemark(txtContent);
            }
            resource.setParamCreateby(((UserDTO) session.get("user")).getId());
            resource.setParamCreatetime(
                    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(uploadify.lastModified()));
            resource.setCanBeDelete(true);
            if (new File(desFilePath).exists()) {
                resourceService.AddResource(resource);
            }
        }

        try {
            // return response
            response.getWriter().print(uploadifyFileName + " ");
            if (log.isDebugEnabled()) {
                log.debug("upload file successfully");
            }
        } catch (IOException e) {
            if (log.isErrorEnabled()) {
                log.error("upload file failed !!!");
                log.error(e.getMessage());
            }
        }
        return null;

    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error("upload file failed !!!");
            log.error(e.getMessage());
        }
        return ERROR;
    }

}

From source file:com.vuze.android.remote.rpc.RestJsonClient.java

public static Map<?, ?> connect(String id, String url, Map<?, ?> jsonPost, Header[] headers,
        UsernamePasswordCredentials creds, boolean sendGzip) throws RPCException {
    long readTime = 0;
    long connSetupTime = 0;
    long connTime = 0;
    int bytesRead = 0;
    if (DEBUG_DETAILED) {
        Log.d(TAG, id + "] Execute " + url);
    }//from   w w w  .j  a v  a 2 s. co  m
    long now = System.currentTimeMillis();
    long then;

    Map<?, ?> json = Collections.EMPTY_MAP;

    try {

        URI uri = new URI(url);
        int port = uri.getPort();

        BasicHttpParams basicHttpParams = new BasicHttpParams();
        HttpProtocolParams.setUserAgent(basicHttpParams, "Vuze Android Remote");

        DefaultHttpClient httpclient;
        if ("https".equals(uri.getScheme())) {
            httpclient = MySSLSocketFactory.getNewHttpClient(port);
        } else {
            httpclient = new DefaultHttpClient(basicHttpParams);
        }

        //AndroidHttpClient.newInstance("Vuze Android Remote");

        // This doesn't set the "Authorization" header!?
        httpclient.getCredentialsProvider().setCredentials(new AuthScope(null, -1), creds);

        // Prepare a request object
        HttpRequestBase httpRequest = jsonPost == null ? new HttpGet(uri) : new HttpPost(uri); // IllegalArgumentException

        if (creds != null) {
            byte[] toEncode = (creds.getUserName() + ":" + creds.getPassword()).getBytes();
            String encoding = Base64Encode.encodeToString(toEncode, 0, toEncode.length);
            httpRequest.setHeader("Authorization", "Basic " + encoding);
        }

        if (jsonPost != null) {
            HttpPost post = (HttpPost) httpRequest;
            String postString = JSONUtils.encodeToJSON(jsonPost);
            if (AndroidUtils.DEBUG_RPC) {
                Log.d(TAG, id + "]  Post: " + postString);
            }

            AbstractHttpEntity entity = (sendGzip && Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO)
                    ? getCompressedEntity(postString)
                    : new StringEntity(postString);
            post.setEntity(entity);

            post.setHeader("Accept", "application/json");
            post.setHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
            setupRequestFroyo(httpRequest);
        }

        if (headers != null) {
            for (Header header : headers) {
                httpRequest.setHeader(header);
            }
        }

        // Execute the request
        HttpResponse response;

        then = System.currentTimeMillis();
        if (AndroidUtils.DEBUG_RPC) {
            connSetupTime = (then - now);
            now = then;
        }

        httpclient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
            @Override
            public boolean retryRequest(IOException e, int i, HttpContext httpContext) {
                if (i < 2) {
                    return true;
                }
                return false;
            }
        });
        response = httpclient.execute(httpRequest);

        then = System.currentTimeMillis();
        if (AndroidUtils.DEBUG_RPC) {
            connTime = (then - now);
            now = then;
        }

        HttpEntity entity = response.getEntity();

        // XXX STATUSCODE!

        StatusLine statusLine = response.getStatusLine();
        if (AndroidUtils.DEBUG_RPC) {
            Log.d(TAG, "StatusCode: " + statusLine.getStatusCode());
        }

        if (entity != null) {

            long contentLength = entity.getContentLength();
            if (contentLength >= Integer.MAX_VALUE - 2) {
                throw new RPCException("JSON response too large");
            }

            // A Simple JSON Response Read
            InputStream instream = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO)
                    ? getUngzippedContent(entity)
                    : entity.getContent();
            InputStreamReader isr = new InputStreamReader(instream, "utf8");

            StringBuilder sb = null;
            BufferedReader br = null;
            // JSONReader is 10x slower, plus I get more OOM errors.. :(
            //            final boolean useStringBuffer = contentLength > (4 * 1024 * 1024) ? false
            //                  : DEFAULT_USE_STRINGBUFFER;
            final boolean useStringBuffer = DEFAULT_USE_STRINGBUFFER;

            if (useStringBuffer) {
                // Setting capacity saves StringBuffer from going through many
                // enlargeBuffers, and hopefully allows toString to not make a copy
                sb = new StringBuilder(contentLength > 512 ? (int) contentLength + 2 : 512);
            } else {
                if (AndroidUtils.DEBUG_RPC) {
                    Log.d(TAG, "Using BR. ContentLength = " + contentLength);
                }
                br = new BufferedReader(isr, 8192);
                br.mark(32767);
            }

            try {

                // 9775 files on Nexus 7 (~2,258,731 bytes)
                // fastjson 1.1.46 (String)       :  527- 624ms
                // fastjson 1.1.39 (String)       :  924-1054ms
                // fastjson 1.1.39 (StringBuilder): 1227-1463ms
                // fastjson 1.1.39 (BR)           : 2233-2260ms
                // fastjson 1.1.39 (isr)          :      2312ms
                // GSON 2.2.4 (String)            : 1539-1760ms
                // GSON 2.2.4 (BufferedReader)    : 2646-3060ms
                // JSON-SMART 1.3.1 (String)      :  572- 744ms (OOMs more often than fastjson)

                if (useStringBuffer) {
                    char c[] = new char[8192];
                    while (true) {
                        int read = isr.read(c);
                        if (read < 0) {
                            break;
                        }
                        sb.append(c, 0, read);
                    }

                    if (AndroidUtils.DEBUG_RPC) {
                        then = System.currentTimeMillis();
                        if (DEBUG_DETAILED) {
                            if (sb.length() > 2000) {
                                Log.d(TAG, id + "] " + sb.substring(0, 2000) + "...");
                            } else {
                                Log.d(TAG, id + "] " + sb.toString());
                            }
                        }
                        bytesRead = sb.length();
                        readTime = (then - now);
                        now = then;
                    }

                    json = JSONUtils.decodeJSON(sb.toString());
                    //json = JSONUtilsGSON.decodeJSON(sb.toString());
                } else {

                    //json = JSONUtils.decodeJSON(isr);
                    json = JSONUtils.decodeJSON(br);
                    //json = JSONUtilsGSON.decodeJSON(br);
                }

            } catch (Exception pe) {

                //               StatusLine statusLine = response.getStatusLine();
                if (statusLine != null && statusLine.getStatusCode() == 409) {
                    throw new RPCException(response, "409");
                }

                try {
                    String line;
                    if (useStringBuffer) {
                        line = sb.subSequence(0, Math.min(128, sb.length())).toString();
                    } else {
                        br.reset();
                        line = br.readLine().trim();
                    }

                    isr.close();

                    if (AndroidUtils.DEBUG_RPC) {
                        Log.d(TAG, id + "]line: " + line);
                    }
                    Header contentType = entity.getContentType();
                    if (line.startsWith("<") || line.contains("<html")
                            || (contentType != null && contentType.getValue().startsWith("text/html"))) {
                        // TODO: use android strings.xml
                        throw new RPCException(response,
                                "Could not retrieve remote client location information.  The most common cause is being on a guest wifi that requires login before using the internet.");
                    }
                } catch (IOException ignore) {

                }

                Log.e(TAG, id, pe);
                if (statusLine != null) {
                    String msg = statusLine.getStatusCode() + ": " + statusLine.getReasonPhrase() + "\n"
                            + pe.getMessage();
                    throw new RPCException(msg, pe);
                }
                throw new RPCException(pe);
            } finally {
                closeOnNewThread(useStringBuffer ? isr : br);
            }

            if (AndroidUtils.DEBUG_RPC) {
                //               Log.d(TAG, id + "]JSON Result: " + json);
            }

        }
    } catch (RPCException e) {
        throw e;
    } catch (Throwable e) {
        Log.e(TAG, id, e);
        throw new RPCException(e);
    }

    if (AndroidUtils.DEBUG_RPC) {
        then = System.currentTimeMillis();
        Log.d(TAG, id + "] conn " + connSetupTime + "/" + connTime + "ms. Read " + bytesRead + " in " + readTime
                + "ms, parsed in " + (then - now) + "ms");
    }
    return json;
}

From source file:org.apache.tajo.plan.function.python.PythonScriptEngine.java

private static List<FunctionInfo> getFunctions(InputStream is) throws IOException {
    List<FunctionInfo> functions = new ArrayList<>();
    InputStreamReader in = new InputStreamReader(is, Charset.defaultCharset());
    BufferedReader br = new BufferedReader(in);
    String line = br.readLine();//  w  w w  .  ja  v a 2  s.c  o m
    String[] quotedSchemaStrings = null;
    AggFuncInfo aggFuncInfo = null;

    while (line != null) {
        try {
            if (pSchema.matcher(line).matches()) {
                int start = line.indexOf("(") + 1; //drop brackets
                int end = line.lastIndexOf(")");
                quotedSchemaStrings = line.substring(start, end).trim().split(",");
            } else if (pDef.matcher(line).matches()) {
                boolean isUdaf = aggFuncInfo != null && line.indexOf("def ") > 0;
                int nameStart = line.indexOf("def ") + "def ".length();
                int nameEnd = line.indexOf('(');
                int signatureEnd = line.indexOf(')');
                String[] params = line.substring(nameEnd + 1, signatureEnd).split(",");
                int paramNum;
                if (params.length == 1) {
                    paramNum = params[0].equals("") ? 0 : 1;
                } else {
                    paramNum = params.length;
                }
                if (params[0].trim().equals("self")) {
                    paramNum--;
                }

                String functionName = line.substring(nameStart, nameEnd).trim();
                quotedSchemaStrings = quotedSchemaStrings == null ? new String[] { "'blob'" }
                        : quotedSchemaStrings;

                if (isUdaf) {
                    if (functionName.equals("eval")) {
                        aggFuncInfo.evalInfo = new ScalarFuncInfo(quotedSchemaStrings, functionName, paramNum);
                    } else if (functionName.equals("merge")) {
                        aggFuncInfo.mergeInfo = new ScalarFuncInfo(quotedSchemaStrings, functionName, paramNum);
                    } else if (functionName.equals("get_partial_result")) {
                        aggFuncInfo.getPartialResultInfo = new ScalarFuncInfo(quotedSchemaStrings, functionName,
                                paramNum);
                    } else if (functionName.equals("get_final_result")) {
                        aggFuncInfo.getFinalResultInfo = new ScalarFuncInfo(quotedSchemaStrings, functionName,
                                paramNum);
                    }
                } else {
                    aggFuncInfo = null;
                    functions.add(new ScalarFuncInfo(quotedSchemaStrings, functionName, paramNum));
                }

                quotedSchemaStrings = null;
            } else if (pClass.matcher(line).matches()) {
                // UDAF
                if (aggFuncInfo != null) {
                    functions.add(aggFuncInfo);
                }
                aggFuncInfo = new AggFuncInfo();
                int classNameStart = line.indexOf("class ") + "class ".length();
                int classNameEnd = line.indexOf("(");
                if (classNameEnd < 0) {
                    classNameEnd = line.indexOf(":");
                }
                aggFuncInfo.className = line.substring(classNameStart, classNameEnd).trim();
                aggFuncInfo.funcName = aggFuncInfo.className.toLowerCase();
            }
        } catch (Throwable t) {
            // ignore unexpected function and source lines
            LOG.warn(t);
        }
        line = br.readLine();
    }
    if (aggFuncInfo != null) {
        functions.add(aggFuncInfo);
    }
    br.close();
    in.close();
    return functions;
}

From source file:com.knowgate.dfs.FileSystem.java

/**
 * <p>Read a text file into a String</p>
 * @param sFilePath Full path of file to be readed. Like "file:///tmp/myfile.txt" or "ftp://myhost:21/dir/myfile.txt"
 * @param sEncoding Text Encoding for file {UTF-8, ISO-8859-1, ...}<BR>
 * if <b>null</b> then if first two bytes of file are FF FE then UTF-8 will be assumed<BR>
 * else ISO-8859-1 will be assumed.//from  w w w  . j  a v a 2 s .c om
 * @return String with full contents of file
 * @throws FileNotFoundException
 * @throws IOException
 * @throws OutOfMemoryError
 * @throws MalformedURLException
 * @throws FTPException
 */
public String readfilestr(String sFilePath, String sEncoding)
        throws MalformedURLException, FTPException, FileNotFoundException, IOException, OutOfMemoryError {

    if (DebugFile.trace) {
        DebugFile.writeln("Begin FileSystem.readfilestr(" + sFilePath + "," + sEncoding + ")");
        DebugFile.incIdent();
    }

    String sRetVal;
    String sLower = sFilePath.toLowerCase();

    if (sLower.startsWith("file://"))
        sFilePath = sFilePath.substring(7);

    if (sLower.startsWith("http://") || sLower.startsWith("https://")) {

        URL oUrl = new URL(sFilePath);
        if (user().equals("anonymous") || user().length() == 0) {
            ByteArrayOutputStream oStrm = new ByteArrayOutputStream();
            DataHandler oHndlr = new DataHandler(oUrl);
            oHndlr.writeTo(oStrm);
            sRetVal = oStrm.toString(sEncoding);
            oStrm.close();
        } else {
            if (null == oHttpCli) {
                oHttpCli = new DefaultHttpClient();
            } // fi (oHttpCli)
            oHttpCli.getCredentialsProvider().setCredentials(
                    new AuthScope(oUrl.getHost(), AuthScope.ANY_PORT, realm()),
                    new UsernamePasswordCredentials(user(), password()));
            HttpGet oGet = null;
            try {

                oGet = new HttpGet(sFilePath);
                HttpResponse oResp = oHttpCli.execute(oGet);
                HttpEntity oEnty = oResp.getEntity();
                int nLen = (int) oEnty.getContentLength();
                if (nLen > 0) {
                    byte[] aRetVal = new byte[nLen];
                    InputStream oBody = oEnty.getContent();
                    oBody.read(aRetVal, 0, nLen);
                    oBody.close();
                    sRetVal = new String(aRetVal, sEncoding);
                } else {
                    sRetVal = "";
                } // fi         
            } finally {
                oHttpCli.getConnectionManager().shutdown();
                oHttpCli = null;
            }
        } // fi
    } else if (sLower.startsWith("ftp://")) {

        FTPClient oFTPC = null;
        boolean bFTPSession = false;

        splitURI(sFilePath);

        try {

            if (DebugFile.trace)
                DebugFile.writeln("new FTPClient(" + sHost + ")");
            oFTPC = new FTPClient(sHost);

            if (DebugFile.trace)
                DebugFile.writeln("FTPClient.login(" + sUsr + "," + sPwd + ")");
            oFTPC.login(sUsr, sPwd);

            bFTPSession = true;

            if (DebugFile.trace)
                DebugFile.writeln("FTPClient.chdir(" + sPath + ")");
            oFTPC.chdir(sPath);

            ByteArrayOutputStream oStrm = new ByteArrayOutputStream();

            oFTPC.setType(FTPTransferType.BINARY);

            if (DebugFile.trace)
                DebugFile.writeln("FTPClient.get(" + sPath + sFile + "," + sFile + ",false)");
            oFTPC.get(oStrm, sFile);

            sRetVal = oStrm.toString(sEncoding);

            oStrm.close();
        } catch (FTPException ftpe) {
            throw new FTPException(ftpe.getMessage());
        } finally {
            if (DebugFile.trace)
                DebugFile.writeln("FTPClient.quit()");
            try {
                if (bFTPSession)
                    oFTPC.quit();
            } catch (Exception ignore) {
            }
        }
    } else {

        File oFile = new File(sFilePath);
        int iFLen = (int) oFile.length();
        if (iFLen > 0) {
            byte byBuffer[] = new byte[3];
            char aBuffer[] = new char[iFLen];
            BufferedInputStream oBfStrm;
            FileInputStream oInStrm;
            InputStreamReader oReader;

            if (sEncoding == null) {
                oInStrm = new FileInputStream(oFile);
                oBfStrm = new BufferedInputStream(oInStrm, iFLen);

                sEncoding = new CharacterSetDetector().detect(oBfStrm, "ISO-8859-1");

                if (DebugFile.trace)
                    DebugFile.writeln("encoding is " + sEncoding);

                oBfStrm.close();
                oInStrm.close();
            } // fi

            oInStrm = new FileInputStream(oFile);
            oBfStrm = new BufferedInputStream(oInStrm, iFLen);

            oReader = new InputStreamReader(oBfStrm, sEncoding);

            int iReaded = oReader.read(aBuffer, 0, iFLen);

            // Skip FF FE character mark for Unidode files
            int iSkip = ((int) aBuffer[0] == 65279 || (int) aBuffer[0] == 65533 || (int) aBuffer[0] == 65534 ? 1
                    : 0);

            oReader.close();
            oBfStrm.close();
            oInStrm.close();

            oReader = null;
            oInStrm = null;
            oFile = null;

            sRetVal = new String(aBuffer, iSkip, iReaded - iSkip);
        } else
            sRetVal = "";
    } // fi (iFLen>0)

    if (DebugFile.trace) {
        DebugFile.decIdent();
        DebugFile.writeln("End FileSystem.readfilestr() : " + String.valueOf(sRetVal.length()));
    }

    return sRetVal;
}

From source file:org.yamj.core.service.mediainfo.MediaInfoService.java

public void parseMediaInfo(InputStream in, Map<String, String> infosGeneral,
        List<Map<String, String>> infosVideo, List<Map<String, String>> infosAudio,
        List<Map<String, String>> infosText) throws IOException {

    InputStreamReader isr = null;
    BufferedReader bufReader = null;

    try {//from www .  j av  a  2  s .com
        isr = new InputStreamReader(in);
        bufReader = new BufferedReader(isr);

        // Improvement, less code line, each cat have same code, so use the same for all.
        Map<String, List<Map<String, String>>> matches = new HashMap<String, List<Map<String, String>>>();

        // Create a fake one for General, we got only one, but to use the same algo we must create this one.
        String generalKey[] = { "General", "Gneral", "* Gnral" };
        matches.put(generalKey[0], new ArrayList<Map<String, String>>());
        matches.put(generalKey[1], matches.get(generalKey[0]));
        matches.put(generalKey[2], matches.get(generalKey[0]));
        matches.put("Video", infosVideo);
        matches.put("Vido", matches.get("Video"));
        matches.put("Audio", infosAudio);
        matches.put("Text", infosText);

        String line = localInputReadLine(bufReader);
        String label;

        while (line != null) {
            // In case of new format : Text #1, Audio #1
            if (line.indexOf('#') >= 0) {
                line = line.substring(0, line.indexOf('#')).trim();
            }

            // Get cat ArrayList from cat name.
            List<Map<String, String>> currentCat = matches.get(line);

            if (currentCat != null) {
                HashMap<String, String> currentData = new HashMap<String, String>();
                int indexSeparator = -1;
                while (((line = localInputReadLine(bufReader)) != null)
                        && ((indexSeparator = line.indexOf(" : ")) != -1)) {
                    label = line.substring(0, indexSeparator).trim();
                    if (currentData.get(label) == null) {
                        currentData.put(label, line.substring(indexSeparator + 3));
                    }
                }
                currentCat.add(currentData);
            } else {
                line = localInputReadLine(bufReader);
            }
        }

        // Setting General Info - Beware of lose data if infosGeneral already have some ...
        try {
            for (String generalKey1 : generalKey) {
                List<Map<String, String>> arrayList = matches.get(generalKey1);
                if (arrayList.size() > 0) {
                    Map<String, String> datas = arrayList.get(0);
                    if (datas.size() > 0) {
                        infosGeneral.putAll(datas);
                        break;
                    }
                }
            }
        } catch (Exception ignore) {
            // We don't care about this exception
        }
    } finally {
        if (isr != null) {
            isr.close();
        }

        if (bufReader != null) {
            bufReader.close();
        }
    }
}

From source file:com.ephesoft.dcma.filebound.FileBoundExporter.java

private void executeCommand(final List<String> cmdList, final String connectionURL, final String userName,
        final String password, final String docFieldValues, final String loanNumberValue,
        final String projectName, final String loanNumberName, final String parameterFileName)
        throws DCMAApplicationException {
    InputStreamReader inputStreamReader = null;
    BufferedReader input = null;/*from  w w w  .j  ava 2s  .  c  om*/
    try {
        final Runtime runtime = Runtime.getRuntime();
        if (cmdList.isEmpty()) {
            LOGGER.error("No proper commands configured in resources");
            throw new DCMAApplicationException("No proper commands configured in resources");
        } else {
            String[] cmds = new String[cmdList.size()];
            for (int i = 0; i < cmdList.size(); i++) {
                if (cmdList.get(i).contains("cmd")) {
                    LOGGER.info("inside cmd");
                    cmds[i] = cmdList.get(i);
                } else if (cmdList.get(i).contains("/c")) {
                    LOGGER.info("inside /c");
                    cmds[i] = cmdList.get(i);
                } else if (cmdList.get(i).contains("FileBoundExport")) {
                    LOGGER.info("inside FileBoundExport");
                    cmds[i] = cmdList.get(i) + " \"" + connectionURL + "\" " + userName + " " + password + " \""
                            + projectName + FileBoundConstants.ESCAPED_SPACE + docFieldValues
                            + FileBoundConstants.ESCAPED_SPACE + loanNumberName
                            + FileBoundConstants.ESCAPED_SPACE + loanNumberValue
                            + FileBoundConstants.ESCAPED_SPACE + parameterFileName + "\"";
                }
            }
            LOGGER.info("command formed is :" + cmds[cmdList.size() - 1]);
            final Process process = runtime.exec(cmds, null,
                    new File(System.getenv(FileBoundConstants.FILEBOUND_BASE_PATH)));
            inputStreamReader = new InputStreamReader(process.getInputStream());
            input = new BufferedReader(inputStreamReader);
            String line = null;
            do {
                line = input.readLine();
                LOGGER.debug(line);
            } while (line != null);
            final int exitValue = process.exitValue();
            LOGGER.info("Command exited with error code no " + exitValue);
            if (exitValue != 0) {
                LOGGER.error("Non-zero exit value for filebound command found. So exiting the application");
                throw new DCMAApplicationException(
                        "Non-zero exit value for filebound command found. So exiting the application");
            }
        }
    } catch (Exception e) {
        LOGGER.error("Exception while expoting ");
        throw new DCMAApplicationException("Exception while expoting ", e);
    } finally {
        try {
            if (input != null) {
                input.close();
            }
            if (inputStreamReader != null) {
                inputStreamReader.close();
            }
        } catch (IOException e) {
            LOGGER.error("Problem in closing stream");
        }
    }
}

From source file:com.nec.harvest.controller.SuihController.java

/**
 * Render page with path variables mapping
 * /{unitLevel}/{unitDept}/{deptCode}/{year:\\d{4}}/{quarter:[1-4]}
 * //w  ww.  j  a va2  s .  c  o  m
 * @param userOrgCode
 *            Logged-in user's code
 * @param businessDay
 *            Actual business day
 * @param proGNo
 *            A path variable user's group code
 * @param unitLevel
 *            A path variable classify's code
 * @param unitDept
 *            A path variable department level2's code
 * @param deptCode
 *            A path variable department selected on page view
 * @param year
 *            A path variable year
 * @param quarter
 *            A path variable quarter
 * @param model
 *            Spring's model that can be used to render a view
 * @return A redirect URL
 */
@RequestMapping(value = "/{unitLevel}/{unitDept}/{deptCode}/{year:\\d{4}}/{quarter:[1-4]}", method = RequestMethod.GET)
public String render(@SessionAttribute(Constants.SESS_ORGANIZATION_CODE) String userOrgCode,
        @SessionAttribute(Constants.SESS_BUSINESS_DAY) Date businessDay, @PathVariable String proGNo,
        @PathVariable String unitLevel, @PathVariable String unitDept, @PathVariable String deptCode,
        @PathVariable String year, @PathVariable String quarter, final HttpServletRequest request,
        final Model model) {
    logger.info(
            "Loading profit and loss manager in a quarter data by full path [/suih/{unitLevel}/{unitDept}/{deptCode}/{year}/{quarter}]");

    Date currentYear = null;
    int currentQuarter = 0;

    // cast year, quarter
    try {
        currentYear = DateFormatUtil.parse(year, DateFormat.DATE_YEAR);
        currentQuarter = Integer.parseInt(quarter);
    } catch (NullPointerException | IllegalArgumentException | ParseException ex) {
        logger.warn(ex.getMessage());
    }

    try {
        /* Get classify list */
        List<Division> divisions;
        try {
            divisions = divisionService.findByKbnId(DEFAULT_KBN_ID);
        } catch (IllegalArgumentException | ObjectNotFoundException ex) {
            logger.warn(ex.getMessage());

            // Set divisions is empty
            divisions = Collections.emptyList();
        }

        // set list classifies first drop down list
        final String CLASSIFIES = "classifies";
        model.addAttribute(CLASSIFIES, divisions);

        // set value selected first drop down list
        final String UNIT_LEVEL = "unitLevel";
        model.addAttribute(UNIT_LEVEL, selectedClassify(divisions, unitLevel));

        List<Organization> departments = null;
        try {
            // Get the list of organizations level 2
            departments = organizationService.findByKaisoBango(unitLevel);
        } catch (IllegalArgumentException | ObjectNotFoundException ex) {
            logger.warn(ex.getMessage());
        }

        // set attribute list departments for drop down list level2
        final String DEPARTMENTS = "departments";
        model.addAttribute(DEPARTMENTS, departments);

        // set attribute name selected for drop down list level2
        final String UNIT_DEPT = "unitDeptName";
        model.addAttribute(UNIT_DEPT, selectedDepartment(departments, unitDept));

        final String UNIT_DEPT_CODE = "unitDeptCode";
        model.addAttribute(UNIT_DEPT_CODE, unitDept);

        // set attribute department code
        final String DEPT_CODE = "deptCode";
        boolean isTotalCalculation = unitDept.equals(deptCode);
        model.addAttribute(DEPT_CODE, isTotalCalculation ? unitDept : deptCode);

        // set attribute current quarter of business
        final String CURRENT_QUARTER = "currentQuarter";
        model.addAttribute(CURRENT_QUARTER, year.concat("/").concat(quarter));

        InputStreamReader in = null;
        try {
            UriComponents uriComponents = UriComponentsBuilder.fromUriString(
                    request.getContextPath() + Constants.PAGINATION_PATH + "/{unitDept}/{deptCode}/{pageindex}")
                    .build();
            URI uri = uriComponents.expand(proGNo, unitDept, deptCode, 0).encode().toUri();

            // initial HttpHost, HttpGet
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            HttpHost httpHost = new HttpHost(request.getServerName(), request.getLocalPort(),
                    request.getScheme());
            HttpGet httpGet = new HttpGet(uri.toString());
            HttpResponse httpResp = httpClient.execute(httpHost, httpGet);
            if (httpResp.getStatusLine().getStatusCode() != 200) {
                // Release the connection
                httpClient.close();
                httpClient = null;

                // call rest paging error
                throw new RuntimeException(
                        "Failed : HTTP error code : " + httpResp.getStatusLine().getStatusCode());
            }

            // read pagination 
            in = new InputStreamReader(httpResp.getEntity().getContent(),
                    HttpServletContentType.DEFAULT_ENCODING);
            BufferedReader rd = new BufferedReader(in);
            StringBuilder textView = new StringBuilder();

            String line = "";
            while ((line = rd.readLine()) != null) {
                textView.append(line);
            }

            // set attribute pagination
            final String HTML_PAGINATION = "pagination";
            model.addAttribute(HTML_PAGINATION, textView);

            // Release the connection
            httpClient.close();
            httpClient = null;
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ex) {
                    logger.warn(ex.getMessage());
                }
            }
        }
    } catch (ServiceException ex) {
        logger.error(ex.getMessage(), ex);

        // ???????????
        model.addAttribute(ERROR, true);
        model.addAttribute(ERROR_MESSAGE, getSystemError());
    }

    // 
    return processingSuih(userOrgCode, businessDay, unitDept, deptCode, currentYear, currentQuarter, model);
}