Пример #1
0
  /**
   * Request a old chart request from the history of a ChartMediator.<br>
   * Referring to a given configuration (id), it requests a chart from the history of a
   * ChartMediator. Thereby it requests the one, indicated by the given number. E.g. 1 stands for
   * the newest one, 6 for the 6 latest.
   *
   * @param number number of the latest computed chart, range from 1 (latest) to 10 (oldest)
   * @return the JSON object of the requested chart, referring to the id and the number
   */
  public JSONObject historyChart(int number) {
    // checks whether a request is allowed
    if (!isInitialized()) {
      Printer.pproblem("Configurations & mediators not initalized!");
      Printer.print("-> Chart creation not possible!");
      return null;
    }

    // checks whether the parameters are legal
    if ((number < 0) || (getMaxSizeOfHistory() <= number)) {
      throw new IllegalArgumentException();
    }

    // checks if enough charts are stored yet
    if (number >= getCurrentSizeOfHistory()) {
      Printer.pproblem("Not so many charts stored yet.");
      return null;
    }

    // request the chart
    JSONObject histo = chartMedi.getHistoryChart(number);
    if (histo == null) {
      Printer.perror("No history for " + number + " found!");
      return null;
    }

    return histo;
  }
Пример #2
0
  private void share(ArrayList<String> params) throws IOException {
    printer.println("All complete files: ");
    // ArrayList<Hash> al = new
    // ArrayList<Hash>(core.getFileManager().getFileDatabase().getAllHashes());
    // for (Hash h : al) {
    //    FileDescriptor fd = core.getFileManager().getFileDatabase().getFd(h);
    // //    printer.println("  " + fd);
    //   }
    printer.println("");

    printer.println("Incomplete files in cache: ");
    for (Hash h : core.getFileManager().getCache().rootHashes()) {
      BlockFile bf = core.getFileManager().getCache().getBlockFile(h);
      printer.println("  " + bf);
    }
    printer.println("");

    printer.println("Incomplete files in downloads: ");
    for (Hash h : core.getFileManager().getDownloadStorage().rootHashes()) {
      BlockFile bf = core.getFileManager().getDownloadStorage().getBlockFile(h);
      printer.println("  " + bf);
    }
    printer.println("");

    printer.println(
        "Sharing "
            + TextUtils.formatByteSize(core.getShareManager().getFileDatabase().getShareSize())
            + " in "
            + core.getShareManager().getFileDatabase().getNumberOfShares()
            + " files.");
    printer.println("");
  }
Пример #3
0
 public void testWithComplexArg() throws Exception {
   ApplicationContext ctx = new ClassPathXmlApplicationContext("jrubyContext.xml", getClass());
   Printer printer = (Printer) ctx.getBean("printer");
   CountingPrintable printable = new CountingPrintable();
   printer.print(printable);
   assertEquals(1, printable.count);
 }
Пример #4
0
 private void invitations() {
   int count = 0;
   printer.println("Stored Invitation codes:");
   Collection<Invitation> invitations = core.getInvitaitonManager().allInvitations();
   for (Invitation i : invitations.toArray(new Invitation[invitations.size()])) {
     count++;
     printer.print(i.getCompleteInvitaitonString());
     if (core.getInvitaitonManager()
         .getInvitation(i.getInvitationPassKey())
         .isForwardedInvitation()) {
       printer.println(
           " (Forwarded)  -  Valid next: "
               + Long.toString(
                   (InvitaitonManager.INVITATION_TIMEOUT_FORWARDED
                           - (System.currentTimeMillis() - i.getCreatedAt()))
                       / (1000 * 60))
               + " minutes.");
     } else {
       printer.println(
           " (Manual)  -  Valid next: "
               + Long.toString(
                   (InvitaitonManager.INVITATION_TIMEOUT
                           - (System.currentTimeMillis() - i.getCreatedAt()))
                       / (1000 * 60 * 60))
               + " hours.");
     }
   }
   printer.println("Found " + count + " Invitations.");
 }
Пример #5
0
  public void handlePrintButtonAction(ActionEvent actionEvent) {
    //        try{
    //            Printer printer = Printer.getDefaultPrinter();
    //            PageLayout pageLayout = printer.createPageLayout(Paper.A4,
    // PageOrientation.PORTRAIT, Printer.MarginType.DEFAULT);
    //            NodePrinter nodePrinter = new NodePrinter();
    //            Rectangle printRectangle = new Rectangle(printForm.getLayoutX(),
    // printForm.getLayoutY(), printForm.getWidth(), printForm.getHeight());
    //            PrinterJob printerJob = PrinterJob.createPrinterJob();
    //
    //            nodePrinter.setScale(1);
    //            nodePrinter.setPrintRectangle(printRectangle);
    //            if(nodePrinter.print(printerJob, false, printForm, pageLayout)){
    //                printerJob.endJob();
    //            }
    //        }catch (Exception ex){
    //            Globals.LOGGER.log(Level.WARNING, ex.getMessage());
    //        }

    try {
      Printer printer = Printer.getDefaultPrinter();
      PageLayout pageLayout =
          printer.createPageLayout(
              Paper.A5, PageOrientation.PORTRAIT, Printer.MarginType.HARDWARE_MINIMUM);
      PrinterJob printerJob = PrinterJob.createPrinterJob();

      if (printerJob.printPage(pageLayout, printForm)) {
        printerJob.endJob();
      }
    } catch (Exception ex) {
      Globals.LOGGER.log(Level.WARNING, ex.getMessage());
    }
  }
 private static Budget loadBudget(int index, File[] foundBudgets) {
   FileInputStream newBudget = null;
   ObjectInputStream toLoad = null;
   Object loadedBudget = null;
   try {
     newBudget = new FileInputStream(foundBudgets[index].toString());
   } catch (FileNotFoundException e) {
     Printer.print("wTF");
     System.out.println("Error making the FileInputStream");
   }
   try {
     toLoad = new ObjectInputStream(newBudget);
   } catch (IOException e) {
     Printer.print("wTF");
     System.out.println("Error making the ObjectInputStream");
   }
   try {
     loadedBudget = toLoad.readObject();
   } catch (ClassNotFoundException | IOException e) {
     Printer.print("wTF");
     System.out.println("IO exception, maybe the file is bad?");
   }
   try {
     toLoad.close();
   } catch (IOException e) {
     Printer.print("wTF");
     System.out.println("Couldn't close the Object/File input streams.");
   }
   BudgetBoss.endLoadSavedBudget();
   return (Budget) loadedBudget;
 }
Пример #7
0
    // Process keys that have become selected
    //
    void processSelectedKeys() throws IOException {
      for (Iterator i = sel.selectedKeys().iterator(); i.hasNext(); ) {

        // Retrieve the next key and remove it from the set
        SelectionKey sk = (SelectionKey) i.next();
        i.remove();

        // Retrieve the target and the channel
        Target t = (Target) sk.attachment();
        SocketChannel sc = (SocketChannel) sk.channel();

        // Attempt to complete the connection sequence
        try {
          if (sc.finishConnect()) {
            sk.cancel();
            t.connectFinish = System.currentTimeMillis();
            sc.close();
            printer.add(t);
          }
        } catch (IOException x) {
          sc.close();
          t.failure = x;
          printer.add(t);
        }
      }
    }
  void saveNewJobsByDate(String folderPath, String printerName)
      throws ClientProtocolException, IOException, ParseJobException {

    List<JobDetail> toSave = new ArrayList<JobDetail>();
    int getJobsFrom;

    String latestLog = LogFiles.getMostRecentLogFileName(folderPath, printerName);

    if (latestLog != null) {
      JobDetailCSV l2csv = new JobDetailCSV(latestLog);

      // We'll be resaving the latest csv as it may have new jobs
      toSave = l2csv.readCSV();

      getJobsFrom = LogFiles.getLastSavedJob(folderPath, printerName).getJobNumber();
    } else {
      getJobsFrom = 0;
    }

    List<JobDetail> newJobs = printer.getJobsSinceJobNumber(getJobsFrom);

    toSave.addAll(newJobs);

    LogFiles.sortJobsByNumber(toSave);

    TreeMap<LocalDate, List<JobDetail>> sorted = LogFiles.splitJobsByDate(toSave);

    for (LocalDate day : sorted.keySet()) {

      JobDetailCSV jd =
          new JobDetailCSV(csvFolder + "/" + printer.getPrinterName() + day.toString());
      jd.write(sorted.get(day));
    }
  }
