private boolean copyAssetsToFilesystem(String assetsSrc, String des) {
   if (SQLiteDebug.isDebug) {
     Log.i(TAG, "Copy " + assetsSrc + " to " + des);
   }
   InputStream istream = null;
   OutputStream ostream = null;
   try {
     AssetManager am = context.getAssets();
     istream = am.open(assetsSrc);
     ostream = new FileOutputStream(des);
     byte[] buffer = new byte[1024 * 64];
     int length;
     while ((length = istream.read(buffer)) > 0) {
       ostream.write(buffer, 0, length);
     }
     istream.close();
     ostream.close();
   } catch (Exception e) {
     e.printStackTrace();
     try {
       if (istream != null) istream.close();
       if (ostream != null) ostream.close();
     } catch (Exception ee) {
       ee.printStackTrace();
     }
     return false;
   }
   return true;
 }
 public String getKnownShipperDetails(String locationCode, String shipperId) {
   Connection connection = null;
   CallableStatement cStmt = null;
   ResultSet rs = null;
   String Code = null;
   try {
     connection = getConnection();
     cStmt = connection.prepareCall("{? = call ETRANS_UTIL.GETKNOWNSHIPPERSTATUS(?,?,?) }");
     cStmt.setString(2, locationCode);
     cStmt.setString(3, shipperId);
     cStmt.setString(4, "OPR");
     cStmt.registerOutParameter(1, java.sql.Types.VARCHAR);
     cStmt.execute();
     Code = cStmt.getString(1);
   } catch (SQLException e) {
     e.printStackTrace();
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     try {
       ConnectionUtil.closeConnection(connection, cStmt, rs);
     } catch (Exception ex) {
       ex.printStackTrace();
     }
   }
   return Code;
 }
 @Override
 public void init(
     FlameTransformationContext pContext, Layer pLayer, XForm pXForm, double pAmount) {
   colorMap = null;
   //    renderColors = pContext.getFlameRenderer().getColorMap();
   // TODO optimize
   renderColors =
       pLayer
           .getPalette()
           .createRenderPalette(pContext.getFlameRenderer().getFlame().getWhiteLevel());
   if (inlinedImage != null) {
     try {
       colorMap = RessourceManager.getImage(inlinedImageHash, inlinedImage);
     } catch (Exception e) {
       e.printStackTrace();
     }
   } else if (imageFilename != null && imageFilename.length() > 0) {
     try {
       colorMap = RessourceManager.getImage(imageFilename);
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   if (colorMap == null) {
     colorMap = getDfltImage();
   }
   imgWidth = colorMap.getImageWidth();
   imgHeight = colorMap.getImageHeight();
 }
Ejemplo n.º 4
0
        public void onCompletion(MediaPlayer arg0) {
          // TODO Auto-generated method stub
          MmpTool.LOG_DBG("play compeletion!");

          if (mmediaplayer != null) {

            saveProgress(0);
            if (videopl.getShuffleMode(Const.FILTER_VIDEO) == Const.SHUFFLE_ON
                || videopl.getRepeatMode(Const.FILTER_VIDEO) == Const.REPEAT_NONE) {
              if (videopl.getCurrentIndex(Const.FILTER_VIDEO)
                  >= ((videopl.getFileNum(Const.FILTER_VIDEO) - 1))) {
                try {
                  isEnd = true;
                  mmediaplayer.stop();
                  mPlayStatus = VideoConst.PLAY_STATUS_END;
                  throw new Exception("End of PlayList!!!");
                } catch (Exception e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                }
              }
            }

            try {
              autoNext();
            } catch (Exception e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }

            if (mOnPBCompleteListener != null) {
              mOnPBCompleteListener.onComplete(pb);
            }
          }
        }
  @SubscribeEvent
  public void serverStopping(FEModuleServerStopEvent e) {
    try {
      votifier.shutdown();
    } catch (Exception e1) {
      FMLLog.severe("Error closing Votifier compat thread.");
      FMLLog.severe(e.toString());
      e1.printStackTrace();
    }

    try {
      log.close();
    } catch (Exception e1) {
      e1.printStackTrace();
    }

    try {
      File file = new File(moduleDir, "offlineVoteList.txt");
      if (!file.exists()) {
        file.createNewFile();
      }

      PrintWriter pw = new PrintWriter(file);
      for (VoteEvent vote : offlineList.values()) {
        pw.println(vote.toString());
      }
      pw.close();
    } catch (Exception e1) {
      e1.printStackTrace();
    }
  }
Ejemplo n.º 6
0
 public void run(String[] args) {
   String script = null;
   try {
     FileInputStream stream = new FileInputStream(new File(args[0]));
     try {
       FileChannel fc = stream.getChannel();
       MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
       script = Charset.availableCharsets().get("UTF-8").decode(bb).toString();
     } finally {
       stream.close();
     }
   } catch (Exception ex) {
     ex.printStackTrace();
     System.exit(1);
   }
   Context cx = Context.enter();
   try {
     ScriptableObject scope = cx.initStandardObjects();
     scope.putConst("language", scope, "java");
     scope.putConst("platform", scope, "android");
     scope.put("util", scope, new Util(cx, scope));
     cx.evaluateString(scope, script, args[0], 1, null);
   } catch (Error ex) {
     ex.printStackTrace();
     System.exit(1);
   } catch (Exception ex) {
     ex.printStackTrace();
     System.exit(1);
   } finally {
     Context.exit();
   }
   System.exit(0);
 }
 /**
  * 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.");
   }
 }
  @Override
  @Test
  public void executeTestCase() throws Exception {
    try {
      OpenAndroidPage.openAndroidPage();
      clickId(AppConstants.Android_phones_id);
      clickXpath(AppConstants.first_android_phone_xpath);
      try {
        if (findElementByName(AppConstants.BuyNow_button_text).isDisplayed()) {
          clickName(AppConstants.BuyNow_button_text);
          GmailLogin.gmailLogin();

        } else {
          System.out.println("Get prices button is displayed");
        }
      } catch (Exception e) {
        e.printStackTrace();
        throw (e);
      }
      sendKeysForID(AppConstants.CouponTextbox_id, AppData.CouponTextboxData);
      clickId(AppConstants.CouponApplyButton_id);
      Assert.assertTrue(
          AppVerificationChecks.CouponErrorText.equals(
              findElementById(AppConstants.CouponError_id).getText()));

    } catch (Exception e) {
      e.printStackTrace();
      takeSnapShot("D:\\takeScreenshots", "Coupon Pormpt Issue");
      throw (e);
    }
  }
Ejemplo n.º 9
0
 /**
  * Save graph line to comma separated value formatted file
  *
  * @param filename
  * @param column
  */
 public void saveAsCsv(String filename, String[] column) {
   CsvWriter csvWriter = null;
   try {
     csvWriter = new CsvWriter(filename, column);
     csvWriter.open();
     String[] value = new String[column.length];
     if (vertex != null) {
       for (int i = 0; i < vertexCount; ++i) {
         value[0] = StringUtil.format(vertex[i * 3]);
         value[1] = StringUtil.format(vertex[i * 3 + 1]);
         csvWriter.writeLine(value);
       }
     }
     csvWriter.close();
     Console.getInstance().println(vertexCount + " records saved to " + filename);
   } catch (Exception e) {
     e.printStackTrace();
     if (csvWriter != null) {
       try {
         csvWriter.close();
       } catch (Exception e2) {
         e.printStackTrace();
       }
     }
   }
 }
  public boolean createFileInData(String path, byte[] buffer) {
    FileOutputStream fileOutputStream = null;
    try {
      File file = new File(path);
      if (file.createNewFile()) {
        fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(buffer, 0, buffer.length);
        fileOutputStream.flush();
        return true;
      }

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        if (fileOutputStream != null) {
          fileOutputStream.close();
          fileOutputStream = null;
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return false;
  }
Ejemplo n.º 11
0
  @BeforeClass
  public static void setUpBeforeClass() throws Exception {
    con.addCustomer(
        "Buddy", "Bear", "1520 Garnet Ave", "", "San Diego", "CA", "92109", "4766666656");
    con.addPublication("Runner Magazine", "Sports", 9.80, "Monthly", 5);

    ResultSet r = con.searchCustomer(0, "Buddy", "");
    try {
      while (r.next()) {
        testCustID = r.getInt("CustomerID");
      }
      r.close();

    } catch (Exception e) {
      e.printStackTrace();
    }

    ResultSet rs = con.searchPublication(0, "", "Runner Magazine");

    try {
      while (rs.next()) {
        testPubID = rs.getInt("PublicationID");
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    subscriptions newSub = new subscriptions(testCustID, testPubID);
  }
Ejemplo n.º 12
0
  // Da uma mensagem personalizada para Razao social, cnpj e login repetidos
  private boolean validaUnique(Empresa empresa, boolean pessoaFisica) {
    Empresa temp = new Empresa();
    try {
      temp =
          this.controller.getObjectByHQLCondition(
              "from Empresa where razaoSocial = '" + empresa.getRazaoSocial() + "'");
    } catch (Exception e) {
      temp = null;
      e.printStackTrace();
    }
    if (temp != null) {
      Mensagem.send(Mensagem.MSG_RAZAO_SOCIAL, Mensagem.ERROR);
      return false;
    }

    try {
      temp =
          this.controller.getObjectByHQLCondition(
              "from Empresa where cnpj = '" + empresa.getCnpj() + "'");
    } catch (Exception e) {
      temp = null;
      e.printStackTrace();
    }
    if (temp != null) {
      if (pessoaFisica) {
        Mensagem.send(Mensagem.MSG_CPF_UNIQUE, Mensagem.ERROR);
      } else {
        Mensagem.send(Mensagem.MSG_CNPJ_UNIQUE, Mensagem.ERROR);
      }

      return false;
    }

    try {
      temp =
          this.controller.getObjectByHQLCondition(
              "from Empresa where login = '******'");
    } catch (Exception e) {
      temp = null;
      e.printStackTrace();
    }
    if (temp != null) {
      Mensagem.send(Mensagem.MSG_LOGIN, Mensagem.ERROR);
      return false;
    }

    try {
      temp =
          this.controller.getObjectByHQLCondition(
              "from Empresa where email = '" + empresa.getEmail() + "'");
    } catch (Exception e) {
      temp = null;
      e.printStackTrace();
    }
    if (temp != null) {
      Mensagem.send(Mensagem.MSG_EMAIL, Mensagem.ERROR);
      return false;
    }
    return true;
  }
  /**
   * 更新群组成员
   *
   * @param members
   * @return
   */
  public static ArrayList<Long> insertGroupMembers(List<ECGroupMember> members) {

    ArrayList<Long> rows = new ArrayList<Long>();
    if (members == null) {
      return rows;
    }
    try {
      synchronized (getInstance().mLock) {
        // Set the start transaction
        getInstance().sqliteDB().beginTransaction();

        // Batch processing operation
        for (ECGroupMember member : members) {
          try {
            long row = insertGroupMember(member);
            if (row != -1) {
              rows.add(row);
            }
          } catch (Exception e) {
            e.printStackTrace();
          }
        }

        // Set transaction successful, do not set automatically
        // rolls back not submitted.
        getInstance().sqliteDB().setTransactionSuccessful();
      }

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      getInstance().sqliteDB().endTransaction();
    }
    return rows;
  }
Ejemplo n.º 14
0
  public static HashMap<Integer, HashSet<String>> getBadPricePhones(Connection oculusconn) {
    HashMap<Integer, HashSet<String>> result = new HashMap<Integer, HashSet<String>>();
    String sqlStr = "SELECT ads_id,phone FROM " + ADS_BAD_PHONE_TABLE;
    Statement stmt = null;
    try {
      stmt = oculusconn.createStatement();
      ResultSet rs = stmt.executeQuery(sqlStr);
      while (rs.next()) {
        Integer adid = rs.getInt("ads_id");
        String phone = rs.getString("phone");
        HashSet<String> phones = result.get(adid);
        if (phones == null) {
          phones = new HashSet<String>();
          result.put(adid, phones);
        }
        phones.add(phone);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        if (stmt != null) {
          stmt.close();
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    return result;
  }
Ejemplo n.º 15
0
  protected void verify(PhaseEvent phaseEvent) {
    FacesContext facesContext = phaseEvent.getFacesContext();
    String viewId = facesContext.getViewRoot().getViewId();
    SecurityBean securityBean = SecurityBean.getInstance();

    /*
     * Primero se valida que la sesión no haya caducado
     * */
    if (SecurityBean.isSessionExpired(facesContext)) {
      try {
        doRedirect(facesContext, "/resources/errorpages/errorSessionExpired.jsp");
        facesContext.responseComplete();

      } catch (Exception e) {
        e.printStackTrace();
      }

    } else if (!securityBean.verifyPageAccess(viewId)) {
      /*
       * Luego se valida que no se esté accediendo a un recurso sin autenticación
       * */
      HttpServletResponse response =
          (HttpServletResponse) facesContext.getExternalContext().getResponse();
      try {
        response.sendError(403); // 403: Forbidden error
        facesContext.responseComplete();

      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
  // method will call when user clicks on the link given in email
  @RequestMapping(value = "/logoutOutAction")
  public String getIssueDetails(
      HttpSession session, HttpServletRequest request, HttpServletResponse response) {

    logger.info("---- Entered getIssueDetails() of LogoutController ----");

    try {
      session = request.getSession(false);
      response.setHeader(
          "Cache-Control",
          "no-cache"); // Forces caches to obtain a new copy of the page from the origin server
      response.setHeader(
          "Cache-Control",
          "no-store"); // Directs caches not to store the page under any circumstance
      response.setDateHeader("Expires", 0); // Causes the proxy cache to see the page as "stale"
      response.setHeader("Pragma", "no-cache"); // HTTP 1.0 backward compatibility
      session.removeAttribute(IssueTrackerConstants.ISSUETRACKERCONSTANTS_LOGIN_USER_SESSION_NAME);
      session.setAttribute(
          IssueTrackerConstants.ISSUETRACKERCONSTANTS_LOGIN_USER_SESSION_NAME, null);
      session.invalidate();
    } catch (Exception e) {
      e.printStackTrace();
      StringWriter errors = new StringWriter();
      e.printStackTrace(new PrintWriter(errors));
      logger.error(errors.toString());
    }

    return "logout";
  }
Ejemplo n.º 17
0
  private void processIncomingPackets() {
    for (RSCPacket p : packetQueue.getPackets()) {
      IoSession session = p.getSession();
      Player player = (Player) session.getAttachment();
      if (player.getUsername() == null && p.getID() != 32 && p.getID() != 77 && p.getID() != 0) {
        final String ip = player.getCurrentIP();
        IPBanManager.throttle(ip);
        continue;
      }
      PacketHandler handler = packetHandlers.get(p.getID());
      player.ping();
      if (handler != null) {
        try {
          handler.handlePacket(p, session);
          try {
            if (p.getID() != 5) {
              // String s = "[PACKET] " +
              // session.getRemoteAddress().toString().replace("/",
              // "") + " : " + p.getID()+
              // " ["+handler.getClass().toString()+"]" + " : "+
              // player.getUsername() + " : ";
              // for(Byte b : p.getData())
              // s += b;
              // Logger.println(s);
            }
          } catch (Exception e) {
            e.printStackTrace();
          }

        } catch (Exception e) {
          String s;
          StringWriter sw = new StringWriter();
          PrintWriter pw = new PrintWriter(sw, true);
          e.printStackTrace(pw);
          pw.flush();
          sw.flush();
          s = sw.toString();
          Logger.error(
              "Exception with p["
                  + p.getID()
                  + "] from "
                  + player.getUsername()
                  + " ["
                  + player.getCurrentIP()
                  + "]: "
                  + s);
          player.getActionSender().sendLogout();
          player.destroy(false);
        }
      } else {
        Logger.error(
            "Unhandled packet from "
                + player.getCurrentIP()
                + ": "
                + p.getID()
                + "len: "
                + p.getLength());
      }
    }
  }
  /**
   * Sets the start quantity of the activity based on the data of the shape.
   *
   * @param activity
   * @param shape The resource shape
   */
  private void setStartAndCompletionQuantity(Activity activity, GenericShape shape) {

    /* Start quantity */

    String startQuantity = shape.getProperty("startquantity");
    if (startQuantity != null) {
      try {
        activity.setStartQuantity(BigInteger.valueOf(Integer.valueOf(startQuantity)));
      } catch (Exception e) {
        e.printStackTrace();
        /* Set to default value in case of an exception */
        activity.setStartQuantity(BigInteger.valueOf(1));
      }
    }

    /* Completion quantity */
    String completionQuantity = shape.getProperty("completionquantity");
    if (completionQuantity != null) {
      try {
        activity.setCompletionQuantity(BigInteger.valueOf(Integer.valueOf(completionQuantity)));
      } catch (Exception e) {
        /* Set to default value in case of an exception */
        e.printStackTrace();
        activity.setCompletionQuantity(BigInteger.valueOf(1));
      }
    }
  }
Ejemplo n.º 19
0
  public static void main(String[] str) {
    Project project = new Project();

    RawSequences rawSequences =
        (new com.bugaco.mioritic.impl.data.raw.RawSequencesFactory()).createRawSequences();
    com.bugaco.mioritic.model.data.sequences.Sequences seqs =
        (new com.bugaco.mioritic.impl.data.sequences.SequencesFactory()).createSequences();
    com.bugaco.mioritic.model.data.distancematrix.DistanceMatrix distanceMatrix =
        new com.bugaco.mioritic.impl.data.distancematrix.DistanceMatrix();
    com.bugaco.mioritic.model.data.clusters.Clusters clusters =
        new com.bugaco.mioritic.impl.data.clusters.Clusters();

    com.bugaco.ui.models.AlgorithmModel algModelSeq =
        new com.bugaco.ui.models.impl.DefaultAlgorithmModel();
    algModelSeq.setText("Select file format:");
    try {
      Properties p = new Properties();
      p.load(algModelSeq.getClass().getResourceAsStream("/conf/SequenceImporter.properties"));
      System.err.println(p);
      algModelSeq.setItemsFromProperties(p);
    } catch (Exception e) {
      e.printStackTrace();
    }
    // algModelSeq.addElement( new com.bugaco.ui.models.impl.DefaultAlgorithmItem( "Fasta" ,
    // "com.bugaco.mioritic.impl.algorithm.rawcompiler.FastaCompilerFactory" ) ) ;
    // algModelSeq.addElement( new com.bugaco.ui.models.impl.DefaultAlgorithmItem( "Nexus" ,
    // "com.bugaco.mioritic.impl.algorithm.rawcompiler.NexusCompilerFactory" ) ) ;

    com.bugaco.ui.models.AlgorithmModel algModelDM =
        new com.bugaco.ui.models.impl.DefaultAlgorithmModel();
    algModelDM.setText("Select algorithm:");
    try {
      Properties p = new Properties();
      p.load(algModelDM.getClass().getResourceAsStream("/conf/DistanceCompiler.properties"));
      algModelDM.setItemsFromProperties(p);
    } catch (Exception e) {
      e.printStackTrace();
    }
    // algModelDM.addElement( new com.bugaco.ui.models.impl.DefaultAlgorithmItem( "Simple" ,
    // "com.bugaco.mioritic.impl.algorithm.distancematrix.VerySimpleCompilerFactory" ) ) ;

    com.l2fprod.common.swing.JTaskPane taskPane = new com.l2fprod.common.swing.JTaskPane();
    taskPane.add(project.projectFeedback(5000));
    taskPane.add(
        project.sequenceBuilder(
            new com.bugaco.mioritic.impl.module.sequencebuilder.SequenceBuilderFactory(),
            rawSequences,
            seqs,
            algModelSeq));
    taskPane.add(project.distanceMatrixBuilder(seqs, distanceMatrix, algModelDM));
    taskPane.add(project.clusterBuilder(distanceMatrix, clusters));
    taskPane.add(project.multiClusterStatistics(seqs, distanceMatrix, clusters));

    javax.swing.JFrame frame = project.getMainFrame(taskPane);

    if (!project.acceptLicense(taskPane)) {
      frame.setVisible(false);
      frame = null;
    }
  }
Ejemplo n.º 20
0
  private void initGlobaleGuiceInjector() {
    List<Module> moduleList = new ArrayList<Module>();
    IExtensionRegistry reg = Platform.getExtensionRegistry();
    IConfigurationElement[] extensions =
        reg.getConfigurationElementsFor(ISharedModuleProvider.EXTENSION_POINT_ID);
    for (int i = 0; i < extensions.length; i++) {
      IConfigurationElement element = extensions[i];
      if (element.getAttribute("class") != null) {
        try {
          ISharedModuleProvider provider =
              (ISharedModuleProvider) element.createExecutableExtension("class");
          moduleList.add(provider.get());
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }

    Injector injector = Guice.createInjector(moduleList);
    try {
      Field field = GuiceContext.class.getDeclaredField("globalSharedInjector");
      field.setAccessible(true);
      field.set(GuiceContext.class, injector);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 21
0
  public void run() {
    ServerSocket server = null;
    try {
      server = new ServerSocket(link.getSerPort());
      System.out.println("System Online!");
    } catch (Exception e) {
      e.printStackTrace();
      return;
    }
    try {
      Socket remoteSocket = server.accept();
      System.out.println("remoteSocket accpet!");
      Socket localSocket = server.accept();
      System.out.println("localSocket  accpet!");
      remoteSocket.setSoTimeout(0);
      localSocket.setSoTimeout(0);

      remoteSocket.setTcpNoDelay(true);
      localSocket.setTcpNoDelay(true);

      new TransferDown(remoteSocket, localSocket, "ToCZ");
      new TransferUp(remoteSocket, localSocket, "ToYonYou");

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 22
0
  /**
   * Use <code> classifyInstance </code> from <code> OSDLCore </code> and assign probability one to
   * the chosen label. The implementation is heavily based on the same method in the <code>
   *  Classifier </code> class.
   *
   * @param instance the instance to be classified
   * @return an array containing a single '1' on the index that <code> classifyInstance </code>
   *     returns.
   */
  public double[] distributionForInstance(Instance instance) {

    // based on the code from the Classifier class
    double[] dist = new double[instance.numClasses()];
    int classification = 0;
    switch (instance.classAttribute().type()) {
      case Attribute.NOMINAL:
        try {
          classification = (int) Math.round(classifyInstance(instance));
        } catch (Exception e) {
          System.out.println("There was a problem with classifyIntance");
          System.out.println(e.getMessage());
          e.printStackTrace();
        }
        if (Utils.isMissingValue(classification)) {
          return dist;
        }
        dist[classification] = 1.0;
        return dist;

      case Attribute.NUMERIC:
        try {
          dist[0] = classifyInstance(instance);
        } catch (Exception e) {
          System.out.println("There was a problem with classifyIntance");
          System.out.println(e.getMessage());
          e.printStackTrace();
        }
        return dist;

      default:
        return dist;
    }
  }
  static {
    String dummy = System.getenv(EnvVarNames.CCP_TASKSYSTEMID);
    taskid = -1;
    if (!Utility.isNullOrEmpty(dummy)) {
      try {
        taskid = Integer.parseInt(dummy);
      } catch (NumberFormatException e) {
        // taskid stays at -1;
      }
    }

    dummy = System.getenv(EnvVarNames.CCP_JOBID);
    jobid = -1;
    if (!Utility.isNullOrEmpty(dummy)) {
      try {
        jobid = Integer.parseInt(dummy);
      } catch (NumberFormatException e) {
        // jobid stays at -1;
      }
    }

    dummy = System.getenv(EnvVarNames.LONG_LOADING_TEST);
    if (!Utility.isNullOrEmpty(dummy)) {
      try {
        Thread.sleep(30 * 1000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }

    scheduler = System.getenv(EnvVarNames.CCP_SCHEDULER);
    try {
      String logPath = System.getenv(EnvVarNames.GRACEFUL_EXIT);
      if (!Utility.isNullOrEmpty(logPath)) {
        File baseDir = new File(logPath);
        File logDir = new File(baseDir, "CCP_AITest_Trace_" + jobid);
        File logFile = new File(logDir, taskid + ".txt");

        if (!System.getenv("CCP_OnAzure").equals("1")) {
          try {
            logDir.mkdirs();
          } catch (Exception e) {
            e.printStackTrace();
          }
          PrintWriter writer = new PrintWriter(new FileWriter(logFile, true));
          writer.println(Utility.getCurrentTime() + ": Svchost starts.");
          writer.close();
        }
        System.out.println(Utility.getCurrentTime() + ": Svchost starts.");

        ServiceContext.exitingEvents.addMyEventListener(new DefaultOnExitHandler(logFile));
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    String pid = ManagementFactory.getRuntimeMXBean().getName();
    int index = pid.indexOf("@");
    processId = Integer.parseInt(pid.substring(0, index));
  }
Ejemplo n.º 24
0
  public void pendientesClaro() throws Exception {
    Connection connPostgres = null;
    String query;

    try {
      // Parámetros de conexión con Postgres
      try {
        Class.forName("org.postgresql.Driver");
      } catch (ClassNotFoundException e) {
        System.out.println("No se encuentra el Driver: " + e.getMessage());
      }
      String username = "******";
      String password = "";
      String url = "jdbc:postgresql://localhost:5432/multipagos";
      connPostgres = DriverManager.getConnection(url, username, password);

      corregirClaroDep();

      query = "drop table tmp_claro_dpts;";
      ejecutarQuery(connPostgres, query);

      query =
          "select	b.departamento_id, a.* "
              + "into	tmp_claro_dpts "
              + "from 	tmp_carteraclaro a "
              + "left 	outer join departamento b on upper(rtrim(ltrim(a.departamento))) = upper(rtrim(ltrim(b.departamento_nombre))) "
              + "ORDER BY 1;";
      ejecutarQuery(connPostgres, query);

      query =
          "select a.* into tmp_claro_dpts_2 from cartera_x_departamento a where departamento_id in (select departamento_id from tmp_claro_dpts);";
      ejecutarQuery(connPostgres, query);

      query =
          "delete from tmp_claro_dpts_2 where factura_interna in (select factura_interna from tmp_claro_dpts);";
      ejecutarQuery(connPostgres, query);

      query =
          "update cartera_x_departamento set pagado_claro=true where factura_interna in (select factura_interna from tmp_claro_dpts_2);";
      ejecutarQuery(connPostgres, query);

      query = "drop table tmp_claro_dpts_2;";
      ejecutarQuery(connPostgres, query);

      query = "drop table tmp_claro_dpts;";
      ejecutarQuery(connPostgres, query);

      // return cantidad;

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        if (connPostgres != null) connPostgres.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    // return 0;
  }
  public void testSearchUser() {
    NetworkDataManager ndm = new NetworkDataManager();
    User user = new User();
    User user2;
    user.setName("Connor");
    user.setUserAddress("1021");
    user.setUserName("ccdunn");
    user.setUserEmail("*****@*****.**");
    user.addFriend("gbullock");

    ndm.saveUser(user);

    try {
      Thread.sleep(500);
    } catch (Exception e) {
      e.printStackTrace();
    }

    assertTrue("Could not find the user", ndm.searchUser(user.getUserName()));

    assertFalse("Found a user that doesnt exist!", ndm.searchUser("NotExistingUser"));

    ndm.deleteUser(user.getUserName());

    try {
      Thread.sleep(500);
    } catch (Exception e) {
      e.printStackTrace();
    }

    assertFalse("Still finding user that should be deleted...", ndm.searchUser(user.getUserName()));
  }
Ejemplo n.º 26
0
 // gather the necessary information to add a publisher
 private void addPublisher() {
   try {
     Connection conn = getConnection();
     try {
       PublisherDAO pubDAO = new PublisherDAO(conn);
       Publisher toAdd = new Publisher();
       System.out.println("What is the Publisher's name?");
       String pubName = getInputString();
       System.out.println("What is the Publisher's address?");
       String pubAddress = getInputString();
       System.out.println("What is the Publisher's phone number?");
       String pubPhone = getInputString();
       toAdd.setPublisherName(pubName);
       toAdd.setPublisherAddress(pubAddress);
       toAdd.setPublisherPhone(pubPhone);
       pubDAO.create(toAdd);
       conn.commit();
       conn.close();
     } catch (Exception e) {
       conn.rollback();
       conn.close();
       e.printStackTrace();
     }
   } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
Ejemplo n.º 27
0
  /** Saves the defaults and missing values. */
  public void save() {
    if (!this.folder.exists()) {
      this.folder.mkdirs();
    }

    if (!this.file.exists()) {
      try {
        this.file.createNewFile();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    this.config = YamlConfiguration.loadConfiguration(this.file);
    for (Entry<String, Object> en : this.defaults.entrySet()) {
      if (!this.config.contains(en.getKey())) {
        ConfigUtils.setObject(this.config, en.getKey(), en.getValue());
      }
    }

    try {
      this.config.save(this.file);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 28
0
 private void addLibrary() {
   try {
     Connection conn = getConnection();
     try {
       LibraryBranchDAO libDAO = new LibraryBranchDAO(conn);
       LibraryBranch toAdd = new LibraryBranch();
       System.out.println("What is the new branch's name?");
       String libName = getInputString();
       System.out.println("What is the Publisher's address?");
       String libAddress = getInputString();
       toAdd.setBranchName(libName);
       toAdd.setAddress(libAddress);
       libDAO.create(toAdd);
       conn.commit();
       conn.close();
     } catch (Exception e) {
       conn.rollback();
       conn.close();
       e.printStackTrace();
     }
   } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
Ejemplo n.º 29
0
  @Override
  public Response serve(IHTTPSession session) {
    Method method = session.getMethod();
    if (Method.POST.equals(method) && session.getUri().startsWith("/upload")) {
      Map<String, String> files = new HashMap<String, String>();
      try {
        session.parseBody(files);
        String fileHEX = JVMClassParser.fileHEX(files.get("JvmClass"));

        return new Response(Status.OK, MIME_HTML, fileHEX);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    Response response = new Response(Status.OK, MIME_HTML, "error");
    try {
      response =
          new Response(Status.OK, MIME_HTML, new FileInputStream("target/classes/index.html"));
      if (null == session.getCookies().read("HTTPD_SESSION")) {
        response.addHeader("Set-Cookie", "HTTPD_SESSION=" + UUID.randomUUID());
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return response;
  }
Ejemplo n.º 30
0
 private void addBorrower() {
   try {
     Connection conn = getConnection();
     try {
       BorrowerDAO borDAO = new BorrowerDAO(conn);
       Borrower toAdd = new Borrower();
       System.out.println("What is the borrower's name?");
       String borName = getInputString();
       System.out.println("What is the borrower's address?");
       String borAddress = getInputString();
       System.out.println("What is the borrower's phone address?");
       String borPhone = getInputString();
       toAdd.setName(borName);
       toAdd.setAddress(borAddress);
       toAdd.setPhone(borPhone);
       borDAO.create(toAdd);
       conn.commit();
       conn.close();
     } catch (Exception e) {
       conn.rollback();
       conn.close();
       e.printStackTrace();
     }
   } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }