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:ReverseConsoleInput.java

public static void main(String args[]) throws Exception {
    InputStreamReader isr = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(isr);

    // Read and process lines from console
    String s;/*from w w  w.  j  a  v  a  2  s. co m*/
    while ((s = br.readLine()) != null) {
        StringBuffer sb = new StringBuffer(s);
        sb.reverse();
        System.out.println(sb);
    }
    isr.close();
}

From source file:Main.java

public static void main(String[] args) throws IOException {
    char[] cbuf = new char[5];

    FileInputStream fis = new FileInputStream("C:/test.txt");
    InputStreamReader isr = new InputStreamReader(fis);

    // reads into the char buffer
    int i = isr.read(cbuf, 2, 3);

    // prints the number of characters
    System.out.println("Number of characters read: " + i);

    // for each character in the character buffer
    for (char c : cbuf) {
        // for empty character
        if (((int) c) == 0)
            c = '-';

        System.out.println(c);//from   w w  w .  j av a 2s  .c o  m
    }
    isr.close();
}

From source file:org.apache.zookeeper.server.quorum.auth.MiniKdc.java

public static void main(String[] args) throws Exception {
    if (args.length < 4) {
        System.out.println("Arguments: <WORKDIR> <MINIKDCPROPERTIES> " + "<KEYTABFILE> [<PRINCIPALS>]+");
        System.exit(ExitCode.UNEXPECTED_ERROR.getValue());
    }/*from  w  ww .jav  a 2s.c  o m*/
    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.apache.hadoop.minikdc.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);//w w w .  j a va  2s  .  co  m
    }
    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), StandardCharsets.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:com.util.finalProy.java

/**
 * @param args the command line arguments
 *//*from   ww w .  j  ava2  s. c om*/
public static void main(String[] args) throws JSONException {
    // TODO code application logic her
    System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON");
    String myURL = "http://192.168.5.44/app_dev.php/cus/getaccount/50241109321.json";
    System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null) {
            urlConn.setReadTimeout(60 * 1000);
        }
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());

            BufferedReader bufferedReader = new BufferedReader(in);
            if (bufferedReader != null) {
                int cp;
                while ((cp = bufferedReader.read()) != -1) {
                    sb.append((char) cp);
                }
                bufferedReader.close();
            }
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }
    String jsonResult = sb.toString();
    System.out.println(sb.toString());
    System.out.println(
            "\n\n--------------------OBTENEMOS OBJETO JSON NATIVO DE LA PAGINA, USAMOS EL ARRAY DATA---------------------------\n\n");
    JSONObject objJason = new JSONObject(jsonResult);
    JSONArray dataJson = new JSONArray();
    dataJson = objJason.getJSONArray("data");

    System.out.println("objeto normal 1 " + dataJson.toString());
    //
    //
    System.out.println(
            "\n\n--------------------CREAMOS UN STRING JSON2 REEMPLAZANDO LOS CORCHETES QUE DAN ERROR---------------------------\n\n");
    String jsonString2 = dataJson.toString();
    String temp = dataJson.toString();
    temp = jsonString2.replace("[", "");
    jsonString2 = temp.replace("]", "");
    System.out.println("new json string" + jsonString2);

    JSONObject objJson2 = new JSONObject(jsonString2);
    System.out.println("el objeto simple json es " + objJson2.toString());

    System.out.println(
            "\n\n--------------------CREAMOS UN OBJETO JSON CON EL ARRAR ACCOUN---------------------------\n\n");

    String account1 = objJson2.optString("account");
    System.out.println(account1);
    JSONObject objJson3 = new JSONObject(account1);
    System.out.println("el ULTIMO OBJETO SIMPLE ES  " + objJson3.toString());
    System.out.println(
            "\n\n--------------------EMPEZAMOS A RECIBIR LOS PARAMETROS QUE HAY EN EL OBJETO JSON---------------------------\n\n");
    String firstName = objJson3.getString("first_name");
    System.out.println(firstName);
    System.out.println(objJson3.get("id"));
    System.out.println(
            "\n\n--------------------TRATAMOS DE PASAR TODO EL ACCOUNT A OBJETO JAVA---------------------------\n\n");
    Gson gson = new Gson();
    Account account = gson.fromJson(objJson3.toString(), Account.class);
    System.out.println(account.getFirst_name());
    System.out.println(account.getCreation());
}

From source file:com.annuletconsulting.homecommand.server.HomeCommand.java

/**
 * This class will accept commands from a node in each room. For it to react to events on the server
 * computer, it must be also running as a node.  However the server can cause all nodes to react
 * to an event happening on any node, such as an email or text arriving.  A call on a node device
 * could pause all music devices, for example.
 * //  ww w  .jav  a2  s. c o m
 * @param args
 */