Пример #9
0
  /**
   * Directs a chart request to a ChartMediator.<br>
   * Referring to a given configuration (id), it directs a request for a chart to a ChartMediator
   * and returns the result.
   *
   * @param json String path to a .json file where request information are stored
   * @return a json-object which contains all information about the requested chart
   * @see ChartMediator
   */
  public JSONObject computeChart(JSONObject json) {
    if (json == null) {
      throw new IllegalArgumentException();
    }

    // checks whether a request is allowed
    if (!isInitialized()) {
      Printer.pproblem("Configurations & mediators not initalized!");
      Printer.print("-> Chart creation not possible!");
      return null;
    }

    if (!(tablesAreCreated())) {
      Printer.pproblem("Tables not created. Request not possible");
      return null;
    }

    // direct request and hopefully receive a JSON object
    JSONObject chart = chartMedi.computeChart(json);

    if (chart == null) {
      Printer.pfail("Computing chart.");
      return null;
    } else {
      Printer.psuccess("Computing chart.");
    }

    return chart;
  }
Пример #10
0
    void add(Target t) {
      SocketChannel sc = null;
      try {

        sc = SocketChannel.open();
        sc.configureBlocking(false);

        boolean connected = sc.connect(t.address);

        t.channel = sc;
        t.connectStart = System.currentTimeMillis();

        if (connected) {
          t.connectFinish = t.connectStart;
          sc.close();
          printer.add(t);
        } else {
          synchronized (pending) {
            pending.add(t);
          }

          sel.wakeup();
        }
      } catch (IOException x) {
        if (sc != null) {
          try {
            sc.close();
          } catch (IOException xx) {
          }
        }
        t.failure = x;
        printer.add(t);
      }
    }
  public static void main(String[] args) {
    ScopeTest test = new ScopeTest();
    Printer lambdaPrinter = test.getLambdaPrinter();
    lambdaPrinter.print("Lambda Expressions");

    Printer anonymousPrinter = test.getAnonymousPrinter();
    anonymousPrinter.print("Anonymous Class");
  }
Пример #12
0
 public PingClient() throws IOException {
   selector = Selector.open();
   Connector connector = new Connector();
   Printer printer = new Printer();
   connector.start();
   printer.start();
   receiveTarget();
 }
Пример #13
0
  protected void implOpen() throws LineUnavailableException {
    if (Printer.trace) Printer.trace(">> PortMixer: implOpen (id=" + id + ")");

    // open the mixer device
    id = nOpen(getMixerIndex());

    if (Printer.trace) Printer.trace("<< PortMixer: implOpen succeeded.");
  }
Пример #14
0
  // CONSTRUCTOR
  PortMixer(PortMixerProvider.PortMixerInfo portMixerInfo) {
    // pass in Line.Info, mixer, controls
    super(
        portMixerInfo, // Mixer.Info
        null, // Control[]
        null, // Line.Info[] sourceLineInfo
        null); // Line.Info[] targetLineInfo

    if (Printer.trace) Printer.trace(">> PortMixer: constructor");

    int count = 0;
    int srcLineCount = 0;
    int dstLineCount = 0;

    try {
      try {
        id = nOpen(getMixerIndex());
        if (id != 0) {
          count = nGetPortCount(id);
          if (count < 0) {
            if (Printer.trace) Printer.trace("nGetPortCount() returned error code: " + count);
            count = 0;
          }
        }
      } catch (Exception e) {
      }

      portInfos = new Port.Info[count];

      for (int i = 0; i < count; i++) {
        int type = nGetPortType(id, i);
        srcLineCount += ((type & SRC_MASK) != 0) ? 1 : 0;
        dstLineCount += ((type & DST_MASK) != 0) ? 1 : 0;
        portInfos[i] = getPortInfo(i, type);
      }
    } finally {
      if (id != 0) {
        nClose(id);
      }
      id = 0;
    }

    // fill sourceLineInfo and targetLineInfos with copies of the ones in portInfos
    sourceLineInfo = new Port.Info[srcLineCount];
    targetLineInfo = new Port.Info[dstLineCount];

    srcLineCount = 0;
    dstLineCount = 0;
    for (int i = 0; i < count; i++) {
      if (portInfos[i].isSource()) {
        sourceLineInfo[srcLineCount++] = portInfos[i];
      } else {
        targetLineInfo[dstLineCount++] = portInfos[i];
      }
    }

    if (Printer.trace) Printer.trace("<< PortMixer: constructor completed");
  }
 private static void searchDirectory(String directoryToSearch) {
   AnsiConsole.out.println(ansi().eraseScreen());
   Printer.print("searchingDirectory");
   File[] foundBudgets = Finder.findBudgets(directoryToSearch);
   if (foundBudgets.length > 0) {
     chooseBudget(foundBudgets);
     BudgetBoss.setDefaultDirectory(directoryToSearch);
   } else Printer.print("noBudgetFound");
 }
 private static void chooseBudget(File[] foundBudgets) {
   Printer.printFoundBudgets(foundBudgets);
   Printer.print("openBudget");
   int index = getChoiceNumber(foundBudgets);
   if (!(index == -5)) {
     System.out.println("Opening " + foundBudgets[index].getName() + "...\n");
     BudgetBoss.setCurrentBudget(loadBudget(index, foundBudgets));
     BudgetBoss.endNeedNewBudget();
   }
 }
Пример #17
0
  /**
   * Returns the dimensions and rows.
   *
   * @return the dimensions and rows
   */
  public ArrayList<DimRow> getDimensions() {
    // checks whether a request against configuration is allowed
    if (!isInitialized()) {
      Printer.pproblem("Configurations not initalized!");
      Printer.print("-> Request on it possible!");
      return null;
    }

    return currentConfig.getDims();
  }
Пример #18
0
 public static void main(String args[]) throws IOException {
   Args arguments = new Args(args);
   TimeZone timeZone = parseTimeZoneConfig(arguments);
   try (Printer printer = getPrinter(arguments)) {
     for (String fileAsString : arguments.orphans()) {
       new DumpLogicalLog(new DefaultFileSystemAbstraction())
           .dump(fileAsString, printer.getFor(fileAsString), timeZone);
     }
   }
 }
Пример #19
0
  /** Precomputes the Strings in the dimensions for the web page selection boxes. */
  private void computeDimensionData() {
    assert (isInitialized());

    if (!(dataMedi.organizeData())) {
      Printer.pfail("Precomputing data for dimensions.");
    } else {
      web.ChartHelper.reset();
      Printer.psuccess("Precomputing data for dimensions.");
    }
  }
  private void fillData(@Nullable Intent intent, @NonNull TextView textView) {
    Uri data = intent == null ? null : intent.getData();
    if (data == null) {
      textView.setText(Printer.EMPTY);
      return;
    }

    Truss truss = new Truss();
    Printer.append(truss, "raw", data);
    Printer.append(truss, "scheme", data.getScheme());
    Printer.append(truss, "host", data.getHost());
    Printer.append(truss, "port", data.getPort());
    Printer.append(truss, "path", data.getPath());
    Printer.appendKey(truss, "query");
    boolean query = false;
    if (data.isHierarchical()) {
      for (String queryParameterName : data.getQueryParameterNames()) {
        Printer.appendSecondary(
            truss, queryParameterName, data.getQueryParameter(queryParameterName));
        query = true;
      }
    }
    if (!query) {
      Printer.appendValue(truss, null);
    }
    Printer.append(truss, "fragment", data.getFragment());
    textView.setText(truss.build());
  }
