Search in sources :

Example 36 with UnsupportedEncodingException

use of java.io.UnsupportedEncodingException in project OkVolley by googolmo.

the class BaseRequest method parseNetworkResponse.

@Override
protected //解析返回的数据
Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
    try {
        byte[] data = response.data;
        String json = new String(data, HttpHeaderParser.parseCharset(response.headers));
        if (VolleyLog.DEBUG) {
            VolleyLog.d("response:%s", json);
        }
        return Response.success(new JSONObject(json), HttpHeaderParser.parseCacheHeaders(response));
    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (JSONException e) {
        return Response.error(new ParseError(e));
    }
}
Also used : JSONObject(org.json.JSONObject) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JSONException(org.json.JSONException) ParseError(com.android.volley.ParseError)

Example 37 with UnsupportedEncodingException

use of java.io.UnsupportedEncodingException in project grpc-java by grpc.

the class Util method shaBase64.

/** Returns a Base 64-encoded string containing a SHA-1 hash of {@code s}. */
public static String shaBase64(String s) {
    try {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
        byte[] sha1Bytes = messageDigest.digest(s.getBytes("UTF-8"));
        return ByteString.of(sha1Bytes).base64();
    } catch (NoSuchAlgorithmException e) {
        throw new AssertionError(e);
    } catch (UnsupportedEncodingException e) {
        throw new AssertionError(e);
    }
}
Also used : UnsupportedEncodingException(java.io.UnsupportedEncodingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) MessageDigest(java.security.MessageDigest)

Example 38 with UnsupportedEncodingException

use of java.io.UnsupportedEncodingException in project SQLWindowing by hbutani.

the class WindowingHiveCliDriver method run.

public static int run(String[] args) throws Exception {
    OptionsProcessor oproc = new OptionsProcessor();
    if (!oproc.process_stage1(args)) {
        return 1;
    }
    // NOTE: It is critical to do this here so that log4j is reinitialized
    // before any of the other core hive classes are loaded
    boolean logInitFailed = false;
    String logInitDetailMessage;
    try {
        logInitDetailMessage = LogUtils.initHiveLog4j();
    } catch (LogInitializationException e) {
        logInitFailed = true;
        logInitDetailMessage = e.getMessage();
    }
    CliSessionState ss = new CliSessionState(new HiveConf(SessionState.class));
    ss.in = System.in;
    try {
        ss.out = new PrintStream(System.out, true, "UTF-8");
        ss.info = new PrintStream(System.err, true, "UTF-8");
        ss.err = new CachingPrintStream(System.err, true, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        return 3;
    }
    if (!oproc.process_stage2(ss)) {
        return 2;
    }
    if (!ss.getIsSilent()) {
        if (logInitFailed) {
            System.err.println(logInitDetailMessage);
        } else {
            SessionState.getConsole().printInfo(logInitDetailMessage);
        }
    }
    // set all properties specified via command line
    HiveConf conf = ss.getConf();
    for (Map.Entry<Object, Object> item : ss.cmdProperties.entrySet()) {
        conf.set((String) item.getKey(), (String) item.getValue());
        ss.getOverriddenConfigurations().put((String) item.getKey(), (String) item.getValue());
    }
    SessionState.start(ss);
    // connect to Hive Server
    if (ss.getHost() != null) {
        ss.connect();
        if (ss.isRemoteMode()) {
            prompt = "[" + ss.getHost() + ':' + ss.getPort() + "] " + prompt;
            char[] spaces = new char[prompt.length()];
            Arrays.fill(spaces, ' ');
            prompt2 = new String(spaces);
        }
    }
    // CLI remote mode is a thin client: only load auxJars in local mode
    if (!ss.isRemoteMode() && !ShimLoader.getHadoopShims().usesJobShell()) {
        // hadoop-20 and above - we need to augment classpath using hiveconf
        // components
        // see also: code in ExecDriver.java
        ClassLoader loader = conf.getClassLoader();
        String auxJars = HiveConf.getVar(conf, HiveConf.ConfVars.HIVEAUXJARS);
        if (StringUtils.isNotBlank(auxJars)) {
            loader = Utilities.addToClassPath(loader, StringUtils.split(auxJars, ","));
        }
        conf.setClassLoader(loader);
        Thread.currentThread().setContextClassLoader(loader);
    }
    WindowingHiveCliDriver cli = new WindowingHiveCliDriver();
    cli.setHiveVariables(oproc.getHiveVariables());
    // use the specified database if specified
    cli.processSelectDatabase(ss);
    // Execute -i init files (always in silent mode)
    cli.processInitFiles(ss);
    cli.setupWindowing();
    if (ss.execString != null) {
        return cli.processLine(ss.execString);
    }
    try {
        if (ss.fileName != null) {
            return cli.processFile(ss.fileName);
        }
    } catch (FileNotFoundException e) {
        System.err.println("Could not open input file for reading. (" + e.getMessage() + ")");
        return 3;
    }
    ConsoleReader reader = new ConsoleReader();
    reader.setBellEnabled(false);
    // true)));
    for (Completor completor : getCommandCompletor()) {
        reader.addCompletor(completor);
    }
    String line;
    final String HISTORYFILE = ".hivehistory";
    String historyDirectory = System.getProperty("user.home");
    try {
        if ((new File(historyDirectory)).exists()) {
            String historyFile = historyDirectory + File.separator + HISTORYFILE;
            reader.setHistory(new History(new File(historyFile)));
        } else {
            System.err.println("WARNING: Directory for Hive history file: " + historyDirectory + " does not exist.   History will not be available during this session.");
        }
    } catch (Exception e) {
        System.err.println("WARNING: Encountered an error while trying to initialize Hive's " + "history file.  History will not be available during this session.");
        System.err.println(e.getMessage());
    }
    int ret = 0;
    String prefix = "";
    String curDB = getFormattedDb(conf, ss);
    String curPrompt = prompt + curDB;
    String dbSpaces = spacesForString(curDB);
    while ((line = reader.readLine(curPrompt + "> ")) != null) {
        if (!prefix.equals("")) {
            prefix += '\n';
        }
        if (line.trim().endsWith(";") && !line.trim().endsWith("\\;")) {
            line = prefix + line;
            ret = cli.processLine(line, true);
            prefix = "";
            curDB = getFormattedDb(conf, ss);
            curPrompt = prompt + curDB;
            dbSpaces = dbSpaces.length() == curDB.length() ? dbSpaces : spacesForString(curDB);
        } else {
            prefix = prefix + line;
            curPrompt = prompt2 + dbSpaces;
            continue;
        }
    }
    ss.close();
    return ret;
}
Also used : CliSessionState(org.apache.hadoop.hive.cli.CliSessionState) SessionState(org.apache.hadoop.hive.ql.session.SessionState) PrintStream(java.io.PrintStream) CachingPrintStream(org.apache.hadoop.hive.common.io.CachingPrintStream) ConsoleReader(jline.ConsoleReader) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) History(jline.History) OptionsProcessor(org.apache.hadoop.hive.cli.OptionsProcessor) CliSessionState(org.apache.hadoop.hive.cli.CliSessionState) FileNotFoundException(java.io.FileNotFoundException) WindowingException(com.sap.hadoop.windowing.WindowingException) LogInitializationException(org.apache.hadoop.hive.common.LogUtils.LogInitializationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CachingPrintStream(org.apache.hadoop.hive.common.io.CachingPrintStream) LogInitializationException(org.apache.hadoop.hive.common.LogUtils.LogInitializationException) HiveConf(org.apache.hadoop.hive.conf.HiveConf) Completor(jline.Completor) Map(java.util.Map) File(java.io.File)

Example 39 with UnsupportedEncodingException

use of java.io.UnsupportedEncodingException in project translationstudio8 by heartsome.

the class Utils method clearTmxFile.

public static File clearTmxFile(File f) throws ImportException {
    Logger logger = LoggerFactory.getLogger(Utils.class);
    File tempFile = null;
    BufferedWriter writer = null;
    try {
        tempFile = File.createTempFile("tmxtemp", ".tmx");
        writer = new BufferedWriter(new FileWriter(tempFile));
    } catch (IOException e1) {
        logger.error("", e1);
    }
    String encoding = FileEncodingDetector.detectFileEncoding(f);
    FileInputStream in = null;
    try {
        in = new FileInputStream(f);
    } catch (FileNotFoundException e) {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e1) {
                logger.error("", e1);
            }
        }
        logger.error("", e);
    }
    InputStreamReader inr = null;
    try {
        inr = new InputStreamReader(in, encoding);
    } catch (UnsupportedEncodingException e1) {
        try {
            if (writer != null) {
                writer.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            logger.error("", e);
        }
        throw new ImportException(Messages.getString("database.Utils.msg1"));
    }
    BufferedReader bfr = new BufferedReader(inr);
    try {
        String line = bfr.readLine();
        // // Bug #3428
        line = clearXMLEnconding(line);
        boolean flg = true;
        while (line != null) {
            if (flg) {
                int tmpos = line.indexOf("<header");
                if (tmpos != -1) {
                    // porp started
                    StringBuffer headerbf = new StringBuffer();
                    headerbf.append(line);
                    int tempeos = line.indexOf(">", tmpos);
                    while (tempeos == -1) {
                        line = bfr.readLine();
                        if (line == null) {
                            throw new ImportException(Messages.getString("database.Utils.msg2"));
                        }
                        headerbf.append("\n").append(line);
                        tempeos = headerbf.indexOf(">");
                    }
                    String headerStart = headerbf.substring(0, tempeos + 1);
                    writer.write(headerStart);
                    int t = line.indexOf("/>");
                    if (t != -1) {
                        String end = line.substring(t + 2, line.length());
                        if (end != null && end.length() != 0) {
                            writer.write(end);
                        }
                        line = bfr.readLine();
                        flg = false;
                        continue;
                    }
                    t = line.indexOf("</header>");
                    if (t != -1) {
                        String end = line.substring(t, line.length());
                        writer.write(end);
                        line = bfr.readLine();
                        flg = false;
                        continue;
                    }
                    // read to </header>
                    line = bfr.readLine();
                    while (line != null) {
                        int endof = line.indexOf("</header>");
                        if (endof != -1) {
                            line = line.substring(endof, line.length());
                            flg = false;
                            break;
                        }
                        line = bfr.readLine();
                    }
                }
            }
            writer.write(line);
            line = bfr.readLine();
        }
    } catch (IOException e) {
        logger.error("", e);
    } finally {
        try {
            if (writer != null) {
                writer.close();
            }
            if (bfr != null) {
                bfr.close();
            }
        } catch (IOException e) {
            logger.error("", e);
        }
    }
    return tempFile;
}
Also used : InputStreamReader(java.io.InputStreamReader) FileWriter(java.io.FileWriter) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) Logger(org.slf4j.Logger) FileInputStream(java.io.FileInputStream) BufferedWriter(java.io.BufferedWriter) ImportException(net.heartsome.cat.common.core.exception.ImportException) BufferedReader(java.io.BufferedReader) File(java.io.File)

Example 40 with UnsupportedEncodingException

use of java.io.UnsupportedEncodingException in project iosched by google.

the class StrictLineReader method readLine.

/**
   * Reads the next line. A line ends with {@code "\n"} or {@code "\r\n"},
   * this end of line marker is not included in the result.
   *
   * @return the next line from the input.
   * @throws IOException for underlying {@code InputStream} errors.
   * @throws EOFException for the end of source stream.
   */
public String readLine() throws IOException {
    synchronized (in) {
        if (buf == null) {
            throw new IOException("LineReader is closed");
        }
        // throw again if that happens; thus we need to handle end == -1 as well as end == pos.
        if (pos >= end) {
            fillBuf();
        }
        // Try to find LF in the buffered data and return the line if successful.
        for (int i = pos; i != end; ++i) {
            if (buf[i] == LF) {
                int lineEnd = (i != pos && buf[i - 1] == CR) ? i - 1 : i;
                String res = new String(buf, pos, lineEnd - pos, charset.name());
                pos = i + 1;
                return res;
            }
        }
        // Let's anticipate up to 80 characters on top of those already read.
        ByteArrayOutputStream out = new ByteArrayOutputStream(end - pos + 80) {

            @Override
            public String toString() {
                int length = (count > 0 && buf[count - 1] == CR) ? count - 1 : count;
                try {
                    return new String(buf, 0, length, charset.name());
                } catch (UnsupportedEncodingException e) {
                    // Since we control the charset this will never happen.
                    throw new AssertionError(e);
                }
            }
        };
        while (true) {
            out.write(buf, pos, end - pos);
            // Mark unterminated line in case fillBuf throws EOFException or IOException.
            end = -1;
            fillBuf();
            // Try to find LF in the buffered data and return the line if successful.
            for (int i = pos; i != end; ++i) {
                if (buf[i] == LF) {
                    if (i != pos) {
                        out.write(buf, pos, i - pos);
                    }
                    pos = i + 1;
                    return out.toString();
                }
            }
        }
    }
}
Also used : UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Aggregations

UnsupportedEncodingException (java.io.UnsupportedEncodingException)1401 IOException (java.io.IOException)385 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)150 ArrayList (java.util.ArrayList)129 File (java.io.File)120 InputStream (java.io.InputStream)117 ByteArrayInputStream (java.io.ByteArrayInputStream)107 ByteArrayOutputStream (java.io.ByteArrayOutputStream)101 InputStreamReader (java.io.InputStreamReader)91 MessageDigest (java.security.MessageDigest)87 OutputStreamWriter (java.io.OutputStreamWriter)83 FileNotFoundException (java.io.FileNotFoundException)79 BufferedReader (java.io.BufferedReader)73 URL (java.net.URL)73 HashMap (java.util.HashMap)66 Map (java.util.Map)63 FileOutputStream (java.io.FileOutputStream)56 List (java.util.List)46 JSONException (org.json.JSONException)45 FileInputStream (java.io.FileInputStream)41