public static void main(String[] args) {
    try {
        socket = Integer.parseInt(HomeComandProperties.getInstance().getServerPort());
        nonJavaUserModulesPath = HomeComandProperties.getInstance().getNonJavaUserDir();
    } catch (Exception exception) {
        System.out.println("Error loading from properties file.");
        exception.printStackTrace();
    }
    try {
        sharedKey = HomeComandProperties.getInstance().getSharedKey();
        if (sharedKey == null)
            System.out.println("shared_key is null, commands without valid signatures will be processed.");
    } catch (Exception exception) {
        System.out.println("shared_key not found in properties file.");
        exception.printStackTrace();
    }
    try {
        if (args.length > 0) {
            String arg0 = args[0];
            if (arg0.equals("help") || arg0.equals("?") || arg0.equals("usage") || arg0.equals("-help")
                    || arg0.equals("-?")) {
                System.out.println(
                        "The defaults can be changed by editing the HomeCommand.properties file, or you can override them temporarily using command line options.");
                System.out.println("\nHome Command Server command line overrride usage:");
                System.out.println(
                        "hcserver [server_port] [java_user_module_directory] [non_java_user_module_directory]"); //TODO make hcserver.sh
                System.out.println("\nDefaults:");
                System.out.println("server_port: " + socket);
                System.out.println("java_user_module_directory: " + userModulesPath);
                System.out.println("non_java_user_module_directory: " + nonJavaUserModulesPath);
                System.out.println("\n2013 | Annulet, LLC");
            }
            socket = Integer.parseInt(arg0);
        }
        if (args.length > 1)
            userModulesPath = args[1];
        if (args.length > 2)
            nonJavaUserModulesPath = args[2];

        System.out.println("Config loaded, initializing modules.");
        modules.add(new HueLightModule());
        System.out.println("HueLightModule initialized.");
        modules.add(new QuestionModule());
        System.out.println("QuestionModule initialized.");
        modules.add(new MathModule());
        System.out.println("MathModule initialized.");
        modules.add(new MusicModule());
        System.out.println("MusicModule initialized.");
        modules.add(new NonCopyrightInfringingGenericSpaceExplorationTVShowModule());
        System.out.println("NonCopyrightInfringingGenericSpaceExplorationTVShowModule initialized.");
        modules.add(new HelpModule());
        System.out.println("HelpModule initialized.");
        modules.add(new SetUpModule());
        System.out.println("SetUpModule initialized.");
        modules.addAll(NonJavaUserModuleLoader.loadModulesAt(nonJavaUserModulesPath));
        System.out.println("NonJavaUserModuleLoader initialized.");
        ServerSocket serverSocket = new ServerSocket(socket);
        System.out.println("Listening...");
        while (!end) {
            Socket socket = serverSocket.accept();
            InputStreamReader isr = new InputStreamReader(socket.getInputStream());
            PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
            int character;
            StringBuffer inputStrBuffer = new StringBuffer();
            while ((character = isr.read()) != 13) {
                inputStrBuffer.append((char) character);
            }
            System.out.println(inputStrBuffer.toString());
            String[] cmd; // = inputStrBuffer.toString().split(" ");
            String result = "YOUR REQUEST WAS NOT VALID JSON";
            if (inputStrBuffer.substring(0, 1).equals("{")) {
                nodeType = extractElement(inputStrBuffer.toString(), "node_type");
                if (sharedKey != null) {
                    if (validateSignature(extractElement(inputStrBuffer.toString(), "time_stamp"),
                            extractElement(inputStrBuffer.toString(), "signature"))) {
                        if ("Y".equalsIgnoreCase(extractElement(inputStrBuffer.toString(), "cmd_encoded")))
                            cmd = decryptCommand(extractElement(inputStrBuffer.toString(), "command"));
                        else
                            cmd = extractElement(inputStrBuffer.toString(), "command").split(" ");
                        result = getResult(cmd);
                    } else
                        result = "YOUR SIGNATURE DID NOT MATCH, CHECK SHARED KEY";
                } else {
                    cmd = extractElement(inputStrBuffer.toString(), "command").split(" ");
                    result = getResult(cmd);
                }
            }
            System.out.println(result);
            output.print(result);
            output.print((char) 13);
            output.close();
            isr.close();
            socket.close();
        }
        serverSocket.close();
        System.out.println("Shutting down.");
    } catch (Exception exception) {
        exception.printStackTrace();
    }
}

From source file:io.s4.util.AvroSchemaSupplementer.java