Пример #21
0
  public ShowComp() throws InterruptedException, IOException {
    super("CONNECTED COMPUTERS");
    int x = 0, d = 20;
    mb = new JMenuBar();
    File = new JMenu("File");
    mb.add(File);
    exit = new JMenuItem("Exit");
    exit.addActionListener(this);
    File.add(exit);
    ta = new JTextArea();
    ta.setBounds(20, 30, 315, 470);
    ta.setEditable(false);
    add(ta);

    setJMenuBar(mb);

    sel = new JLabel("The connected computers are..");
    sel.setBounds(15, 5, 300, 30);
    add(sel);
    b1 = new JButton("<< BACK");
    b1.setBounds(140, 510, 100, 30);
    b1.setToolTipText("Back to main page");
    b1.addActionListener(this);
    add(b1);
    setLayout(null);
    while (x < 360) {
      x = x + d;
      setBounds(675, 50, x, 600);
      this.show();
    }
    // setVisible(true);
    String s = "192.168.0.", temp = null;
    Printer printer = new Printer();
    printer.start();
    Connector connector = new Connector(printer);
    connector.start();

    LinkedList targets = new LinkedList();
    for (int i = 1; i <= 255; i++) {
      temp = s + Integer.toString(i);
      Target t = new Target(temp);
      targets.add(t);
      connector.add(t);
    }
    Thread.sleep(2000);
    connector.shutdown();
    connector.join();

    for (Iterator i = targets.iterator(); i.hasNext(); ) {
      Target t = (Target) i.next();
      if (!t.shown) t.show();
    }

    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
  }
Пример #22
0
  @Test
  public void testDefaultPrinter() {
    StringWriter sw = new StringWriter();
    Printer p = Printers.newPrinter(sw);

    ArrayList<Object> al = new ArrayList<Object>();
    al.add(1);
    al.add(2);
    p.printValue(al);
    assertEquals("[1 2]", sw.toString());
  }
Пример #23
0
 private void list() {
   printer.println("Friends: ");
   for (Friend f : manager.friends()) {
     printer.println(
         "  "
             + f.getNickname()
             + " "
             + (f.getFriendConnection() == null
                 ? "disconnected"
                 : f.getFriendConnection().getSocketAddress()));
   }
 }
Пример #24
0
  public static void main(String[] args) {
    /*
     * Wait for startup button press
     * Button.ID_LEFT = BangBang Type
     * Button.ID_RIGHT = P Type
     */

    int option = 0;
    Printer.printMainMenu();
    while (option == 0)
      // option = Button.waitForPress();
      option = Button.waitForAnyPress();
    // depends on version

    // Setup controller objects
    BangBangController bangbang =
        new BangBangController(bandCenter, bandWidth, motorLow, motorHigh);
    PController p = new PController(bandCenter, bandWidth);

    // Setup ultrasonic sensor
    UltrasonicSensor usSensor = new UltrasonicSensor(usPort);

    // Setup Printer
    Printer printer = null;

    // Setup Ultrasonic Poller
    UltrasonicPoller usPoller = null;

    switch (option) {
      case Button.ID_LEFT:
        usPoller = new UltrasonicPoller(usSensor, bangbang);
        printer = new Printer(option, bangbang);
        break;
      case Button.ID_RIGHT:
        usPoller = new UltrasonicPoller(usSensor, p);
        printer = new Printer(option, p);
        break;
      default:
        System.out.println("Error - invalid button");
        System.exit(-1);
        break;
    }

    usPoller.start();
    printer.start();

    // Wait for another button press to exit
    // Button.waitForPress();
    Button.waitForAnyPress();
    // depends on version
    System.exit(0);
  }
 public static void getLoadDirectory() {
   AnsiConsole.out.println(ansi().eraseScreen());
   Printer.print("savedInDefault");
   System.out.println(BudgetBoss.getDefaultDirectory());
   Printer.print("whereSaved");
   String toCheck = Listener.getInput();
   while (InputValidator.pathIsInvalid(toCheck)) toCheck = Listener.getInput();
   if (!(toCheck.equals("exit"))) {
     if (toCheck.equalsIgnoreCase("y")) {
       searchDirectory(BudgetBoss.getDefaultDirectory());
     } else searchDirectory(toCheck);
   }
 }
