Exemplo n.º 1
0
  public static void main(String[] args) {
    if (args.length < 5) {
      System.out.println(
          "\n  Usage: java prob.mdp.MDPSim prob_file " + "spudd_vfun trials steps rand_seed\n");
      System.exit(1);
    }

    MDPSim mdpsim = new MDPSim(args[0], args[1]);

    ArrayList vals = null;
    int trials = -1, steps = -1;
    long seed = -1;
    try {
      trials = Integer.parseInt(args[2]);
      steps = Integer.parseInt(args[3]);
      seed = Long.parseLong(args[4]);
      vals = mdpsim.simulate(trials, steps, seed);
    } catch (NumberFormatException nfe) {
      System.out.println(nfe);
      System.exit(1);
    }

    System.out.println("\n Problem:  " + args[0]);
    System.out.println(" VFun:     " + args[1]);
    System.out.println(" Trials:   " + trials);
    System.out.println(" Steps:    " + steps);
    System.out.println(" Seed:     " + seed);
    System.out.println(" Data:     " + PrintList(vals));
    System.out.println(" Average:  " + MDP._df.format(Average(vals)) + "\n");
  }
Exemplo n.º 2
0
  public static void main(String[] args) throws Exception {
    if (args.length == 0) {
      printUsage(args.length);
      System.exit(0);
    } else {
      processArgsAndInitialize(args);
    }
    // non-specified args will be set to default values in processArgsAndInitialize

    if (candFileFormat.equals("plain")) {
      println("Evaluating candidate translations in plain file " + candFileName + "...");
      evaluateCands_plain(candFileName);
    } else if (candFileFormat.equals("nbest")) {
      println(
          "Evaluating set of "
              + candRank
              + "'th candidate translations from "
              + candFileName
              + "...");
      evaluateCands_nbest(candFileName, candRank);
    }
    println("");

    if (evaluateRefs) {
      // evaluate the references themselves; useful if developing a new evaluation metric

      println("");
      println("PERFORMING SANITY CHECK:");
      println("------------------------");
      println("");
      println(
          "This metric's scores range from "
              + evalMetric.worstPossibleScore()
              + " (worst) to "
              + evalMetric.bestPossibleScore()
              + " (best).");

      for (int r = 1; r <= refsPerSen; ++r) {
        println("");
        println("(*) Evaluating reference set " + r + ":");
        println("");
        evaluateRefSet(r);
        println("");
      }
    }

    System.exit(0);
  } // main(String[] args)
Exemplo n.º 3
0
  public static void main(String[] args) {
    try {
      Context ctx = new InitialContext();
      Object objref = ctx.lookup(JNDI_NAME);

      SavingsAccountHome home =
          (SavingsAccountHome) PortableRemoteObject.narrow(objref, SavingsAccountHome.class);

      BigDecimal zeroAmount = new BigDecimal("0.00");
      SavingsAccount John = home.create("100", "John", "Smith", zeroAmount);

      System.out.println("Account Name: " + John.getFirstName());
      System.out.println("Credit: 88.50");

      John.credit(new BigDecimal("88.50"));
      System.out.println("Debit: 20.25");

      John.debit(new BigDecimal("20.25"));
      BigDecimal balance = John.getBalance();
      System.out.println("Balance = " + balance);
      // John.remove();
      System.exit(0);
    } catch (InsufficientBalanceException ex) {
      System.err.println("Caught an InsufficientBalanceException: " + ex.getMessage());
    } catch (Exception ex) {
      System.err.println("Caught an exception.");
      ex.printStackTrace();
    }
  }
Exemplo n.º 4
0
 public static void main(String[] args) {
   InputReader in = new InputReader(System.in);
   OutputWriter out = new OutputWriter(System.out);
   A1Task solver = new A1Task();
   solver.solve(in, out);
   out.close();
   System.exit(0);
 }
Exemplo n.º 5
0
 private void receiveEGTable() {
   int nBytes = (nBits - 1) / 8 + 1;
   try {
     for (int j = 0; j < nCols; j++)
       EGTable[j] = Utils.readBigInteger(nBytes * Wire.labelBitLength, ois);
   } catch (Exception e) {
     e.printStackTrace();
     System.exit(1);
   }
 }
Exemplo n.º 6
0
 private static void usage() {
   Print.logInfo("Usage:");
   Print.logInfo("  java ... " + URIArg.class.getName() + " {options}");
   Print.logInfo("Options:");
   Print.logInfo("  -encode=<ASCII>    Encode ASCII string to URL argument string");
   Print.logInfo("  -decode=<args>     Decode URL argument string to ASCII");
   Print.logInfo("  -rtpEnc=<url>      RTP Encode URL [key = 'rtp']");
   Print.logInfo("  -rtpDec=<url>      RTP Decode URL [key = 'rtp']");
   System.exit(1);
 }
 static {
   try {
     System.loadLibrary("primitive_ref");
   } catch (UnsatisfiedLinkError e) {
     System.err.println(
         "Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n"
             + e);
     System.exit(1);
   }
 }
Exemplo n.º 8
0
  private void init() {
    try {
      receiveParams();
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }

    EGTable = new BigInteger[nCols];
    outputLabels = new BigInteger[nBits];
  }
Exemplo n.º 9
0
	public static void main(String args[]){
		String infilename = args[0];
		String outfilename= args[1];
		if(args.length <1 || args.length >=3){
			usage();
			System.exit(2);
		}
		if(!new File(infilename).exists()){
			System.out.println("No such file:"+infilename);
			System.exit(1);
		}
		if(new File(outfilename).exists()){
			//To Overwrite?
		}
		System.out.println("write:"+infilename+">"+outfilename);
		//@ToDo - Check arguments are valid files...
		 

		CDToolParser me=new CDToolParser(infilename,outfilename);
	}
Exemplo n.º 10
0
  void run() {
    Scanner sc = new Scanner(System.in);
    int oo = sc.nextInt();
    for (int o = 1; o <= oo; o++) {
      que = new PriorityQueue<E>();
      int n = sc.nextInt();
      tank = new Tank();
      count = 0;
      int[] h = new int[n + 3], b = new int[n + 3];
      h[0] = 100;
      b[0] = 0;
      h[n + 1] = 50;
      b[n + 1] = 100;
      h[n + 2] = 50;
      b[n + 2] = INF;
      for (int i = 1; i <= n; i++) {
        b[i] = sc.nextInt();
        h[i] = sc.nextInt();
      }
      n += 3;
      for (int i = 1; i < n; i++) {
        tank.bs.add(new Box(b[i - 1], b[i], h[i - 1], h[i], 0, 0));
      }
      int m = sc.nextInt();
      for (int i = 0; i < m; i++) {
        int f = sc.nextInt();
        double a = sc.nextDouble() / 30;
        for (Box box : tank.bs) {
          if (box.b1 < f && f < box.b2) box.f += a;
        }
      }
      debug(tank.bs);

      int l = sc.nextInt();
      res = new double[l];
      for (int i = 0; i < l; i++) {
        que.offer(new W(sc.nextInt(), sc.nextDouble(), i));
      }
      que.offer(tank.nextEvent());
      debug(que.size());
      while (!que.isEmpty()) {
        if (res[0] < 0) System.exit(1);
        que.poll().go();
        debug(que.peek().time());
        debug(tank.bs);
        debug(res);
        debug();
        if (count == l) break;
      }
      for (double r : res) {
        System.out.println(r);
      }
    }
  }
Exemplo n.º 11
0
 private static void usage() {
   Print.logInfo("Usage:");
   Print.logInfo("  java ... " + StatusCode.class.getName() + " {options}");
   Print.logInfo("Options:");
   Print.logInfo("  -account=<id>   Account ID owning StatusCode");
   Print.logInfo("  -device=<id>    Device ID owning StatusCode (use '/' for ALL)");
   Print.logInfo("  -code=<id>      StatusCode to create/delete/edit");
   Print.logInfo("  -create         Create a new StatusCode");
   Print.logInfo("  -edit           To edit an existing StatusCode");
   Print.logInfo("  -delete         Delete specified StatusCode");
   System.exit(1);
 }
Exemplo n.º 12
0
 public static void main(String[] args) throws IOException {
   // InputStream inputStream = new FileInputStream("replaceme.in");
   // OutputStream outputStream = new FileOutputStream("replaceme.out");
   /////////////////////////////////////////////////////////////////////
   InputStream inputStream = System.in;
   OutputStream outputStream = System.out;
   InputReader in = new InputReader(inputStream);
   OutputWriter out = new OutputWriter(outputStream);
   Task solver = new Task();
   solver.solve(1, in, out);
   out.close();
   System.exit(0);
 }
