@SuppressWarnings("finally")
  public JSONObject getKeyWords(JSONObject semiData) {
    JSONObject keyWords = new JSONObject();

    try {
      this.buildIndex(semiData);
      this.getIndexInfo(this.indexDir, 4);
      this.generateWekaFile(this.termList, this.maxDocNum, this.wekaFile);
      JSONArray array = this.Cluster(this.wekaFile, 7);
      int totalNum = 0;
      for (int i = 0; i < array.length(); i++) {
        totalNum += array.getJSONArray(i).length();
      }
      keyWords.put("maxFreq", this.maxFreq);
      keyWords.put("totalNum", totalNum);
      keyWords.put("WordList", array);
    } catch (WeiboException e) {
      System.out.print("getKeyWords++++++weibo\n");
      System.out.print("error:" + e.getError() + "toString:" + e.toString());
      keyWords.put("error", e.getError());
      e.printStackTrace();
    } catch (Exception e) {
      System.out.print("getKeyWords++++++Exception");
      keyWords.put("error", e.toString());
      e.printStackTrace();
    } finally {
      try {
        this.myDelete(this.indexDir);
        this.myDelete(this.wekaFile);
      } catch (Exception e) {
        e.printStackTrace();
      }
      return keyWords;
    }
  }
Beispiel #2
0
 public static void main(String[] args) {
   try {
     getConnectionParameters(args);
     getInputParameters(args);
     if (help) {
       printUsage();
       return;
     }
     connect();
     displayStats();
   } catch (IllegalArgumentException e) {
     System.out.println(e.getMessage());
     printUsage();
   } catch (SOAPFaultException sfe) {
     printSoapFaultException(sfe);
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     try {
       disconnect();
     } catch (SOAPFaultException sfe) {
       printSoapFaultException(sfe);
     } catch (Exception e) {
       System.out.println("Failed to disconnect - " + e.getMessage());
       e.printStackTrace();
     }
   }
 }
