Example usage for java.io ByteArrayOutputStream toByteArray

List of usage examples for java.io ByteArrayOutputStream toByteArray

Introduction

In this page you can find the example usage for java.io ByteArrayOutputStream toByteArray.

Prototype

public synchronized byte[] toByteArray() 

Source Link

Document

Creates a newly allocated byte array.

Usage

From source file:com.openteach.diamond.network.waverider.command.Command.java

public static void main(String[] args) {

    ByteArrayOutputStream bout = null;
    ObjectOutputStream objOutputStream = null;

    try {//from w w  w. ja  va 2 s .  com
        bout = new ByteArrayOutputStream();
        objOutputStream = new ObjectOutputStream(bout);
        SlaveState slaveState = new SlaveState();
        slaveState.setId(1L);
        slaveState.setIsMasterCandidate(false);
        objOutputStream.writeObject(slaveState);
        objOutputStream.flush();
        Command command = CommandFactory.createHeartbeatCommand(ByteBuffer.wrap(bout.toByteArray()));

        ByteBuffer buffer = command.marshall();
        Command cmd = Command.unmarshall(buffer);
        SlaveState ss = SlaveState.fromByteBuffer(cmd.getPayLoad());
        System.out.println(cmd.toString());
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            if (objOutputStream != null) {
                objOutputStream.close();
            }
            if (bout != null) {
                bout.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.iflytek.spider.util.EncodingDetector.java

public static void main(String[] args) throws IOException {
    if (args.length != 1) {
        System.err.println("Usage: EncodingDetector <file>");
        System.exit(1);/*  w w w .j  a v a  2 s  . c  o m*/
    }

    Configuration conf = SpiderConfiguration.create();
    EncodingDetector detector = new EncodingDetector(SpiderConfiguration.create());

    // do everything as bytes; don't want any conversion
    BufferedInputStream istr = new BufferedInputStream(new FileInputStream(args[0]));
    ByteArrayOutputStream ostr = new ByteArrayOutputStream();
    byte[] bytes = new byte[1000];
    boolean more = true;
    while (more) {
        int len = istr.read(bytes);
        if (len < bytes.length) {
            more = false;
            if (len > 0) {
                ostr.write(bytes, 0, len);
            }
        } else {
            ostr.write(bytes);
        }
    }

    byte[] data = ostr.toByteArray();

    // make a fake Content
    Content content = new Content("", data, null);

    detector.autoDetectClues(content, true);
    String encoding = detector.guessEncoding(content, conf.get("parser.character.encoding.default"));
    System.out.println("Guessed encoding: " + encoding);
}

From source file:net.itransformers.snmp2xml4j.snmptoolkit.XsltExecutor.java

/**
 * <p>main.</p>/*from   ww w .  jav a2  s. com*/
 *
 * @param args an array of {@link java.lang.String} objects.
 * @throws java.io.IOException if any.
 */
public static void main(String[] args) throws IOException {

    if (args.length != 3 && args.length != 4) {
        System.out.println("Missing input parameters");
        System.out.println(
                " Example usage: xsltTransform.sh /home/test/test.xslt /usr/data/Input.xml /usr/data/Output.xml ");
        return;
    }

    String inputXslt = args[0];
    if (inputXslt == null) {
        System.out.println("Missing input xslt file path");
        System.out.println(
                " Example usage: xsltTransformer.sh /home/test/test.xslt /usr/data/Input.xml /usr/data/Output.xml");
        return;
    }
    String inputFilePath = args[1];
    if (inputFilePath == null) {
        System.out.println("Missing input xml file path");
        System.out.println(
                " Example usage: xsltTransformer.sh /home/test/test.xslt /usr/data/Input.xml /usr/data/Output.xml");
        return;
    }

    String outputFilePath = args[2];
    if (outputFilePath == null) {
        System.out.println("Missing output file path");
        System.out.println(
                " Example usage: xsltTransformer.sh /home/test/test.xslt /usr/data/Input.xml /usr/data/Output.xml");
        return;
    }
    Map params = new HashMap<String, String>();
    if (args.length == 4) {
        String deviceOS = args[3];
        if (deviceOS != null) {
            params.put("DeviceOS", deviceOS);

        }
    }
    ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream();
    File xsltFileName1 = new File(inputXslt);

    FileInputStream inputStream1 = new FileInputStream(new File(inputFilePath));

    XsltTransformer xsltTransformer = new XsltTransformer();
    try {
        xsltTransformer.transformXML(inputStream1, xsltFileName1, outputStream1, params);
    } catch (TransformerException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    FileUtils.writeStringToFile(new File(outputFilePath), new String(outputStream1.toByteArray()));

    System.out.println("Done! please review the transformed file " + outputFilePath);

}

From source file:edu.nyupoly.cs6903.ag3671.FTPClientExample.java

public static void main(String[] args) throws UnknownHostException, Exception {
    // MY CODE//  w  w  w.ja v a  2s.c om
    if (crypto(Collections.unmodifiableList(Arrays.asList(args)))) {
        return;
    }
    ;
    // MY CODE -- END

    boolean storeFile = false, binaryTransfer = true, error = false, listFiles = false, listNames = false,
            hidden = false;
    boolean localActive = false, useEpsvWithIPv4 = false, feat = false, printHash = false;
    boolean mlst = false, mlsd = false;
    boolean lenient = false;
    long keepAliveTimeout = -1;
    int controlKeepAliveReplyTimeout = -1;
    int minParams = 5; // listings require 3 params
    String protocol = null; // SSL protocol
    String doCommand = null;
    String trustmgr = null;
    String proxyHost = null;
    int proxyPort = 80;
    String proxyUser = null;
    String proxyPassword = null;
    String username = null;
    String password = null;

    int base = 0;
    for (base = 0; base < args.length; base++) {
        if (args[base].equals("-s")) {
            storeFile = true;
        } else if (args[base].equals("-a")) {
            localActive = true;
        } else if (args[base].equals("-A")) {
            username = "anonymous";
            password = System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName();
        }
        // Always use binary transfer 
        //            else if (args[base].equals("-b")) {
        //                binaryTransfer = true;
        //            }
        else if (args[base].equals("-c")) {
            doCommand = args[++base];
            minParams = 3;
        } else if (args[base].equals("-d")) {
            mlsd = true;
            minParams = 3;
        } else if (args[base].equals("-e")) {
            useEpsvWithIPv4 = true;
        } else if (args[base].equals("-f")) {
            feat = true;
            minParams = 3;
        } else if (args[base].equals("-h")) {
            hidden = true;
        } else if (args[base].equals("-k")) {
            keepAliveTimeout = Long.parseLong(args[++base]);
        } else if (args[base].equals("-l")) {
            listFiles = true;
            minParams = 3;
        } else if (args[base].equals("-L")) {
            lenient = true;
        } else if (args[base].equals("-n")) {
            listNames = true;
            minParams = 3;
        } else if (args[base].equals("-p")) {
            protocol = args[++base];
        } else if (args[base].equals("-t")) {
            mlst = true;
            minParams = 3;
        } else if (args[base].equals("-w")) {
            controlKeepAliveReplyTimeout = Integer.parseInt(args[++base]);
        } else if (args[base].equals("-T")) {
            trustmgr = args[++base];
        } else if (args[base].equals("-PrH")) {
            proxyHost = args[++base];
            String parts[] = proxyHost.split(":");
            if (parts.length == 2) {
                proxyHost = parts[0];
                proxyPort = Integer.parseInt(parts[1]);
            }
        } else if (args[base].equals("-PrU")) {
            proxyUser = args[++base];
        } else if (args[base].equals("-PrP")) {
            proxyPassword = args[++base];
        } else if (args[base].equals("-#")) {
            printHash = true;
        } else {
            break;
        }
    }

    int remain = args.length - base;
    if (username != null) {
        minParams -= 2;
    }
    if (remain < minParams) // server, user, pass, remote, local [protocol]
    {
        System.err.println(USAGE);
        System.exit(1);
    }

    String server = args[base++];
    int port = 0;
    String parts[] = server.split(":");
    if (parts.length == 2) {
        server = parts[0];
        port = Integer.parseInt(parts[1]);
    }
    if (username == null) {
        username = args[base++];
        password = args[base++];
    }

    String remote = null;
    if (args.length - base > 0) {
        remote = args[base++];
    }

    String local = null;
    if (args.length - base > 0) {
        local = args[base++];
    }

    final FTPClient ftp;
    if (protocol == null) {
        if (proxyHost != null) {
            System.out.println("Using HTTP proxy server: " + proxyHost);
            ftp = new FTPHTTPClient(proxyHost, proxyPort, proxyUser, proxyPassword);
        } else {
            ftp = new FTPClient();
        }
    } else {
        FTPSClient ftps;
        if (protocol.equals("true")) {
            ftps = new FTPSClient(true);
        } else if (protocol.equals("false")) {
            ftps = new FTPSClient(false);
        } else {
            String prot[] = protocol.split(",");
            if (prot.length == 1) { // Just protocol
                ftps = new FTPSClient(protocol);
            } else { // protocol,true|false
                ftps = new FTPSClient(prot[0], Boolean.parseBoolean(prot[1]));
            }
        }
        ftp = ftps;
        if ("all".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
        } else if ("valid".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());
        } else if ("none".equals(trustmgr)) {
            ftps.setTrustManager(null);
        }
    }

    if (printHash) {
        ftp.setCopyStreamListener(createListener());
    }
    if (keepAliveTimeout >= 0) {
        ftp.setControlKeepAliveTimeout(keepAliveTimeout);
    }
    if (controlKeepAliveReplyTimeout >= 0) {
        ftp.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout);
    }
    ftp.setListHiddenFiles(hidden);

    // suppress login details
    ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

    try {
        int reply;
        if (port > 0) {
            ftp.connect(server, port);
        } else {
            ftp.connect(server);
        }
        System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));

        // After connection attempt, you should check the reply code to verify
        // success.
        reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
            System.exit(1);
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        System.exit(1);
    }

    __main: try {
        if (!ftp.login(username, password)) {
            ftp.logout();
            error = true;
            break __main;
        }

        System.out.println("Remote system is " + ftp.getSystemType());

        if (binaryTransfer) {
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
        } else {
            // in theory this should not be necessary as servers should default to ASCII
            // but they don't all do so - see NET-500
            ftp.setFileType(FTP.ASCII_FILE_TYPE);
        }

        // Use passive mode as default because most of us are
        // behind firewalls these days.
        if (localActive) {
            ftp.enterLocalActiveMode();
        } else {
            ftp.enterLocalPassiveMode();
        }

        ftp.setUseEPSVwithIPv4(useEpsvWithIPv4);

        if (storeFile) {
            InputStream input;

            input = new FileInputStream(local);
            // MY CODE
            byte[] bytes = IOUtils.toByteArray(input);
            InputStream encrypted = new ByteArrayInputStream(cryptor.encrypt(bytes));
            // MY CODE -- END
            ftp.storeFile(remote, encrypted);

            input.close();
        } else if (listFiles) {
            if (lenient) {
                FTPClientConfig config = new FTPClientConfig();
                config.setLenientFutureDates(true);
                ftp.configure(config);
            }

            for (FTPFile f : ftp.listFiles(remote)) {
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString());
            }
        } else if (mlsd) {
            for (FTPFile f : ftp.mlistDir(remote)) {
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString());
            }
        } else if (mlst) {
            FTPFile f = ftp.mlistFile(remote);
            if (f != null) {
                System.out.println(f.toFormattedString());
            }
        } else if (listNames) {
            for (String s : ftp.listNames(remote)) {
                System.out.println(s);
            }
        } else if (feat) {
            // boolean feature check
            if (remote != null) { // See if the command is present
                if (ftp.hasFeature(remote)) {
                    System.out.println("Has feature: " + remote);
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " was not detected");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }

                // Strings feature check
                String[] features = ftp.featureValues(remote);
                if (features != null) {
                    for (String f : features) {
                        System.out.println("FEAT " + remote + "=" + f + ".");
                    }
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " is not present");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }
            } else {
                if (ftp.features()) {
                    //                        Command listener has already printed the output
                } else {
                    System.out.println("Failed: " + ftp.getReplyString());
                }
            }
        } else if (doCommand != null) {
            if (ftp.doCommand(doCommand, remote)) {
                //                  Command listener has already printed the output
                //                    for(String s : ftp.getReplyStrings()) {
                //                        System.out.println(s);
                //                    }
            } else {
                System.out.println("Failed: " + ftp.getReplyString());
            }
        } else {
            OutputStream output;

            output = new FileOutputStream(local);

            // MY CODE
            ByteArrayOutputStream remoteFile = new ByteArrayOutputStream();
            //InputStream byteIn = new ByteArrayInputStream(buf);
            ftp.retrieveFile(remote, remoteFile);
            remoteFile.flush();
            Optional<byte[]> opt = cryptor.decrypt(remoteFile.toByteArray());
            if (opt.isPresent()) {
                output.write(opt.get());
            }
            remoteFile.close();
            // MY CODE -- END
            output.close();
        }

        ftp.noop(); // check that control connection is working OK

        ftp.logout();
    } catch (FTPConnectionClosedException e) {
        error = true;
        System.err.println("Server closed connection.");
        e.printStackTrace();
    } catch (IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
    }

    System.exit(error ? 1 : 0);
}

