List of usage examples for java.io OutputStream close
public void close() throws IOException
From source file:hu.sztaki.lpds.pgportal.services.dspace.LNIclient.java
/** * Optional main for standalone testing, demonstrate usage. * *///w ww . j ava 2 s . c om public static void main(String[] argv) { // Args: -G | -P [ -i file ] [ -o file ] URL handle // -e eperson -p password [ -t type ] Options options = new Options(); options.addOption("h", "help", false, "show help message"); options.addOption("o", "output", true, "output file for GET"); options.addOption("i", "input", true, "input file for PUT"); options.addOption("G", "get", false, "GET contents of Handle"); options.addOption("P", "put", false, "PUT package into Handle"); options.addOption("e", "eperson", true, "eperson to authenticate as (required)"); options.addOption("p", "password", true, "password for eperson (required)"); options.addOption("t", "type", true, "package type for GET/PUT"); try { CommandLine line = (new PosixParser()).parse(options, argv); String eperson = line.getOptionValue("e"); String password = line.getOptionValue("p"); String type = line.getOptionValue("t"); String rest[] = line.getArgs(); if (eperson == null || password == null || rest.length < 2) Usage(options, 1, "Missing a required option or argument"); String url = rest[0]; String handle = rest[1]; LNIclient lni = new LNIclient(url, eperson, password); if (type == null) type = "METS"; if (line.hasOption("G")) { OutputStream pkg = System.out; if (line.hasOption("o")) pkg = new FileOutputStream(line.getOptionValue("o")); // TODO: add option to convey packager options here. try { InputStream g = lni.startGet(handle, type, null); copy(g, pkg); pkg.close(); } finally { lni.finishGet(); } } else if (line.hasOption("P")) { InputStream pkg = System.in; if (line.hasOption("i")) pkg = new FileInputStream(line.getOptionValue("i")); String result = lni.put(handle, type, null, pkg); System.err.println("LNI PUT created Handle: " + result); } else Usage(options, 1, "Missing required 'G' or 'P' option."); } catch (org.apache.commons.cli.ParseException pe) { Usage(options, 1, "Error in arguments: " + pe.toString()); } catch (Throwable e) { System.err.println("Got exception: " + e.toString()); e.printStackTrace(); } finally { System.exit(0); } }
From source file:MainClass.java
public static void main(String[] args) throws IOException { SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); SSLServerSocket ss = (SSLServerSocket) ssf.createServerSocket(8080); ss.setNeedClientAuth(true);/* ww w. ja v a2 s . c om*/ while (true) { try { Socket s = ss.accept(); OutputStream out = s.getOutputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream())); String line = null; while (((line = in.readLine()) != null) && (!("".equals(line)))) { System.out.println(line); } System.out.println(""); StringBuffer buffer = new StringBuffer(); buffer.append("<HTML>\n"); buffer.append("<HEAD><TITLE>HTTPS Server</TITLE></HEAD>\n"); buffer.append("<BODY>\n"); buffer.append("<H1>Success!</H1>\n"); buffer.append("</BODY>\n"); buffer.append("</HTML>\n"); String string = buffer.toString(); byte[] data = string.getBytes(); out.write("HTTP/1.0 200 OK\n".getBytes()); out.write(new String("Content-Length: " + data.length + "\n").getBytes()); out.write("Content-Type: text/html\n\n".getBytes()); out.write(data); out.flush(); out.close(); in.close(); s.close(); } catch (Exception e) { e.printStackTrace(); } } }
From source file:HTTPServer.java
public static void main(String[] args) throws Exception { ServerSocket sSocket = new ServerSocket(1777); while (true) { System.out.println("Waiting for a client..."); Socket newSocket = sSocket.accept(); System.out.println("accepted the socket"); OutputStream os = newSocket.getOutputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(newSocket.getInputStream())); String inLine = null;// w w w .j a va2 s . com while (((inLine = br.readLine()) != null) && (!(inLine.equals("")))) { System.out.println(inLine); } System.out.println(""); StringBuffer sb = new StringBuffer(); sb.append("<html>\n"); sb.append("<head>\n"); sb.append("<title>Java \n"); sb.append("</title>\n"); sb.append("</head>\n"); sb.append("<body>\n"); sb.append("<H1>HTTPServer Works!</H1>\n"); sb.append("</body>\n"); sb.append("</html>\n"); String string = sb.toString(); byte[] byteArray = string.getBytes(); os.write("HTTP/1.0 200 OK\n".getBytes()); os.write(new String("Content-Length: " + byteArray.length + "\n").getBytes()); os.write("Content-Type: text/html\n\n".getBytes()); os.write(byteArray); os.flush(); os.close(); br.close(); newSocket.close(); } }
From source file:com.tc.simple.apn.quicktests.Test.java
/** * @param args/*from w w w . ja v a 2 s. c o m*/ */ public static void main(String[] args) { SSLSocket socket = null; try { String host = "gateway.sandbox.push.apple.com"; int port = 2195; String token = "de7f197546e41a76684f8e2d89f397ed165298d7772f4bd9b0f39c674b185b0f"; System.out.println(token.toCharArray().length); //String token = "8cebc7c08f79fa62f0994eb4298387ff930857ff8d14a50de431559cf476b223"; KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(Test.class.getResourceAsStream("egram-dev-apn.p12"), "xxxxxxxxx".toCharArray()); KeyManagerFactory keyMgrFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyMgrFactory.init(keyStore, "xxxxxxxxx".toCharArray()); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyMgrFactory.getKeyManagers(), null, null); SSLSocketFactory socketFactory = sslContext.getSocketFactory(); socket = (SSLSocket) socketFactory.createSocket(host, port); String[] cipherSuites = socket.getSupportedCipherSuites(); socket.setEnabledCipherSuites(cipherSuites); socket.startHandshake(); char[] t = token.toCharArray(); byte[] b = Hex.decodeHex(t); OutputStream outputstream = socket.getOutputStream(); String payload = "{\"aps\":{\"alert\":\"yabadabadooo\"}}"; int expiry = (int) ((System.currentTimeMillis() / 1000L) + 7200); ByteArrayOutputStream bout = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bout); //command dos.writeByte(1); //id dos.writeInt(900); //expiry dos.writeInt(expiry); //token length. dos.writeShort(b.length); //token dos.write(b); //payload length dos.writeShort(payload.length()); //payload. dos.write(payload.getBytes()); byte[] byteMe = bout.toByteArray(); socket.getOutputStream().write(byteMe); socket.setSoTimeout(900); InputStream in = socket.getInputStream(); System.out.println(APNErrors.getError(in.read())); in.close(); outputstream.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
From source file:bpgead2pdf.java
/** * Main method./*w w w. j av a 2s.c om*/ * @param args command-line arguments */ public static void main(String[] args) { try { System.out.println("Preparing..."); // Setup directories File baseDir = new File("."); File outDir = new File(baseDir, "out"); outDir.mkdirs(); // Setup input and output files File xmlfile = new File(args[0]); String xsltfile = new String("http://www.library.yale.edu/facc/xsl/fo/yul.ead2002.pdf.xsl"); String pdffn = new String(FilenameUtils.getBaseName(args[0]) + ".pdf"); File pdffile = new File(outDir, pdffn); System.out.println("Input: XML (" + xmlfile + ")"); System.out.println("Stylesheet: " + xsltfile); System.out.println("Output: PDF (" + pdffile + ")"); System.out.println(); System.out.println("Transforming..."); // configure fopFactory as desired FopFactory fopFactory = FopFactory.newInstance(); FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); // configure foUserAgent as desired // configure XSLT Processor Processor processor = new Processor(false); // Setup output OutputStream out = new java.io.FileOutputStream(pdffile); out = new java.io.BufferedOutputStream(out); try { // Construct fop with desired output format Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out); // Setup XSLT XsltCompiler compiler = processor.newXsltCompiler(); XsltExecutable transform = compiler.compile(new StreamSource(xsltfile)); XsltTransformer transformer = transform.load(); // Set the value of a <param> in the stylesheet // transformer.setParameter("versionParam", "2.0"); // Setup input for XSLT transformation Source src = new StreamSource(xmlfile); // Resulting SAX events (the generated FO) must be piped through to FOP SAXDestination res = new SAXDestination(fop.getDefaultHandler()); // Start XSLT transformation and FOP processing transformer.setDestination(res); transformer.setSource(src); transformer.transform(); } finally { out.close(); } System.out.println("Success!"); } catch (Exception e) { e.printStackTrace(System.err); System.exit(-1); } }
From source file:edu.nyupoly.cs6903.ag3671.FTPClientExample.java
public static void main(String[] args) throws UnknownHostException, Exception { // MY CODE//from www . j ava 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.momab.dstool.DSTool.java
public static void main(String[] args) throws ParseException, IOException, ClassNotFoundException { final CommandLineParser parser = new BasicParser(); final Options options = commandLineOptions(); final CommandLine line = parser.parse(options, args); if (args.length == 0) { printUsage(options, System.out); System.exit(0);/*from ww w. j a v a 2s . co m*/ } if (args.length == 1 && line.hasOption("h")) { printHelp(options, System.out); System.exit(0); } if (!line.hasOption("r") && !line.hasOption("w") && !line.hasOption("d")) { printErrorMessage("One of the options -r -w or -d must be specified.", System.err); System.exit(-1); } if (line.getArgs().length != 2) { printErrorMessage("To few arguments.", System.err); System.exit(-1); } DSOperation op = null; // Required operands/arguments DSOperationBuilder opBuilder = new DSOperationBuilder(line.getArgs()[0], line.getArgs()[1]); // Username and password if (line.hasOption("u") || line.hasOption("p")) { if (!line.hasOption("u") || !line.hasOption("p")) { printErrorMessage("Missing username or password", System.err); System.exit(-1); } opBuilder.asUser(line.getOptionValue("u"), line.getOptionValue("p")); } // Port if (line.hasOption("P")) { opBuilder = opBuilder.usingPort(Integer.valueOf(line.getOptionValue("P"))); } // File File file = null; OutputStream out = null; InputStream in = null; if (line.hasOption("f")) { if (line.hasOption("d")) { printErrorMessage("Option -f is invalid for a -d delete operation", System.err); System.exit(-1); } file = new File(line.getOptionValue("f")); } // Read (download) operation if (line.hasOption("r")) { if (file != null) { out = new FileOutputStream(file); } else { out = System.out; } opBuilder = opBuilder.writeTo(out); op = opBuilder.buildDownload(); } // Write (upload) operation if (line.hasOption("w")) { if (file != null) { in = new FileInputStream(file); } else { in = System.in; } opBuilder = opBuilder.readFrom(in); op = opBuilder.buildUpload(); } // Delete (upload) operation if (line.hasOption("d")) { op = opBuilder.buildDelete(); } if (file != null || line.hasOption("d")) { boolean result = op.Run(new ProgressPrinter() { }); if (in != null) in.close(); if (out != null) out.close(); System.exit(result ? 0 : -1); } else { System.exit(op.Run(null) ? 0 : -1); } }
From source file:de.mpg.escidoc.services.common.util.Util.java
/** * Command line transformation./* w ww.ja va 2 s.c om*/ * * @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:com.lxf.spider.client.QuickStart.java
public static void main(String[] args) throws Exception { InputStream input = null;//from w w w .ja v a2s . c o m OutputStream output = null; //httpclient CloseableHttpClient httpclient = HttpClients.createDefault(); try { //get HttpGet httpGet = new HttpGet("http://127.0.0.1:8080/pdqx.jc.web/cen/center.html"); // CloseableHttpResponse response1 = httpclient.execute(httpGet); // The underlying HTTP connection is still held by the response object // to allow the response content to be streamed directly from the network socket. // In order to ensure correct deallocation of system resources // the user MUST call CloseableHttpResponse#close() from a finally clause. // Please note that if response content is not fully consumed the underlying // connection cannot be safely re-used and will be shut down and discarded // by the connection manager. try { //??? int statusCode = response1.getStatusLine().getStatusCode(); //??200? if (statusCode == HttpStatus.SC_OK) { // input = httpGet.getRequestLine(); System.out.println(response1.getStatusLine()); // HttpEntity entity1 = response1.getEntity(); // do something useful with the response body // and ensure it is fully consumed input = entity1.getContent(); output = new FileOutputStream("d:/lxf.data"); //? int tempByte = -1; while ((tempByte = input.read()) > 0) { output.write(tempByte); } EntityUtils.consume(entity1); //? if (input != null) { input.close(); } if (output != null) { output.close(); } } } finally { response1.close(); } /*HttpPost httpPost = new HttpPost("http://targethost/login"); List <NameValuePair> nvps = new ArrayList <NameValuePair>(); nvps.add(new BasicNameValuePair("username", "vip")); nvps.add(new BasicNameValuePair("password", "secret")); httpPost.setEntity(new UrlEncodedFormEntity(nvps)); CloseableHttpResponse response2 = httpclient.execute(httpPost); try { System.out.println(response2.getStatusLine()); HttpEntity entity2 = response2.getEntity(); // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity2); } finally { response2.close(); }*/ } finally { httpclient.close(); } }
From source file:net.sf.mcf2pdf.Main.java
@SuppressWarnings("static-access") public static void main(String[] args) { Options options = new Options(); Option o = OptionBuilder.hasArg().isRequired() .withDescription("Installation location of My CEWE Photobook. REQUIRED.").create('i'); options.addOption(o);// w w w. jav a 2 s . c o m options.addOption("h", false, "Prints this help and exits."); options.addOption("t", true, "Location of MCF temporary files."); options.addOption("w", true, "Location for temporary images generated during conversion."); options.addOption("r", true, "Sets the resolution to use for page rendering, in DPI. Default is 150."); options.addOption("n", true, "Sets the page number to render up to. Default renders all pages."); options.addOption("b", false, "Prevents rendering of binding between double pages."); options.addOption("x", false, "Generates only XSL-FO content instead of PDF content."); options.addOption("q", false, "Quiet mode - only errors are logged."); options.addOption("d", false, "Enables debugging logging output."); CommandLine cl; try { CommandLineParser parser = new PosixParser(); cl = parser.parse(options, args); } catch (ParseException pe) { printUsage(options, pe); System.exit(3); return; } if (cl.hasOption("h")) { printUsage(options, null); return; } if (cl.getArgs().length != 2) { printUsage(options, new ParseException("INFILE and OUTFILE must be specified. Arguments were: " + cl.getArgList())); System.exit(3); return; } File installDir = new File(cl.getOptionValue("i")); if (!installDir.isDirectory()) { printUsage(options, new ParseException("Specified installation directory does not exist.")); System.exit(3); return; } File tempDir = null; String sTempDir = cl.getOptionValue("t"); if (sTempDir == null) { tempDir = new File(new File(System.getProperty("user.home")), ".mcf"); if (!tempDir.isDirectory()) { printUsage(options, new ParseException("MCF temporary location not specified and default location " + tempDir + " does not exist.")); System.exit(3); return; } } else { tempDir = new File(sTempDir); if (!tempDir.isDirectory()) { printUsage(options, new ParseException("Specified temporary location does not exist.")); System.exit(3); return; } } File mcfFile = new File(cl.getArgs()[0]); if (!mcfFile.isFile()) { printUsage(options, new ParseException("MCF input file does not exist.")); System.exit(3); return; } mcfFile = mcfFile.getAbsoluteFile(); File tempImages = new File(new File(System.getProperty("user.home")), ".mcf2pdf"); if (cl.hasOption("w")) { tempImages = new File(cl.getOptionValue("w")); if (!tempImages.mkdirs() && !tempImages.isDirectory()) { printUsage(options, new ParseException("Specified working dir does not exist and could not be created.")); System.exit(3); return; } } int dpi = 150; if (cl.hasOption("r")) { try { dpi = Integer.valueOf(cl.getOptionValue("r")).intValue(); if (dpi < 30 || dpi > 600) throw new IllegalArgumentException(); } catch (Exception e) { printUsage(options, new ParseException("Parameter for option -r must be an integer between 30 and 600.")); } } int maxPageNo = -1; if (cl.hasOption("n")) { try { maxPageNo = Integer.valueOf(cl.getOptionValue("n")).intValue(); if (maxPageNo < 0) throw new IllegalArgumentException(); } catch (Exception e) { printUsage(options, new ParseException("Parameter for option -n must be an integer >= 0.")); } } boolean binding = true; if (cl.hasOption("b")) { binding = false; } OutputStream finalOut; if (cl.getArgs()[1].equals("-")) finalOut = System.out; else { try { finalOut = new FileOutputStream(cl.getArgs()[1]); } catch (IOException e) { printUsage(options, new ParseException("Output file could not be created.")); System.exit(3); return; } } // configure logging, if no system property is present if (System.getProperty("log4j.configuration") == null) { PropertyConfigurator.configure(Main.class.getClassLoader().getResource("log4j.properties")); Logger.getRootLogger().setLevel(Level.INFO); if (cl.hasOption("q")) Logger.getRootLogger().setLevel(Level.ERROR); if (cl.hasOption("d")) Logger.getRootLogger().setLevel(Level.DEBUG); } // start conversion to XSL-FO // if -x is specified, this is the only thing we do OutputStream xslFoOut; if (cl.hasOption("x")) xslFoOut = finalOut; else xslFoOut = new ByteArrayOutputStream(); Log log = LogFactory.getLog(Main.class); try { new Mcf2FoConverter(installDir, tempDir, tempImages).convert(mcfFile, xslFoOut, dpi, binding, maxPageNo); xslFoOut.flush(); if (!cl.hasOption("x")) { // convert to PDF log.debug("Converting XSL-FO data to PDF"); byte[] data = ((ByteArrayOutputStream) xslFoOut).toByteArray(); PdfUtil.convertFO2PDF(new ByteArrayInputStream(data), finalOut, dpi); finalOut.flush(); } } catch (Exception e) { log.error("An exception has occured", e); System.exit(1); return; } finally { if (finalOut instanceof FileOutputStream) { try { finalOut.close(); } catch (Exception e) { } } } }