Exemplo n.º 13
0
 private void receiveEGTable_EXT() {
   int nBytes = (nBits - 1) / 8 + 1;
   try {
     for (int j = 0; j < nCols; j++) {
       boolean temp = ois.readBoolean();
       if (temp) EGTable[j] = Utils.readBigInteger(nBytes * Wire.labelBitLength, ois);
       else EGTable[j] = null;
     }
   } catch (Exception e) {
     e.printStackTrace();
     System.exit(1);
   }
 }
Exemplo n.º 14
0
 public void run() {
   Locale.setDefault(Locale.US);
   try {
     sc = new FastScanner("access.in");
     out = new PrintWriter("access.out");
     solve();
     sc.close();
     out.close();
   } catch (Throwable e) {
     e.printStackTrace();
     System.exit(1);
   }
 }
Exemplo n.º 15
0
 public void run() {
   // long time = System.currentTimeMillis();
   try {
     br = new BufferedReader(new FileReader(new File("cell.in")));
     out = new PrintWriter("cell.out");
     solve();
   } catch (Exception e) {
     e.printStackTrace();
     System.exit(111);
   }
   // System.err.println(System.currentTimeMillis() - time);
   out.close();
 }
Exemplo n.º 16
0
  /** ** Main entry point for testing/debugging ** @param argv Comand-line arguments */
  public static void main(String argv[]) {
    RTConfig.setCommandLineArgs(argv);

    /* decode URI argument strings */
    if (RTConfig.hasProperty(ARG_DECODE)) {
      String a = RTConfig.getString(ARG_DECODE, "");
      String s = URIArg.decodeArg(new StringBuffer(), a).toString();
      Print.sysPrintln("ASCII: " + s);
      System.exit(0);
    }

    /* encode Base64 strings */
    if (RTConfig.hasProperty(ARG_ENCODE)) {
      String s = RTConfig.getString(ARG_ENCODE, "");
      String a = URIArg.encodeArg(new StringBuffer(), s).toString();
      Print.sysPrintln("Args: " + a);
      System.exit(0);
    }

    /* RTP decode */
    if (RTConfig.hasProperty(ARG_RTPDEC)) {
      URIArg rtpUrl = new URIArg(RTConfig.getString(ARG_RTPDEC, ""));
      URIArg decUrl = rtpUrl.rtpDecode("rtp");
      Print.sysPrintln("URL: " + decUrl.toString());
      System.exit(0);
    }

    /* RTP encode */
    if (RTConfig.hasProperty(ARG_RTPENC)) {
      URIArg decUrl = new URIArg(RTConfig.getString(ARG_RTPENC, ""));
      URIArg rtpUrl = decUrl.rtpEncode("rtp");
      Print.sysPrintln("URL: " + rtpUrl.toString());
      System.exit(0);
    }

    /* no options */
    usage();
  }
Exemplo n.º 17
0
 private static void usage() {
   Print.logInfo("Usage:");
   Print.logInfo("  java ... " + RoleAcl.class.getName() + " {options}");
   Print.logInfo("Common Options:");
   Print.logInfo("  -account=<id>   Acount ID which owns Role");
   Print.logInfo("  -role=<id>      Role ID which owns RoleAcl");
   Print.logInfo("  -list           List Acls for Role");
   Print.logInfo("  -acl=<id>       Role ID to create/edit");
   Print.logInfo("  -set=<val>      RoleAcl value (create if necessary)");
   Print.logInfo("  -create         Create a new RoleAcl");
   Print.logInfo("  -edit           Edit an existing (or newly created) RoleAcl");
   Print.logInfo("  -delete         Delete specified RoleAcl");
   System.exit(1);
 }
Exemplo n.º 18
0
 public void run() {
   try {
     in = new BufferedReader(new InputStreamReader(System.in));
     out = new BufferedWriter(new OutputStreamWriter(System.out));
     // in = new BufferedReader(new FileReader(filename + ".in"));
     // out = new BufferedWriter(new FileWriter(filename+".out"));
     int kase = iread();
     for (int i = 1; i <= kase; ++i) {
       // TODO CODE HERE
       solve1245(i);
     }
     out.flush();
   } catch (Exception e) {
     System.exit(1);
   }
 }