From source file:com.weibo.wesync.client.NHttpClient2.java

public static void main(String[] args) throws Exception {
    RSAPublicKey publicKey = RSAEncrypt.loadPublicKey("D:\\weibo\\meyou_gw\\conf\\public.pem");
    //  //from   w  ww  . j ava  2 s  .  com
    byte[] cipher = RSAEncrypt.encrypt(publicKey, password.getBytes());
    password = RSAEncrypt.toHexString(cipher);

    // HTTP parameters for the client
    HttpParams params = new SyncBasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000)
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);

    // Create HTTP protocol processing chain
    HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
            // Use standard client-side protocol interceptors
            new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(),
            new RequestExpectContinue() });
    // Create client-side HTTP protocol handler
    HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor();
    // Create client-side I/O event dispatch
    final IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler, params);
    // Create client-side I/O reactor
    IOReactorConfig config = new IOReactorConfig();
    config.setIoThreadCount(1);
    final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(config);
    // Create HTTP connection pool
    BasicNIOConnPool pool = new BasicNIOConnPool(ioReactor, params);
    // Limit total number of connections to just two
    pool.setDefaultMaxPerRoute(2);
    pool.setMaxTotal(1);

    // Run the I/O reactor in a separate thread
    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                // Ready to go!
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException ex) {
                System.err.println("Interrupted");
            } catch (IOException e) {
                System.err.println("I/O error: " + e.getMessage());
            }
            System.out.println("Shutdown");
        }

    });
    // Start the client thread
    t.start();
    // Create HTTP requester
    //        HttpAsyncRequester requester = new HttpAsyncRequester(
    //                httpproc, new DefaultConnectionReuseStrategy(), params);
    // Execute HTTP GETs to the following hosts and
    HttpHost[] targets = new HttpHost[] {
            //              new HttpHost("123.125.106.28", 8093, "http"),
            //              new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            new HttpHost("123.125.106.28", 8082, "http") };

    final CountDownLatch latch = new CountDownLatch(targets.length);
    int callbackId = 0;

    for (int i = 0; i < 1; i++) {
        for (final HttpHost target : targets) {
            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/wesync");

            //              String usrpwd = Base64.encodeBase64String((username + ":" + password).getBytes());
            //              request.setHeader("authorization", "Basic " + usrpwd);
            request.setHeader("uid", "2565640713");
            Meyou.MeyouPacket packet = null;

            if (callbackId == 0) {
                packet = Meyou.MeyouPacket.newBuilder().setCallbackId(String.valueOf(callbackId++))
                        .setSort(MeyouSort.notice).build();
            } else {
                packet = Meyou.MeyouPacket.newBuilder().setCallbackId(String.valueOf(callbackId++))
                        .setSort(MeyouSort.wesync).build();
            }

            ByteArrayEntity entity = new ByteArrayEntity(packet.toByteArray());
            request.setEntity(entity);
            //           BasicHttpRequest request = new BasicHttpRequest("GET", "/test.html");

            System.out.println("send ...");
            HttpAsyncRequester requester = new HttpAsyncRequester(httpproc,
                    new DefaultConnectionReuseStrategy(), params);
            requester.execute(new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(),
                    pool, new BasicHttpContext(),
                    // Handle HTTP response from a callback
                    new FutureCallback<HttpResponse>() {
                        public void completed(final HttpResponse response) {
                            StatusLine status = response.getStatusLine();
                            int code = status.getStatusCode();

                            if (code == 200) {
                                try {
                                    latch.countDown();
                                    DataInputStream in;
                                    in = new DataInputStream(response.getEntity().getContent());
                                    int packetLength = in.readInt();
                                    int start = 0;

                                    while (packetLength > 0) {
                                        ByteArrayOutputStream outstream = new ByteArrayOutputStream(
                                                packetLength);
                                        byte[] buffer = new byte[1024];
                                        int len = 0;

                                        while (start < packetLength
                                                && (len = in.read(buffer, start, packetLength)) > 0) {
                                            outstream.write(buffer, 0, len);
                                            start += len;
                                        }

                                        Meyou.MeyouPacket packet0 = Meyou.MeyouPacket
                                                .parseFrom(outstream.toByteArray());
                                        System.out.println(target + "->" + packet0);

                                        if ((len = in.read(buffer, start, 4)) > 0) {
                                            packetLength = Util.readPacketLength(buffer);
                                        } else {
                                            break;
                                        }
                                    }
                                } catch (IllegalStateException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                } catch (IOException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            } else {
                                System.out.println("error code=" + code + "|" + status.getReasonPhrase());
                            }
                        }

                        public void failed(final Exception ex) {
                            latch.countDown();
                            System.out.println(target + "->" + ex);
                        }

                        public void cancelled() {
                            latch.countDown();
                            System.out.println(target + " cancelled");
                        }

                    });

            Thread.sleep((long) (Math.random() * 10000));
        }
    }
    //        latch.await();
    //        System.out.println("Shutting down I/O reactor");
    //        ioReactor.shutdown();
    //        System.out.println("Done");
}

From source file:de.mpg.escidoc.services.common.util.Util.java

/**
 *  Command line transformation.//www .jav  a  2  s .  co m
 *  
 * @param see usage
 * @throws Exception Any exception
 */
public static void main(String[] args) throws Exception {
    if (args.length < 7) {
        System.out.println("Usage: ");
        System.out.println(
                "Util <srcFile> <srcFormatName> <srcFormatType> <srcFormatEncoding> <trgFormatName> <trgFormatType> <trgFormatEncoding> [<trgFile> [<service>]]");
        System.out.println("Example:");
        System.out.println(
                "Util /tmp/source.xml eDoc application/xml UTF-8 eSciDoc application/xml UTF-8 /tmp/target.xml");
    } else {
        // Init
        Transformation transformation = new TransformationBean(true);
        Format srcFormat = new Format(args[1], args[2], args[3]);
        Format trgFormat = new Format(args[4], args[5], args[6]);
        File srcFile = new File(args[0]);
        OutputStream trgStream;
        if (args.length > 7) {
            trgStream = new FileOutputStream(new File(args[7]));
        } else {
            trgStream = System.out;
        }
        String service = "eSciDoc";
        if (args.length > 8) {
            service = args[8];
        }

        // Get file content
        FileInputStream inputStream = new FileInputStream(srcFile);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[2048];
        int read;
        while ((read = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, read);
        }
        byte[] content = outputStream.toByteArray();

        // Transform
        byte[] result = transformation.transform(content, srcFormat, trgFormat, service);

        // Stream back
        trgStream.write(result);
        trgStream.close();

    }

}

From source file:Main.java

public static void main(String args[]) throws Exception {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    float sampleRate = 8000;
    int sampleSizeInBits = 8;
    int channels = 1;
    boolean signed = true;
    boolean bigEndian = true;
    final AudioFormat format = new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian);
    DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
    final TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info);
    line.open(format);//from w ww. j a  v a  2  s  .com
    line.start();
    Runnable runner = new Runnable() {
        int bufferSize = (int) format.getSampleRate() * format.getFrameSize();

        byte buffer[] = new byte[bufferSize];

        public void run() {
            try {

                int count = line.read(buffer, 0, buffer.length);
                if (count > 0) {
                    out.write(buffer, 0, count);
                }

                out.close();
            } catch (IOException e) {
                System.err.println("I/O problems: " + e);
                System.exit(-1);
            }
        }
    };
    Thread captureThread = new Thread(runner);
    captureThread.start();

    byte audio[] = out.toByteArray();
    InputStream input = new ByteArrayInputStream(audio);
    final SourceDataLine line1 = (SourceDataLine) AudioSystem.getLine(info);
    final AudioInputStream ais = new AudioInputStream(input, format, audio.length / format.getFrameSize());
    line1.open(format);
    line1.start();

    runner = new Runnable() {
        int bufferSize = (int) format.getSampleRate() * format.getFrameSize();

        byte buffer[] = new byte[bufferSize];

        public void run() {
            try {
                int count;
                while ((count = ais.read(buffer, 0, buffer.length)) != -1) {
                    if (count > 0) {
                        line1.write(buffer, 0, count);
                    }
                }
                line1.drain();
                line1.close();
            } catch (IOException e) {
                System.err.println("I/O problems: " + e);
                System.exit(-3);
            }
        }
    };
    Thread playThread = new Thread(runner);
    playThread.start();

}