public static void main(String args[]) {
    if (args.length < 1) {
        System.err.println("No schema filename specified");
        System.exit(1);/* ww  w.  jav a 2s . c  om*/
    }

    String filename = args[0];
    FileReader fr = null;
    BufferedReader br = null;
    InputStreamReader isr = null;
    try {
        if (filename == "-") {
            isr = new InputStreamReader(System.in);
            br = new BufferedReader(isr);
        } else {
            fr = new FileReader(filename);
            br = new BufferedReader(fr);
        }

        String inputLine = "";
        StringBuffer jsonBuffer = new StringBuffer();
        while ((inputLine = br.readLine()) != null) {
            jsonBuffer.append(inputLine);
        }

        JSONObject jsonRecord = new JSONObject(jsonBuffer.toString());

        JSONObject keyPathElementSchema = new JSONObject();
        keyPathElementSchema.put("name", "KeyPathElement");
        keyPathElementSchema.put("type", "record");

        JSONArray fieldsArray = new JSONArray();
        JSONObject fieldRecord = new JSONObject();
        fieldRecord.put("name", "index");
        JSONArray typeArray = new JSONArray("[\"int\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "keyName");
        typeArray = new JSONArray("[\"string\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);

        keyPathElementSchema.put("fields", fieldsArray);

        JSONObject keyInfoSchema = new JSONObject();
        keyInfoSchema.put("name", "KeyInfo");
        keyInfoSchema.put("type", "record");

        fieldsArray = new JSONArray();
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "keyPath");
        typeArray = new JSONArray("[\"string\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "fullKeyPath");
        typeArray = new JSONArray("[\"string\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "keyPathElementList");
        JSONObject typeRecord = new JSONObject();
        typeRecord.put("type", "array");
        typeRecord.put("items", keyPathElementSchema);
        fieldRecord.put("type", typeRecord);
        fieldsArray.put(fieldRecord);

        keyInfoSchema.put("fields", fieldsArray);

        JSONObject partitionInfoSchema = new JSONObject();
        partitionInfoSchema.put("name", "PartitionInfo");
        partitionInfoSchema.put("type", "record");
        fieldsArray = new JSONArray();
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "partitionId");
        typeArray = new JSONArray("[\"int\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "compoundKey");
        typeArray = new JSONArray("[\"string\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "compoundValue");
        typeArray = new JSONArray("[\"string\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "keyInfoList");
        typeRecord = new JSONObject();
        typeRecord.put("type", "array");
        typeRecord.put("items", keyInfoSchema);
        fieldRecord.put("type", typeRecord);
        fieldsArray.put(fieldRecord);

        partitionInfoSchema.put("fields", fieldsArray);

        fieldRecord = new JSONObject();
        fieldRecord.put("name", "S4__PartitionInfo");
        typeRecord = new JSONObject();
        typeRecord.put("type", "array");
        typeRecord.put("items", partitionInfoSchema);
        fieldRecord.put("type", typeRecord);

        fieldsArray = jsonRecord.getJSONArray("fields");
        fieldsArray.put(fieldRecord);

        System.out.println(jsonRecord.toString(3));
    } catch (Exception ioe) {
        throw new RuntimeException(ioe);
    } finally {
        if (br != null)
            try {
                br.close();
            } catch (Exception e) {
            }
        if (isr != null)
            try {
                isr.close();
            } catch (Exception e) {
            }
        if (fr != null)
            try {
                fr.close();
            } catch (Exception e) {
            }
    }
}

From source file:Main.java

static String downloadHtml(String urlString) {
    StringBuffer buffer = new StringBuffer();

    try {/*from   w w w  . j a  v  a  2s. co  m*/
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        HttpURLConnection.setFollowRedirects(true);
        conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
        String encoding = conn.getContentEncoding();
        InputStream inStr = null;

        if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
            inStr = new GZIPInputStream(conn.getInputStream());
        } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
            inStr = new InflaterInputStream(conn.getInputStream(), new Inflater(true));
        } else {
            inStr = conn.getInputStream();
        }
        int ptr = 0;
        InputStreamReader inStrReader = new InputStreamReader(inStr, Charset.forName("GB2312"));

        while ((ptr = inStrReader.read()) != -1) {
            buffer.append((char) ptr);
        }
        inStrReader.close();
        conn.disconnect();
        inStr.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return buffer.toString();
}

From source file:de.dentrassi.pm.jenkins.AbstractUploader.java

protected static String makeString(final HttpEntity entity) throws IOException {
    final InputStreamReader reader = new InputStreamReader(entity.getContent(), UTF_8);
    try {/*from   w w  w.j  a  va 2 s.  c  o  m*/
        return CharStreams.toString(reader).trim();
    } finally {
        reader.close();
    }
}

From source file:com.yolodata.tbana.testutils.FileTestUtils.java

public static String readContentFromLocalFile(URI path) throws IOException {
    InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(new File(path)));
    String content = org.apache.tools.ant.util.FileUtils.readFully(inputStreamReader);
    inputStreamReader.close();

    return content;
}