Search in sources :

Example 46 with CharArrayReader

use of java.io.CharArrayReader in project BKCommonLib by bergerhealer.

the class FileConfiguration method load.

/**
 * Loads this File Configuration from file
 */
public void load() {
    // Make sure a previous save() is completed first
    flushSaveOperation(this.file);
    // Ignore loading if file doesn't exist
    if (!file.exists()) {
        return;
    }
    try {
        if (CommonPlugin.hasInstance() && CommonPlugin.getInstance().forceSynchronousSaving()) {
            char[] data;
            {
                // Read bytes
                byte[] data_bytes = Files.readAllBytes(this.file.toPath());
                // Decode as char[] using UTF-8
                String s = new String(data_bytes, StandardCharsets.UTF_8);
                data = s.toCharArray();
            }
            // Safety: erase any use of 0-char values in the original data
            for (int i = 0; i < data.length; i++) {
                if (data[i] == 0) {
                    int num_nul_chars = 1;
                    for (int j = i + 1; j < data.length && data[j] == 0; j++) {
                        num_nul_chars++;
                    }
                    char[] new_data = new char[data.length - num_nul_chars];
                    System.arraycopy(data, 0, new_data, 0, i);
                    System.arraycopy(data, i + num_nul_chars, new_data, i, new_data.length - i);
                    data = new_data;
                    i--;
                }
            }
            // Load it in
            this.loadFromReader(new CharArrayReader(data));
        } else {
            this.loadFromStream(new FileInputStream(this.file));
        }
    } catch (Throwable t) {
        Logging.LOGGER_CONFIG.log(Level.SEVERE, "An error occured while loading file '" + this.file + "'");
        try {
            File backup = new File(this.file.getPath() + ".old");
            StreamUtil.copyFile(this.file, backup);
            Logging.LOGGER_CONFIG.log(Level.SEVERE, "A backup of this (corrupted?) file named '" + backup.getName() + "' can be found in case you wish to restore", t);
        } catch (IOException ex) {
            Logging.LOGGER_CONFIG.log(Level.SEVERE, "A backup of this (corrupted?) file could not be made and its contents may be lost (overwritten)", t);
        }
    }
}
Also used : CharArrayReader(java.io.CharArrayReader) IOException(java.io.IOException) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 47 with CharArrayReader

use of java.io.CharArrayReader in project cxf by apache.

the class CachedWriter method getReader.

public Reader getReader() throws IOException {
    flush();
    if (inmem) {
        if (currentStream instanceof LoadingCharArrayWriter) {
            LoadingCharArrayWriter lcaw = (LoadingCharArrayWriter) currentStream;
            return new CharArrayReader(lcaw.rawCharArray(), 0, lcaw.size());
        }
        return null;
    }
    try {
        InputStream fileInputStream = new FileInputStream(tempFile) {

            boolean closed;

            @Override
            public void close() throws IOException {
                if (!closed) {
                    super.close();
                    maybeDeleteTempFile(this);
                }
                closed = true;
            }
        };
        streamList.add(fileInputStream);
        if (cipherTransformation != null) {
            fileInputStream = new CipherInputStream(fileInputStream, ciphers.getDecryptor()) {

                boolean closed;

                @Override
                public void close() throws IOException {
                    if (!closed) {
                        super.close();
                        closed = true;
                    }
                }
            };
        }
        return new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
    } catch (FileNotFoundException e) {
        throw new IOException("Cached file was deleted, " + e.toString());
    }
}
Also used : CharArrayReader(java.io.CharArrayReader) CipherInputStream(javax.crypto.CipherInputStream) InputStreamReader(java.io.InputStreamReader) CipherInputStream(javax.crypto.CipherInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream)

Example 48 with CharArrayReader

use of java.io.CharArrayReader in project leopard by tanhaichao.

the class tls_sigature method CheckTLSSignature.

/**
 * @brief 校验 tls 票据
 * @param urlSig 返回 tls 票据
 * @param strAppid3rd 填写与 sdkAppid 一致的字符串形式的值
 * @param skdAppid 应的 appid
 * @param identifier 用户 id
 * @param accountType 创建应用后在配置页面上展示的 acctype
 * @param publicKey 用于校验 tls 票据的公钥内容,但是需要先将公钥文件转换为 java 原生 api 使用的格式,下面是推荐的命令
 *         openssl pkcs8 -topk8 -in ec_key.pem -outform PEM -out p8_priv.pem -nocrypt
 * @return 如果出错 CheckTLSSignatureResult 中的 verifyResult 为 false,错误信息在 errMsg,校验成功为 true
 * @throws DataFormatException
 */
@Deprecated
public static CheckTLSSignatureResult CheckTLSSignature(String urlSig, String strAppid3rd, long skdAppid, String identifier, long accountType, String publicKey) throws DataFormatException {
    CheckTLSSignatureResult result = new CheckTLSSignatureResult();
    Security.addProvider(new BouncyCastleProvider());
    // DeBaseUrl64 urlSig to json
    Base64 decoder = new Base64();
    // byte [] compressBytes = decoder.decode(urlSig.getBytes());
    byte[] compressBytes = base64_url.base64DecodeUrl(urlSig.getBytes(Charset.forName("UTF-8")));
    // System.out.println("#compressBytes Passing in[" + compressBytes.length + "] " + Hex.encodeHexString(compressBytes));
    // Decompression
    Inflater decompression = new Inflater();
    decompression.setInput(compressBytes, 0, compressBytes.length);
    byte[] decompressBytes = new byte[1024];
    int decompressLength = decompression.inflate(decompressBytes);
    decompression.end();
    String jsonString = new String(Arrays.copyOfRange(decompressBytes, 0, decompressLength));
    // System.out.println("#Json String passing in : \n" + jsonString);
    // Get TLS.Sig from json
    JSONObject jsonObject = new JSONObject(jsonString);
    String sigTLS = jsonObject.getString("TLS.sig");
    // debase64 TLS.Sig to get serailString
    byte[] signatureBytes = decoder.decode(sigTLS.getBytes(Charset.forName("UTF-8")));
    try {
        String sigTime = jsonObject.getString("TLS.time");
        String sigExpire = jsonObject.getString("TLS.expire_after");
        // + Long.parseLong(sigTime) + "-" + Long.parseLong(sigExpire));
        if (System.currentTimeMillis() / 1000 - Long.parseLong(sigTime) > Long.parseLong(sigExpire)) {
            result.errMessage = new String("TLS sig is out of date ");
            System.out.println("Timeout");
            return result;
        }
        // Get Serial String from json
        String SerialString = "TLS.appid_at_3rd:" + strAppid3rd + "\n" + "TLS.account_type:" + accountType + "\n" + "TLS.identifier:" + identifier + "\n" + "TLS.sdk_appid:" + skdAppid + "\n" + "TLS.time:" + sigTime + "\n" + "TLS.expire_after:" + sigExpire + "\n";
        // System.out.println("#SerialString : \n" + SerialString);
        Reader reader = new CharArrayReader(publicKey.toCharArray());
        PEMParser parser = new PEMParser(reader);
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
        Object obj = parser.readObject();
        parser.close();
        PublicKey pubKeyStruct = converter.getPublicKey((SubjectPublicKeyInfo) obj);
        Signature signature = Signature.getInstance("SHA256withECDSA", "BC");
        signature.initVerify(pubKeyStruct);
        signature.update(SerialString.getBytes(Charset.forName("UTF-8")));
        boolean bool = signature.verify(signatureBytes);
        // System.out.println("#jdk ecdsa verify : " + bool);
        result.verifyResult = bool;
    } catch (Exception e) {
        e.printStackTrace();
        result.errMessage = "Failed in checking sig";
    }
    return result;
}
Also used : Base64(org.apache.commons.codec.binary.Base64) PublicKey(java.security.PublicKey) CharArrayReader(java.io.CharArrayReader) Reader(java.io.Reader) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) IOException(java.io.IOException) DataFormatException(java.util.zip.DataFormatException) CharArrayReader(java.io.CharArrayReader) JSONObject(org.json.JSONObject) PEMParser(org.bouncycastle.openssl.PEMParser) Signature(java.security.Signature) Inflater(java.util.zip.Inflater) JSONObject(org.json.JSONObject) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 49 with CharArrayReader

use of java.io.CharArrayReader in project vcell by virtualcell.

the class SolverDescriptionRegression method readback.

// @Test
public void readback() throws IOException {
    CharArrayWriter buffer = new CharArrayWriter();
    PrintWriter record = new PrintWriter(buffer);
    for (String name : SolverNames) {
        dumpOne(name, record);
    }
    record.flush();
    char[] b = buffer.toCharArray();
    BufferedReader current = new BufferedReader(new CharArrayReader(b));
    LineNumberReader reference = new LineNumberReader(new FileReader("solvers.ref"));
    boolean nameNext = false;
    String currentSolver = null;
    while (reference.ready()) {
        String currentLine = current.readLine();
        String referenceLine = reference.readLine();
        if (nameNext) {
            currentSolver = currentLine;
            nameNext = false;
        } else if (currentLine.equals(SOLVER_SEP)) {
            nameNext = true;
        }
        if (!currentLine.equals(referenceLine)) {
            System.err.println("mismatch in " + currentSolver + " line " + reference.getLineNumber());
            System.err.println("\treference " + referenceLine);
            System.err.println("\tcurrent " + currentLine);
        }
    }
    reference.close();
}
Also used : CharArrayReader(java.io.CharArrayReader) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) CharArrayWriter(java.io.CharArrayWriter) PrintWriter(java.io.PrintWriter) LineNumberReader(java.io.LineNumberReader)

Example 50 with CharArrayReader

use of java.io.CharArrayReader in project OpenGrok by OpenGrok.

the class ContextTest method testLongLineNearBufferBoundary.

/**
 * Test that we don't get an {@code ArrayIndexOutOfBoundsException} when a
 * long (&gt;100 characters) line which contains a match is not terminated
 * with a newline character before the buffer boundary. Bug #383.
 * @throws org.apache.lucene.queryparser.classic.ParseException parse exception
 */
@Test
public void testLongLineNearBufferBoundary() throws ParseException {
    char[] chars = new char[Context.MAXFILEREAD];
    Arrays.fill(chars, 'a');
    char[] substring = " this is a test ".toCharArray();
    System.arraycopy(substring, 0, chars, Context.MAXFILEREAD - substring.length, substring.length);
    Reader in = new CharArrayReader(chars);
    QueryBuilder qb = new QueryBuilder().setFreetext("test");
    Context c = new Context(qb.build(), qb);
    StringWriter out = new StringWriter();
    boolean match = c.getContext(in, out, "", "", "", null, true, qb.isDefSearch(), null);
    assertTrue(match, "No match found");
    String s = out.toString();
    assertTrue(s.contains(" this is a <b>test</b>"), "Match not written to Writer");
    assertTrue(s.contains("href=\"#1\""), "No match on line #1");
}
Also used : CharArrayReader(java.io.CharArrayReader) StringWriter(java.io.StringWriter) CharArrayReader(java.io.CharArrayReader) Reader(java.io.Reader) StringReader(java.io.StringReader) QueryBuilder(org.opengrok.indexer.search.QueryBuilder) Test(org.junit.jupiter.api.Test)

Aggregations

CharArrayReader (java.io.CharArrayReader)102 IOException (java.io.IOException)45 BufferedReader (java.io.BufferedReader)22 Reader (java.io.Reader)19 File (java.io.File)11 InputStreamReader (java.io.InputStreamReader)10 Test (org.junit.Test)9 ByteArrayInputStream (java.io.ByteArrayInputStream)8 StringReader (java.io.StringReader)8 FileReader (java.io.FileReader)7 PreparedStatement (java.sql.PreparedStatement)7 BufferedWriter (java.io.BufferedWriter)5 CharArrayWriter (java.io.CharArrayWriter)5 FileWriter (java.io.FileWriter)5 InputStream (java.io.InputStream)5 ResultSet (java.sql.ResultSet)5 InputSource (org.xml.sax.InputSource)5 PipedReader (java.io.PipedReader)4 CharBuffer (java.nio.CharBuffer)4 Signature (java.security.Signature)4