From source file:com.netscape.cmstools.CRMFPopClient.java

public static void main(String args[]) throws Exception {

    Options options = createOptions();//from   www.  j av a 2 s.  c o  m
    CommandLine cmd = null;

    try {
        CommandLineParser parser = new PosixParser();
        cmd = parser.parse(options, args);

    } catch (Exception e) {
        printError(e.getMessage());
        System.exit(1);
    }

    if (cmd.hasOption("help")) {
        printHelp();
        System.exit(0);
    }

    boolean verbose = cmd.hasOption("v");

    String databaseDir = cmd.getOptionValue("d", ".");
    String tokenPassword = cmd.getOptionValue("p");
    String tokenName = cmd.getOptionValue("h");

    String algorithm = cmd.getOptionValue("a", "rsa");
    int keySize = Integer.parseInt(cmd.getOptionValue("l", "2048"));

    String profileID = cmd.getOptionValue("f");
    String subjectDN = cmd.getOptionValue("n");
    boolean encodingEnabled = Boolean.parseBoolean(cmd.getOptionValue("k", "false"));

    // if transportCertFilename is not specified then assume no key archival
    String transportCertFilename = cmd.getOptionValue("b");

    String popOption = cmd.getOptionValue("q", "POP_SUCCESS");

    String curve = cmd.getOptionValue("c", "nistp256");
    boolean sslECDH = Boolean.parseBoolean(cmd.getOptionValue("x", "false"));
    boolean temporary = Boolean.parseBoolean(cmd.getOptionValue("t", "true"));
    int sensitive = Integer.parseInt(cmd.getOptionValue("s", "-1"));
    int extractable = Integer.parseInt(cmd.getOptionValue("e", "-1"));

    boolean self_sign = cmd.hasOption("y");

    // get the keywrap algorithm
    KeyWrapAlgorithm keyWrapAlgorithm = null;
    String kwAlg = KeyWrapAlgorithm.AES_KEY_WRAP_PAD.toString();
    if (cmd.hasOption("w")) {
        kwAlg = cmd.getOptionValue("w");
    } else {
        String alg = System.getenv("KEY_ARCHIVAL_KEYWRAP_ALGORITHM");
        if (alg != null) {
            kwAlg = alg;
        }
    }

    String output = cmd.getOptionValue("o");

    String hostPort = cmd.getOptionValue("m");
    String username = cmd.getOptionValue("u");
    String requestor = cmd.getOptionValue("r");

    if (hostPort != null) {
        if (cmd.hasOption("w")) {
            printError("Any value specified for the key wrap parameter (-w) "
                    + "will be overriden.  CRMFPopClient will contact the "
                    + "CA to determine the supported algorithm when " + "hostport is specified");
        }
    }

    if (subjectDN == null) {
        printError("Missing subject DN");
        System.exit(1);
    }

    if (tokenPassword == null) {
        printError("Missing token password");
        System.exit(1);
    }

    if (algorithm.equals("rsa")) {
        if (cmd.hasOption("c")) {
            printError("Illegal parameter for RSA: -c");
            System.exit(1);
        }

        if (cmd.hasOption("t")) {
            printError("Illegal parameter for RSA: -t");
            System.exit(1);
        }

        if (cmd.hasOption("s")) {
            printError("Illegal parameter for RSA: -s");
            System.exit(1);
        }

        if (cmd.hasOption("e")) {
            printError("Illegal parameter for RSA: -e");
            System.exit(1);
        }

        if (cmd.hasOption("x")) {
            printError("Illegal parameter for RSA: -x");
            System.exit(1);
        }

    } else if (algorithm.equals("ec")) {
        if (cmd.hasOption("l")) {
            printError("Illegal parameter for ECC: -l");
            System.exit(1);
        }

        if (sensitive != 0 && sensitive != 1 && sensitive != -1) {
            printError("Illegal input parameters for -s: " + sensitive);
            System.exit(1);
        }

        if (extractable != 0 && extractable != 1 && extractable != -1) {
            printError("Illegal input parameters for -e: " + extractable);
            System.exit(1);
        }

    } else {
        printError("Invalid algorithm: " + algorithm);
        System.exit(1);
    }

    if (!popOption.equals("POP_SUCCESS") && !popOption.equals("POP_FAIL") && !popOption.equals("POP_NONE")) {
        printError("Invalid POP option: " + popOption);
        System.exit(1);
    }

    if (profileID == null) {
        if (algorithm.equals("rsa")) {
            profileID = "caEncUserCert";

        } else if (algorithm.equals("ec")) {
            profileID = "caEncECUserCert";

        } else {
            throw new Exception("Unknown algorithm: " + algorithm);
        }
    }

    try {
        if (verbose)
            System.out.println("Initializing security database: " + databaseDir);
        CryptoManager.initialize(databaseDir);

        CryptoManager manager = CryptoManager.getInstance();

        CryptoToken token = CryptoUtil.getKeyStorageToken(tokenName);
        tokenName = token.getName();
        manager.setThreadToken(token);

        Password password = new Password(tokenPassword.toCharArray());
        try {
            token.login(password);
        } catch (Exception e) {
            throw new Exception("Unable to login: " + e, e);
        }

        CRMFPopClient client = new CRMFPopClient();
        client.setVerbose(verbose);

        String encoded = null;
        X509Certificate transportCert = null;
        if (transportCertFilename != null) {
            if (verbose)
                System.out.println("archival option enabled");
            if (verbose)
                System.out.println("Loading transport certificate");
            encoded = new String(Files.readAllBytes(Paths.get(transportCertFilename)));
            byte[] transportCertData = Cert.parseCertificate(encoded);
            transportCert = manager.importCACertPackage(transportCertData);
        } else {
            if (verbose)
                System.out.println("archival option not enabled");
        }

        if (verbose)
            System.out.println("Parsing subject DN");
        Name subject = client.createName(subjectDN, encodingEnabled);

        if (subject == null) {
            subject = new Name();
            subject.addCommonName("Me");
            subject.addCountryName("US");
            subject.addElement(
                    new AVA(new OBJECT_IDENTIFIER("0.9.2342.19200300.100.1.1"), new PrintableString("MyUid")));
        }

        if (verbose)
            System.out.println("Generating key pair");
        KeyPair keyPair;
        if (algorithm.equals("rsa")) {
            keyPair = CryptoUtil.generateRSAKeyPair(token, keySize);
        } else if (algorithm.equals("ec")) {
            keyPair = client.generateECCKeyPair(token, curve, sslECDH, temporary, sensitive, extractable);

        } else {
            throw new Exception("Unknown algorithm: " + algorithm);
        }

        // print out keyid to be used in cmc decryptPOP
        PrivateKey privateKey = (PrivateKey) keyPair.getPrivate();
        @SuppressWarnings("deprecation")
        byte id[] = privateKey.getUniqueID();
        String kid = CryptoUtil.encodeKeyID(id);
        System.out.println("Keypair private key id: " + kid);

        if ((transportCert != null) && (hostPort != null)) {
            // check the CA for the required key wrap algorithm
            // if found, override whatever has been set by the command line
            // options for the key wrap algorithm

            ClientConfig config = new ClientConfig();
            String host = hostPort.substring(0, hostPort.indexOf(':'));
            int port = Integer.parseInt(hostPort.substring(hostPort.indexOf(':') + 1));
            config.setServerURL("http", host, port);

            PKIClient pkiclient = new PKIClient(config);
            kwAlg = getKeyWrapAlgotihm(pkiclient);
        }

        if (verbose && (transportCert != null))
            System.out.println("Using key wrap algorithm: " + kwAlg);
        if (transportCert != null) {
            keyWrapAlgorithm = KeyWrapAlgorithm.fromString(kwAlg);
        }

        if (verbose)
            System.out.println("Creating certificate request");
        CertRequest certRequest = client.createCertRequest(self_sign, token, transportCert, algorithm, keyPair,
                subject, keyWrapAlgorithm);

        ProofOfPossession pop = null;

        if (!popOption.equals("POP_NONE")) {

            if (verbose)
                System.out.println("Creating signer");
            Signature signer = client.createSigner(token, algorithm, keyPair);

            if (popOption.equals("POP_SUCCESS")) {

                ByteArrayOutputStream bo = new ByteArrayOutputStream();
                certRequest.encode(bo);
                signer.update(bo.toByteArray());

            } else if (popOption.equals("POP_FAIL")) {

                byte[] data = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 };

                signer.update(data);
            }

            byte[] signature = signer.sign();

            if (verbose)
                System.out.println("Creating POP");
            pop = client.createPop(algorithm, signature);
        }

        if (verbose)
            System.out.println("Creating CRMF request");
        String request = client.createCRMFRequest(certRequest, pop);

        StringWriter sw = new StringWriter();
        try (PrintWriter out = new PrintWriter(sw)) {
            out.println(Cert.REQUEST_HEADER);
            out.print(request);
            out.println(Cert.REQUEST_FOOTER);
        }
        String csr = sw.toString();

        if (hostPort != null) {
            System.out.println("Submitting CRMF request to " + hostPort);
            client.submitRequest(request, hostPort, username, profileID, requestor);

        } else if (output != null) {
            System.out.println("Storing CRMF request into " + output);
            try (FileWriter out = new FileWriter(output)) {
                out.write(csr);
            }

        } else {
            System.out.println(csr);
        }

    } catch (Exception e) {
        if (verbose)
            e.printStackTrace();
        printError(e.getMessage());
        System.exit(1);
    }
}

