Exemple #1
0
 public void model_admin() {
   if (ajf != null) {
     ajf.dispose();
   }
   if (jf != null) {
     jf.dispose();
   }
   ajf = new AdminRunningFrame(this);
   ajf.startPage();
   if (DBfile.exists()) {
     try {
       cust = returnSavedData("p2.dat");
       if (cust.isEmpty()) {
         ajf.errorMessage("There are no customers in this database.");
       }
     } catch (ClassNotFoundException | IOException e) {
       e.printStackTrace();
     }
   }
   if (logFile.exists()) {
     try {
       adminLogs = returnLog("p2.log");
       if (adminLogs.isEmpty()) {
         ajf.errorMessage("No entries have been found!");
       }
     } catch (ClassNotFoundException | IOException e) {
       e.printStackTrace();
     }
   }
 }
  void listen() {
    LOGGER.info("Listening on port " + port);

    //	ExecutorService executor = Executors.newCachedThreadPool();

    while (true) {

      LOGGER.finer("Receiving ...");
      try {
        Message mess = communication.receive(port, true, false);

        System.out.println("Message from Port: [" + mess.getPort() + "] received!");

        // if (!mess.getContent().equals("fertig")){
        new TaskThread(communication, mess).start();
        //	counter++;
        // }

        // if (mess.getContent().equals("fertig")){
        // counter--;
        // }
        // System.out.println("Anzahl Threads: " + counter);

      } catch (ClassNotFoundException | IOException e) {
        e.printStackTrace();
      }
      // LOGGER.fine(request.toString()+" received.");

    }
  }
  @Override
  public Object execute(Object obj) {
    List<Object> params = (List<Object>) obj;

    // param 0: groupId
    groupId = ((String) params.get(0));

    // param 1: to indicate if all Servers will run in a single computer
    // or they will run Servers hosted in different computers (or more than one
    // Server in a single computer but this computer having the same internal and external IP
    // address)
    // * true: all Server run in a single computer
    // * false: Servers running in different computers (or more than one Server in a single computer
    // but
    // 			this computer having the same internal and external IP address)
    SimulationData.getInstance().setLocalExecution(((String) params.get(1)).equals("localMode"));

    try {
      users = (List<String>) params.get(2);
      operations = (List<Operation>) Serializer.deserialize((byte[]) params.get(3));
    } catch (ClassNotFoundException | IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return null;
  }
  /**
   * Checks if the score is high enough to get to the high scores list, adds the name and score and
   * organizes the list. If HighScores.dat is not found, the method generates a blank one.
   *
   * @param name The nickname of the person getting to the list.
   * @param score The score gained.
   */
  public static void addHighScore(String name, int score) {

    // If we don't yet have a high scores table, we create a blank (and let the user know about it)
    if (!new File("HighScores.dat").exists()) {
      // This object matrix actually stores the information of the high scores list
      Object[][] highScores = new Object[10][3];
      // We fill the high scores list with blank entries:  #.    " "    0
      for (int i = 0; i < highScores.length; i++) {
        highScores[i][0] = (i + 1) + ".";
        highScores[i][1] = " ";
        highScores[i][2] = 0;
      }
      // This actually writes and makes the high scores file
      try {
        ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("HighScores.dat"));
        o.writeObject(highScores);
        o.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    // We read the file to check if we have a new high score, and then rewrite the highscore
    // This is done even if we didn't previously have a high scores list
    try {
      ObjectInputStream o = new ObjectInputStream(new FileInputStream("HighScores.dat"));
      // The object matrix does the same as the previous one.
      // Here we just take what we read from the HighScores.dat to the Object[][] HighScores.
      Object[][] highScores = (Object[][]) o.readObject();
      // Then we start searching for an entry for which the score is smaller than the achieved score
      for (int i = 0; i < highScores.length; i++) {
        if ((Integer) highScores[i][2] < score) {
          // Once found we start to move entries, which are below the score we had, downwards.
          // I.e. 10. becomes whatever 9. was. 9. becomes what 8. was etc...
          for (int j = 9; j > i; j--) {
            highScores[j][0] = (j + 1) + ".";
            highScores[j][1] = highScores[j - 1][1];
            highScores[j][2] = highScores[j - 1][2];
          }
          // Then we write the score and the name we just got to the correct place
          highScores[i][0] = (i + 1) + ".";
          highScores[i][1] = name;
          highScores[i][2] = score;
          // And break the loop.
          /*Maybe this could be avoided somehow? I haven't been able to come up with an easy way yet.*/
          break;
        }
      }
      try {
        // And finally we overwrite the HighScores.dat with our highScores object matrix
        ObjectOutputStream n = new ObjectOutputStream(new FileOutputStream("HighScores.dat"));
        n.writeObject(highScores);
        n.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    } catch (ClassNotFoundException | IOException e) {
      e.printStackTrace();
    }
  }
Exemple #5
0
 // initiates the klient
 public void startRunning(String address, int port) {
   connect(address, port);
   try {
     receive();
   } catch (ClassNotFoundException | IOException e) {
     System.err.println("ERROR: " + e.getMessage());
   }
 }
Exemple #6
0
 /**
  * Loads translation from a .slon file Or reads a monolingual source file, if no translation is
  * available yet
  *
  * @param table the translation table
  * @param f the translation file
  * @param btnClose the "Close" button
  * @param closeItem the menu item "Close"
  */
 public void resumeProject(File projectDir, JTable table) {
   try {
     project = new Project(projectDir.toPath());
     paragraphs = deserializeAll(project.translationFile.getAbsolutePath());
   } catch (ClassNotFoundException | IOException e) {
     e.printStackTrace();
   }
   showParagraphs(table);
 }
Exemple #7
0
 public static void loadAlarmFile(Context context) {
   try {
     allAlarms = RapplaUtils.readSerializedObject(context, serializedAlarmsFileName);
   } catch (FileNotFoundException e) {
   } catch (ClassNotFoundException | IOException i) {
     i.printStackTrace();
   } finally {
     if (allAlarms == null) allAlarms = new HashMap<>();
   }
 }
 public int predict(String text) {
   LMClassifier<?, ?> model = null;
   try {
     model = createModelInputAndTrain(true, INPUT_TWEETS_ORIG_TXT);
   } catch (ClassNotFoundException | IOException e) {
     e.printStackTrace();
   }
   ConditionalClassification classification = model.classify(text);
   String category = classification.bestCategory();
   // System.out.println("Tweet: " + text + "\tSentiment: " + category);
   return Integer.parseInt(category);
 }
Exemple #9
0
  @RolesAllowed(Roles.OWNER)
  @POST
  @Path("/{stream_name}")
  @Consumes(MediaType.APPLICATION_JSON)
  @ApiOperation(value = "Add a new tuple to the stream.", notes = "TBD")
  @ApiResponses(value = {@ApiResponse(code = 500, message = "Interval Server Error")})
  public ResponseMsg doPostStream(
      @PathParam("stream_name") String streamName,
      @ApiParam(
              name = "str_tuple",
              value =
                  "<pre>Usage:\n"
                      + "[ timestamp, 1st_channel, 2nd_channel, 3rd_channel, .. ]\n"
                      + "\n"
                      + "  e.g., [ \"2013-01-01 09:20:12.12345\", 12.4, 1.2, 5.5 ]\n"
                      + "  e.g., [ null, 12.4, 1.2, 5.5 ]\n"
                      + "\n"
                      + "Or,\n"
                      + "{ \"timestamp\": timestamp\n"
                      + "  \"tuple\": [ 1st_channel, 2nd_channel, 3rd_channel, .. ] }\n"
                      + "\n"
                      + "  e.g., { \"timestamp\": \"2013-01-01 09:20:12.12345\"\n"
                      + "          \"tuple\": [ 12.4, 1.2, 5.5 ] }\n"
                      + "  e.g., { \"timestamp\": null\n"
                      + "          \"tuple\": [ 12.4, 1.2, 5.5 ] }\n"
                      + "\n"
                      + "If timestamp is null, current server time will be used.</pre>")
          String strTuple)
      throws JsonProcessingException {

    String ownerName = securityContext.getUserPrincipal().getName();
    StreamDatabaseDriver db = null;
    try {
      db = DatabaseConnector.getStreamDatabase();
      db.addTuple(ownerName, streamName, strTuple);
    } catch (ClassNotFoundException | IOException | NamingException | SQLException e) {
      e.printStackTrace();
      throw WebExceptionBuilder.buildInternalServerError(e);
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
      throw WebExceptionBuilder.buildBadRequest(e);
    } finally {
      if (db != null) {
        try {
          db.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    }
    return new ResponseMsg("Successfully added the tuple.");
  }
Exemple #10
0
  public static Student getStudent() {
    Student student = null;
    ;
    try {
      FileInputStream input = new FileInputStream(fileName);
      ObjectInputStream objInput = new ObjectInputStream(input);
      student = (Student) objInput.readObject();

      objInput.close();
      input.close();
    } catch (ClassNotFoundException | IOException e) {
      e.printStackTrace();
    }
    return student;
  }
  @SuppressWarnings("unchecked")
  public List<News> fileReader(Context inContext) {

    FileInputStream fis;
    List<News> internalDataStored = new ArrayList<>();

    try {

      fis = inContext.openFileInput(File);
      ObjectInputStream ois = new ObjectInputStream(fis);

      internalDataStored = (List<News>) ois.readObject();

      ois.close();

    } catch (ClassNotFoundException | IOException e) {

      e.printStackTrace();
    }

    return internalDataStored;
  }
Exemple #12
0
  public static ArrayList<Class<?>> GetClassesForPlugin(ACivMod plugin, Class<?> ofType) {
    ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
    try {
      Package pack = plugin.getClass().getPackage();
      if (pack == null) {
        plugin.info("Package name REQUIRED for annotation loading");
      } else {

        String packageName = pack.getName();
        ClassLoader classloader = plugin.classLoader;
        ClassPath path = ClassPath.from(classloader);

        for (ClassPath.ClassInfo info : path.getTopLevelClassesRecursive(packageName)) {
          Class clazz = null;
          try {
            clazz = Class.forName(info.getName(), true, classloader);
          } catch (NoClassDefFoundError e) {
            plugin
                .getLogger()
                .log(
                    Level.INFO,
                    "CivModCore failed to load class "
                        + info.getName()
                        + ", you could be missing a dependency. "
                        + "This message is more of an info message useful for debugging. If you see this message you can usually ignore it "
                        + "unless the plugin itself throws an error.");
            continue;
          }
          if (ofType == null || ofType.isAssignableFrom(clazz)) {
            classes.add(clazz);
          }
        }
      }
    } catch (ClassNotFoundException | IOException e) {
      e.printStackTrace();
    }
    return classes;
  }
  public ConnectedClients(Socket inputSocket) {
    clientSocket = inputSocket; // initialization of connections.
    // super.init(clientSocket);
    Object msg = null;

    try {

      os = new ObjectOutputStream(clientSocket.getOutputStream());
      in = new ObjectInputStream(clientSocket.getInputStream());
      CommonUtils.PrintMe("invoke themethod to create a instance of connected client");
      msg = in.readObject();

    } catch (ClassNotFoundException | IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return;
    }

    Messages firstMsg = (Messages) msg;
    CommonUtils.PrintMe(
        "the server get the frist  message from the new client:"
            + firstMsg.getContent()
            + "是否加密:"
            + firstMsg.getEncryptedStatus()
            + "消息类型:"
            + firstMsg.getMsgType());
    firstMsg.DecryptedMe(
        SingletonEncryptionMethod.getInstance()); // use ROT13 decrypt the incomming Msg

    clientName = firstMsg.getSenderName();
    clientIp = firstMsg.getSenderIp();

    firstMsg.printMsg();

    CommonUtils.PrintMe(
        "the instance of client send a  message:---" + firstMsg.getContent() + "---");
  }
 static List<MessageTestCase> getTestCasesToRun(String[] ids) {
   List<MessageTestCase> testsToRun = new ArrayList<>();
   if (ids.length > 0) {
     for (String id : ids) {
       try {
         final String name = TESTCASES_PACKAGE_NAME + id;
         MessageTestCase tc = (MessageTestCase) Class.forName(name).newInstance();
         tc.setId(id);
         testsToRun.add(tc);
       } catch (ClassNotFoundException e) {
         LOG.error("Could not find testcase with id '{}'", id);
       } catch (InstantiationException | IllegalAccessException e) {
         LOG.error(e.toString());
       }
     }
   } else {
     try {
       testsToRun.addAll(getAllTestCases(TESTCASES_PACKAGE_NAME));
     } catch (ClassNotFoundException | IOException e) {
       LOG.error(e.toString());
     }
   }
   return testsToRun;
 }
Exemple #15
0
  public Atm() // constructor
        // sets the customer array to that found in the file if the file exists
      {
    try {
      // Set cross-platform Java L&F (also called "Metal")
      UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
    } catch (UnsupportedLookAndFeelException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } catch (InstantiationException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    }

    if (logFile.exists()) {
      try {
        adminLogs = returnLog("p2.log");
        if (!adminLogs.isEmpty()) {
          // there may be customer data but perhaps no transactions yet.
          ArrayList<Integer> allTransactions = new ArrayList<>(100);
          for (AdminLog a : adminLogs) {

            int transaction = a.getTransactionID();
            ;
            allTransactions.add(transaction);
          }
          transaction_counter = Collections.max(allTransactions) + 1;
        }
      } catch (ClassNotFoundException | IOException e) {
        e.printStackTrace();
      }
    }

    if (DBfile.exists()) {
      try {

        cust = returnSavedData("p2.dat");

        // sets the starting ID to the max of all the IDs stored in the file.
        allIDs = new ArrayList<Integer>(100);
        ArrayList<Integer> allAccounts = new ArrayList<>();
        for (Customer customer : cust) {
          String idString = customer.returnID();
          int id = Integer.parseInt(idString);
          allIDs.add(id);
          int accountNumber = customer.returnMaxAccount();
          allAccounts.add(accountNumber);
        }
        // checks to see if the customer has even made any accounts, if not, max accounts will be
        // set at 1001
        if (starting_account_number != 1) {
          starting_account_number = Collections.max(allAccounts) + 1;
        }
        starting_customer_number = Collections.max(allIDs) + 1;

      } catch (ClassNotFoundException | IOException e) {
        e.printStackTrace();
      }
    } else {
      cust = new ArrayList<>(100);
      // creates the file if it does not exist
      try {
        saveFile(cust, DBfile);
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    interest_rate = 5;
  }
  /**
   * Creates a new configuration method
   *
   * @param backMenu Menu instance used to control its music
   */
  public Config(Menu backMenu) {

    try {
      UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
      try (ObjectInputStream entradaObjs =
          new ObjectInputStream(new FileInputStream("Saves" + File.separator + "config.dat"))) {
        configSave = (float[]) entradaObjs.readObject();
      }
    } catch (ClassNotFoundException
        | IOException
        | InstantiationException
        | IllegalAccessException
        | UnsupportedLookAndFeelException e) {
      System.out.println(e.getMessage());
    }

    this.setSize(800, 300);
    this.add(fondo = new Fondo("fondoConfig.png"));
    this.setUndecorated(true);
    this.setLocationRelativeTo(null);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setIconImage(Toolkit.getDefaultToolkit().getImage("Images" + File.separator + "logo.png"));
    this.backMenu = backMenu;

    icon = new ImageIcon("Images/brick.png");

    fondo.setLayout(new BorderLayout());

    returns = CustomButton.createButton("Go Back", this.getGraphicsConfiguration(), 18);
    returns.addActionListener(this);

    musicSlider = new JSlider(JSlider.HORIZONTAL, -30, 0, (int) configSave[0]);
    musicSlider.setOpaque(false);
    musicSlider.setMajorTickSpacing(10);
    musicSlider.setMinorTickSpacing(2);
    musicSlider.setPaintTicks(true);

    volumeSlider = new JSlider(JSlider.HORIZONTAL, -30, 0, (int) configSave[1]);
    volumeSlider.setOpaque(false);
    volumeSlider.setMajorTickSpacing(10);
    volumeSlider.setMinorTickSpacing(2);
    volumeSlider.setPaintTicks(true);

    fondo.add(returns, BorderLayout.SOUTH);
    fondo.add(musicSlider, BorderLayout.NORTH);
    fondo.add(volumeSlider, BorderLayout.CENTER);

    try {
      this.getContentPane()
          .setCursor(
              Toolkit.getDefaultToolkit()
                  .createCustomCursor(
                      CompatibleImage.toCompatibleImage(
                          ImageIO.read(new File("Images" + File.separator + "cursor.png"))),
                      new Point(0, 0),
                      "cursor"));
    } catch (IOException ex) {
      Logger.getLogger(Menu.class.getName()).log(Level.SEVERE, null, ex);
    }

    this.setVisible(true);
  }
Exemple #17
0
  /**
   * start a vina hadoop job
   *
   * @param confLocalPath
   * @param receptorLocalPath
   * @param ligandPath
   * @param seed
   * @param topK
   * @param vinaJobID
   * @param node
   * @return
   */
  public HashMap<String, String> startJob(
      String confLocalPath,
      String receptorLocalPath,
      ArrayList<String> ligandPath,
      String seed,
      int topK,
      String vinaJobID,
      int numPerNode,
      boolean verbose) {
    HashMap<String, String> hm = new HashMap<String, String>();
    if (confLocalPath == null
        || receptorLocalPath == null
        || ligandPath == null
        || seed == null
        || vinaJobID == null
        || ligandPath.size() == 0
        || topK < 0) {
      hm.put("flag", "false");
      hm.put("hadoopID", "null");
      hm.put("vinaJobID", vinaJobID);
      hm.put("log", "error arguments");
      return hm;
    }
    GeneratePath gp = new GeneratePath(jobPath, srcDataPath);
    String confName = confLocalPath.substring(confLocalPath.lastIndexOf("/"));
    String confHDFSPath = jobPath + vinaJobID + confName;
    String receptorName = receptorLocalPath.substring(receptorLocalPath.lastIndexOf("/"));
    String receptorHDFSPATH = jobPath + vinaJobID + receptorName;
    HadoopFile hf;
    final String input = jobPath + vinaJobID + "/metadata";
    final String output = jobPath + vinaJobID + "/order";
    Path path = new Path(output);
    Configuration conf;
    FileSystem fs;
    Job job;
    try {
      gp.createMeta(ligandPath, vinaJobID, numPerNode);
      hf = new HadoopFile();
      hf.mkdir(jobPath + "/" + vinaJobID + "/exception");
      hf.mkdir(jobPath + "/" + vinaJobID + "/exceptionBackup");
      hf.localToHadoop(confLocalPath, confHDFSPath);
      hf.localToHadoop(receptorLocalPath, receptorHDFSPATH);
      conf = (new HadoopConf()).getConf();
      fs = FileSystem.get(conf);
      // set heart beat time 45min
      long milliSeconds = 45 * 60 * 1000;
      conf.setLong("mapred.task.timeout", milliSeconds);
      conf.set("vinaJobID", vinaJobID);
      conf.setInt("k", topK);
      conf.set("conf2HDFS", confHDFSPath);
      conf.set("receptorHDFS", receptorHDFSPATH);
      conf.set("seed", seed);
      if (fs.exists(path)) {
        fs.delete(path, true);
      }
      job = new Job(conf, vinaJobID);
      job.setNumReduceTasks(1);
      job.setJarByClass(VinaHadoop.class);
      job.setMapperClass(VinaMapper.class);
      job.setReducerClass(VinaReducer.class);
      job.setMapOutputKeyClass(DoubleWritable.class);
      job.setMapOutputValueClass(DataPair.class);
      job.setOutputKeyClass(DoubleWritable.class);
      job.setOutputValueClass(Text.class);
      FileInputFormat.addInputPath(job, new Path(input));
      FileOutputFormat.setOutputPath(job, new Path(output));

    } catch (IOException e) {
      // TODO Auto-generated catch block
      hm.put("flag", "false");
      hm.put("hadoopID", "null");
      hm.put("vinaJobID", vinaJobID);
      hm.put("log", e.getMessage());
      return hm;
    }

    try {
      if (verbose) {
        // System.exit(job.waitForCompletion(true) ? 0 : 1);
        job.waitForCompletion(true);
      } else {
        job.submit();
      }

    } catch (ClassNotFoundException | IOException | InterruptedException e) {
      // TODO Auto-generated catch block
      hm.put("flag", "false");
      hm.put("hadoopID", "null");
      hm.put("vinaJobID", vinaJobID);
      hm.put("log", e.getMessage());
      return hm;
    }
    hm.put("flag", "true");
    hm.put("hadoopID", job.getJobID().toString());
    hm.put("vinaJobID", vinaJobID);
    hm.put("log", "null");
    return hm;
  }
Exemple #18
0
  /**
   * Adds Attachemnts based on formData to task.
   *
   * @param oFormData FormData from task where we search file fields.
   * @param oTask where we add Attachments.
   */
  public void addAttachmentsToTask(FormData oFormData, DelegateTask oTask) {
    DelegateExecution oExecution = oTask.getExecution();

    LOG.info("SCAN:file");
    List<String> asFieldID = getListFieldCastomTypeFile(oFormData);
    LOG.info("[addAttachmentsToTask]");
    LOG.info("(asFieldID={})", asFieldID.toString());
    List<String> asFieldValue = getVariableValues(oExecution, asFieldID);
    LOG.info("(asFieldValue={})", asFieldValue.toString());
    List<String> asFieldName = getListCastomFieldName(oFormData);
    LOG.info("(asFieldName={})", asFieldName.toString());
    if (!asFieldValue.isEmpty()) {
      int n = 0;
      for (String sKeyRedis : asFieldValue) {
        LOG.info("(sKeyRedis={})", sKeyRedis);
        if (sKeyRedis != null
            && !sKeyRedis.isEmpty()
            && !"".equals(sKeyRedis.trim())
            && !"null".equals(sKeyRedis.trim())
            && sKeyRedis.length() > 15) {
          if (!asFieldName.isEmpty() && n < asFieldName.size()) {
            // String sDescription = asFieldName.get((asFieldName.size() - 1) - n);
            String sDescription = asFieldName.get(n);
            LOG.info("(sDescription={})", sDescription);
            String sID_Field = asFieldID.get(n);
            LOG.info("(sID_Field={})", sID_Field);

            byte[] aByteFile;
            ByteArrayMultipartFile oByteArrayMultipartFile = null;
            try {
              aByteFile = oBytesDataInmemoryStorage.getBytes(sKeyRedis);
              oByteArrayMultipartFile = getByteArrayMultipartFileFromStorageInmemory(aByteFile);
            } catch (ClassNotFoundException | IOException | RecordInmemoryException e1) {
              throw new ActivitiException(e1.getMessage(), e1);
            }
            if (oByteArrayMultipartFile != null) {
              String sFileName = null;
              try {
                sFileName =
                    new String(oByteArrayMultipartFile.getOriginalFilename().getBytes(), "UTF-8");
              } catch (java.io.UnsupportedEncodingException oException) {
                LOG.error("error on getting sFileName: {}", oException.getMessage());
                throw new ActivitiException(oException.getMessage(), oException);
              }
              LOG.info("(sFileName={})", sFileName);

              // ===
              InputStream oInputStream = null;
              try {
                oInputStream = oByteArrayMultipartFile.getInputStream();
              } catch (Exception e) {
                throw new ActivitiException(e.getMessage(), e);
              }
              Attachment oAttachment =
                  oExecution
                      .getEngineServices()
                      .getTaskService()
                      .createAttachment(
                          oByteArrayMultipartFile.getContentType()
                              + ";"
                              + oByteArrayMultipartFile.getExp(),
                          oTask.getId(),
                          oExecution.getProcessInstanceId(),
                          sFileName,
                          sDescription,
                          oInputStream);

              if (oAttachment != null) {
                String nID_Attachment = oAttachment.getId();
                // LOG.info("(nID_Attachment={})", nID_Attachment);
                LOG.info(
                    "Try set variable(sID_Field={}) with the value(nID_Attachment={}), for new attachment...",
                    sID_Field,
                    nID_Attachment);
                oExecution
                    .getEngineServices()
                    .getRuntimeService()
                    .setVariable(oExecution.getProcessInstanceId(), sID_Field, nID_Attachment);
                LOG.info(
                    "Finished setting new value for variable with attachment (sID_Field={})",
                    sID_Field);
              } else {
                LOG.error("Can't add attachment to (oTask.getId()={})", oTask.getId());
              }
              // ===

            } else {
              LOG.error("oByteArrayMultipartFile==null!  (sKeyRedis={})", sKeyRedis);
            }
          } else {
            LOG.error("asFieldName has nothing! (asFieldName={})", asFieldName);
          }
        } else {
          LOG.error("Invalid Redis Key!!! (sKeyRedis={})", sKeyRedis);
        }
        n++;
      }
    }

    scanExecutionOnQueueTickets(oExecution, oFormData); // , oTask);//startformData

    /*LOG.info("SCAN:queueData");
    asFieldID = getListField_QueueDataFormType(formData);
    LOG.info("asFieldID="+asFieldID.toString());
    asFieldValue = getVariableValues(execution, asFieldID);
    LOG.info("asFieldValue="+asFieldValue.toString());
    //asFieldName = getListCastomFieldName(formData);
    //LOG.info("asFieldName="+asFieldName.toString());
    if (!asFieldValue.isEmpty()) {
    String sValue = asFieldValue.get(0);
    LOG.info("sValue=" + sValue);
    long nID_FlowSlotTicket=0;
    int nAt=sValue.indexOf(":");
    int nTo=sValue.indexOf(",");
    String s=sValue.substring(nAt+1,nTo);
    LOG.info("s=" + s);
    try{
    nID_FlowSlotTicket = Long.valueOf(s);
    LOG.info("Ok!");
    }catch(Exception oException){
    LOG.error(oException.getMessage());
    nID_FlowSlotTicket=1;
    }
    LOG.info("nID_FlowSlotTicket=" + nID_FlowSlotTicket);

    try{


    //                FlowSlotTicket oFlowSlotTicket = baseEntityDao.getById(FlowSlotTicket.class, nID_FlowSlotTicket);
    //                if (oFlowSlotTicket == null) {
    //                    LOG.error("FlowSlotTicket with id=" + nID_FlowSlotTicket + " is not found!");
    //                }else{
    //                    long nID_FlowSlot=oFlowSlotTicket.getoFlowSlot().getId();
    //                    LOG.error("nID_FlowSlot="+nID_FlowSlot);
    //                    long nID_Subject = oFlowSlotTicket.getnID_Subject();
    //                    LOG.error("nID_Subject="+nID_Subject);
    //                    long nID_Task_Activiti = 1; //TODO set real ID!!!
    //                    oFlowSlotTicket.setnID_Task_Activiti(nID_Task_Activiti);
    //                    baseEntityDao.saveOrUpdate(oFlowSlotTicket);
    //                    LOG.info("JSON:" + JsonRestUtils.toJsonResponse(new SaveFlowSlotTicketResponse(oFlowSlotTicket.getId())));
    //                }

    }catch(Exception oException){
    LOG.error(oException.getMessage());
    }

    }*/

  }
  private File createPNG(
      String streamName,
      int width,
      int height,
      String outputPath,
      boolean isLine,
      boolean isShape) {

    StreamDatabaseDriver db = null;
    String requestingUser = owner;
    String streamOwner = owner;

    String startTime = fmt.print(startDate);
    String endTime = fmt.print(endDate);

    try {
      db = DatabaseConnector.getStreamDatabase();

      boolean isData =
          db.prepareQuery(
              requestingUser,
              streamOwner,
              streamName,
              startTime,
              endTime,
              null,
              null,
              0,
              0,
              0,
              true,
              null);
      Stream stream = db.getStoredStreamInfo();

      if (!isData) {
        Log.error("isData null");
        return null;
      }

      if (stream.num_samples > width) {
        db.close();
        db = DatabaseConnector.getStreamDatabase();
        int skipEveryNth = (int) (stream.num_samples / width);
        isData =
            db.prepareQuery(
                requestingUser,
                streamOwner,
                streamName,
                startTime,
                endTime,
                null,
                null,
                0,
                0,
                skipEveryNth,
                false,
                null);
        stream = db.getStoredStreamInfo();

        if (!isData) {
          Log.error("isData null");
          return null;
        }
      }

      // Prepare data
      XYSeries[] series = null;
      long minTsInterval = Long.MAX_VALUE; // to determine whether to use marker on the plot.
      long prevTimestamp = -1;
      Object[] tuple = new Object[db.getStoredStreamInfo().channels.size() + 1];
      while (db.getNextTuple(tuple)) {
        // Init XYSeries array
        if (series == null) {
          series = new XYSeries[tuple.length - 1];
          for (int i = 0; i < series.length; i++) {
            series[i] = new XYSeries(stream.channels.get(i).name);
          }
        }

        long timestamp = ((Long) tuple[0]).longValue();
        for (int i = 1; i < tuple.length; i++) {
          try {
            series[i - 1].add(timestamp, (Number) tuple[i]);
          } catch (ClassCastException e) {
            continue;
          }
        }

        long diff = timestamp - prevTimestamp;
        if (diff > 0 && diff < minTsInterval) {
          minTsInterval = diff;
        }

        prevTimestamp = timestamp;
      }

      db.close();
      db = null;

      if (series == null) {
        throw new UnsupportedOperationException("No data for " + streamName);
      }

      XYSeriesCollection xyDataset = new XYSeriesCollection();
      for (XYSeries s : series) {
        xyDataset.addSeries(s);
      }

      // Generate title string
      long start = (long) series[0].getMinX();
      long end = (long) series[0].getMaxX();
      Timestamp startTimestamp = new Timestamp(start);
      Timestamp endTimestamp = new Timestamp(end);
      String title =
          stream.owner
              + ": "
              + stream.name
              + "\n"
              + startTimestamp.toString()
              + " ~ "
              + endTimestamp.toString();

      //  Create the chart object
      DateAxis xAxis = new DateAxis("Time");
      xAxis.setDateFormatOverride(new SimpleDateFormat("hh:mm aa"));
      // NumberAxis xAxis = new NumberAxis("");
      long margin = (endDate.getMillis() - startDate.getMillis()) / 24;
      xAxis.setRange(
          new Date(startDate.getMillis() - margin), new Date(endDate.getMillis() + margin));

      NumberAxis yAxis = new NumberAxis("Value");
      yAxis.setAutoRangeIncludesZero(false); // override default

      if (streamName.equals(ACTIVITY_SENSOR)) {
        yAxis.setTickUnit(new NumberTickUnit(1.0));
        yAxis.setRange(0.0, 4.0);
      } else if (streamName.equals(STRESS_SENSOR)) {
        yAxis.setTickUnit(new NumberTickUnit(1.0));
        yAxis.setRange(0.0, 1.0);
      } else if (streamName.equals(CONVERSATION_SENSOR)) {
        yAxis.setTickUnit(new NumberTickUnit(1.0));
        yAxis.setRange(0.0, 2.0);
      }

      StandardXYItemRenderer renderer;
      // long dataCount = (end - start) / minTsInterval;
      // if (dataCount <= width) {
      //	renderer = new StandardXYItemRenderer(StandardXYItemRenderer.LINES +
      // StandardXYItemRenderer.SHAPES);
      // } else {
      //	renderer = new StandardXYItemRenderer(StandardXYItemRenderer.LINES);
      // }
      if (isLine && isShape) {
        renderer =
            new StandardXYItemRenderer(
                StandardXYItemRenderer.LINES + StandardXYItemRenderer.SHAPES);
      } else if (isLine && !isShape) {
        renderer = new StandardXYItemRenderer(StandardXYItemRenderer.LINES);
      } else if (!isLine && isShape) {
        renderer = new StandardXYItemRenderer(StandardXYItemRenderer.SHAPES);
      } else {
        renderer = new StandardXYItemRenderer(StandardXYItemRenderer.LINES);
      }
      // renderer.setShapesFilled(true);

      XYPlot plot = new XYPlot(xyDataset, xAxis, yAxis, renderer);
      JFreeChart chart =
          new JFreeChart(title, new Font(Font.SANS_SERIF, Font.BOLD, 12), plot, true);
      // JFreeChart chart = new JFreeChart(title, plot);
      chart.setBackgroundPaint(java.awt.Color.WHITE);
      chart.removeLegend();

      // Marker
      final Color c = new Color(255, 60, 24, 63);
      List<Range> markerRanges = getUnsharedRanges(streamOwner, streamName);

      for (Range range : markerRanges) {
        Marker marker =
            new IntervalMarker(
                range.startTimeInMillis,
                range.endTimeInMillis,
                c,
                new BasicStroke(2.0f),
                null,
                null,
                1.0f);
        plot.addDomainMarker(marker, Layer.BACKGROUND);
      }

      ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
      String filename = ServletUtilities.saveChartAsPNG(chart, width, height, info, null);

      File imageFile = new File("/tmp/" + filename);
      File toFile =
          new File(outputPath + "/" + streamName + "_" + fileFmt.print(startDate) + ".png");
      imageFile.renameTo(toFile);

      return toFile;

    } catch (ClassNotFoundException
        | IOException
        | NamingException
        | SQLException
        | UnsupportedOperationException e) {
      e.printStackTrace();
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } finally {
      if (db != null) {
        try {
          db.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    }
    return null;
  }
Exemple #20
0
  @RolesAllowed({Roles.OWNER, Roles.CONSUMER})
  @GET
  @Path("/{stream_name}.png")
  @Produces("image/png")
  @ApiOperation(value = "Retrieve the stream.", notes = GET_STREAM_NOTES)
  @ApiResponses(value = {@ApiResponse(code = 500, message = "Internal Server Error")})
  public Response doGetStreamAsPng(
      @PathParam("stream_name") final String streamName,
      @ApiParam(
              name = "stream_owner",
              value = "If null, get currently authenticated user's streams.")
          @QueryParam("stream_owner")
          final String streamOwnerParam,
      @ApiParam(name = "start_time", value = "Expected format: YYYY-MM-DD HH:MM:SS.[SSSSS]")
          @QueryParam("start_time")
          final String startTime,
      @ApiParam(name = "end_time", value = "Expected format: YYYY-MM-DD HH:MM:SS.[SSSSS]")
          @QueryParam("end_time")
          final String endTime,
      @ApiParam(name = "filter", value = "Please refer to the above Implementation Notes.")
          @QueryParam("filter")
          final String filter,
      @ApiParam(name = "aggregator", value = "Please refer to the above Implementation Notes.")
          @QueryParam("aggregator")
          String aggregator,
      /*@ApiParam(name = "limit", value = "Default value is 100.")
      @DefaultValue("100") @QueryParam("limit") 	final int limit,
      @ApiParam(name = "offset", value = "Default value is 0.")
      @QueryParam("offset") 						final int offset,*/
      @ApiParam(name = "width", value = "Chart width in pixels. Default is 500.")
          @DefaultValue("500")
          @QueryParam("width")
          int width,
      @ApiParam(name = "height", value = "Chart width in pixels. Default is 300.")
          @DefaultValue("300")
          @QueryParam("height")
          int height)
      throws IOException {

    StreamDatabaseDriver db = null;
    String requestingUser = securityContext.getUserPrincipal().getName();
    String streamOwner = streamOwnerParam == null ? requestingUser : streamOwnerParam;

    try {
      db = DatabaseConnector.getStreamDatabase();

      boolean isData =
          db.prepareQuery(
              requestingUser,
              streamOwner,
              streamName,
              startTime,
              endTime,
              aggregator,
              filter,
              0,
              0,
              0,
              true,
              null);
      Stream stream = db.getStoredStreamInfo();

      if (!isData) {
        return Response.ok("No data").build();
      }

      if (stream.num_samples > width) {
        db.close();
        db = DatabaseConnector.getStreamDatabase();
        int skipEveryNth = (int) (stream.num_samples / width);
        isData =
            db.prepareQuery(
                requestingUser,
                streamOwner,
                streamName,
                startTime,
                endTime,
                aggregator,
                filter,
                0,
                0,
                skipEveryNth,
                true,
                null);
        stream = db.getStoredStreamInfo();

        if (!isData) {
          return Response.ok("No data").build();
        }
      }

      // Prepare data
      XYSeries[] series = null;
      long minTsInterval = Long.MAX_VALUE; // to determine whether to use marker on the plot.
      long prevTimestamp = -1;
      Object[] tuple = new Object[db.getStoredStreamInfo().channels.size() + 1];
      while (db.getNextTuple(tuple)) {
        // Init XYSeries array
        if (series == null) {
          series = new XYSeries[tuple.length - 1];
          for (int i = 0; i < series.length; i++) {
            series[i] = new XYSeries(stream.channels.get(i).name);
          }
        }

        long timestamp = ((Long) tuple[0]).longValue();
        for (int i = 1; i < tuple.length; i++) {
          try {
            series[i - 1].add(timestamp, (Number) tuple[i]);
          } catch (ClassCastException e) {
            continue;
          }
        }

        long diff = timestamp - prevTimestamp;
        if (diff > 0 && diff < minTsInterval) {
          minTsInterval = diff;
        }

        prevTimestamp = timestamp;
      }

      XYSeriesCollection xyDataset = new XYSeriesCollection();
      for (XYSeries s : series) {
        xyDataset.addSeries(s);
      }

      // Generate title string
      long start = (long) series[0].getMinX();
      long end = (long) series[0].getMaxX();
      Timestamp startTimestamp = new Timestamp(start);
      Timestamp endTimestamp = new Timestamp(end);
      String title =
          stream.owner
              + ": "
              + stream.name
              + "\n"
              + startTimestamp.toString()
              + " ~ "
              + endTimestamp.toString();

      //  Create the chart object
      ValueAxis xAxis = new DateAxis("Time");
      // NumberAxis xAxis = new NumberAxis("");
      NumberAxis yAxis = new NumberAxis("Value");
      yAxis.setAutoRangeIncludesZero(false); // override default

      StandardXYItemRenderer renderer;
      long dataCount = (end - start) / minTsInterval;
      if (dataCount <= width) {
        renderer =
            new StandardXYItemRenderer(
                StandardXYItemRenderer.LINES + StandardXYItemRenderer.SHAPES);
      } else {
        renderer = new StandardXYItemRenderer(StandardXYItemRenderer.LINES);
      }
      // renderer.setShapesFilled(true);

      XYPlot plot = new XYPlot(xyDataset, xAxis, yAxis, renderer);
      JFreeChart chart =
          new JFreeChart(title, new Font(Font.SANS_SERIF, Font.BOLD, 12), plot, true);
      // JFreeChart chart = new JFreeChart(title, plot);
      chart.setBackgroundPaint(java.awt.Color.WHITE);

      ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
      String filename = ServletUtilities.saveChartAsPNG(chart, width, height, info, session);

      File imageFile = new File("/tmp/" + filename);
      byte[] imageData = FileUtils.readFileToByteArray(imageFile);
      imageFile.delete();

      // Send non-streamed
      // return Response.ok(imageData).build();

      // Send streamed
      return Response.ok(new ByteArrayInputStream(imageData)).build();
    } catch (ClassNotFoundException
        | IOException
        | NamingException
        | SQLException
        | UnsupportedOperationException e) {
      e.printStackTrace();
      throw WebExceptionBuilder.buildInternalServerError(e);
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
      throw WebExceptionBuilder.buildBadRequest(e);
    } finally {
      if (db != null) {
        try {
          db.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    }
  }
Exemple #21
0
  @RolesAllowed({Roles.OWNER, Roles.CONSUMER})
  @GET
  @Path("/{stream_name}")
  @ApiOperation(value = "Retrieve the stream.", notes = GET_STREAM_NOTES)
  @ApiResponses(value = {@ApiResponse(code = 500, message = "Internal Server Error")})
  public Object doGetStream(
      @PathParam("stream_name") final String streamName,
      @ApiParam(
              name = "stream_owner",
              value = "If null, get currently authenticated user's streams.")
          @QueryParam("stream_owner")
          final String streamOwnerParam,
      @ApiParam(name = "start_time", value = "Expected format: YYYY-MM-DD HH:MM:SS.[SSSSS]")
          @QueryParam("start_time")
          final String startTime,
      @ApiParam(name = "end_time", value = "Expected format: YYYY-MM-DD HH:MM:SS.[SSSSS]")
          @QueryParam("end_time")
          final String endTime,
      @ApiParam(name = "filter", value = "Please refer to the above Implementation Notes.")
          @QueryParam("filter")
          final String filter,
      @ApiParam(name = "aggregator", value = "Please refer to the above Implementation Notes.")
          @QueryParam("aggregator")
          final String aggregator,
      @ApiParam(name = "limit", value = "Default value is 100.")
          @DefaultValue("100")
          @QueryParam("limit")
          final int limit,
      @ApiParam(name = "offset", value = "Default value is 0.") @QueryParam("offset")
          final int offset,
      @ApiParam(name = "http_streaming", value = "Default value is true.")
          @DefaultValue("false")
          @QueryParam("http_streaming")
          final boolean isHttpStreaming)
      throws JsonProcessingException {

    StreamDatabaseDriver db = null;
    final String requestingUser = securityContext.getUserPrincipal().getName();
    final String streamOwner = streamOwnerParam == null ? requestingUser : streamOwnerParam;
    try {
      db = DatabaseConnector.getStreamDatabase();
      if (!isHttpStreaming && limit > ROW_LIMIT_WITHOUT_HTTP_STREAMING) {
        throw WebExceptionBuilder.buildBadRequest(
            "Too mcuh data requested without HTTP streaming.");
      }

      if (!isHttpStreaming) {
        boolean isData =
            db.prepareQuery(
                requestingUser,
                streamOwner,
                streamName,
                startTime,
                endTime,
                aggregator,
                filter,
                limit,
                offset,
                0,
                false,
                null);
        String strJson = getStreamJsonPrefix(db.getStoredStreamInfo());
        if (isData) {
          Object[] tuple = db.getNextTuple();
          if (tuple != null) {
            strJson += convertTupleToJsonString(tuple);
            while ((tuple = db.getNextTuple()) != null) {
              strJson += "," + convertTupleToJsonString(tuple);
            }
          }
        }
        return strJson + "]}";
      } else {
        return new StreamingOutput() {
          @Override
          public void write(OutputStream output) throws IOException, WebApplicationException {
            StreamDatabaseDriver db = null;
            try {
              db = DatabaseConnector.getStreamDatabase();
              boolean isData =
                  db.prepareQuery(
                      requestingUser,
                      streamOwner,
                      streamName,
                      startTime,
                      endTime,
                      aggregator,
                      filter,
                      limit,
                      offset,
                      0,
                      false,
                      null);
              String strJson = getStreamJsonPrefix(db.getStoredStreamInfo());
              IOUtils.write(strJson, output);
              if (isData) {
                Object[] tuple = db.getNextTuple();
                if (tuple != null) {
                  IOUtils.write(convertTupleToJsonString(tuple), output);
                  while ((tuple = db.getNextTuple()) != null) {
                    IOUtils.write("," + convertTupleToJsonString(tuple), output);
                  }
                }
              }
              IOUtils.write("]}", output);
            } catch (SQLException
                | ClassNotFoundException
                | NamingException
                | UnsupportedOperationException e) {
              e.printStackTrace();
              throw WebExceptionBuilder.buildInternalServerError(e);
            } catch (IllegalArgumentException e) {
              e.printStackTrace();
              throw WebExceptionBuilder.buildBadRequest(e);
            } finally {
              if (db != null) {
                try {
                  db.close();
                } catch (SQLException e) {
                  e.printStackTrace();
                }
              }
            }
          }
        };
      }
    } catch (ClassNotFoundException
        | IOException
        | NamingException
        | SQLException
        | UnsupportedOperationException e) {
      e.printStackTrace();
      throw WebExceptionBuilder.buildInternalServerError(e);
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
      throw WebExceptionBuilder.buildBadRequest(e);
    } finally {
      if (db != null) {
        try {
          db.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    }
  }