Exemplo n.º 19
0
  // event handling
  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == btnok) {
      PreparedStatement pstm;
      ResultSet rs;
      String sql;
      // if no entries has been made and hit ok button throw an error
      // you can do this step using try clause as well
      if ((tf1.getText().equals("") && (tf2.getText().equals("")))) {
        lblmsg.setText("Enter your details ");
        lblmsg.setForeground(Color.magenta);
      } else {

        try {
          Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
          Connection connect = DriverManager.getConnection("jdbc:odbc:student_base");
          System.out.println("Connected to the database");
          pstm = connect.prepareStatement("insert into student_base values(?,?)");
          pstm.setString(1, tf1.getText());
          pstm.setString(2, tf2.getText());
          // execute method to execute the query
          pstm.executeUpdate();
          lblmsg.setText("Details have been added to database");

          // closing the prepared statement  and connection object
          pstm.close();
          connect.close();
        } catch (SQLException sqe) {
          System.out.println("SQl error");
        } catch (ClassNotFoundException cnf) {
          System.out.println("Class not found error");
        }
      }
    }
    // upon clickin button addnew , your textfield will be empty to enternext record
    if (e.getSource() == btnaddnew) {
      tf1.setText("");
      tf2.setText("");
    }

    if (e.getSource() == btnexit) {
      System.exit(1);
    }
  }
Exemplo n.º 20
0
  private static void processArgsAndInitialize(String[] args) throws Exception {
    EvaluationMetric.set_knownMetrics();

    // set default values
    candFileName = "candidates.txt";
    candFileFormat = "plain";
    candRank = 1;
    refFileName = "references.txt";
    refsPerSen = 1;
    metricName = "BLEU";
    metricOptions = new String[2];
    metricOptions[0] = "4";
    metricOptions[1] = "closest";
    evaluateRefs = false;
    verbose = false;

    int i = 0;

    while (i < args.length) {
      String option = args[i];
      if (option.equals("-cand")) {
        candFileName = args[i + 1];
      } else if (option.equals("-format")) {
        candFileFormat = args[i + 1];
        if (!candFileFormat.equals("plain") && !candFileFormat.equals("nbest")) {
          println("candFileFormat must be either plain or nbest.");
          System.exit(10);
        }
      } else if (option.equals("-rank")) {
        candRank = Integer.parseInt(args[i + 1]);
        if (refsPerSen < 1) {
          println("Argument for -rank must be positive.");
          System.exit(10);
        }
      } else if (option.equals("-ref")) {
        refFileName = args[i + 1];
      } else if (option.equals("-rps")) {
        refsPerSen = Integer.parseInt(args[i + 1]);
        if (refsPerSen < 1) {
          println("refsPerSen must be positive.");
          System.exit(10);
        }
      } else if (option.equals("-m")) {
        metricName = args[i + 1];
        if (EvaluationMetric.knownMetricName(metricName)) {
          int optionCount = EvaluationMetric.metricOptionCount(metricName);
          metricOptions = new String[optionCount];
          for (int opt = 0; opt < optionCount; ++opt) {
            metricOptions[opt] = args[i + opt + 2];
          }
          i += optionCount;
        } else {
          println("Unknown metric name " + metricName + ".");
          System.exit(10);
        }
      }

      /*
            else if (option.equals("-m")) {
              metricName = args[i+1];
              if (!EvaluationMetric.knownMetricName(metricName)) { println("Unknown metric name " + metricName + "."); System.exit(10); }
              if (metricName.equals("BLEU")) {
                metricOptions = new String[2];
                metricOptions[0] = args[i+2];
                metricOptions[1] = args[i+3];
                i += 2;
              }
            }
      */
      else if (option.equals("-evr")) {
        int evr = Integer.parseInt(args[i + 1]);
        if (evr == 1) evaluateRefs = true;
        else if (evr == 0) evaluateRefs = false;
        else {
          println("evalRefs must be either 0 or 1.");
          System.exit(10);
        }
      } else if (option.equals("-v")) {
        int v = Integer.parseInt(args[i + 1]);
        if (v == 1) verbose = true;
        else if (v == 0) verbose = false;
        else {
          println("verbose must be either 0 or 1.");
          System.exit(10);
        }
      } else {
        println("Unknown option " + option);
        System.exit(10);
      }

      i += 2;
    } // while (i)

    if (refsPerSen > 1) {
      // the provided refFileName might be a prefix
      File dummy = new File(refFileName);
      if (!dummy.exists()) {
        refFileName = createUnifiedRefFile(refFileName, refsPerSen);
      }
    } else {
      checkFile(refFileName);
    }

    // initialize
    numSentences = countLines(refFileName) / refsPerSen;

    // read in reference sentences
    refSentences = new String[numSentences][refsPerSen];
    BufferedReader inFile_refs = new BufferedReader(new FileReader(refFileName));
    String line;

    for (i = 0; i < numSentences; ++i) {
      for (int r = 0; r < refsPerSen; ++r) {
        // read the rth reference translation for the ith sentence
        refSentences[i][r] = inFile_refs.readLine();
      }
    }

    inFile_refs.close();

    // set static data members for the EvaluationMetric class
    EvaluationMetric.set_numSentences(numSentences);
    EvaluationMetric.set_refsPerSen(refsPerSen);
    EvaluationMetric.set_refSentences(refSentences);

    // do necessary initialization for the evaluation metric
    evalMetric = EvaluationMetric.getMetric(metricName, metricOptions);

    println("Processing " + numSentences + " sentences...");
  } // processArgsAndInitialize(String[] args)