From source file:com.tremolosecurity.openunison.util.OpenUnisonUtils.java

public static void main(String[] args) throws Exception {

    logger = org.apache.logging.log4j.LogManager.getLogger(OpenUnisonUtils.class.getName());

    Options options = new Options();
    options.addOption("unisonXMLFile", true, "The full path to the Unison xml file");
    options.addOption("keystorePath", true, "The full path to the Unison keystore");
    options.addOption("chainName", true, "The name of the authentication chain");
    options.addOption("mechanismName", true, "The name of the authentication mechanism for SAML2");
    options.addOption("idpName", true, "The name of the identity provider application");
    options.addOption("pathToMetaData", true, "The full path to the saml2 metadata file");
    options.addOption("createDefault", false, "If set, add default parameters");
    options.addOption("action", true,
            "export-sp-metadata, import-sp-metadata, export-secretkey, print-secretkey, import-idp-metadata, export-idp-metadata, clear-dlq, import-secretkey, create-secretkey");
    options.addOption("urlBase", true, "Base URL, no URI; https://host:port");
    options.addOption("alias", true, "Key alias");
    options.addOption("newKeystorePath", true, "Path to the new keystore");
    options.addOption("newKeystorePassword", true, "Password for the new keystore");
    options.addOption("help", false, "Prints this message");
    options.addOption("signMetadataWithKey", true, "Signs the metadata with the specified key");
    options.addOption("dlqName", true, "The name of the dead letter queue");
    options.addOption("upgradeFrom106", false, "Updates workflows from 1.0.6");
    options.addOption("secretkey", true, "base64 encoded secret key");
    options.addOption("envFile", true, "Environment variables for parmaterized configs");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args, true);

    if (args.length == 0 || cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("OpenUnisonUtils", options);
    }//w w w . ja  v a2 s .co  m

    logger.info("Loading Unison Configuration");
    String unisonXMLFile = loadOption(cmd, "unisonXMLFile", options);
    TremoloType ttRead = loadTremoloType(unisonXMLFile, cmd, options);

    String action = loadOption(cmd, "action", options);
    TremoloType ttWrite = null;
    if (action.equalsIgnoreCase("import-sp-metadata") || action.equalsIgnoreCase("import-idp-metadata")) {
        ttWrite = loadTremoloType(unisonXMLFile);
    }

    logger.info("Configuration loaded");

    logger.info("Loading the keystore...");
    String ksPath = loadOption(cmd, "keystorePath", options);

    KeyStore ks = loadKeyStore(ksPath, ttRead);

    logger.info("...loaded");

    if (action.equalsIgnoreCase("import-sp-metadata")) {

        importMetaData(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks);
    } else if (action.equalsIgnoreCase("export-sp-metadata")) {
        exportSPMetaData(options, cmd, ttRead, ks);

    } else if (action.equalsIgnoreCase("print-secretkey")) {
        printSecreyKey(options, cmd, ttRead, ks);
    } else if (action.equalsIgnoreCase("import-secretkey")) {
        importSecreyKey(options, cmd, ttRead, ks, ksPath);
    } else if (action.equalsIgnoreCase("create-secretkey")) {
        Security.addProvider(new BouncyCastleProvider());
        logger.info("Creating AES-256 secret key");
        String alias = loadOption(cmd, "alias", options);
        logger.info("Alias : '" + alias + "'");
        KeyGenerator kg = KeyGenerator.getInstance("AES", "BC");
        kg.init(256, new SecureRandom());
        SecretKey sk = kg.generateKey();
        ks.setKeyEntry(alias, sk, ttRead.getKeyStorePassword().toCharArray(), null);
        logger.info("Saving key");
        ks.store(new FileOutputStream(ksPath), ttRead.getKeyStorePassword().toCharArray());
        logger.info("Finished");
    } else if (action.equalsIgnoreCase("export-secretkey")) {
        logger.info("Export Secret Key");

        logger.info("Loading key");
        String alias = loadOption(cmd, "alias", options);
        SecretKey key = (SecretKey) ks.getKey(alias, ttRead.getKeyStorePassword().toCharArray());
        logger.info("Loading new keystore path");
        String pathToNewKeystore = loadOption(cmd, "newKeystorePath", options);
        logger.info("Loading new keystore password");
        String ksPassword = loadOption(cmd, "newKeystorePassword", options);

        KeyStore newKS = KeyStore.getInstance("PKCS12");
        newKS.load(null, ttRead.getKeyStorePassword().toCharArray());
        newKS.setKeyEntry(alias, key, ksPassword.toCharArray(), null);
        newKS.store(new FileOutputStream(pathToNewKeystore), ksPassword.toCharArray());
        logger.info("Exported");
    } else if (action.equalsIgnoreCase("import-idp-metadata")) {
        importIdpMetadata(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks);

    } else if (action.equalsIgnoreCase("export-idp-metadata")) {
        exportIdPMetadata(options, cmd, ttRead, ks);
    } else if (action.equalsIgnoreCase("clear-dlq")) {
        logger.info("Getting the DLQ Name...");
        String dlqName = loadOption(cmd, "dlqName", options);
        QueUtils.emptyDLQ(ttRead, dlqName);
    } else if (action.equalsIgnoreCase("upgradeFrom106")) {
        logger.info("Upgrading OpenUnison's configuration from 1.0.6");

        String backupFileName = unisonXMLFile + ".bak";

        logger.info("Backing up to '" + backupFileName + "'");

        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(unisonXMLFile)));
        PrintWriter out = new PrintWriter(new FileOutputStream(backupFileName));
        String line = null;
        while ((line = in.readLine()) != null) {
            out.println(line);
        }
        out.flush();
        out.close();
        in.close();

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        AddChoiceToTasks.convert(new FileInputStream(unisonXMLFile), bout);
        FileOutputStream fsout = new FileOutputStream(unisonXMLFile);
        fsout.write(bout.toByteArray());
        fsout.flush();
        fsout.close();

    }

}