Пример #26
0
 private void dir(String sharebase, String path) {
   printer.println("Directory listing for " + path + ": ");
   sharebase = TextUtils.makeSurePathIsMultiplatform(sharebase);
   ShareBase b = core.getFileManager().getShareManager().getBaseByPath(sharebase);
   if (b == null) {
     printer.println("Could not find share base for " + sharebase);
     return;
   }
   printer.println("Found share base: " + b);
   /*  for (String s : core.getFileManager().getFileDatabase().getDirectoryListing(b, path)) {
   printer.println(s);
   }*/
 }
Пример #27
0
 /**
  * Method that calls print() methods on each printer
  *
  * @param message message to log
  * @throws PrinterManagerException
  */
 public void print(String message) throws PrinterManagerException {
   PrinterManagerException printerManagerException = new PrinterManagerException();
   for (Printer printer : printers) {
     try {
       printer.print(message);
     } catch (PrinterException e) {
       printerManagerException.addPrinterException(e);
     }
   }
   if (!printerManagerException.getPrinterExceptions().isEmpty()) {
     throw printerManagerException;
   }
 }
 @Override
 public void execute() {
   printer.print("Executing output features as csv process: ");
   printer.print("loading segments...");
   List<Segment> trainSet = loadFromJsonAndUpdateSegments(pathManager.getTrainSetPath());
   List<Segment> testSet = loadFromJsonAndUpdateSegments(pathManager.getTestSetPath());
   List<Segment> validationSet = loadFromJsonAndUpdateSegments(pathManager.getValidationSetPath());
   List<Segment> unclassified = getUnclassifiedSegments();
   printer.print("saving output...");
   String csv = segmentsCsvBuilder.buildCsv(trainSet, testSet, validationSet, unclassified);
   saveOutputToFile(csv);
   schemaToJobDirectorySaver.saveSchemaToJobDirectory();
   printer.print("done.\n");
 }
Пример #29
0
 @Test
 public void testLoosePrinter() {
   StringWriter sw = new StringWriter();
   Printer p = LoosePrinter.newLoosePrinter(sw);
   ArrayList<Object> al = new ArrayList<Object>();
   al.add(Keyword.newKeyword("test"));
   al.add("test");
   al.add(Keyword.newKeyword("value"));
   Map map = new HashMap();
   map.put(Keyword.newKeyword("name"), "Test");
   al.add(map);
   p.printValue(al);
   assertEquals("[:test \"test\" :value {:name \"Test\"}]", sw.toString());
 }
Пример #30
0
 @Override
 protected void print(
     ExportHelper helper,
     List<EventInterface> events,
     int eventCookieFlags,
     EventMeetingSortBy sort,
     boolean asc)
     throws IOException {
   sort(events, sort, asc);
   Printer printer = new CSVPrinter(helper.getWriter(), false);
   helper.setup(printer.getContentType(), reference(), false);
   hideColumns(printer, events, eventCookieFlags);
   print(printer, events);
 }