Exemplo n.º 21
0
  private static String createUnifiedRefFile(String prefix, int numFiles) throws Exception {
    if (numFiles < 2) {
      println(
          "Warning: createUnifiedRefFile called with numFiles = " + numFiles + "; doing nothing.");
      return prefix;
    } else {
      File checker;
      checker = new File(prefix + "1");

      if (!checker.exists()) {
        checker = new File(prefix + ".1");
        if (!checker.exists()) {
          println("Can't find reference files.");
          System.exit(50);
        } else {
          prefix = prefix + ".";
        }
      }

      String outFileName;
      if (prefix.endsWith(".")) {
        outFileName = prefix + "all";
      } else {
        outFileName = prefix + ".all";
      }

      PrintWriter outFile = new PrintWriter(outFileName);

      BufferedReader[] inFile = new BufferedReader[numFiles];

      int nextIndex;
      checker = new File(prefix + "0");
      if (checker.exists()) {
        nextIndex = 0;
      } else {
        nextIndex = 1;
      }
      int lineCount = countLines(prefix + nextIndex);

      for (int r = 0; r < numFiles; ++r) {
        if (countLines(prefix + nextIndex) != lineCount) {
          println("Line count mismatch in " + (prefix + nextIndex) + ".");
          System.exit(60);
        }
        inFile[r] = new BufferedReader(new FileReader(prefix + nextIndex));
        ++nextIndex;
      }

      String line;

      for (int i = 0; i < lineCount; ++i) {
        for (int r = 0; r < numFiles; ++r) {
          line = inFile[r].readLine();
          outFile.println(line);
        }
      }

      outFile.close();

      for (int r = 0; r < numFiles; ++r) {
        inFile[r].close();
      }

      return outFileName;
    }
  } // createUnifiedRefFile(String prefix, int numFiles)