From source file:ch.kostceco.tools.kostsimy.KOSTSimy.java

/** Die Eingabe besteht aus 2 Parameter: [0] Original-Ordner [1] Replica-Ordner
 * //from  w  ww.j a  v a  2 s .  c om
 * @param args
 * @throws IOException */

public static void main(String[] args) throws IOException {
    ApplicationContext context = new ClassPathXmlApplicationContext("classpath:config/applicationContext.xml");

    // Zeitstempel Start
    java.util.Date nowStart = new java.util.Date();
    java.text.SimpleDateFormat sdfStart = new java.text.SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
    String ausgabeStart = sdfStart.format(nowStart);

    KOSTSimy kostsimy = (KOSTSimy) context.getBean("kostsimy");
    File configFile = new File("configuration" + File.separator + "kostsimy.conf.xml");

    // Ueberprfung des Parameters (Log-Verzeichnis)
    String pathToLogfile = kostsimy.getConfigurationService().getPathToLogfile();

    File directoryOfLogfile = new File(pathToLogfile);

    if (!directoryOfLogfile.exists()) {
        directoryOfLogfile.mkdir();
    }

    // Im Logverzeichnis besteht kein Schreibrecht
    if (!directoryOfLogfile.canWrite()) {
        System.out.println(
                kostsimy.getTextResourceService().getText(ERROR_LOGDIRECTORY_NOTWRITABLE, directoryOfLogfile));
        System.exit(1);
    }

    if (!directoryOfLogfile.isDirectory()) {
        System.out.println(kostsimy.getTextResourceService().getText(ERROR_LOGDIRECTORY_NODIRECTORY));
        System.exit(1);
    }

    // Ist die Anzahl Parameter (2) korrekt?
    if (args.length > 3) {
        System.out.println(kostsimy.getTextResourceService().getText(ERROR_PARAMETER_USAGE));
        System.exit(1);
    }

    File origDir = new File(args[0]);
    File repDir = new File(args[1]);
    File logDatei = null;
    logDatei = origDir;

    // Informationen zum Arbeitsverzeichnis holen
    String pathToWorkDir = kostsimy.getConfigurationService().getPathToWorkDir();
    /* Nicht vergessen in "src/main/resources/config/applicationContext-services.xml" beim
     * entsprechenden Modul die property anzugeben: <property name="configurationService"
     * ref="configurationService" /> */

    // Konfiguration des Loggings, ein File Logger wird zustzlich erstellt
    LogConfigurator logConfigurator = (LogConfigurator) context.getBean("logconfigurator");
    String logFileName = logConfigurator.configure(directoryOfLogfile.getAbsolutePath(), logDatei.getName());
    File logFile = new File(logFileName);
    // Ab hier kann ins log geschrieben werden...

    LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_HEADER));
    LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_START, ausgabeStart));
    LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_END));
    LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_INFO));
    System.out.println("KOST-Simy");
    System.out.println("");

    if (!origDir.exists()) {
        // Das Original-Verzeichnis existiert nicht
        LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_IOE,
                kostsimy.getTextResourceService().getText(ERROR_NOORIGDIR, origDir.getAbsolutePath())));
        System.out
                .println(kostsimy.getTextResourceService().getText(ERROR_NOORIGDIR, origDir.getAbsolutePath()));
        System.exit(1);
    }

    if (!repDir.exists()) {
        // Das Replica-Verzeichnis existiert nicht
        LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_IOE,
                kostsimy.getTextResourceService().getText(ERROR_NOREPDIR1, repDir.getAbsolutePath())));
        System.out
                .println(kostsimy.getTextResourceService().getText(ERROR_NOREPDIR1, repDir.getAbsolutePath()));
        System.exit(1);
    }

    File xslOrig = new File("resources" + File.separator + "kost-simy.xsl");
    File xslCopy = new File(directoryOfLogfile.getAbsolutePath() + File.separator + "kost-simy.xsl");
    if (!xslCopy.exists()) {
        Util.copyFile(xslOrig, xslCopy);
    }

    // Informationen zur prozentualen Stichprobe holen
    String randomTest = kostsimy.getConfigurationService().getRandomTest();
    /* Nicht vergessen in "src/main/resources/config/applicationContext-services.xml" beim
     * entsprechenden Modul die property anzugeben: <property name="configurationService"
     * ref="configurationService" /> */
    int iRandomTest = 100;
    try {
        iRandomTest = Integer.parseInt(randomTest);
    } catch (Exception ex) {
        // unzulaessige Eingabe --> 50 wird gesetzt
        iRandomTest = 50;
    }
    if (iRandomTest > 100 || iRandomTest < 1) {
        // unzulaessige Eingabe --> 50 wird gesetzt
        iRandomTest = 50;
    }

    File tmpDir = new File(pathToWorkDir);

    /* bestehendes Workverzeichnis Abbruch wenn nicht leer, da am Schluss das Workverzeichnis
     * gelscht wird und entsprechend bestehende Dateien gelscht werden knnen */
    if (tmpDir.exists()) {
        if (tmpDir.isDirectory()) {
            // Get list of file in the directory. When its length is not zero the folder is not empty.
            String[] files = tmpDir.list();
            if (files.length > 0) {
                LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_IOE,
                        kostsimy.getTextResourceService().getText(ERROR_WORKDIRECTORY_EXISTS, pathToWorkDir)));
                System.out.println(
                        kostsimy.getTextResourceService().getText(ERROR_WORKDIRECTORY_EXISTS, pathToWorkDir));
                System.exit(1);
            }
        }
    }

    // Im Pfad keine Sonderzeichen Programme knnen evtl abstrzen

    String patternStr = "[^!#\\$%\\(\\)\\+,\\-_\\.=@\\[\\]\\{\\}\\~:\\\\a-zA-Z0-9 ]";
    Pattern pattern = Pattern.compile(patternStr);

    String name = tmpDir.getAbsolutePath();

    String[] pathElements = name.split("/");
    for (int i = 0; i < pathElements.length; i++) {
        String element = pathElements[i];

        Matcher matcher = pattern.matcher(element);

        boolean matchFound = matcher.find();
        if (matchFound) {
            LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_IOE,
                    kostsimy.getTextResourceService().getText(ERROR_SPECIAL_CHARACTER, name)));
            System.out.println(kostsimy.getTextResourceService().getText(ERROR_SPECIAL_CHARACTER, name));
            System.exit(1);
        }
    }

    // die Anwendung muss mindestens unter Java 6 laufen
    String javaRuntimeVersion = System.getProperty("java.vm.version");
    if (javaRuntimeVersion.compareTo("1.6.0") < 0) {
        LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_IOE,
                kostsimy.getTextResourceService().getText(ERROR_WRONG_JRE)));
        System.out.println(kostsimy.getTextResourceService().getText(ERROR_WRONG_JRE));
        System.exit(1);
    }

    // bestehendes Workverzeichnis wieder anlegen
    if (!tmpDir.exists()) {
        tmpDir.mkdir();
        File origDirTmp = new File(tmpDir.getAbsolutePath() + File.separator + "orig");
        File repDirTmp = new File(tmpDir.getAbsolutePath() + File.separator + "rep");
        origDirTmp.mkdir();
        repDirTmp.mkdir();
    }

    // Im workverzeichnis besteht kein Schreibrecht
    if (!tmpDir.canWrite()) {
        LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_IOE,
                kostsimy.getTextResourceService().getText(ERROR_WORKDIRECTORY_NOTWRITABLE, tmpDir)));
        System.out.println(kostsimy.getTextResourceService().getText(ERROR_WORKDIRECTORY_NOTWRITABLE, tmpDir));
        System.exit(1);
    }

    // Im Pfad keine Sonderzeichen --> Absturzgefahr
    name = origDir.getAbsolutePath();
    pathElements = name.split("/");
    for (int i = 0; i < pathElements.length; i++) {
        String element = pathElements[i];
        Matcher matcher = pattern.matcher(element);
        boolean matchFound = matcher.find();
        if (matchFound) {
            LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_IOE,
                    kostsimy.getTextResourceService().getText(ERROR_SPECIAL_CHARACTER, name)));
            System.out.println(kostsimy.getTextResourceService().getText(ERROR_SPECIAL_CHARACTER, name));
            System.exit(1);
        }
    }
    name = repDir.getAbsolutePath();
    pathElements = name.split("/");
    for (int i = 0; i < pathElements.length; i++) {
        String element = pathElements[i];
        Matcher matcher = pattern.matcher(element);
        boolean matchFound = matcher.find();
        if (matchFound) {
            LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_IOE,
                    kostsimy.getTextResourceService().getText(ERROR_SPECIAL_CHARACTER, name)));
            System.out.println(kostsimy.getTextResourceService().getText(ERROR_SPECIAL_CHARACTER, name));
            System.exit(1);
        }
    }

    LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_IMAGE1));
    float count = 0;
    int countNio = 0;
    int countIo = 0;
    float countVal = 0;
    int countNotVal = 0;
    float percentage = (float) 0.0;

    if (!origDir.isDirectory()) {
        // TODO: Bildervergleich zweier Dateien --> erledigt --> nur Marker

        if (repDir.isDirectory()) {
            // Das Replica-ist ein Verzeichnis, aber Original eine Datei
            LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_IOE,
                    kostsimy.getTextResourceService().getText(ERROR_NOREPDIR2, repDir.getAbsolutePath())));
            System.out.println(
                    kostsimy.getTextResourceService().getText(ERROR_NOREPDIR2, repDir.getAbsolutePath()));
            System.exit(1);
        }
        boolean compFile = compFile(origDir, logFileName, directoryOfLogfile, repDir, tmpDir);

        float statIo = 0;
        int statNio = 0;
        float statUn = 0;
        if (compFile) {
            statIo = 100;
        } else {
            statNio = 100;
        }

        LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_IMAGE2));
        LOGGER.logError(
                kostsimy.getTextResourceService().getText(MESSAGE_XML_STATISTICS, statIo, statNio, statUn));

        LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_LOGEND));
        // Zeitstempel End
        java.util.Date nowEnd = new java.util.Date();
        java.text.SimpleDateFormat sdfEnd = new java.text.SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
        String ausgabeEnd = sdfEnd.format(nowEnd);
        ausgabeEnd = "<End>" + ausgabeEnd + "</End>";
        Util.valEnd(ausgabeEnd, logFile);
        Util.amp(logFile);

        // Die Konfiguration hereinkopieren
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);

            factory.setExpandEntityReferences(false);

            Document docConfig = factory.newDocumentBuilder().parse(configFile);
            NodeList list = docConfig.getElementsByTagName("configuration");
            Element element = (Element) list.item(0);

            Document docLog = factory.newDocumentBuilder().parse(logFile);

            Node dup = docLog.importNode(element, true);

            docLog.getDocumentElement().appendChild(dup);
            FileWriter writer = new FileWriter(logFile);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ElementToStream(docLog.getDocumentElement(), baos);
            String stringDoc2 = new String(baos.toByteArray());
            writer.write(stringDoc2);
            writer.close();

            // Der Header wird dabei leider verschossen, wieder zurck ndern
            String newstring = kostsimy.getTextResourceService().getText(MESSAGE_XML_HEADER);
            String oldstring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><KOSTSimyLog>";
            Util.oldnewstring(oldstring, newstring, logFile);

        } catch (Exception e) {
            LOGGER.logError(
                    "<Error>" + kostsimy.getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
            System.out.println("Exception: " + e.getMessage());
        }

        if (compFile) {
            // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
            if (tmpDir.exists()) {
                Util.deleteDir(tmpDir);
            }
            // Validierte Datei valide
            System.exit(0);
        } else {
            // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde
            if (tmpDir.exists()) {
                Util.deleteDir(tmpDir);
            }
            // Fehler in Validierte Datei --> invalide
            System.exit(2);

        }
    } else {
        // TODO: Bildervergleich zweier Verzeichnisse --> in Arbeit --> nur Marker
        if (!repDir.isDirectory()) {
            // Das Replica-ist eine Datei, aber Original ein Ordner
            LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_IOE,
                    kostsimy.getTextResourceService().getText(ERROR_NOREPDIR3, repDir.getAbsolutePath())));
            System.out.println(
                    kostsimy.getTextResourceService().getText(ERROR_NOREPDIR3, repDir.getAbsolutePath()));
            System.exit(1);
        }

        Map<String, File> fileMap = Util.getFileMap(origDir, false);
        Set<String> fileMapKeys = fileMap.keySet();
        boolean other = false;

        for (Iterator<String> iterator = fileMapKeys.iterator(); iterator.hasNext();) {
            String entryName = iterator.next();
            File newFile = fileMap.get(entryName);
            if (!newFile.isDirectory()) {
                origDir = newFile;
                count = count + 1;
                if ((origDir.getAbsolutePath().toLowerCase().endsWith(".pdf")
                        || origDir.getAbsolutePath().toLowerCase().endsWith(".pdfa")
                        || origDir.getAbsolutePath().toLowerCase().endsWith(".tif")
                        || origDir.getAbsolutePath().toLowerCase().endsWith(".tiff")
                        || origDir.getAbsolutePath().toLowerCase().endsWith(".jpeg")
                        || origDir.getAbsolutePath().toLowerCase().endsWith(".jpg")
                        || origDir.getAbsolutePath().toLowerCase().endsWith(".jpe")
                        || origDir.getAbsolutePath().toLowerCase().endsWith(".jp2")
                        || origDir.getAbsolutePath().toLowerCase().endsWith(".gif")
                        || origDir.getAbsolutePath().toLowerCase().endsWith(".png")
                        || origDir.getAbsolutePath().toLowerCase().endsWith(".bmp"))) {
                    percentage = 100 / count * countVal;
                    if (percentage < iRandomTest) {
                        // if ( 100 / count * (countVal + 1) <= iRandomTest ) {

                        countVal = countVal + 1;

                        String origWithOutExt = FilenameUtils.removeExtension(origDir.getName());

                        File repFile = new File(
                                repDir.getAbsolutePath() + File.separator + origWithOutExt + ".pdf");
                        if (!repFile.exists()) {
                            repFile = new File(
                                    repDir.getAbsolutePath() + File.separator + origWithOutExt + ".pdfa");
                            if (!repFile.exists()) {
                                repFile = new File(
                                        repDir.getAbsolutePath() + File.separator + origWithOutExt + ".tif");
                                if (!repFile.exists()) {
                                    repFile = new File(repDir.getAbsolutePath() + File.separator
                                            + origWithOutExt + ".tiff");
                                    if (!repFile.exists()) {
                                        repFile = new File(repDir.getAbsolutePath() + File.separator
                                                + origWithOutExt + ".jpeg");
                                        if (!repFile.exists()) {
                                            repFile = new File(repDir.getAbsolutePath() + File.separator
                                                    + origWithOutExt + ".jpg");
                                            if (!repFile.exists()) {
                                                repFile = new File(repDir.getAbsolutePath() + File.separator
                                                        + origWithOutExt + ".jpe");
                                                if (!repFile.exists()) {
                                                    repFile = new File(repDir.getAbsolutePath() + File.separator
                                                            + origWithOutExt + ".jp2");
                                                    if (!repFile.exists()) {
                                                        repFile = new File(repDir.getAbsolutePath()
                                                                + File.separator + origWithOutExt + ".gif");
                                                        if (!repFile.exists()) {
                                                            repFile = new File(repDir.getAbsolutePath()
                                                                    + File.separator + origWithOutExt + ".png");
                                                            if (!repFile.exists()) {
                                                                repFile = new File(repDir.getAbsolutePath()
                                                                        + File.separator + origWithOutExt
                                                                        + ".bmp");
                                                                if (!repFile.exists()) {
                                                                    other = true;
                                                                    LOGGER.logError(kostsimy
                                                                            .getTextResourceService()
                                                                            .getText(MESSAGE_XML_VALERGEBNIS));
                                                                    LOGGER.logError(kostsimy
                                                                            .getTextResourceService()
                                                                            .getText(MESSAGE_XML_COMPFILE,
                                                                                    origDir));
                                                                    LOGGER.logError(kostsimy
                                                                            .getTextResourceService().getText(
                                                                                    MESSAGE_XML_VALERGEBNIS_NOTVALIDATED));
                                                                    LOGGER.logError(
                                                                            kostsimy.getTextResourceService()
                                                                                    .getText(ERROR_NOREP,
                                                                                            origDir.getName()));
                                                                    LOGGER.logError(kostsimy
                                                                            .getTextResourceService().getText(
                                                                                    MESSAGE_XML_VALERGEBNIS_CLOSE));
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        if (!other) {
                            boolean compFile = compFile(origDir, logFileName, directoryOfLogfile, repFile,
                                    tmpDir);
                            if (compFile) {
                                // Vergleich bestanden
                                countIo = countIo + 1;
                            } else {
                                // Vergleich nicht bestanden
                                countNio = countNio + 1;
                            }
                        }
                    } else {
                        countNotVal = countNotVal + 1;
                        LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS));
                        LOGGER.logError(
                                kostsimy.getTextResourceService().getText(MESSAGE_XML_COMPFILE, origDir));
                        LOGGER.logError(kostsimy.getTextResourceService()
                                .getText(MESSAGE_XML_VALERGEBNIS_NOTVALIDATED));
                        LOGGER.logError(
                                kostsimy.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_CLOSE));
                    }
                } else {
                    countNotVal = countNotVal + 1;
                    LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS));
                    LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_COMPFILE, origDir));
                    LOGGER.logError(
                            kostsimy.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_NOTVALIDATED));
                    LOGGER.logError(
                            kostsimy.getTextResourceService().getText(ERROR_INCORRECTFILEENDING, origDir));
                    LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_CLOSE));
                }
            }
        }

        if (countNio == 0 && countIo == 0) {
            // keine Dateien verglichen
            LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_INCORRECTFILEENDINGS));
            System.out.println(kostsimy.getTextResourceService().getText(ERROR_INCORRECTFILEENDINGS));
        }

        float statIo = 100 / (float) count * (float) countIo;
        float statNio = 100 / (float) count * (float) countNio;
        float statUn = 100 - statIo - statNio;

        LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_IMAGE2));
        LOGGER.logError(
                kostsimy.getTextResourceService().getText(MESSAGE_XML_STATISTICS, statIo, statNio, statUn));
        LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_LOGEND));
        // Zeitstempel End
        java.util.Date nowEnd = new java.util.Date();
        java.text.SimpleDateFormat sdfEnd = new java.text.SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
        String ausgabeEnd = sdfEnd.format(nowEnd);
        ausgabeEnd = "<End>" + ausgabeEnd + "</End>";
        Util.valEnd(ausgabeEnd, logFile);
        Util.amp(logFile);

        // Die Konfiguration hereinkopieren
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);

            factory.setExpandEntityReferences(false);

            Document docConfig = factory.newDocumentBuilder().parse(configFile);
            NodeList list = docConfig.getElementsByTagName("configuration");
            Element element = (Element) list.item(0);

            Document docLog = factory.newDocumentBuilder().parse(logFile);

            Node dup = docLog.importNode(element, true);

            docLog.getDocumentElement().appendChild(dup);
            FileWriter writer = new FileWriter(logFile);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ElementToStream(docLog.getDocumentElement(), baos);
            String stringDoc2 = new String(baos.toByteArray());
            writer.write(stringDoc2);
            writer.close();

            // Der Header wird dabei leider verschossen, wieder zurck ndern
            String newstring = kostsimy.getTextResourceService().getText(MESSAGE_XML_HEADER);
            String oldstring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><KOSTSimyLog>";
            Util.oldnewstring(oldstring, newstring, logFile);

        } catch (Exception e) {
            LOGGER.logError(
                    "<Error>" + kostsimy.getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
            System.out.println("Exception: " + e.getMessage());
        }

        if (countNio == 0 && countIo == 0) {
            // keine Dateien verglichen bestehendes Workverzeichnis ggf. lschen
            if (tmpDir.exists()) {
                Util.deleteDir(tmpDir);
            }
            System.exit(1);
        } else if (countNio == 0) {
            // bestehendes Workverzeichnis ggf. lschen
            if (tmpDir.exists()) {
                Util.deleteDir(tmpDir);
            }
            // alle Validierten Dateien valide
            System.exit(0);
        } else {
            // bestehendes Workverzeichnis ggf. lschen
            if (tmpDir.exists()) {
                Util.deleteDir(tmpDir);
            }
            // Fehler in Validierten Dateien --> invalide
            System.exit(2);
        }
        if (tmpDir.exists()) {
            Util.deleteDir(tmpDir);
            tmpDir.deleteOnExit();
        }
    }
}