Java/Development Class/UNIX Win32
Содержание
- 1 Create some temp files, ls them, and rm them
- 2 dealing with Excel dates
- 3 ExecDemoHelp shows how to use the Win32 start command
- 4 Help
- 4.1 ExecDemo shows how to execute an external program
- 4.2 ExecDemo shows how to execute an external program 2
- 4.3 ExecDemo shows how to execute an external program and read its output
- 4.4 ExecDemo shows how to execute an external program and read its output 3
- 4.5 Execute an external program read its output, and print its exit status
- 4.6 Handles program arguments like Unix getopt()
- 4.7 Helper method to execute shell command
- 4.8 How to execute an external program
- 4.9 How to execute a program from within Java
- 4.10 Java 1.5 (5.0) Changes to the API: ProcessBuilder.
- 4.11 Show how to use exec to pass complex args
- 4.12 Unix Crypt
- 4.13 UNIX getopt() system call
Create some temp files, ls them, and rm them
<source lang="java">
import java.io.*; /*
* create some temp files, ls them, and rm them */
public class ExecDemoRm {
public static void main(String[] args) throws IOException { for (int i=0; i<10; i++) { new File("/tmp/ww" + i).createNewFile(); } Runtime.getRuntime().exec("ls -l /tmp/ww? > /tmp/report"); Runtime.getRuntime().exec("rm -f /tmp/ww?"); }
}
</source>
dealing with Excel dates
<source lang="java">
/**
* * LibFormula : a free Java formula library * * * Project Info: http://reporting.pentaho.org/libformula/ * * (C) Copyright 2006-2007, by Pentaho Corporation and Contributors. * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * * ------------ * $Id: HSSFDateUtil.java 3522 2007-10-16 10:56:57Z tmorgner $ * ------------ * (C) Copyright 2006-2007, by Pentaho Corporation. */
/*
* DateUtil.java * * Created on January 19, 2002, 9:30 AM */
import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; /**
* Contains methods for dealing with Excel dates.
Modified by Cedric * Pronzato * * @author Michael Harhen * @author Glen Stampoultzis (glens at apache.org) * @author Dan Sherman (dsherman at isisph.ru) * @author Hack Kampbjorn (hak at 2mba.dk) */
public class HSSFDateUtil {
private HSSFDateUtil() { } private static final int BAD_DATE = -1; // used to specify that date is // invalid private static final long DAY_MILLISECONDS = 24 * 60 * 60 * 1000; private static final double CAL_1900_ABSOLUTE = (double) absoluteDay(new GregorianCalendar(1900, Calendar.JANUARY, 1)) - 2.0; /** * Given a Date, converts it into a double representing its internal Excel * representation, which is the number of days since 1/1/1900. Fractional days * represent hours, minutes, and seconds. * * @return Excel representation of Date (-1 if error - test for error by * checking for less than 0.1) * @param date * the Date */ public static double getExcelDate(final Date date) { Calendar calStart = new GregorianCalendar(); calStart.setTime(date); // If date includes hours, minutes, and seconds, set // them to 0 // if (calStart.get(Calendar.YEAR) < 1900) // { // return BAD_DATE; // } // else // { // Because of daylight time saving we cannot use // date.getTime() - calStart.getTimeInMillis() // as the difference in milliseconds between 00:00 and 04:00 // can be 3, 4 or 5 hours but Excel expects it to always // be 4 hours. // E.g. 2004-03-28 04:00 CEST - 2004-03-28 00:00 CET is 3 hours // and 2004-10-31 04:00 CET - 2004-10-31 00:00 CEST is 5 hours final double fraction = (((calStart.get(Calendar.HOUR_OF_DAY) * 60 + calStart .get(Calendar.MINUTE)) * 60 + calStart.get(Calendar.SECOND)) * 1000 + calStart .get(Calendar.MILLISECOND)) / (double) DAY_MILLISECONDS; calStart = dayStart(calStart); return fraction + (double) absoluteDay(calStart) - CAL_1900_ABSOLUTE; } // } /** * Given a excel date, converts it into a Date. Assumes 1900 date windowing. * * @param date * the Excel Date * * @return Java representation of a date (null if error) * @see #getJavaDate(double,boolean) */ public static Date getJavaDate(final double date) { return getJavaDate(date, true); } /** * Given an Excel date with either 1900 or 1904 date windowing, converts it to * a java.util.Date. * * NOTE: If the defaultTimeZone
in Java uses Daylight Saving * Time then the conversion back to an Excel date may not give the same value, * that is the comparisonexcelDate == * getExcelDate(getJavaDate(excelDate,false))
is not always true. For * example if default timezone isEurope/Copenhagen
, on * 2004-03-28 the minute after 01:59 CET is 03:00 CEST, if the excel date * represents a time between 02:00 and 03:00 then it is converted to past * 03:00 summer time * * @param date * The Excel date. * @param use1904windowing * true if date uses 1904 windowing, or false if using 1900 date * windowing. * @return Java representation of the date, or null if date is not a valid * Excel date * @see java.util.TimeZone */ public static Date getJavaDate(final double date, final boolean use1904windowing) { if (isValidExcelDate(date)) { int startYear = 1900; int dayAdjust = -1; // Excel thinks 2/29/1900 is a valid date, which it // isn"t final int wholeDays = (int) Math.floor(date); if (use1904windowing) { startYear = 1904; dayAdjust = 1; // 1904 date windowing uses 1/2/1904 as the first day } else if (wholeDays < 61) { // Date is prior to 3/1/1900, so adjust because Excel thinks 2/29/1900 // exists // If Excel date == 2/29/1900, will become 3/1/1900 in Java // representation dayAdjust = 0; } final GregorianCalendar calendar = new GregorianCalendar(startYear, 0, wholeDays + dayAdjust); final int millisecondsInDay = (int) ((date - Math.floor(date)) * (double) DAY_MILLISECONDS + 0.5); calendar.set(GregorianCalendar.MILLISECOND, millisecondsInDay); return calendar.getTime(); } else { return null; } } /** * given a format ID this will check whether the format represents an internal * date format or not. */ public static boolean isInternalDateFormat(final int format) { boolean retval; switch (format) { // Internal Date Formats as described on page 427 in // Microsoft Excel Dev"s Kit... case 0x0e: case 0x0f: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x2d: case 0x2e: case 0x2f: retval = true; break; default: retval = false; break; } return retval; } /** * Given a double, checks if it is a valid Excel date. * * @return true if valid * @param value * the double value */ public static boolean isValidExcelDate(final double value) { return (value > -Double.MIN_VALUE); } /** * Given a Calendar, return the number of days since 1600/12/31. * * @return days number of days since 1600/12/31 * @param cal * the Calendar * @exception IllegalArgumentException * if date is invalid */ private static int absoluteDay(final Calendar cal) { return cal.get(Calendar.DAY_OF_YEAR) + daysInPriorYears(cal.get(Calendar.YEAR)); } /** * Return the number of days in prior years since 1601 * * @return days number of days in years prior to yr. * @param yr * a year (1600 < yr < 4000) * @exception IllegalArgumentException * if year is outside of range. */ private static int daysInPriorYears(final int yr) { if (yr < 1601) { throw new IllegalArgumentException(""year" must be 1601 or greater"); } final int y = yr - 1601; return 365 * y // days in prior years + y / 4 // plus julian leap days in prior years - y / 100 // minus prior century years + y / 400; } // set HH:MM:SS fields of cal to 00:00:00:000 private static Calendar dayStart(final Calendar cal) { cal.get(Calendar.HOUR_OF_DAY); // force recalculation of internal fields cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); cal.get(Calendar.HOUR_OF_DAY); // force recalculation of internal fields return cal; } // ---------------------------------------------------------------------------------------------------------
}
</source>
ExecDemoHelp shows how to use the Win32 start command
<source lang="java">
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002. * All rights reserved. Software written by Ian F. Darwin and others. * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS"" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s, * pioneering role in inventing and promulgating (and standardizing) the Java * language and environment is gratefully acknowledged. * * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for * inventing predecessor languages C and C++ is also gratefully acknowledged. */
import java.io.IOException; /**
* ExecDemoHelp shows how to use the Win32 "start" command to load a help file. * Written long before JavaHelp API, which probably should be use instead. */
public class HelpDemo {
/** A simple main program, to show calling help(). */ public static void main(String[] av) throws IOException { new HelpDemo().help(); return; } /** * help() -- start a help viewer. On Win32, we use the "start" command. For * UNIX, we"ll try for Netscape or HotJava in the user"s path. For the Mac, * not sure what we"ll do. */ public void help() throws IOException { // A Runtime object has methods for dealing with the OS Runtime r = Runtime.getRuntime(); // A process object tracks one external running process Process p; // Start Netscape from Java Applications (not Applets though) p = r.exec("c:/windows/command/start.exe HelpDemo.htm"); return; }
} //helpdemo.htm /*
Help
Here is the help for our demo application: <P>This page still under construction, sorry.
- /
ExecDemo shows how to execute an external program
<source lang="java">
import java.io.*; /**
* ExecDemo shows how to execute an external program (in this case * the UNIX directory lister /bin/ls) and read its output. */
public class ExecDemoLs {
/** The program to run */ public static final String PROGRAM = "ls"; // "dir" for Windows /** Set to true to end the loop */ static boolean done = false; public static void main(String argv[]) throws IOException { final Process p; // Process tracks one external native process BufferedReader is; // reader for output of process String line; p = Runtime.getRuntime().exec(PROGRAM); // Optional: start a thread to wait for the process to terminate. // Don"t just wait in main line, but here set a "done" flag and // use that to control the main reading loop below. Thread waiter = new Thread() { public void run() { try { p.waitFor(); } catch (InterruptedException ex) { // OK, just quit. return; } System.out.println("Program terminated!"); done = true; } }; waiter.start(); // getInputStream gives an Input stream connected to // the process p"s standard output (and vice versa). We use // that to construct a BufferedReader so we can readLine() it. is = new BufferedReader(new InputStreamReader(p.getInputStream())); while (!done && ((line = is.readLine()) != null)) System.out.println(line); return; }
}
</source>
ExecDemo shows how to execute an external program 2
<source lang="java">
import java.io.*; /**
* ExecDemo shows how to execute an external program (in this case * the UNIX directory lister /bin/ls) and read its output. * This version handles the case where the program may exit abnormally. */
public class ExecDemoPartial {
/** The program to run */ public static final String PROGRAM = "ls"; /** Set to true to end the loop */ static boolean done = false; public static void main(String argv[]) throws IOException { BufferedReader is; // reader for output of process String line; final Process p = Runtime.getRuntime().exec(PROGRAM); Thread waiter = new Thread() { public void run() { try { p.waitFor(); } catch (InterruptedException ex) { // OK, just quit this thread. return; } System.out.println("Program terminated!"); done = true; } }; waiter.start(); // getInputStream gives an Input stream connected to // the process p"s standard output (and vice versa). We use // that to construct a BufferedReader so we can readLine() it. is = new BufferedReader(new InputStreamReader(p.getInputStream())); while (!done && ((line = is.readLine()) != null)) System.out.println(line); return; }
}
</source>
ExecDemo shows how to execute an external program and read its output
<source lang="java">
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002. * All rights reserved. Software written by Ian F. Darwin and others. * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS"" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s, * pioneering role in inventing and promulgating (and standardizing) the Java * language and environment is gratefully acknowledged. * * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for * inventing predecessor languages C and C++ is also gratefully acknowledged. */
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /**
* ExecDemo shows how to execute an external program and read its output. */
public class ExecDemoSort {
public static void main(String[] av) throws IOException { // A Runtime object has methods for dealing with the OS Runtime r = Runtime.getRuntime(); // A process object tracks one external running process Process p; // file contains unsorted data p = r.exec("sort sortdemo.txt"); // getInputStream gives an Input stream connected to // the process p"s standard output (and vice versa). We use // that to construct a BufferedReader so we can readLine() it. BufferedReader is = new BufferedReader(new InputStreamReader(p .getInputStream())); System.out.println("Here is your sorted data:"); String aLine; while ((aLine = is.readLine()) != null) System.out.println(aLine); System.out.println("That is all, folks!"); return; }
}
</source>
ExecDemo shows how to execute an external program and read its output 3
<source lang="java">
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002. * All rights reserved. Software written by Ian F. Darwin and others. * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS"" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s, * pioneering role in inventing and promulgating (and standardizing) the Java * language and environment is gratefully acknowledged. * * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for * inventing predecessor languages C and C++ is also gratefully acknowledged. */
/**
* ExecDemo shows how to execute an external program and read its output. This * version tries to let the sort"s standard output appear at the terminal. */
public class ExecDemoSort2 {
public static void main(String[] av) { // A Runtime object has methods for dealing with the OS Runtime r = Runtime.getRuntime(); // A process object tracks one external running process Process p; try { // file contains unsorted data p = r.exec("sort sortdemo.txt"); p.waitFor(); } catch (java.io.IOException e) { System.err.println("I/O error: " + e); } catch (InterruptedException e) { // nothing to do } }
}
</source>
Execute an external program read its output, and print its exit status
<source lang="java">
import java.io.*; /**
* ExecDemo shows how to execute an external program * read its output, and print its exit status. */
public class ExecDemoWait {
public static void main(String argv[]) throws IOException { // A Runtime object has methods for dealing with the OS Runtime r = Runtime.getRuntime(); Process p; // Process tracks one external native process BufferedReader is; // reader for output of process String line; // Our argv[0] contains the program to run; remaining elements // of argv contain args for the target program. This is just // what is needed for the String[] form of exec. p = r.exec(argv); System.out.println("In Main after exec"); // getInputStream gives an Input stream connected to // the process p"s standard output. Just use it to make // a BufferedReader to readLine() what the program writes out. is = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((line = is.readLine()) != null) System.out.println(line); System.out.println("In Main after EOF"); System.out.flush(); try { p.waitFor(); // wait for process to complete } catch (InterruptedException e) { System.err.println(e); // "Can"tHappen" return; } System.err.println("Process done, exit status was " + p.exitValue()); return; }
}
</source>
Handles program arguments like Unix getopt()
<source lang="java">
/* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * monoped@users.sourceforge.net */
import java.io.*; import java.util.*;
/** Handles program arguments like Unix getopt(). Example:* void main(String[] argv) * { * int opt; * boolean x = false; * Getopt getopt = new Getopt(argv, "a:hx"); * String argA = ""; * * // get Options * * while ((opt = getopt.getOption()) != -1) * { * switch (opt) * { * case "a": argA = getopt.getOptarg(); * break; * case "h": help(); * break; * case "x": x = true; * break; * default: System.out.println("wrong option: " + getOptopt()); * } * } * * // handle non-option parameters * * String[] files = getopt.getParms(); * * for (int i = 0; i < files.length; ++i) * doSomethingWith(files[i]); * } * * Legal calls: * java Mainclass -hx file1 file2 * java Mainclass -xa blurp -h -- file3 * * Illegal calls: * java Mainclass -y f * java Mainclass -a * * The special argument -- denotes the end of the options. All Arguments * after this will be considered as non-options, even if starting with -. * * If any command line argument is of the form "@filename", this file * is read and each line is considered a program parameter. * *
* * @author Bernd Eggink (monoped@users.sourceforge.net) */
public class Getopt {
private String[] argv; private ArrayList arglist; private String optarg, opts; private int ichr = 0, optind = 0; private char optopt; private boolean opterr = true; //---------------------------------------------------------------------- /** Default constructor * * @param opts The possible options. */ private Getopt(String opts) { this.opts = opts; arglist = new ArrayList(); } //---------------------------------------------------------------------- /** Constructs a Getopt object by reading all arguments from a file. * @param filename Name of the file to read. * @param opts The possible options. * @param opterr If true, an error message will be printed if an illegal option character * is found. */ public Getopt(String filename, String opts, boolean opterr) throws IOException { this(filename, opts); this.opterr = opterr; } //---------------------------------------------------------------------- /** Like Getopt(filename, opts, true) */ public Getopt(String filename, String opts) throws IOException { this(opts); addArgsFromFile(filename); } //---------------------------------------------------------------------- /** Constructs a Getopt object using the main() parameter list. * @param argv The arguments of main() * @param opts The possible options. Each option is a single character. * If followed by a colon, the option given in the command line * must be followed by an argument. * @param opterr If true, an error message will be printed if an illegal option character * is encountered. */ public Getopt(String[] argv, String opts, boolean opterr) throws IOException { this(argv, opts); this.opterr = opterr; } //---------------------------------------------------------------------- /** Like Getopt(argv, opts, true). */ public Getopt(String[] argv, String opts) throws IOException { this(opts); for (int i = 0; i < argv.length; ++i) { String arg = argv[i]; if (arg.startsWith("@")) addArgsFromFile(arg.substring(1)); else arglist.add(arg); } this.argv = (String[])arglist.toArray(new String[0]); } //---------------------------------------------------------------------- private void addArgsFromFile(String name) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(new File(name))); String zeile; while ((zeile = reader.readLine()) != null) arglist.add(zeile); reader.close(); } //---------------------------------------------------------------------- /** Returns the current argument or null. */ public String getOptarg() { return optarg; } //---------------------------------------------------------------------- /** Returns the next option as int value, * -1 if no more options are available, "?" if the option is illegal. */ public int getOption() { char c; int iopt; if (ichr == 0) { // beginning of word if (optind >= argv.length || argv[optind].charAt(0) != "-") return -1; if (argv[optind].equals("-") || argv[optind].equals("--")) { ++optind; return -1; } } // had - c = argv[optind].charAt(++ichr); if (c == ":" || (iopt = opts.indexOf(c)) < 0) { if (opterr) System.err.println("+++ Illegal option: " + c); if (++ichr >= argv[optind].length()) { ++optind; ichr = 0; } optopt = c; optarg = null; return "?"; } if (iopt + 1 < opts.length() && opts.charAt(iopt + 1) == ":") { // must have optarg if (++ichr < argv[optind].length()) optarg = argv[optind++].substring(ichr); else if (++optind >= argv.length) { if (opterr) System.err.println("+++ Option " + c + " requires an argument"); ichr = 0; optopt = c; return "?"; } else optarg = argv[optind++]; ichr = 0; } else { // no optarg if (ichr + 1 >= argv[optind].length()) { ++optind; ichr = 0; } optarg = null; } return c; } //---------------------------------------------------------------------- /** Returns the unrecognized option character. */ public char getOptopt() { return optopt; } //---------------------------------------------------------------------- /** Returns parameters not handled by getOption() as array of Strings. */ public String[] getParms() { String[] parms = new String[argv.length - optind]; for (int i = 0; optind + i < argv.length; ++i) parms[i] = argv[optind + i]; return parms; } //----------------------------------------------------------------------
/*
static public void main(String[] args) { try { Getopt g = new Getopt(args, "ab:c:d:e"); int opt; while ((opt = g.getOption()) >= 0) System.out.println("opt = " + (char)opt + ", optarg = " + g.getOptarg()); String[] words = g.getParms(); for (int i = 0; i < words.length; ++i) System.out.println(words[i]); } catch (IOException ex) { System.err.println(ex); } }
- /
}
</source>
Helper method to execute shell command
<source lang="java">
/*
* Copyright (c) 1998-2002 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS"" AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */
import java.io.*; public abstract class Exec {
public static Process exec (String[] cmdarray) throws IOException { return exec (cmdarray, null, null); } public static Process exec (String[] cmdarray, String[] envp) throws IOException { return exec (cmdarray, envp, null); } public static Process exec (String[] cmdarray, String[] envp, File directory) throws IOException { return isWindows () ? execWindows (cmdarray, envp, directory) : execUnix (cmdarray, envp, directory); } /* * Unix */ static Process execUnix (String[] cmdarray, String[] envp, File directory) throws IOException { // instead of calling command directly, we"ll call the shell to change // directory and set environment variables. // start constructing the sh command line. StringBuffer buf = new StringBuffer (); if (directory != null) { // change to directory buf.append ("cd ""); buf.append (escapeQuote (directory.toString ())); buf.append (""; "); } if (envp != null) { // set environment variables. Quote the value (but not the name). for (int i = 0; i < envp.length; ++i) { String nameval = envp[i]; int equals = nameval.indexOf ("="); if (equals == -1) throw new IOException ("environment variable "" + nameval + "" should have form NAME=VALUE"); buf.append (nameval.substring (0, equals+1)); buf.append ("\""); buf.append (escapeQuote (nameval.substring (equals+1))); buf.append ("\" "); } } // now that we have the directory and environment, run "which" // to test if the command name is found somewhere in the path. // If "which" fails, throw an IOException. String cmdname = escapeQuote (cmdarray[0]); Runtime rt = Runtime.getRuntime (); String[] sharray = new String[] { "sh", "-c", buf.toString () + " which \"" + cmdname + "\"" }; Process which = rt.exec (sharray); try { which.waitFor (); } catch (InterruptedException e) { throw new IOException ("interrupted"); } if (which.exitValue () != 0) throw new IOException ("can"t execute " + cmdname + ": bad command or filename"); // finish in buf.append ("exec \""); buf.append (cmdname); buf.append ("\" "); // quote each argument in the command for (int i = 1; i < cmdarray.length; ++i) { buf.append ("\""); buf.append (escapeQuote (cmdarray[i])); buf.append ("\" "); } System.out.println ("executing " + buf); sharray[2] = buf.toString (); return rt.exec (sharray); } static String escapeQuote (String s) { // replace single quotes with a bit of magic (end-quote, escaped-quote, start-quote) // that works in a single-quoted string in the Unix shell if (s.indexOf ("\"") != -1) { System.out.println ("replacing single-quotes in " + s); s = s.replace(""", ""\\"""); System.out.println ("to get " + s); } return s; } /* * Windows */ static boolean isWindows () { String os = System.getProperty ("os.name"); return (os != null && os.startsWith ("Windows")); } static boolean isJview () { String vendor = System.getProperty ("java.vendor"); return (vendor != null && vendor.startsWith ("Microsoft")); } static Process execWindows (String[] cmdarray, String[] envp, File directory) throws IOException { if (envp != null || directory != null) { if (isJview ()) // jview doesn"t support JNI, so can"t call putenv/chdir throw new IOException ("can"t use Exec.exec() under Microsoft JVM"); if (!linked) { try { System.loadLibrary ("win32exec"); linked = true; } catch (LinkageError e) { throw new IOException ("can"t use Exec.exec(): " + e.getMessage ()); } } if (envp != null) { for (int i = 0; i < envp.length; ++i) putenv (envp[i]); } if (directory != null) chdir (directory.toString ()); } return Runtime.getRuntime ().exec (cmdarray); } static boolean linked = false; // true after System.loadLibrary() is called static native boolean putenv (String env); static native boolean chdir (String dir);
}
</source>
How to execute an external program
<source lang="java">
import java.util.List; import java.util.ArrayList; import java.util.Map; import java.io.File; import java.io.IOException; /**
* ProcessBuilderDemo shows how to execute an external * program (in this case the MS-Windows notepad program). */
public class ProcessBuilderDemo {
public static void main(String argv[]) throws InterruptedException, IOException { List<String> command = new ArrayList<String>(); command.add("notepad"); command.add("foo.txt"); ProcessBuilder builder = new ProcessBuilder(command); Map<String, String> environ = builder.environment(); environ.put("PATH", "/windows;/windows/system32;/winnt"); builder.directory( new File(System.getProperty("user.home"))); final Process godot = builder.start(); godot.waitFor(); System.out.println("Program terminated!"); return; }
}
</source>
How to execute a program from within Java
<source lang="java">
import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.io.*; import java.net.*; import java.util.*; /**
* ExecDemoNS shows how to execute a program from within Java. */
public class ExecDemoNS extends JFrame {
/** The name of the help file. */ protected final static String HELPFILE = "./help/index.html"; /** A stack of process objects; each entry tracks one external running process */ Stack<Process> pStack = new Stack<Process>(); /** main - instantiate and run */ public static void main(String av[]) throws Exception { String program = av.length == 0 ? "netscape" : av[0]; new ExecDemoNS(program).setVisible(true); } /** The path to the binary executable that we will run */ protected static String program; /** Constructor - set up strings and things. */ public ExecDemoNS(String prog) { super("ExecDemo: " + prog); String osname = System.getProperty("os.name"); if (osname == null) throw new IllegalArgumentException("no os.name"); if (prog.equals("netscape")) program = // Windows or UNIX only for now, sorry Mac fans (osname.toLowerCase().indexOf("windows")!=-1) ? "c:/program files/netscape/communicator/program/netscape.exe" : "/usr/local/netscape/netscape"; else program = prog; Container cp = getContentPane(); cp.setLayout(new FlowLayout()); JButton b; cp.add(b=new JButton("Exec")); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { runProg(); } }); cp.add(b=new JButton("Wait")); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { doWait(); } }); cp.add(b=new JButton("Exit")); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { System.exit(0); } }); pack(); } /** Start the help, in its own Thread. */ public void runProg() { new Thread() { public void run() { try { // Get the URL for the Help File URL helpURL = this.getClass().getClassLoader(). getResource(HELPFILE); // Start Netscape from the Java Application. pStack.push(Runtime.getRuntime().exec(program + " " + helpURL)); } catch (Exception ex) { JOptionPane.showMessageDialog(ExecDemoNS.this, "Error" + ex, "Error", JOptionPane.ERROR_MESSAGE); } } }.start(); } public void doWait() { if (pStack.size() == 0) return; try { pStack.peek().waitFor(); // wait for process to complete (does not work as expected for Windows programs) } catch (Exception ex) { JOptionPane.showMessageDialog(this, "Error" + ex, "Error", JOptionPane.ERROR_MESSAGE); } pStack.pop(); }
}
</source>
Java 1.5 (5.0) Changes to the API: ProcessBuilder.
<source lang="java">
/* Java 2, v5.0 (Tiger) New Features by Herbert Schildt ISBN: 0072258543 Publisher: McGraw-Hill/Osborne, 2004
- /
import java.io.*;
public class PBDemo {
public static void main(String args[]) throws IOException { ProcessBuilder proc = new ProcessBuilder("notepad.exe", "testfile"); proc.start(); }
}
</source>
Show how to use exec to pass complex args
<source lang="java">
import java.io.*; /*
* Show how to use exec to pass complex args (which are almost * certainly system-dependant) to a command-line interpreter. */
public class ExecShellArgs {
public static void main(String[] args) throws IOException { Runtime r = Runtime.getRuntime(); String[] nargs = { "sh", "-c", "for i in 1 2 3; do echo $i; done" }; Process p = r.exec(nargs); BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; while ((line = is.readLine()) != null) System.out.println(line); }
}
</source>
Unix Crypt
<source lang="java">
/*
* @(#)UnixCrypt.java 0.9 96/11/25 * * Copyright (c) 1996 Aki Yoshida. All rights reserved. * * Permission to use, copy, modify and distribute this software * for non-commercial or commercial purposes and without fee is * hereby granted provided that this copyright notice appears in * all copies. */
/**
* Unix crypt(3C) utility * * @version 0.9, 11/25/96 * @author Aki Yoshida */
/**
* modified April 2001 * by Iris Van den Broeke, Daniel Deville */
/* ------------------------------------------------------------ */ /** Unix Crypt.
* Implements the one way cryptography used by Unix systems for * simple password protection. * @version $Id: UnixCrypt.java,v 1.5 2004/10/11 00:28:41 gregwilkins Exp $ * @author Greg Wilkins (gregw) */
public class UnixCrypt extends Object {
/* (mostly) Standard DES Tables from Tom Truscott */ private static final byte[] IP = { /* initial permutation */ 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7}; /* The final permutation is the inverse of IP - no table is necessary */ private static final byte[] ExpandTr = { /* expansion operation */ 32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1}; private static final byte[] PC1 = { /* permuted choice table 1 */ 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4}; private static final byte[] Rotates = { /* PC1 rotation schedule */ 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1};
private static final byte[] PC2 = { /* permuted choice table 2 */ 9, 18, 14, 17, 11, 24, 1, 5, 22, 25, 3, 28, 15, 6, 21, 10, 35, 38, 23, 19, 12, 4, 26, 8, 43, 54, 16, 7, 27, 20, 13, 2, 0, 0, 41, 52, 31, 37, 47, 55, 0, 0, 30, 40, 51, 45, 33, 48, 0, 0, 44, 49, 39, 56, 34, 53, 0, 0, 46, 42, 50, 36, 29, 32}; private static final byte[][] S = { /* 48->32 bit substitution tables */ /* S[1] */ {14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7, 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8, 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0, 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13}, /* S[2] */ {15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10, 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5, 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15, 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9}, /* S[3] */ {10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8, 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1, 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7, 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12}, /* S[4] */ {7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15, 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9, 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4, 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14}, /* S[5] */ {2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9, 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6, 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14, 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3}, /* S[6] */ {12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11, 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8, 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6, 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13}, /* S[7] */ {4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1, 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6, 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2, 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12}, /* S[8] */ {13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7, 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2, 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8, 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11}}; private static final byte[] P32Tr = { /* 32-bit permutation function */ 16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25}; private static final byte[] CIFP = { /* compressed/interleaved permutation */ 1, 2, 3, 4, 17, 18, 19, 20, 5, 6, 7, 8, 21, 22, 23, 24, 9, 10, 11, 12, 25, 26, 27, 28, 13, 14, 15, 16, 29, 30, 31, 32, 33, 34, 35, 36, 49, 50, 51, 52, 37, 38, 39, 40, 53, 54, 55, 56, 41, 42, 43, 44, 57, 58, 59, 60, 45, 46, 47, 48, 61, 62, 63, 64}; private static final byte[] ITOA64 = { /* 0..63 => ascii-64 */ (byte)".",(byte) "/",(byte) "0",(byte) "1",(byte) "2",(byte) "3",(byte) "4",(byte) "5", (byte)"6",(byte) "7",(byte) "8",(byte) "9",(byte) "A",(byte) "B",(byte) "C",(byte) "D", (byte)"E",(byte) "F",(byte) "G",(byte) "H",(byte) "I",(byte) "J",(byte) "K",(byte) "L", (byte)"M",(byte) "N",(byte) "O",(byte) "P",(byte) "Q",(byte) "R",(byte) "S",(byte) "T", (byte)"U",(byte) "V",(byte) "W",(byte) "X",(byte) "Y",(byte) "Z",(byte) "a",(byte) "b", (byte)"c",(byte) "d",(byte) "e",(byte) "f",(byte) "g",(byte) "h",(byte) "i",(byte) "j", (byte)"k",(byte) "l",(byte) "m",(byte) "n",(byte) "o",(byte) "p",(byte) "q",(byte) "r", (byte)"s",(byte) "t",(byte) "u",(byte) "v",(byte) "w",(byte) "x",(byte) "y",(byte) "z"}; /* Tables that are initialized at run time */ private static byte[] A64TOI = new byte[128]; /* ascii-64 => 0..63 */ /* Initial key schedule permutation */ private static long[][] PC1ROT = new long[16][16]; /* Subsequent key schedule rotation permutations */ private static long[][][] PC2ROT = new long[2][16][16]; /* Initial permutation/expansion table */ private static long[][] IE3264 = new long[8][16]; /* Table that combines the S, P, and E operations. */ private static long[][] SPE = new long[8][64]; /* compressed/interleaved => final permutation table */ private static long[][] CF6464 = new long[16][16];
/* */ static { byte[] perm = new byte[64]; byte[] temp = new byte[64]; // inverse table. for (int i=0; i<64; i++) A64TOI[ITOA64[i]] = (byte)i; // PC1ROT - bit reverse, then PC1, then Rotate, then PC2 for (int i=0; i<64; i++) perm[i] = (byte)0;; for (int i=0; i<64; i++) { int k; if ((k = (int)PC2[i]) == 0) continue; k += Rotates[0]-1; if ((k%28) < Rotates[0]) k -= 28; k = (int)PC1[k]; if (k > 0) { k--; k = (k|0x07) - (k&0x07); k++; } perm[i] = (byte)k; } init_perm(PC1ROT, perm, 8); // PC2ROT - PC2 inverse, then Rotate, then PC2 for (int j=0; j<2; j++) { int k; for (int i=0; i<64; i++) perm[i] = temp[i] = 0; for (int i=0; i<64; i++) { if ((k = (int)PC2[i]) == 0) continue; temp[k-1] = (byte)(i+1); } for (int i=0; i<64; i++) { if ((k = (int)PC2[i]) == 0) continue; k += j; if ((k%28) <= j) k -= 28; perm[i] = temp[k]; } init_perm(PC2ROT[j], perm, 8); } // Bit reverse, intial permupation, expantion for (int i=0; i<8; i++) { for (int j=0; j<8; j++) { int k = (j < 2)? 0: IP[ExpandTr[i*6+j-2]-1]; if (k > 32) k -= 32; else if (k > 0) k--; if (k > 0) { k--; k = (k|0x07) - (k&0x07); k++; } perm[i*8+j] = (byte)k; } } init_perm(IE3264, perm, 8); // Compression, final permutation, bit reverse for (int i=0; i<64; i++) { int k = IP[CIFP[i]-1]; if (k > 0) { k--; k = (k|0x07) - (k&0x07); k++; } perm[k-1] = (byte)(i+1); } init_perm(CF6464, perm, 8); // SPE table for (int i=0; i<48; i++) perm[i] = P32Tr[ExpandTr[i]-1]; for (int t=0; t<8; t++) { for (int j=0; j<64; j++) { int k = (((j >> 0) & 0x01) << 5) | (((j >> 1) & 0x01) << 3) | (((j >> 2) & 0x01) << 2) | (((j >> 3) & 0x01) << 1) | (((j >> 4) & 0x01) << 0) | (((j >> 5) & 0x01) << 4); k = S[t][k]; k = (((k >> 3) & 0x01) << 0) | (((k >> 2) & 0x01) << 1) | (((k >> 1) & 0x01) << 2) | (((k >> 0) & 0x01) << 3); for (int i=0; i<32; i++) temp[i] = 0; for (int i=0; i<4; i++) temp[4*t+i] = (byte)((k >> i) & 0x01); long kk = 0; for (int i=24; --i>=0; ) kk = ((kk<<1) | ((long)temp[perm[i]-1])<<32 | ((long)temp[perm[i+24]-1])); SPE[t][j] = to_six_bit(kk); } } } /** * You can"t call the constructer. */ private UnixCrypt() { } /** * Returns the transposed and split code of a 24-bit code * into a 4-byte code, each having 6 bits. */ private static int to_six_bit(int num) { return (((num << 26) & 0xfc000000) | ((num << 12) & 0xfc0000) | ((num >> 2) & 0xfc00) | ((num >> 16) & 0xfc)); } /** * Returns the transposed and split code of two 24-bit code * into two 4-byte code, each having 6 bits. */ private static long to_six_bit(long num) { return (((num << 26) & 0xfc000000fc000000L) | ((num << 12) & 0xfc000000fc0000L) | ((num >> 2) & 0xfc000000fc00L) | ((num >> 16) & 0xfc000000fcL)); } /** * Returns the permutation of the given 64-bit code with * the specified permutataion table. */ private static long perm6464(long c, long[][]p) { long out = 0L; for (int i=8; --i>=0; ) { int t = (int)(0x00ff & c); c >>= 8; long tp = p[i<<1][t&0x0f]; out |= tp; tp = p[(i<<1)+1][t>>4]; out |= tp; } return out; } /** * Returns the permutation of the given 32-bit code with * the specified permutataion table. */ private static long perm3264(int c, long[][]p) { long out = 0L; for (int i=4; --i>=0; ) { int t = (0x00ff & c); c >>= 8; long tp = p[i<<1][t&0x0f]; out |= tp; tp = p[(i<<1)+1][t>>4]; out |= tp; } return out; } /** * Returns the key schedule for the given key. */ private static long[] des_setkey(long keyword) { long K = perm6464(keyword, PC1ROT); long[] KS = new long[16]; KS[0] = K&~0x0303030300000000L; for (int i=1; i<16; i++) { KS[i] = K; K = perm6464(K, PC2ROT[Rotates[i]-1]); KS[i] = K&~0x0303030300000000L; } return KS; } /** * Returns the DES encrypted code of the given word with the specified * environment. */ private static long des_cipher(long in, int salt, int num_iter, long[] KS) { salt = to_six_bit(salt); long L = in; long R = L; L &= 0x5555555555555555L; R = (R & 0xaaaaaaaa00000000L) | ((R >> 1) & 0x0000000055555555L); L = ((((L << 1) | (L << 32)) & 0xffffffff00000000L) | ((R | (R >> 32)) & 0x00000000ffffffffL)); L = perm3264((int)(L>>32), IE3264); R = perm3264((int)(L&0xffffffff), IE3264); while (--num_iter >= 0) { for (int loop_count=0; loop_count<8; loop_count++) { long kp; long B; long k; kp = KS[(loop_count<<1)]; k = ((R>>32) ^ R) & salt & 0xffffffffL; k |= (k<<32); B = (k ^ R ^ kp); L ^= (SPE[0][(int)((B>>58)&0x3f)] ^ SPE[1][(int)((B>>50)&0x3f)] ^ SPE[2][(int)((B>>42)&0x3f)] ^ SPE[3][(int)((B>>34)&0x3f)] ^ SPE[4][(int)((B>>26)&0x3f)] ^ SPE[5][(int)((B>>18)&0x3f)] ^ SPE[6][(int)((B>>10)&0x3f)] ^ SPE[7][(int)((B>>2)&0x3f)]); kp = KS[(loop_count<<1)+1]; k = ((L>>32) ^ L) & salt & 0xffffffffL; k |= (k<<32); B = (k ^ L ^ kp); R ^= (SPE[0][(int)((B>>58)&0x3f)] ^ SPE[1][(int)((B>>50)&0x3f)] ^ SPE[2][(int)((B>>42)&0x3f)] ^ SPE[3][(int)((B>>34)&0x3f)] ^ SPE[4][(int)((B>>26)&0x3f)] ^ SPE[5][(int)((B>>18)&0x3f)] ^ SPE[6][(int)((B>>10)&0x3f)] ^ SPE[7][(int)((B>>2)&0x3f)]); } // swap L and R L ^= R; R ^= L; L ^= R; } L = ((((L>>35) & 0x0f0f0f0fL) | (((L&0xffffffff)<<1) & 0xf0f0f0f0L))<<32 | (((R>>35) & 0x0f0f0f0fL) | (((R&0xffffffff)<<1) & 0xf0f0f0f0L))); L = perm6464(L, CF6464); return L; } /** * Initializes the given permutation table with the mapping table. */ private static void init_perm(long[][] perm, byte[] p,int chars_out) { for (int k=0; k<chars_out*8; k++) { int l = p[k] - 1; if (l < 0) continue; int i = l>>2; l = 1<<(l&0x03); for (int j=0; j<16; j++) { int s = ((k&0x07)+((7-(k>>3))<<3)); if ((j & l) != 0x00) perm[i][j] |= (1L<<s); } } } /** * Encrypts String into crypt (Unix) code. * @param key the key to be encrypted * @param setting the salt to be used * @return the encrypted String */ public static String crypt(String key, String setting) { long constdatablock = 0L; /* encryption constant */ byte[] cryptresult = new byte[13]; /* encrypted result */ long keyword = 0L; /* invalid parameters! */ if(key==null||setting==null) return "*"; // will NOT match under ANY circumstances! int keylen = key.length(); for (int i=0; i<8 ; i++) { keyword = (keyword << 8) | ((i < keylen)? 2*key.charAt(i): 0); } long[] KS = des_setkey(keyword); int salt = 0; for (int i=2; --i>=0;) { char c = (i < setting.length())? setting.charAt(i): "."; cryptresult[i] = (byte)c; salt = (salt<<6) | (0x00ff&A64TOI[c]); } long rsltblock = des_cipher(constdatablock, salt, 25, KS); cryptresult[12] = ITOA64[(((int)rsltblock)<<2)&0x3f]; rsltblock >>= 4; for (int i=12; --i>=2; ) { cryptresult[i] = ITOA64[((int)rsltblock)&0x3f]; rsltblock >>= 6; } return new String(cryptresult, 0x00, 0, 13); } public static void main(String[] arg) { if (arg.length!=2) { System.err.println("Usage - java org.mortbay.util.UnixCrypt <key> <salt>"); System.exit(1); } System.err.println("Crypt="+crypt(arg[0],arg[1])); }
}
</source>
UNIX getopt() system call
<source lang="java">
import java.util.HashMap; /**
* Getopts is similar to the UN*X getopt() system call. It parses an array of * Strings (usually the command line), looking for specified option flags and * values. * <p> * An instance of Getopts parses the whole args list at once, and stores the * option flags and values that it finds. * * @author Jim Menard, * */
public class Getopts { String[] argv; HashMap options = new HashMap(); boolean errorFlag = false; /**
* This constructor takes a list of legal options and a list of (usually * command line) arguments. Each option in optionListString may be followed * by a ":" to signify that option takes an argument. * * @param optionListString option chars with optional ":" specifying arg. * For example, "ab:c" specifies three options, a, b, and c. Option b takes * a (required) argument. * @param args array of command line arguments */
public Getopts(String optionListString, String[] args) {
String optChoices = optionListString; for (int index = 0; index < args.length; ++index) { String arg = args[index]; if (arg.startsWith("-")) { char optionChar = arg.charAt(1); int optionLoc = optChoices.indexOf(optionChar); if (optionLoc == -1) errorFlag = true; else { // Look for argument, if any boolean hasArgument = optChoices.length() > optionLoc + 1 && optChoices.charAt(optionLoc + 1) == ":"; if (hasArgument) { String optarg = arg.substring(2); if (optarg.equals("")) { ++index; try { optarg = args[index]; } catch (Exception e) { // Catch ArrayOutOfBounds optarg = ""; errorFlag = true; } } options.put(new Character(optionChar), optarg); } else { // No arg, store empty string options.put(new Character(optionChar), ""); } } } else { // End of options. Store rest of args argv = new String[args.length - index]; int offset = index; while (index < args.length) { argv[index - offset] = args[index]; ++index; } break; } }
} /**
* * Return true if there was an error while parsing the command line. */
public boolean error() {
return errorFlag;
} /**
* Returns existence of an option. * * @return true of option "c" exists, else return false. * @param c any character */
public boolean hasOption(char c) {
if (options == null) return false; return options.containsKey(new Character(c));
} /**
* Return an option or, if missing, the empty string. * * @return option string, or "" if error or option has no argument * @param c the option whose value is returned */
public String option(char c) {
return option(c, "");
} /**
* Return an option or, if missing, a default value. * * @return option string, or defaultValue if error or option has no argument * @param c the option whose value is returned * @param defaultValue the value to return if there is no such option */
public String option(char c, String defaultValue) {
if (options == null) return defaultValue; String s; try { Object o = options.get(new Character(c)); if (o == null || !(o instanceof String)) s = defaultValue; else s = (String)o; } catch (Exception e) { s = defaultValue; } return s;
} /**
* Return the remaining command-line arguments. * * @return an array of Strings * @see #argc * @see #argv */
public String[] args() {
return argv;
} /**
* Return the number of non-option args. */
public int argc() {
if (argv == null) return 0; return argv.length;
} /**
* Return a command line argument or "" if argv is *null
. Index starts at 0. * * @param index which argument to return * @return the index"th arg or "" if argv isnull
*/
public String argv(int index) {
if (argv == null) return ""; return argv[index];
} }
</source>