Exemplo n.º 22
0
  private static void evaluate(
      String inFileName, String inFileFormat, int candPerSen, int testIndex) throws Exception {
    // candPerSen: how many candidates are provided per sentence?
    //             (if inFileFormat is nbest, then candPerSen is ignored, since it is variable)
    // testIndex: which of the candidates (for each sentence) should be tested?
    //            e.g. testIndex=1 means first candidate should be evaluated
    //                 testIndex=candPerSen means last candidate should be evaluated

    if (inFileFormat.equals("plain") && candPerSen < 1) {
      println("candPerSen must be positive for a file in plain format.");
      System.exit(30);
    }

    if (inFileFormat.equals("plain") && (testIndex < 1 || testIndex > candPerSen)) {
      println("For the plain format, testIndex must be in [1,candPerSen]");
      System.exit(31);
    }

    // read the candidates
    String[] topCand_str = new String[numSentences];

    BufferedReader inFile = new BufferedReader(new FileReader(inFileName));
    String line, candidate_str;

    if (inFileFormat.equals("plain")) {

      for (int i = 0; i < numSentences; ++i) {

        // skip candidates 1 through testIndex-1
        for (int n = 1; n < testIndex; ++n) {
          line = inFile.readLine();
        }

        // read testIndex'th candidate
        candidate_str = inFile.readLine();

        topCand_str[i] = candidate_str;

        for (int n = testIndex + 1; n <= candPerSen; ++n) {
          // skip candidates testIndex+1 through candPerSen-1
          line = inFile.readLine();
        }
      } // for (i)

    } else { // nbest format

      int i = 0;
      int n = 1;
      line = inFile.readLine();

      while (line != null && i < numSentences) {

        /*
        line format:

        .* ||| words of candidate translation . ||| feat-1_val feat-2_val ... feat-numParams_val .*

        */

        while (n < candRank) {
          line = inFile.readLine();
          ++n;
        }

        // at the moment, line stores the candRank'th candidate (1-indexed) of the i'th sentence
        // (0-indexed)

        if (line == null) {
          println(
              "Not enough candidates in "
                  + inFileName
                  + " to extract the "
                  + candRank
                  + "'th candidate for each sentence.");
          println("(Failed to extract one for the " + i + "'th sentence (0-indexed).)");
          System.exit(32);
        }

        int read_i = Integer.parseInt(line.substring(0, line.indexOf(" |||")));
        if (read_i == i) {
          line = line.substring(line.indexOf("||| ") + 4); // get rid of initial text
          candidate_str = line.substring(0, line.indexOf(" |||"));
          topCand_str[i] = candidate_str;
          if (i < numSentences - 1) {
            while (read_i == i) {
              line = inFile.readLine();
              read_i = Integer.parseInt(line.substring(0, line.indexOf(" |||")));
            }
          }
          n = 1;
          i += 1;
        } else {
          println(
              "Not enough candidates in "
                  + inFileName
                  + " to extract the "
                  + candRank
                  + "'th candidate for each sentence.");
          println("(Failed to extract one for the " + i + "'th sentence (0-indexed).)");
          System.exit(32);
        }
      } // while (line != null)

      if (i != numSentences) {
        println(
            "Not enough candidates were found (i = " + i + "; was expecting " + numSentences + ")");
        System.exit(33);
      }
    }

    inFile.close();

    evalMetric.printDetailedScore(topCand_str, false);

    if (verbose) {
      println("");
      println("Printing detailed scores for individual sentences...");
      for (int i = 0; i < numSentences; ++i) {
        print("Sentence #" + i + ": ");
        evalMetric.printDetailedScore(topCand_str[i], i, true);
        // already prints a \n
      }
    }
  } // void evaluate(...)
Exemplo n.º 23
0
  public static void main(String argv[]) {
    DBConfig.cmdLineInit(argv, true); // main
    String accountID = RTConfig.getString(ARG_ACCOUNT, "");
    String deviceID = RTConfig.getString(ARG_DEVICE, "");
    int statusCode = RTConfig.getInt(ARG_CODE, 0);
    boolean anyCode = true; // RTConfig.hasProperty(ARG_ECODE);

    /* account-id specified? */
    if (StringTools.isBlank(accountID)) {
      Print.logError("Account-ID not specified.");
      usage();
    }

    /* get account */
    Account account = null;
    try {
      account = Account.getAccount(accountID); // may throw DBException
      if (account == null) {
        Print.logError("Account-ID does not exist: " + accountID);
        usage();
      }
    } catch (DBException dbe) {
      Print.logException("Error loading Account: " + accountID, dbe);
      // dbe.printException();
      System.exit(99);
    }

    /* device-id specified? */
    if (StringTools.isBlank(deviceID) || deviceID.startsWith("/")) {
      deviceID = ALL_DEVICES;
    }

    /* check device existance */
    if (!deviceID.equals(ALL_DEVICES)) {
      try {
        Device device = Device.getDevice(account, deviceID); // may throw DBException
        if (device == null) {
          Print.logError("Device-ID does not exist: " + accountID + " / " + deviceID);
          usage();
        }
      } catch (DBException dbe) {
        Print.logException("Error loading Device: " + accountID + " / " + deviceID, dbe);
        System.exit(99);
      }
    }

    /* status-code specified? */
    if ((statusCode > 0)
        && !anyCode
        && !StatusCodes.IsValid(statusCode, account.getPrivateLabel())) {
      Print.logError("Invalid Status Code specified.");
      usage();
    }

    /* statusCode specified? */
    if (statusCode <= 0) {
      Print.logError("StatusCode not specified.");
      usage();
    }

    /* statusCode exists? */
    boolean statusCodeExists = false;
    try {
      statusCodeExists = StatusCode.exists(accountID, deviceID, statusCode);
    } catch (DBException dbe) {
      Print.logError(
          "Error determining if StatusCode exists: "
              + accountID
              + "/"
              + deviceID
              + "/"
              + statusCode);
      System.exit(99);
    }

    /* option count */
    int opts = 0;

    /* delete */
    if (RTConfig.getBoolean(ARG_DELETE, false)) {
      opts++;
      if (!statusCodeExists) {
        Print.logWarn(
            "StatusCode does not exist: " + accountID + "/" + deviceID + "/" + statusCode);
        Print.logWarn("Continuing with delete process ...");
      }
      try {
        StatusCode.Key scKey = new StatusCode.Key(accountID, deviceID, statusCode);
        scKey.delete(true); // also delete dependencies (if any)
        Print.logInfo("StatusCode deleted: " + accountID + "/" + deviceID + "/" + statusCode);
        statusCodeExists = false;
      } catch (DBException dbe) {
        Print.logError(
            "Error deleting StatusCode: " + accountID + "/" + deviceID + "/" + statusCode);
        dbe.printException();
        System.exit(99);
      }
      System.exit(0);
    }

    /* create */
    if (RTConfig.getBoolean(ARG_CREATE, false)) {
      opts++;
      if (statusCodeExists) {
        Print.logWarn(
            "StatusCode already exists: " + accountID + "/" + deviceID + "/" + statusCode);
      } else {
        try {
          StatusCode.createNewStatusCode(account, deviceID, statusCode);
          Print.logInfo("Created StatusCode: " + accountID + "/" + deviceID + "/" + statusCode);
          statusCodeExists = true;
        } catch (DBException dbe) {
          Print.logError(
              "Error creating StatusCode: " + accountID + "/" + deviceID + "/" + statusCode);
          dbe.printException();
          System.exit(99);
        }
      }
    }

    /* edit */
    if (RTConfig.getBoolean(ARG_EDIT, false)) {
      opts++;
      if (!statusCodeExists) {
        Print.logError(
            "StatusCode does not exist: " + accountID + "/" + deviceID + "/" + statusCode);
      } else {
        try {
          StatusCode sc =
              StatusCode.getStatusCode(account, deviceID, statusCode); // may throw DBException
          DBEdit editor = new DBEdit(sc);
          editor.edit(); // may throw IOException
        } catch (IOException ioe) {
          if (ioe instanceof EOFException) {
            Print.logError("End of input");
          } else {
            Print.logError("IO Error");
          }
        } catch (DBException dbe) {
          Print.logError(
              "Error editing StatusCode: " + accountID + "/" + deviceID + "/" + statusCode);
          dbe.printException();
        }
      }
      System.exit(0);
    }

    /* list */
    if (RTConfig.hasProperty(ARG_LIST)) {
      opts++;
      String listType = RTConfig.getString(ARG_LIST, null);
      // TODO: complete ...
    }

    /* no options specified */
    if (opts == 0) {
      Print.logWarn("Missing options ...");
      usage();
    }
  }
Exemplo n.º 24
0
 /* Prints an error message and exits (intended for user errors) */
 private static void ErrorExit(String errorMessage, Object... formatArgs) {
   System.err.printf("ERROR: " + errorMessage + "\n", formatArgs);
   System.exit(0);
 }
Exemplo n.º 25
0
  public static void main(String args[]) {
    DBConfig.cmdLineInit(args, true); // main
    String acctID = RTConfig.getString(ARG_ACCOUNT, "");
    String roleID = RTConfig.getString(ARG_ROLE, "");
    String aclID = RTConfig.getString(ARG_ACL, "");

    /* account-id specified? */
    if ((acctID == null) || acctID.equals("")) {
      Print.logError("Account-ID not specified.");
      usage();
    }

    /* get account */
    Account acct = null;
    try {
      acct = Account.getAccount(acctID); // may return DBException
      if (acct == null) {
        Print.logError("Account-ID does not exist: " + acctID);
        usage();
      }
    } catch (DBException dbe) {
      Print.logException("Error loading Account: " + acctID, dbe);
      // dbe.printException();
      System.exit(99);
    }

    /* role-id specified? */
    if ((roleID == null) || roleID.equals("")) {
      Print.logError("Role-ID not specified.");
      usage();
    }

    /* get role */
    Role role = null;
    try {
      role = Role.getRole(acct, roleID); // may return DBException
      if (role == null) {
        Print.logError("Role-ID does not exist: " + acctID + "/" + roleID);
        usage();
      }
    } catch (DBException dbe) {
      Print.logException("Error loading Role: " + acctID + "/" + roleID, dbe);
      // dbe.printException();
      System.exit(99);
    }

    /* RoleAcl exists? */
    boolean aclExists = false;
    if ((aclID != null) && !aclID.equals("")) {
      try {
        aclExists = RoleAcl.exists(acctID, roleID, aclID);
      } catch (DBException dbe) {
        Print.logError(
            "Error determining if RoleAcl exists: " + acctID + "/" + roleID + "/" + aclID);
        System.exit(99);
      }
    }

    /* option count */
    int opts = 0;

    /* list */
    if (RTConfig.getBoolean(ARG_LIST, false)) {
      opts++;
      try {
        String aclList[] = role.getAclsForRole();
        for (int i = 0; i < aclList.length; i++) {
          AccessLevel level = RoleAcl.getAccessLevel(role, aclList[i], AccessLevel.NONE);
          Print.sysPrintln("  " + aclList[i] + " ==> " + level);
        }
      } catch (DBException dbe) {
        Print.logError("Error getting Acl list: " + dbe);
        System.exit(99);
      }
      System.exit(0);
    }

    /* delete */
    if (RTConfig.getBoolean(ARG_DELETE, false) && !acctID.equals("") && !roleID.equals("")) {
      opts++;
      if (!aclExists) {
        Print.logWarn("RoleAcl does not exist: " + acctID + "/" + roleID + "/" + aclID);
        Print.logWarn("Continuing with delete process ...");
      }
      try {
        RoleAcl.Key aclKey = new RoleAcl.Key(acctID, roleID, aclID);
        aclKey.delete(true); // also delete dependencies
        Print.logInfo("RoleAcl deleted: " + acctID + "/" + roleID + "/" + aclID);
      } catch (DBException dbe) {
        Print.logError("Error deleting RoleAcl: " + acctID + "/" + roleID + "/" + aclID);
        dbe.printException();
        System.exit(99);
      }
      System.exit(0);
    }

    /* create */
    if (RTConfig.getBoolean(ARG_CREATE, false)) {
      opts++;
      if (aclExists) {
        Print.logWarn("RoleAcl already exists: " + acctID + "/" + roleID + "/" + aclID);
      } else {
        try {
          RoleAcl.createNewRoleAcl(role, aclID);
          Print.logInfo("Created RoleAcl: " + acctID + "/" + roleID + "/" + aclID);
          aclExists = true;
        } catch (DBException dbe) {
          Print.logError("Error creating RoleAcl: " + acctID + "/" + roleID + "/" + aclID);
          dbe.printException();
          System.exit(99);
        }
      }
    }

    /* set */
    if (RTConfig.hasProperty(ARG_SET)) {
      opts++;
      AccessLevel aclLevel = EnumTools.getValueOf(AccessLevel.class, RTConfig.getInt(ARG_SET, -1));
      try {
        RoleAcl.setAccessLevel(role, aclID, aclLevel);
        Print.logInfo(
            "Set RoleAcl '" + acctID + "/" + roleID + "/" + aclID + "' to level " + aclLevel);
      } catch (DBException dbe) {
        Print.logError("Error setting RoleAcl: " + acctID + "/" + roleID + "/" + aclID);
        dbe.printException();
        System.exit(99);
      }
      System.exit(0);
    }

    /* edit */
    if (RTConfig.getBoolean(ARG_EDIT, false)) {
      opts++;
      if (!aclExists) {
        Print.logError("RoleAcl does not exist: " + acctID + "/" + roleID + "/" + aclID);
      } else {
        try {
          RoleAcl roleAcl = RoleAcl.getRoleAcl(role, aclID, false); // may throw DBException
          DBEdit editor = new DBEdit(roleAcl);
          editor.edit(); // may throw IOException
        } catch (IOException ioe) {
          if (ioe instanceof EOFException) {
            Print.logError("End of input");
          } else {
            Print.logError("IO Error");
          }
        } catch (DBException dbe) {
          Print.logError("Error editing RoleAcl: " + acctID + "/" + roleID + "/" + aclID);
          dbe.printException();
        }
      }
      System.exit(0);
    }

    /* no options specified */
    if (opts == 0) {
      Print.logWarn("Missing options ...");
      usage();
    }
  }
Exemplo n.º 26
0
 private static void checkFile(String fileName) {
   if (!fileExists(fileName)) {
     println("The file " + fileName + " was not found!");
     System.exit(40);
   }
 }