Beispiel #3
0
 public static boolean download(
     URL url, String file, int prefix, int totalFilesize, IProgressUpdater updater) {
   File fFile = new File(new File(file).getParentFile().getPath());
   if (!fFile.exists()) fFile.mkdirs();
   boolean downloaded = true;
   BufferedInputStream in = null;
   FileOutputStream out = null;
   BufferedOutputStream bout = null;
   try {
     int count;
     int totalCount = 0;
     byte data[] = new byte[BUFFER];
     in = new BufferedInputStream(url.openStream());
     out = new FileOutputStream(file);
     bout = new BufferedOutputStream(out);
     while ((count = in.read(data, 0, BUFFER)) != -1) {
       bout.write(data, 0, count);
       totalCount += count;
       if (updater != null) updater.update(prefix + totalCount, totalFilesize);
     }
   } catch (Exception e) {
     e.printStackTrace();
     Utils.logger.log(Level.SEVERE, "Download error!");
     downloaded = false;
   } finally {
     try {
       close(in);
       close(bout);
       close(out);
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return downloaded;
 }
  @Test
  public void checkHappyPathStreamStoreOperations() {

    try {
      cassandraConnector.saveStreamDefinitionToStore(getCluster(), streamDefinition1);
    } catch (StreamDefinitionStoreException e) {
      e.printStackTrace();
      fail();
    }

    StreamDefinition streamDefinitionFromStore = null;
    try {
      Credentials credentials = getCredentials(cluster);
      streamDefinitionFromStore =
          cassandraConnector.getStreamDefinitionFromCassandra(
              getCluster(), streamDefinition1.getStreamId());
    } catch (Exception e) {
      e.printStackTrace();
      fail();
    }
    assertEquals(streamDefinition1, streamDefinitionFromStore);
    List<Event> eventList =
        EventConverterUtils.convertFromJson(
            CassandraTestConstants.properEvent, streamDefinition1.getStreamId());
    try {
      int eventCounter = 0;
      for (Event event : eventList) {
        insertEvent(cluster, event, eventCounter++);
      }
    } catch (Exception e) {
      e.printStackTrace();
      fail();
    }
  }
Beispiel #5
0
 public static void setEnv(Map<String, String> newenv) {
   try {
     Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
     Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
     theEnvironmentField.setAccessible(true);
     Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null);
     env.putAll(newenv);
     Field theCaseInsensitiveEnvironmentField =
         processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment");
     theCaseInsensitiveEnvironmentField.setAccessible(true);
     Map<String, String> cienv =
         (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
     cienv.putAll(newenv);
   } catch (NoSuchFieldException e) {
     try {
       Class[] classes = Collections.class.getDeclaredClasses();
       Map<String, String> env = System.getenv();
       for (Class cl : classes) {
         if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
           Field field = cl.getDeclaredField("m");
           field.setAccessible(true);
           Object obj = field.get(env);
           Map<String, String> map = (Map<String, String>) obj;
           map.clear();
           map.putAll(newenv);
         }
       }
     } catch (Exception e2) {
       e2.printStackTrace();
     }
   } catch (Exception e1) {
     e1.printStackTrace();
   }
 }
Beispiel #6
0
 /**
  * Method toMyString:
  *
  * @param verboseflag sets whether we want to list the results info inside the XML or not at all.
  * @return the XML String representing this requested Query Definition XML fields
  */
 public String toMyString(boolean verboseflag) {
   StringWriter outStringWriter = new StringWriter();
   WstxOutputFactory fout = new WstxOutputFactory();
   fout.configureForXmlConformance();
   SMOutputDocument doc = null;
   try {
     // output
     XMLStreamWriter2 sw = (XMLStreamWriter2) fout.createXMLStreamWriter(outStringWriter);
     doc = SMOutputFactory.createOutputDocument(sw, "1.0", "UTF-8", true);
     doc.setIndentation("\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", 2, 1);
     createInfoInDocument(doc, null, verboseflag);
     doc.closeRoot();
   } catch (Exception e) {
     e.printStackTrace();
     return "Errors encountered while attempting to print this Query Definition!";
   }
   String retString = "";
   try {
     retString = outStringWriter.toString();
     outStringWriter.close();
   } catch (Exception e) {
     logger.error("Errors encountered while attempting to print this XML document!");
     e.printStackTrace();
   }
   return retString;
   //           StructuredTextDocument document = (StructuredTextDocument)
   // StructuredDocumentFactory.newStructuredDocument(new MimeMediaType("text/xml"),
   // IndexOfQueries.getQueryDefTag());
 }
Beispiel #7
0
 public static void main(String[] args) {
   try {
     getConnectionParameters(args);
     if (help) {
       printUsage();
       return;
     }
     long bTime = System.currentTimeMillis();
     connect();
     printHostProductDetails();
     long eTime = System.currentTimeMillis();
     System.out.println("Total time in milli secs to get the product line id: " + (eTime - bTime));
   } catch (IllegalArgumentException e) {
     System.out.println(e.getMessage());
     printUsage();
   } catch (SOAPFaultException sfe) {
     printSoapFaultException(sfe);
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     try {
       disconnect();
     } catch (SOAPFaultException sfe) {
       printSoapFaultException(sfe);
     } catch (Exception e) {
       System.out.println("Failed to disconnect - " + e.getMessage());
       e.printStackTrace();
     }
   }
 }
 /**
  * invoke as: <CODE>
  * java -cp &lt;classpath&gt; parallel.distributed.PDBTExecSingleCltWrkInitSrv [workers_port(7890)] [client_port(7891)]
  * </CODE>
  *
  * @param args String[]
  */
 public static void main(String[] args) {
   int wport = 7890; // default port
   int cport = 7891;
   if (args.length > 0) {
     try {
       wport = Integer.parseInt(args[0]);
     } catch (Exception e) {
       e.printStackTrace();
       usage();
       System.exit(-1);
     }
     if (args.length > 1) {
       try {
         cport = Integer.parseInt(args[1]);
       } catch (Exception e) {
         e.printStackTrace();
         usage();
         System.exit(-1);
       }
     }
   }
   PDBTExecSingleCltWrkInitSrv server = new PDBTExecSingleCltWrkInitSrv(wport, cport);
   try {
     server.run();
   } catch (Exception e) {
     e.printStackTrace();
     System.err.println("Server exits due to exception.");
   }
 }
  /**
   * @param args arg[0] - URL of the Virtual Center Server / ESX host https://<Server host name /
   *     ip>/sdk arg[1] - User name arg[2] - Password arg[3] - One of vminfo, hostvminfo, or vmmor
   *     arg[4] - If vmmor is arg[3], then vmname argument is mandatory
   */
  public static void main(String[] args) {
    // This is to accept all SSL certifcates by default.
    System.setProperty(
        "org.apache.axis.components.net.SecureSocketFactory",
        "org.apache.axis.components.net.SunFakeTrustSocketFactory");
    if (args.length < 3) {
      printUsage();
    } else {
      try {
        /**
         * ****************************** ******************************* ** *** ** Your code goes
         * here *** ** (fill-in 1 of 1) *** ** *** *******************************
         * *******************************
         */
        VIM_HOST = args[0];
        USER_NAME = args[1];
        PASSWORD = args[2];
        initAll();
        System.out.println("***************************************************************");

        long st = System.currentTimeMillis();
        getVMInfo();
        long et = System.currentTimeMillis();
        System.out.println(
            "\nTotal time (msec) to retrieve the properties of all VMs in one call: " + (et - st));
        System.out.println("\n***************************************************************");
        System.out.println("\n***************************************************************");
        st = System.currentTimeMillis();
        initVMMorList();
        Iterator<ManagedObjectReference> iter = VM_MOR_LIST.iterator();
        StringBuilder sb = new StringBuilder();
        String name = "name";
        String powerState = "runtime.powerState";
        while (iter.hasNext()) {
          ManagedObjectReference vmMor = iter.next();
          String vmName = (String) getVMProperty(vmMor, name);
          sb.append(vmName);
          VirtualMachinePowerState vmPs =
              (VirtualMachinePowerState) getVMProperty(vmMor, powerState);
          sb.append(" : ");
          sb.append(vmPs);
          sb.append("\n");
        }
        et = System.currentTimeMillis();
        System.out.println(sb.toString());
        System.out.println(
            "\nTotal time (msec) to retrieve the properties of all VMs individually: " + (et - st));
        System.out.println("\n***************************************************************");
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        try {
          disconnect();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
  }
  public void handleCustomPayload(Packet250CustomPayload par1Packet250CustomPayload) {
    if ("MC|BEdit".equals(par1Packet250CustomPayload.channel)) {
      try {
        DataInputStream datainputstream =
            new DataInputStream(new ByteArrayInputStream(par1Packet250CustomPayload.data));
        ItemStack itemstack = Packet.readItemStack(datainputstream);

        if (!ItemWritableBook.validBookTagPages(itemstack.getTagCompound())) {
          throw new IOException("Invalid book tag!");
        }

        ItemStack itemstack2 = playerEntity.inventory.getCurrentItem();

        if (itemstack != null
            && itemstack.itemID == Item.writableBook.shiftedIndex
            && itemstack.itemID == itemstack2.itemID) {
          itemstack2.setTagCompound(itemstack.getTagCompound());
        }
      } catch (Exception exception) {
        exception.printStackTrace();
      }
    } else if ("MC|BSign".equals(par1Packet250CustomPayload.channel)) {
      try {
        DataInputStream datainputstream1 =
            new DataInputStream(new ByteArrayInputStream(par1Packet250CustomPayload.data));
        ItemStack itemstack1 = Packet.readItemStack(datainputstream1);

        if (!ItemEditableBook.validBookTagContents(itemstack1.getTagCompound())) {
          throw new IOException("Invalid book tag!");
        }

        ItemStack itemstack3 = playerEntity.inventory.getCurrentItem();

        if (itemstack1 != null
            && itemstack1.itemID == Item.writtenBook.shiftedIndex
            && itemstack3.itemID == Item.writableBook.shiftedIndex) {
          itemstack3.setTagCompound(itemstack1.getTagCompound());
          itemstack3.itemID = Item.writtenBook.shiftedIndex;
        }
      } catch (Exception exception1) {
        exception1.printStackTrace();
      }
    } else if ("MC|TrSel".equals(par1Packet250CustomPayload.channel)) {
      try {
        DataInputStream datainputstream2 =
            new DataInputStream(new ByteArrayInputStream(par1Packet250CustomPayload.data));
        int i = datainputstream2.readInt();
        Container container = playerEntity.craftingInventory;

        if (container instanceof ContainerMerchant) {
          ((ContainerMerchant) container).setCurrentRecipeIndex(i);
        }
      } catch (Exception exception2) {
        exception2.printStackTrace();
      }
    } else {
      ModLoader.serverCustomPayload(this, par1Packet250CustomPayload);
    }
  }
  @SuppressWarnings("unchecked")
  public void dumpCoverageAndConceptVectorAll(
      String fileEntityMI, String fileEntityEntropy, String fileEntityFreq, String fileCoverage) {
    BufferedWriter bwFileCoverage;

    HashMap<String, Double> entityMIMap = new GetEntityMI().getEntityMI(fileEntityMI);

    HashMap<String, Double> entityEntropyMap = new GetEntityMI().getEntityMI(fileEntityEntropy);

    HashMap<String, Double> entityFreqMap = new GetEntityFreq().getEntityFreq(fileEntityFreq);
    if (entityMIMap == null) {
      try {
        bwFileCoverage = new BufferedWriter(new FileWriter(fileCoverage));
        bwFileCoverage.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
      return;
    }

    conceptCoverageMap = new HashMap<>();
    Vector<Integer> conceptList = new Vector<>();

    try {
      for (Integer id : ProbaseData.conceptEntitySetMap.keySet()) {
        double coverage =
            getConceptCoverage(
                ProbaseData.idTermMap.get(id), entityMIMap, entityEntropyMap, entityFreqMap);
        if (coverage != 0) {
          conceptCoverageMap.put(id, coverage);
          conceptList.add(id);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");
    Collections.sort(conceptList, new cmp());
    try {
      bwFileCoverage = new BufferedWriter(new FileWriter(fileCoverage));

      for (Integer id : conceptList) {
        bwFileCoverage.write(
            String.valueOf(id)
                + "\t"
                + ProbaseData.idTermMap.get(id)
                + "\t"
                + String.valueOf(conceptCoverageMap.get(id)));
        bwFileCoverage.newLine();
        bwFileCoverage.flush();
      }
      bwFileCoverage.flush();
      bwFileCoverage.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /**
   * Si está habilitada la actualización de la persona mediante el componente de persona del MINSA
   * se actualizan municipio, comunidad y dirección de residencia
   *
   * @param municipioResidencia nuevo municipio
   * @param comunidadResidencia nueva comunidad
   * @param direccionResidencia nueva dirección
   * @param personaId persona a actualizar
   * @param idNotificacion de la persona
   * @param request con datos de autenticación
   * @return resultado de la acción
   * @throws Exception
   */
  @RequestMapping(
      value = "updatePerson",
      method = RequestMethod.GET,
      consumes = MediaType.APPLICATION_JSON_VALUE)
  public ResponseEntity<String> updatePerson(
      @RequestParam(value = "municipioResidencia", required = false) String municipioResidencia,
      @RequestParam(value = "comunidadResidencia", required = false) String comunidadResidencia,
      @RequestParam(value = "direccionResidencia", required = false) String direccionResidencia,
      @RequestParam(value = "personaId", required = false) Integer personaId,
      @RequestParam(value = "idNotificacion", required = false) String idNotificacion,
      HttpServletRequest request)
      throws Exception {

    logger.debug("Actualizando datos persona");
    SisPersona pers = new SisPersona();
    InfoResultado infoResultado;
    if (personaId != null) {
      pers = personaService.getPersona(personaId);
      pers.setMunicipioResidencia(
          divisionPoliticaService.getDivisionPolitiacaByCodNacional(municipioResidencia));
      pers.setComunidadResidencia(comunidadesService.getComunidad(comunidadResidencia));
      pers.setDireccionResidencia(direccionResidencia);
      if (ConstantsSecurity.ENABLE_PERSON_COMPONENT) {
        Persona persona = personaService.ensamblarObjetoPersona(pers);
        try {
          personaService.iniciarTransaccion();

          infoResultado =
              personaService.guardarPersona(
                  persona, seguridadService.obtenerNombreUsuario(request));
          if (infoResultado.isOk() && infoResultado.getObjeto() != null) {
            updateNotificacion(idNotificacion, pers);
          } else
            throw new Exception(
                infoResultado.getMensaje() + "----" + infoResultado.getMensajeDetalle());
          personaService.commitTransaccion();
        } catch (Exception ex) {
          logger.error(ex.getMessage(), ex);
          ex.printStackTrace();
          try {
            personaService.rollbackTransaccion();
          } catch (Exception e) {
            e.printStackTrace();
          }
          throw new Exception(ex);
        } finally {
          try {
            personaService.remover();
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      } else {
        updateNotificacion(idNotificacion, pers);
      }
    }
    return createJsonResponse(pers);
  }
Beispiel #13
0
  public static void main(String args[]) throws Exception {
    int count = 0;
    ServerSocket serv = null;
    InputStream in = null;
    OutputStream out = null;
    Socket sock = null;
    int clientId = 0;
    Map<Integer, Integer> totals = new HashMap<Integer, Integer>();

    try {
      serv = new ServerSocket(8888);
    } catch (Exception e) {
      e.printStackTrace();
    }
    while (serv.isBound() && !serv.isClosed()) {
      System.out.println("Ready...");
      try {
        sock = serv.accept();
        in = sock.getInputStream();
        out = sock.getOutputStream();

        char c = (char) in.read();

        System.out.print("Server received " + c);
        switch (c) {
          case 'r':
            clientId = in.read();
            totals.put(clientId, 0);
            out.write(0);
            break;
          case 't':
            clientId = in.read();
            int x = in.read();
            System.out.print(" for client " + clientId + " " + x);
            Integer total = totals.get(clientId);
            if (total == null) {
              total = 0;
            }
            totals.put(clientId, total + x);
            out.write(totals.get(clientId));
            break;
          default:
            int x2 = in.read();
            int y = in.read();
            System.out.print(" " + x2 + " " + y);
            out.write(x2 + y);
        }
        System.out.println("");
        out.flush();
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        if (out != null) out.close();
        if (in != null) in.close();
        if (sock != null) sock.close();
      }
    }
  }
Beispiel #14
0
  /**
   * Helper method for running yaml workflows using an instance of WorkflowRunner.
   *
   * @param yamlFile The workflow yaml file
   * @param workflow Workflow definition object
   * @param settings A map of the settings provided as input to the runner
   * @return json containing the id of this run
   */
  private static ObjectNode runYamlWorkflow(
      String yamlFile, Workflow workflow, Map<String, Object> settings) {
    InputStream yamlStream = null;
    try {
      yamlStream = loadYamlStream(yamlFile);
    } catch (Exception e) {
      throw new RuntimeException("Could not load workflow from yaml file.", e);
    }

    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    ByteArrayOutputStream errStream = new ByteArrayOutputStream();

    // This instance of runnable will be executed at the end of a workflow run
    AsyncWorkflowRunnable runnable = new AsyncWorkflowRunnable();

    try {

      // Get jython home and path variables from application.conf and set them in workflow runner
      // global config
      String jythonPath = ConfigFactory.defaultApplication().getString("jython.packages");
      String jythonHome = ConfigFactory.defaultApplication().getString("jython.home");

      Map<String, Object> config = new HashMap<String, Object>();
      config.put("jython_home", jythonHome);
      config.put("jython_path", jythonPath);

      // Initialize and run the yaml workflow
      WorkflowRunner runner =
          new YamlStreamWorkflowRunner().yamlStream(yamlStream).configure(config);

      runnable.init(workflow, runner, errStream, outStream);

      runner
          .apply(settings)
          .outputStream(new PrintStream(outStream))
          .errorStream(new PrintStream(errStream))
          .runAsync(runnable);
    } catch (Exception e) {
      e.printStackTrace();

      // Log exceptions as part of the workflow error log
      StringWriter writer = new StringWriter();
      e.printStackTrace(new PrintWriter(writer));

      String errorText = writer.toString();
      String outputText = new String(outStream.toByteArray());

      runnable.error(errorText, outputText);
    }

    // The response json contains the workflow run id for later reference
    ObjectNode response = Json.newObject();

    WorkflowRun run = runnable.getWorkflowRun();
    response.put("runId", run.id);

    return response;
  }
 private Connection getSOLIDConnection() {
   try {
     Class.forName("solid.jdbc.SolidDriver");
     return DriverManager.getConnection("jdbc:solid://nms-clienttest1:1313/dba/dba", "dba", "dba");
   } catch (Exception e) {
     e.printStackTrace();
     return null;
   }
 }
 private Connection getTIMESTENConnection() {
   try {
     Class.forName("com.timesten.jdbc.TimesTenDriver");
     return DriverManager.getConnection("jdbc:timesten:direct:WebNmsDB", "root", null);
   } catch (Exception e) {
     e.printStackTrace();
     return null;
   }
 }
 private Connection getMYSQLConnection() {
   try {
     Class.forName("org.gjt.mm.mysql.Driver");
     return DriverManager.getConnection("jdbc:mysql://localhost/WebNmsDB", "root", null);
   } catch (Exception e) {
     e.printStackTrace();
     return null;
   }
 }
 private Connection getSYBASEConnection() {
   try {
     Class.forName("com.sybase.jdbc2.jdbc.SybDriver");
     return DriverManager.getConnection("jdbc:sybase:Tds:fe-test:2048/feDB", "sa", null);
   } catch (Exception e) {
     e.printStackTrace();
     return null;
   }
 }
Beispiel #19
0
 public static void tests() {
   System.err.println("HEY!");
   Mat p0 = Mat.encodePoint(0, 0);
   Mat p1 = Mat.encodePoint(1, .1);
   Mat p2 = Mat.encodePoint(.1, 1);
   Mat p3 = Mat.encodePoint(-1, -.1);
   Mat p4 = Mat.encodePoint(-.1, -1);
   Mat p5 = Mat.encodePoint(0.0001, 0);
   Mat p6 = Mat.encodePoint(-0.0001, 0);
   if (!lineSegIntersect(p1, p3, p2, p4)) {
     try {
       throw new Exception();
     } catch (Exception e) {
       e.printStackTrace();
       System.err.println("hey there");
       System.exit(1);
     }
   }
   if (lineSegIntersect(p1, p4, p2, p3)) {
     try {
       throw new Exception();
     } catch (Exception e) {
       e.printStackTrace();
       System.err.println("hey there");
       System.exit(1);
     }
   }
   if (lineSegIntersect(p1, p5, p2, p4)) {
     try {
       throw new Exception();
     } catch (Exception e) {
       e.printStackTrace();
       System.err.println("hey there");
       System.exit(1);
     }
   }
   if (!lineSegIntersect(p1, p6, p2, p4)) {
     try {
       throw new Exception();
     } catch (Exception e) {
       e.printStackTrace();
       System.err.println("hey there");
       System.exit(1);
     }
   }
   Mat inter = lineSegIntersection(p1, p3, p2, p4);
   if (inter.data[0][0] != 0 || inter.data[1][0] != 0) {
     try {
       throw new Exception();
     } catch (Exception e) {
       e.printStackTrace();
       System.err.println("hey there");
       System.exit(1);
     }
   }
 }
Beispiel #20
0
 private static void monitor() {
   long nowInMillis;
   long dailyTimeStampInMillis;
   init();
   String subject = "HTTP Uptime monitor started: " + remoteHost + ".";
   String message = "Monitoring from " + Server.getHostName() + Names.NEW_LINE;
   message += "URL: " + url + Names.NEW_LINE;
   message += "remote host: " + remoteHost + Names.NEW_LINE;
   message += "local down command:" + downCommand + " " + remoteHost + Names.NEW_LINE;
   message += "local up command:" + upCommand + " " + remoteHost + Names.NEW_LINE;
   try {
     EMail.send(FROM, mailTo, subject, message, smtpHost);
   } catch (Exception e) {
     e.printStackTrace();
   }
   dailyTimeStamp = getToday();
   dailyTimeStampInMillis = dailyTimeStamp.getTimeInMillis();
   int year, month, day;
   year = dailyTimeStamp.get(Calendar.YEAR);
   month = dailyTimeStamp.get(Calendar.MONTH);
   day = dailyTimeStamp.get(Calendar.DAY_OF_MONTH);
   dailyTimeStamp = new GregorianCalendar(year, month, day, 5, 0, 0);
   Calendar currentTimeStamp;
   int i = 0;
   while (true) {
     i++;
     try {
       int code = getResponseCode();
       for (int x = 0; x < (i % 8); x++) System.out.print(".");
       {
       } // System.out.println("Http Response=" + HTTPCodes[code] + "[" +code + "] for " + url);
       if (code < 200 || code > 204) restartServer(code);
     } catch (Exception e) {
       e.printStackTrace();
       restartServer(601);
     }
     Sleep.sleep(POLLING_INTERVAL * 1000);
     currentTimeStamp = new GregorianCalendar();
     nowInMillis = currentTimeStamp.getTimeInMillis();
     if (nowInMillis > (dailyTimeStampInMillis + (1000 * 60 * 60 * 24))) {
       dailyTimeStamp = getToday();
       dailyTimeStampInMillis = dailyTimeStamp.getTimeInMillis();
       subject = "HTTP Uptime monitor running: " + remoteHost + ".";
       message = "Monitoring from " + Server.getHostName() + Names.NEW_LINE;
       message += "URL: " + url + Names.NEW_LINE;
       message += "remote host: " + remoteHost + Names.NEW_LINE;
       message += "local down command:" + downCommand + " " + remoteHost + Names.NEW_LINE;
       message += "local up command:" + upCommand + " " + remoteHost + Names.NEW_LINE;
       try {
         EMail.send(FROM, mailTo, subject, message, smtpHost);
       } catch (Exception e) {
         e.printStackTrace();
       }
     }
   }
 }
  private void executeTestCase004() {

    try {
      System.out.println("Properties " + dbxmlutil.getAllAttributes("test", "Network Database"));
    } catch (Exception es) {
      // return new OperationResult(userName,"Failed", "Failed", es.toString());
      // es.printStackTrace();
      es.printStackTrace();
    }
  }
  private void executeTestCase034() {
    try {
      System.out.println(
          "Properties "
              + dbxmlutil.getNodeAttributes("Network Database", "root", "Network Database"));

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public static void main(String args[]) {
    boolean debug = true;

    // Parse command-line arguments
    try {
      for (int i = 0; i < args.length; i++) {
        if (args[i].equals("-help")) {
          System.out.println("Usage: java Mesh <filename>");
          System.out.println("   or: java Mesh <shape> [uSize vSize]");
          System.out.println(" where <shape> is one of:");
          System.out.println(" -ellipsoid  -torus");
          System.exit(0);
        } else if (args[i].equals("-nodebug")) {
          debug = false;
        } else if (args[i].charAt(0) == '-') {
          // Primitive
          String primName = args[i].substring(1);

          int uSize = 24, vSize = 24;

          // Check for u/v
          if (args.length >= i + 3) {
            uSize = (new Integer(args[i + 1])).intValue();
            vSize = (new Integer(args[i + 2])).intValue();
            i += 2;
          }

          // Create primitive
          if (primName.equals("ellipsoid")) {
            shape = new Ellipsoid(uSize, vSize);
          } else if (primName.equals("torus")) {
            shape = new Torus(uSize, vSize);
          } else {
            throw new Exception("Unknown primitive: " + primName);
          }
        } else {
          // Filename
          shape = new PolyMesh(args[i]);
        }
      }
      if (shape == null) throw new Exception("No shape specified.");
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("Error: " + e.getMessage());
      System.exit(1);
    }

    // Create main window
    try {
      Mesh m = new Mesh(debug);
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }
  }
Beispiel #24
0
  public Cedars(String args[]) throws ArchiveException, IOException, HoneycombTestException {

    verbose = false;

    parseArgs(args);
    initHCClient(host);

    // generate lists of random sizes around 30M and 3M
    // sort ascending to allow continuous expansion
    try {
      initRandom();
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }
    sizes = new long[n_files];
    for (int i = 0; i < sizes.length; i++) {
      sizes[i] = MIN_SIZE + (long) (rand.nextDouble() * (double) RANGE);
    }
    Arrays.sort(sizes);

    sizes2 = new long[n_files];
    for (int i = 0; i < sizes2.length; i++) {
      sizes2[i] = MIN_SIZE2 + (long) (rand.nextDouble() * (double) RANGE2);
    }
    Arrays.sort(sizes2);

    sizes3 = new long[n_files];
    for (int i = 0; i < sizes3.length; i++) {
      sizes3[i] = MIN_SIZE3 + (long) (rand.nextDouble() * (double) RANGE3);
    }
    Arrays.sort(sizes3);

    oids = new String[n_files];
    Arrays.fill(oids, null);
    shas = new String[n_files];
    Arrays.fill(shas, null);

    if (out_file != null) {
      try {
        String host = clnthost;
        fo = new FileWriter(out_file, true); // append=true
        flog("#S Cedars [" + host + "] " + new Date() + "\n");
      } catch (Exception e) {
        System.err.println("Opening " + out_file);
        e.printStackTrace();
        System.exit(1);
      }
    }
    Runtime.getRuntime().addShutdownHook(new Thread(new Shutdown(), "Shutdown"));
    doIt();

    done = true;
  }
  /**
   * convert Map to PrivacyLevelObjectKeyFilter.
   *
   * @param record the Map containing the data to convert to the object, not including the root
   * @return PrivacyLevelObjectKeyFilter the converted object
   */
  public static PrivacyLevelObjectKeyFilter getFilter(Map record) {
    Object[] list = null;
    Object obj = null;
    if (record == null) return null;
    PrivacyLevelObjectKeyFilter out = new PrivacyLevelObjectKeyFilter();

    Map LevelMap = (Map) record.get("Level");
    Boolean LevelFetch = DataHelper.getFetch(LevelMap);
    Boolean LevelSortDir = DataHelper.getSortDirection(LevelMap);
    Integer LevelSortOrder = DataHelper.getSortOrder(LevelMap);
    if (LevelFetch != null) out.setLevelFetch(LevelFetch);
    if (LevelSortDir != null) out.setLevelSortDirection(LevelSortDir);
    if (LevelSortOrder != null) out.setLevelSortOrder(LevelSortOrder);

    Filter[] LevelFilter = DataHelper.mapToFilterArray(LevelMap, Integer.class);
    if (LevelFilter != null) {
      IntegerFilter[] LevelFilters = new IntegerFilter[LevelFilter.length];
      for (int i = 0; i < LevelFilters.length; i++) {
        LevelFilters[i] = (IntegerFilter) LevelFilter[i];
      }
      try {
        out.setLevelFilter(LevelFilters);
      } catch (Exception x) {
        x.printStackTrace();
      }
    }

    Map LanguageCodeMap = (Map) record.get("LanguageCode");
    Boolean LanguageCodeFetch = DataHelper.getFetch(LanguageCodeMap);
    Boolean LanguageCodeSortDir = DataHelper.getSortDirection(LanguageCodeMap);
    Integer LanguageCodeSortOrder = DataHelper.getSortOrder(LanguageCodeMap);
    if (LanguageCodeFetch != null) out.setLanguageCodeFetch(LanguageCodeFetch);
    if (LanguageCodeSortDir != null) out.setLanguageCodeSortDirection(LanguageCodeSortDir);
    if (LanguageCodeSortOrder != null) out.setLanguageCodeSortOrder(LanguageCodeSortOrder);

    Filter[] LanguageCodeFilter = DataHelper.mapToFilterArray(LanguageCodeMap, Integer.class);
    if (LanguageCodeFilter != null) {
      IntegerFilter[] LanguageCodeFilters = new IntegerFilter[LanguageCodeFilter.length];
      for (int i = 0; i < LanguageCodeFilters.length; i++) {
        LanguageCodeFilters[i] = (IntegerFilter) LanguageCodeFilter[i];
      }
      try {
        out.setLanguageCodeFilter(LanguageCodeFilters);
      } catch (Exception x) {
        x.printStackTrace();
      }
    }

    Boolean Fetch = DataHelper.getFetch(record);
    if (Fetch != null) out.setFetch(Fetch);
    Integer Index = DataHelper.getIndex(record);
    if (Index != null) out.setIndex(Index);
    return out;
  }
  private Connection getORACLEConnection() {
    try {

      Class.forName("oracle.jdbc.driver.OracleDriver");
      return DriverManager.getConnection(
          "jdbc:oracle:thin:@kernel-win:1521:oracle", "BFW3", "BFW3");
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
Beispiel #27
0
	protected void recalcV(Sign tl, int pos, Node destination, boolean light, int Ktl)
	{
		/* The calculation of the V values in TC-3 */
		float newVvalue;
		float tempSumGreen=0, tempSumRed=0;
		float V;
		int[] amount = count(tl, pos, destination);
		int tlId = tl.getId();
		int desId = destination.getId();
		float total = (float) amount[green_index] + (float) amount[red_index];

		newVvalue = va_table[tl.getId()][pos][destination.getId()];
		
		CountEntry currentsituation_green = new CountEntry (tl, pos, destination, green, tl, pos, Ktl);
		CountEntry currentsituation_red = new CountEntry (tl, pos, destination, red, tl, pos, Ktl);
		
		Enumeration e = pKtl_table[tlId][pos][desId].elements();
		
		while(e.hasMoreElements()) {
			//Green part
			PKtlEntry P = (PKtlEntry) e.nextElement();
			
			if(P.sameSourceKtl(currentsituation_green) != -1) {
				try {				
					V = v_table[P.tl_new.getId()][P.pos_new][destination.getId()];
					tempSumGreen += P.getValue() *gamma * V;
				}
				catch (Exception excep) {
					System.out.println(excep+"");
					excep.printStackTrace();
				}
			}
			//Red Part
			if(P.sameSourceKtl(currentsituation_red) != -1) {
				try {				
					V = v_table[P.tl_new.getId()][P.pos_new][destination.getId()];
					tempSumRed += P.getValue() *gamma * V;
				}
				catch (Exception excep) {
					System.out.println("ERROR in recalc V2");
					System.out.println(excep+"");
					excep.printStackTrace();
				}
			}
		}
		
		newVvalue += ((float)amount[green_index]/ (float)total) * tempSumGreen + ((float)amount[red_index]/ (float)total) * tempSumRed;
		try {
			v_table[tl.getId()][pos][destination.getId()] = newVvalue;
		}
		catch (Exception excep) {
			System.out.println("Error in v");
		}
	}
Beispiel #28
0
  public void run() {
    Controller controller = Controller.getController();
    try {
      String ST_OPENING_FILE = controller.getMsgString("ST_OPENING_FILE");
      controller.setStatusMessage(ST_OPENING_FILE);
      try {
        Thread.sleep(10);
      } catch (Exception e) {
        e.printStackTrace();
      }
      controller.setWaitCursors();

      TreeGrowXMLReader xUtil = new TreeGrowXMLReader(m_FileName, true);
      controller.setEditableContributors(new Vector(xUtil.getEditableContributors()));
      xUtil.gatherContent();

      String treeString = xUtil.getTreeStructure();

      ArrayList actualNodes = new ArrayList();
      ArrayList terminalChildrenNodes = new ArrayList();
      Iterator it = xUtil.getNodeList().iterator();
      while (it.hasNext()) {
        Node node = (Node) it.next();
        if (treeString.indexOf("" + node.getId()) != -1) {
          actualNodes.add(node);
        } else {
          terminalChildrenNodes.add(node);
        }
      }
      Tree tree = xUtil.getTree();
      controller.openTreeEditor(tree);
      controller.getTree().setImages(xUtil.getImageList());
      if (prevUploadId != -1) {
        controller.setUploadId(prevUploadId);
      }
      controller.setDefaultCursors();
      controller.getTreeEditor().setToolbarEnabled();
      it = tree.getNodeList().iterator();
      while (it.hasNext()) {
        Node node = (Node) it.next();
        TreePanel.getTreePanel().setNodeComplete(node);
      }
      it = tree.getImages().iterator();
      while (it.hasNext()) {
        NodeImage img = (NodeImage) it.next();
        img.initializeThumbnail();
      }
      controller.setDownloadComplete(true);
    } catch (Exception error) {
      error.printStackTrace();
      controller.setDefaultCursors();
    }
  }
 private void executeTestCase001() {
   try {
     Vector v = dbxmlutil.getAllNodeID("root", "Events");
     if (v != null) {
       System.out.println("CATS-JCF-API-DXU-001   ---> PASSED");
     } else {
       System.out.println("CATS-JCF-API-DXU-001   ---> FAILED");
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
 private void executeTestCase028() {
   try {
     boolean movenode = dbxmlutil.moveNode("ipnet.netmap", "All", "WebNMS-Panels");
     if (movenode) {
       System.out.println("CATS-JCF-API-DXU-028   ---> PASSED");
     } else {
       System.out.println("CATS-JCF-API-DXU-028   ---> FAILED");
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }