/**
   * Method 'execute'
   *
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @throws Exception
   * @return ActionForward
   */
  public ActionForward handle(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    try {
      // parse parameters
      // create the DAO class
      TelesalesCallSourceDao dao = TelesalesCallSourceDaoFactory.create();

      // execute the finder
      TelesalesCallSource dto[] = dao.findAll();

      // store the results
      request.setAttribute("result", dto);

      return mapping.findForward("success");
    } catch (Exception e) {
      ActionErrors _errors = new ActionErrors();
      _errors.add(
          ActionErrors.GLOBAL_ERROR,
          new ActionError("internal.error", e.getClass().getName() + ": " + e.getMessage()));
      saveErrors(request, _errors);
      return mapping.findForward("failure");
    }
  }
  public AttributeField attributeField() throws ParseException {
    try {
      AttributeField attributeField = new AttributeField();

      this.lexer.match('a');

      this.lexer.SPorHT();
      this.lexer.match('=');

      this.lexer.SPorHT();

      NameValue nameValue = new NameValue();

      int ptr = this.lexer.markInputPosition();
      try {
        String name = lexer.getNextToken(':');
        this.lexer.consume(1);
        String value = lexer.getRest();
        nameValue = new NameValue(name.trim(), value.trim());
      } catch (ParseException ex) {
        this.lexer.rewindInputPosition(ptr);
        String rest = this.lexer.getRest();
        if (rest == null) throw new ParseException(this.lexer.getBuffer(), this.lexer.getPtr());
        nameValue = new NameValue(rest.trim(), ""); // jvB: use empty string for flag values
      }
      attributeField.setAttribute(nameValue);

      this.lexer.SPorHT();

      return attributeField;
    } catch (Exception e) {
      e.printStackTrace();
      throw new ParseException(e.getMessage(), 0);
    }
  }
 static {
   try {
     SoundMixer mixer = SoundMixerEnumerator.getMixerByVendor("mm's computing");
     System.out.println("Mixer " + mixer.getMixerInfo() + " is available");
   } catch (Exception e) {
     System.out.println("9\b" + e.getMessage());
   }
 }
  public void run() {
    // ///////////////////////////
    Gateway.addLiveThread(this);
    // ///////////////////////////
    while (Gateway.running) {
      try {
        pdud = (PDUData) fromSMSC.dequeue(); // blocks until having
        // an item
        // pdu = (PDU) fromSMSC.dequeue(); //blocks until having an item
        pdu = (PDU) pdud.getPDU();
        if (pdu.isRequest()) {
          this.RequestID = pdud.getRequestID();
          processRequest(pdu);
        }
      } catch (DBException ex) { // when lost connection to db
        Logger.error(this.getClass().getName(), "DBException: " + ex.getMessage());
        DBTools.ALERT(
            "RequestProcessor",
            "RequestProcessor",
            Constants.ALERT_WARN,
            Preference.Channel + "DBException: " + ex.getMessage(),
            Preference.ALERT_CONTACT);
        Logger.error(this.getClass().getName(), "Alert2YM DBException: " + ex.getMessage());
      } catch (Exception e) {
        Logger.error(this.getClass().getName(), "Exception: " + e.getMessage());

        DBTools.ALERT(
            "RequestProcessor",
            "RequestProcessor",
            Constants.ALERT_WARN,
            Preference.Channel + "Exception: " + e.getMessage(),
            Preference.ALERT_CONTACT);
      }

      try {
        Thread.sleep(50);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    // /////////////////////////////
    Logger.info(this.getClass().getName(), "{" + this.getClass().getName() + " stopped}");
    this.destroy();
    // /////////////////////////////
  }
Exemple #5
0
 public void setTime(String theTime) {
   time = theTime;
   try {
     this.theDate = dateFormat.parse(time);
   } catch (Exception ex) {
     jade.util.Logger.getMyLogger(this.getClass().getName())
         .log(jade.util.Logger.WARNING, ex.getMessage());
   }
 }
Exemple #6
0
  public List<MersVO> mersData() {
    List<MersVO> list = new ArrayList<MersVO>();
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");
    StringTokenizer st = new StringTokenizer(sdf.format(date), "-");
    int year = Integer.parseInt(st.nextToken());
    int month = Integer.parseInt(st.nextToken());
    int day = Integer.parseInt(st.nextToken());
    try {
      Document doc = Jsoup.connect("http://www.cdc.go.kr/CDC/cms/content/15/63315_view.html").get();
      // System.out.println(doc);
      Elements trs = doc.select("table tbody tr");
      // System.out.println(trs);
      String data = "";
      String[] temp = {"panel panel-primary", "panel panel-green", "panel panel-yellow"};
      int i = 0;
      for (Element tr : trs) {
        Iterator<Element> it = tr.getElementsByTag("td").iterator();

        // if(i==2) break;
        while (it.hasNext()) {

          MersVO vo = new MersVO();
          vo.setType(it.next().text());
          vo.setMers(it.next().text().replace("*", ""));
          /*vo.setYsum(it.next().text().replace(",", ""));
          vo.setPlus(it.next().text());
          vo.setMinus(it.next().text());*/

          if (data.equals("")) {
            data = it.next().text();
            vo.setIng(data);
          } else {
            vo.setIng(data);
          }
          vo.setNsum(it.next().text().replace(",", ""));
          vo.setHouse(it.next().text());
          vo.setOffice(it.next().text());
          vo.setDis(it.next().text().replace(",", ""));
          vo.setDiv1(temp[i]);
          vo.setYear(year);
          vo.setMonth(month);
          if (i == 2) {
            vo.setDay(day - 1);
          } else {
            vo.setDay(day);
          }
          list.add(vo);
          i++;
        }
      }
    } catch (Exception ex) {
      System.out.println(ex.getMessage());
    }
    return list;
  }
Exemple #7
0
  public List<MersHPVO> mersHPData() {
    List<MersHPVO> list = new ArrayList<MersHPVO>();
    try {
      Document doc = Jsoup.connect("http://www.cdc.go.kr/CDC/cms/content/16/63316_view.html").get();
      // System.out.println(doc);
      Elements trs = doc.select("table tbody tr");
      // System.out.println(trs);
      String data = "";

      for (Element tr : trs) {
        Iterator<Element> it = tr.getElementsByTag("td").iterator();
        int size = tr.getElementsByTag("td").size();
        MersHPVO vo = new MersHPVO();
        if (size == 5) {
          it.next().html();
          vo.setGugun(it.next().html());
          vo.setName(it.next().html());
          vo.setDuration(it.next().html());
          vo.setNum(it.next().html());
        } else {
          vo.setGugun(it.next().html());
          vo.setName(it.next().html());
          vo.setDuration(it.next().html());
          vo.setNum(it.next().html());
        }
        list.add(vo);
        // if(i==2) break;
        /*while(it.hasNext())
        {

         MersHPVO vo=new MersHPVO();
         String str=it.next().html();
         if(str.startsWith("<strong>"))
         {
          vo.setGugun(it.next().html());
          vo.setName(it.next().html());
          vo.setDuration(it.next().html());
          vo.setNum(it.next().html());
         }
         else
         {
          vo.setGugun(str);
          vo.setName(it.next().html());
          vo.setDuration(it.next().html());
          vo.setNum(it.next().html());
         }
         list.add(vo);
        }*/

      }
    } catch (Exception ex) {
      System.out.println(ex.getMessage());
    }
    return list;
  }
  public List<MarketSnapshot> load(ProgressListener progressListener) throws JBookTraderException {
    String line = "";
    int lineSeparatorSize = System.getProperty("line.separator").length();
    long sizeRead = 0, lineNumber = 0;

    List<MarketSnapshot> snapshots = new ArrayList<MarketSnapshot>();

    try {
      while ((line = reader.readLine()) != null) {
        if (lineNumber % 50000 == 0) {
          progressListener.setProgress(sizeRead, fileSize, "Loading historical data file");
          if (progressListener.isCancelled()) {
            break;
          }
        }
        lineNumber++;
        sizeRead += line.length() + lineSeparatorSize;
        boolean isComment = line.startsWith("#");
        boolean isProperty = line.contains("=");
        boolean isBlankLine = (line.trim().length() == 0);
        boolean isMarketDepthLine = !(isComment || isProperty || isBlankLine);
        if (isMarketDepthLine) {
          MarketSnapshot marketSnapshot = toMarketDepth(line);
          if (filter == null || filter.contains(time)) {
            snapshots.add(marketSnapshot);
          }
          previousTime = time;
        } else if (isProperty) {
          if (line.startsWith("timeZone")) {
            setTimeZone(line);
          }
        }
      }

      if (sdf == null) {
        String msg = "Property " + "\"timeZone\"" + " is not defined in the data file." + LINE_SEP;
        throw new JBookTraderException(msg);
      }

    } catch (IOException ioe) {
      throw new JBookTraderException("Could not read data file");
    } catch (Exception e) {
      String errorMsg = "Problem parsing line #" + lineNumber + ": " + line + LINE_SEP;
      String description = e.getMessage();
      if (description == null) {
        description = e.toString();
      }
      errorMsg += description;
      throw new RuntimeException(errorMsg);
    }

    return snapshots;
  }
  @RequestMapping(
      value = "/home",
      method = {RequestMethod.GET, RequestMethod.POST})
  public String getCity(HttpServletRequest request, ModelMap model) {

    try {
      List<City> cityList = cityService.getCity();
      utilities.setSuccessResponse(response, cityList);
    } catch (Exception ex) {
      logger.error("getCity :" + ex.getMessage());
    }
    model.addAttribute("model", response);
    return "home";
  }
Exemple #10
0
 /**
  * JSP调用的函数
  *
  * @param request 网页的请求对象
  * @param response 网页的响应对象
  * @return 返回HTML或javascipt的语句
  * @throws Exception 异常
  */
 public String doService(HttpServletRequest request, HttpServletResponse response) {
   try {
     String operate = request.getParameter(OPERATE_KEY);
     if (operate != null && operate.trim().length() > 0) {
       RunData data = notifyObactioners(operate, request, response, null);
       if (data == null) return showMessage("无效操作", false);
       if (data.hasMessage()) return data.getMessage();
     }
     return "";
   } catch (Exception ex) {
     if (dsMasterTable.isOpen() && dsMasterTable.changesPending()) dsMasterTable.reset();
     log.error("doService", ex);
     return showMessage(ex.getMessage(), true);
   }
 }
  private void jButton4ActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jButton4ActionPerformed
    // TODO add your handling code here:
    String wash = chrg.getText();
    cname = custname.getText();
    addr1 = addr.getText();
    total.setText(String.valueOf(tamount));
    String a = lcharge.getText();
    String b = total.getText();
    String j = la.getText();
    String c = con.getText();
    int d = Integer.parseInt(b);
    int e = Integer.parseInt(a);
    int g = Integer.parseInt(wash);
    int h = Integer.parseInt(c);
    int i = Integer.parseInt(j);
    int f = d + e + g + h + i;
    toamnt.setText(String.valueOf(f));
    String sql =
        "insert into bill(Bill_No,Bill_Date,Cust_Name,Cust_Addr,P_Details,Amount) values('"
            + no1
            + "','"
            + bill1
            + "','"
            + cname
            + "','"
            + addr1
            + "','"
            + pd
            + "','"
            + toamnt
            + "')";

    try {
      Class.forName("com.mysql.jdbc.Driver");
      Connection con =
          (Connection)
              DriverManager.getConnection("jdbc:mysql://localhost:3306/bharatmotors", "root", "");
      Statement stmt = con.createStatement();
      stmt.executeUpdate(sql);

    } catch (Exception e2) {
      JOptionPane.showMessageDialog(this, e2.getMessage());
    }
  } // GEN-LAST:event_jButton4ActionPerformed
Exemple #12
0
  public static final void getCurrentDateString(IData pipeline) throws ServiceException {
    // --- <<IS-START(getCurrentDateString)>> ---
    // @subtype unknown
    // @sigtype java 3.5
    // [i] field:0:required pattern
    // [i] field:0:optional timezone
    // [i] field:0:optional locale
    // [o] field:0:required value
    IDataCursor idcPipeline = pipeline.getCursor();
    try {
      String inPattern = "";
      if (idcPipeline.first("pattern")) {
        inPattern = (String) idcPipeline.getValue();
      } else {
        throw new ServiceException("Input parameter 'pattern' was not found.");
      }

      IData output = Service.doInvoke("pub.date", "getCurrentDateString", pipeline);
      IDataCursor outCur = output.getCursor();

      String stDate = IDataUtil.getString(outCur, "value");
      IDataUtil.remove(outCur, "value");

      outCur.destroy();

      if (inPattern.endsWith("Z")) {
        Matcher matcher = specialTimezonePattern.matcher(stDate);
        if (matcher.find()) {
          stDate = matcher.replaceAll(":" + matcher.group(1));
        }
      }

      idcPipeline.insertAfter("value", stDate);
    } catch (Exception e) {
      throw new ServiceException(e.getMessage());
    }

    idcPipeline.destroy();
    // --- <<IS-END>> ---

  }
  /**
   * Main program.
   *
   * <p>\u0040param args Program parameters.
   */
  public static void main(String[] args) {
    //  Initialize.
    try {
      if (!initialize(args)) {
        System.exit(1);
      }
      //  Process all files.

      long startTime = System.currentTimeMillis();

      int filesProcessed = processFiles(args);

      long processingTime = (System.currentTimeMillis() - startTime + 999) / 1000;

      //  Terminate.

      terminate(filesProcessed, processingTime);
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }
  public String verify(JarFile jar, String... algorithms) throws IOException {
    if (algorithms == null || algorithms.length == 0) algorithms = new String[] {"MD5", "SHA"};
    else if (algorithms.length == 1 && algorithms[0].equals("-")) return null;

    try {
      Manifest m = jar.getManifest();
      if (m.getEntries().isEmpty()) return "No name sections";

      for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements(); ) {
        JarEntry je = e.nextElement();
        if (MANIFEST_ENTRY.matcher(je.getName()).matches()) continue;

        Attributes nameSection = m.getAttributes(je.getName());
        if (nameSection == null) return "No name section for " + je.getName();

        for (String algorithm : algorithms) {
          try {
            MessageDigest md = MessageDigest.getInstance(algorithm);
            String expected = nameSection.getValue(algorithm + "-Digest");
            if (expected != null) {
              byte digest[] = Base64.decodeBase64(expected);
              copy(jar.getInputStream(je), md);
              if (!Arrays.equals(digest, md.digest()))
                return "Invalid digest for "
                    + je.getName()
                    + ", "
                    + expected
                    + " != "
                    + Base64.encodeBase64(md.digest());
            } else reporter.error("could not find digest for " + algorithm + "-Digest");
          } catch (NoSuchAlgorithmException nsae) {
            return "Missing digest algorithm " + algorithm;
          }
        }
      }
    } catch (Exception e) {
      return "Failed to verify due to exception: " + e.getMessage();
    }
    return null;
  }
  @RequestMapping(
      value = "/getCityApi",
      method = {RequestMethod.GET, RequestMethod.POST})
  public String getCityApi(
      HttpServletRequest request,
      @RequestParam(value = "locationname") String locationname,
      ModelMap model) {

    Map<Object, Object> map = new HashMap<Object, Object>();
    JSONArray jSONArray = new JSONArray();
    try {
      String status = "active";
      List<City> cityList = cityService.getCityApi(locationname, status);
      if (cityList != null && cityList.size() > 0) {
        for (int i = 0; i < cityList.size(); i++) {
          City city = (City) cityList.get(i);
          String cityName = (String) city.getCity();
          String stateName = (String) city.getState();

          int ID = (Integer) (city.getId());
          JSONObject jSONObject = new JSONObject();

          jSONObject.put("id", ID);
          jSONObject.put("text", cityName);
          jSONArray.put(jSONObject);
        }
        utilities.setSuccessResponse(response, jSONArray.toString());
      } else {
        throw new ConstException(ConstException.ERR_CODE_NO_DATA, ConstException.ERR_MSG_NO_DATA);
      }
    } catch (Exception ex) {
      logger.error("getCity :" + ex.getMessage());
      utilities.setErrResponse(ex, response);
    }
    model.addAttribute("model", jSONArray.toString());
    return "home";
  }
Exemple #16
0
  public static String generateRoster()
  {
    String rostere="";
       database.openBusDatabase();

       // get available drivers here ------
       int[] drivers = DriverInfo.getDrivers();
       int[] buses = BusInfo.getBuses();
       // SET weekly/daily/isBack times of all drivers to 0
       for (int index = 0; index < drivers.length; index++)
       {
         DriverInfo.setHoursThisWeek(drivers[index], 0);
         DriverInfo.setHoursThisDay(drivers[index], 0);
         DriverInfo.setIsBackTime(drivers[index], 0);
       } // for

       // Starting route 65, goes up to 68
       int route = 65;

       // Counting variables for stats
       int totalWeeklyTimes = 0;
       int totalSaturdayTimes = 0;
       int totalSundayTimes = 0;

       int totalTimes = 0;

       // Array that stores the duration of services of each route
       List<ArrayList<Integer>> routeServicesDuration = new ArrayList<ArrayList<Integer>>();

       // Array that stores the driver name/id at a SLOT "day/route/service"
       //List<ArrayList<ArrayList<Integer>>> slots = new ArrayList<ArrayList<ArrayList<Integer>>>();

       //for (int k = 65; k < 69; k++)
       //{
         //totalWeekdayServices = TimetableInfo.getNumberOfServices
         //                 (i, TimetableInfo.timetableKind.weekday);
         //routesServiceDuration = int[j][totalWeekdayServices];
       //}

       // Day range: 0-6 (Mon-Sun)
       int day = 0;
       //routeServicesDuration.add(new ArrayList<Integer>());
       TimetableInfo.timetableKind.weekday;
       while( day < 7) // change to <7 to include sat/sun
       {
         // SET daily/isBack times of all drivers to 0
         for (int index = 0; index < drivers.length; index++)
         {
           DriverInfo.setHoursThisDay(drivers[index], 0);
           DriverInfo.setIsBackTime(drivers[index], 0);

         } // for

         for (int index = 0; index < buses.length; index++)
         {
           BusInfo.setIsBackTime(buses[index], 0);
         }

         Sort.sortDrivers(drivers);

         if (day < 5)
         {
            kind = TimetableInfo.timetableKind.weekday;
         }
         else if (day == 5)
         {
            kind = TimetableInfo.timetableKind.saturday;
         }
         else
         {
            kind = TimetableInfo.timetableKind.sunday;
         }
           //routeServicesDuration.add(new ArrayList<Integer>());
           slots.add(new ArrayList<ArrayList<Integer>>());
           busSlots.add(new ArrayList<ArrayList<Integer>>());
           //slots.get(day).add(new ArrayList<Integer>());
           route=65;
        while (route <= 66) // add to include all routes
        {
           routeServicesDuration.add(new ArrayList<Integer>());
           //slots.add(new ArrayList<ArrayList<Integer>>());
           slots.get(day).add(new ArrayList<Integer>());
           busSlots.get(day).add(new ArrayList<Integer>());
           //slots.add(new ArrayList<ArrayList<Integer>>());
           //slots.get(day).add(new ArrayList<Integer>());

         //slots.get(day).add(new ArrayList<Integer>());
         //slots.get(day).get(route-65).add(0);
         //System.out.println(slots.get(day).get(route-65).get(0));

           int[] busStops = BusStopInfo.getBusStops(route);
         //totalWeekdayServicesForRoute = TimetableInfo.getNumberOfServices
         //                 (route, TimetableInfo.timetableKind.weekday);
         //totalWeekdayServices = totalWeekdayServices + totalWeekdayServicesForRoute;


         //TimetableInfo.timetableKind kind = TimetableInfo.timetableKind.weekday;

         //System.out.print("Weekday Services : ");
           int[] services = TimetableInfo.getServices(route,kind);
           for (int i=0;i<services.length;i++)
           {

             // Array that stores the service times
             int[] times = TimetableInfo.getServiceTimes(route,kind, i);

             // Calculating and storing the service's duration
             routeServicesDuration.get(route-65).add(times[times.length-1]-times[0]);


             //Integer toPrint = routeServicesDuration.get(route-65).get(i);
             //totalWeeklyTimes = totalWeeklyTimes + toPrint;
             //System.out.println("Duration of Service " + services[i] + "(" + route + "): "
             //                    + toPrint);

             // Index to go through all the drivers
             int index = 0;

             // Boolean variable to check if a driver is allocated to the service
             boolean driverNotAllocated = true;
             // Stupid variable to check if driver isBack to take another service
             // change it to int
             //int isBackTime = DriverInfo.getIsBackTime(drivers[index]);



             while (driverNotAllocated && index < drivers.length)
             {
               int hoursThisWeek = DriverInfo.getHoursThisWeek(drivers[index]);
               int hoursThisDay = DriverInfo.getHoursThisDay(drivers[index]);
               int isBackTime = DriverInfo.getIsBackTime(drivers[index]);

               // If driver's daily and weekly hours dont exceed the maximums(5h / 50h)
               // and he is back from the previous taken service (and he is available
               // - for iteration 3) then he can take this service slot.
               if( hoursThisDay + routeServicesDuration.get(route-65).get(i) < 300
                   && hoursThisWeek + routeServicesDuration.get(route-65).get(i) < 3000
                   && isBackTime < times[0])
               {
                 // System.out.println("Day: "+ day + " ,Route/Service: " + (route-65) + "/" + i);
                 slots.get(day).get(route-65).add(drivers[index]);
                 //System.out.println(slots.get(day).get(route-65).get(i));


                 // Update driver's daily and weekly hours (could do it for yearly too)
                 DriverInfo.setHoursThisWeek(drivers[index],
                         hoursThisWeek + routeServicesDuration.get(route-65).get(i));
                 DriverInfo.setHoursThisDay(drivers[index],
                         hoursThisDay + routeServicesDuration.get(route-65).get(i));

                 // Update isBackTime to service's end time
                 // 65-66 : end time is at Stockport so dont care
                 // 67-68 : to check
                 //isBackTime = times[times.length-1];
                 //System.out.println(times[times.length-1]);
                 DriverInfo.setIsBackTime(drivers[index], times[times.length-1]);
                 // Driver allocated successfully
                 driverNotAllocated = false;

//IAM
                 boolean busNotAllocated=true;
                 int bindex = 0;
                 // Now allocate a bus to that slot too // another 3d array? yes prolly
                 while (busNotAllocated)
                 {
                   int isBusBackTime = BusInfo.getIsBackTime(buses[bindex]);
                   if (isBusBackTime < times[0])
                   {
                     busSlots.get(day).get(route-65).add(buses[bindex]);
                     BusInfo.setIsBackTime(buses[bindex], times[times.length-1]);
                     // Bus allocated successfully
                     busNotAllocated = false;
                   }
                   bindex++;
                 }
               }
               index++;
             }
           }
         //}

         //System.out.println("\nTotal: " + TimetableInfo.getNumberOfServices(route, kind));
         //System.out.println("=================================================");
         //day++;

           route++;
         } // inner while
         day++;
       } // while
       route=65;
         System.out.println("=================================================");
         TimetableInfo.timetableKind dayKind;
try
{
// Create file
FileWriter fstream = new FileWriter("roster");
BufferedWriter out = new BufferedWriter(fstream);

         for(int dayIndex=0; dayIndex<7; dayIndex++ )
         {
           out.write("\n=================================================");
           rostere += "\n=================================================";
           switch(dayIndex)
           {
             case 0:
               System.out.println("Monday");
               out.write("\nMonday");
               rostere+="\nMonday";
               break;
             case 1:
               System.out.println("Tuesday");
               out.write("\nTuesday");
               rostere+="\nTuesday";
               break;
             case 2:
               System.out.println("Wednesday");
               out.write("\nWednesday");
               rostere+="\nWednesday";
               break;
             case 3:
               System.out.println("Thursday");
               out.write("\nThursday");
               rostere+="\nThursday";
               break;
             case 4:
               System.out.println("Friday");
               out.write("\nFriday");
               rostere+="\nFriday";
               break;
             case 5:
               System.out.println("Saturday");
               out.write("\nSaturday");
               rostere+="\nSaturday";
               break;
             case 6:
               System.out.println("Sunday");
               out.write("\nSunday");
               rostere+="\nSunday";
               break;
           }
           out.write("\n=================================================");
           rostere += "\n=================================================";
           if (day < 5)
           {
             dayKind = TimetableInfo.timetableKind.weekday;
           }
           else if (day == 5)
           {
             dayKind = TimetableInfo.timetableKind.saturday;
           }
           else
           {
             dayKind = TimetableInfo.timetableKind.sunday;
           }
           for (int routeIndex=0; routeIndex<2; routeIndex++)
           {
             int[] servicesS = TimetableInfo.getServices(route+routeIndex, dayKind);
             switch(routeIndex)
             {
               case 0:
                 System.out.println("Route 65:");
                 out.write("\nRoute 65:");
                 rostere+="\nRoute 65:";
                 break;
               case 1:
                 System.out.println("Route 66:");
                 out.write("\nRoute 66:");
                 rostere+="\nRoute 66:";
                 break;
               case 2:
                 System.out.println("Route 67:");
                 out.write("\nRoute 67:");
                 rostere+="\nRoute 67:";
                 break;
               case 3:
                 System.out.println("Route 68:");
                 out.write("\nRoute 68:");
                 rostere+="\nRoute 68:";
                 break;
             } // switch
             //System.out.println(servicesS.length);
             rostere+="\n=================================================";
             out.write("\n=================================================");

             for (int service=0; service<servicesS.length; service++)
             {
               int id = slots.get(dayIndex).get(routeIndex).get(service);
               int busID = busSlots.get(dayIndex).get(routeIndex).get(service);
               String name = DriverInfo.getName(id);
               System.out.println("\nRoute / Service: " + (routeIndex+route) + "/"
                                  + servicesS[service]
                                  + "\nDriver: "
                                  + name  + "\nBus:" + busID + "\n");
                       out.write("\nRoute / Service: " + (routeIndex+route) + "/"
                                  + servicesS[service]
                                  + "\nDriver: "
                                  + name + "\nBus:" + busID  + "\n");
                       rostere+="\nRoute / Service: " + (routeIndex+route) + "/"
                                  + servicesS[service]
                                  + "\nDriver: "
                                  + name + "\nBus:" + busID  + "\n";
               //System.out.println("Hours: " + DriverInfo.getHoursThisWeek(id)/60);
             }
             out.write("\n=================================================");
             System.out.println("=================================================");
           }
           //out.write("\n=================================================");
           //System.out.println("=================================================");
           //System.out.println("Successfull generation of roster.");
          // System.out.println("=================================================");
          // rostere+="\n=================================================";
           //out.write("\n=================================================");
         }
rostere+="\n=================================================";
out.write("\n=================================================");
rostere+="\nSuccessfull generation of roster.";
out.close();
  } // try
         catch (Exception e)
         {//Catch exception if any
               System.err.println("Error: " + e.getMessage());
         }
return rostere;
    } // generateRoster
    public static void main(java.lang.String[] args) {
   	 
    	NumberFormat currencyFmt = NumberFormat.getCurrencyInstance();
    	
        try
        {
            authorizationData = new AuthorizationData();
            authorizationData.setDeveloperToken(DeveloperToken);
            authorizationData.setAuthentication(new PasswordAuthentication(UserName, Password));
            authorizationData.setCustomerId(CustomerId);
            authorizationData.setAccountId(AccountId);
	         
            AdIntelligenceService = new ServiceClient<IAdIntelligenceService>(
                    authorizationData, 
                    IAdIntelligenceService.class);
        

            // Set the Currency, Keywords, Language, PublisherCountries, and TargetPositionForAds
            // for the estimated bid by keywords request.
            
            Currency currency = Currency.US_DOLLAR;
            
            ArrayOfKeywordAndMatchType keywordAndMatchTypes = new ArrayOfKeywordAndMatchType();
            ArrayOfMatchType matchTypes = new ArrayOfMatchType();
            matchTypes.getMatchTypes().add(MatchType.EXACT);
            matchTypes.getMatchTypes().add(MatchType.PHRASE);
            matchTypes.getMatchTypes().add(MatchType.BROAD);
            KeywordAndMatchType keywordAndMatchType1 = new KeywordAndMatchType();
            keywordAndMatchType1.setKeywordText("flower");
            keywordAndMatchType1.setMatchTypes(matchTypes);
            keywordAndMatchTypes.getKeywordAndMatchTypes().add(keywordAndMatchType1);
            KeywordAndMatchType keywordAndMatchType2 = new KeywordAndMatchType();
            keywordAndMatchType2.setKeywordText("delivery");
            keywordAndMatchType2.setMatchTypes(matchTypes);
            keywordAndMatchTypes.getKeywordAndMatchTypes().add(keywordAndMatchType2);
            
            java.lang.String language = "English";
            
            ArrayOfstring publisherCountries = new ArrayOfstring();
            publisherCountries.getStrings().add("US");
            
            TargetAdPosition targetPositionForAds = TargetAdPosition.SIDE_BAR;
            
            // GetKeywordEstimatedBidByKeywords helper method calls the corresponding Bing Ads AdIntelligenceService.getService() operation 
            // to request the KeywordEstimatedBids.
            
            ArrayOfKeywordEstimatedBid keywordEstimatedBids = getKeywordEstimatedBidByKeywords(
            	currency,
                keywordAndMatchTypes, 
                language, 
                publisherCountries, 
                targetPositionForAds
                );

            // GetAdGroupEstimatedBidByKeywords helper method calls the corresponding Bing Ads AdIntelligenceService.getService() operation 
            // to request the AdGroupEstimatedBid.
            
            AdGroupEstimatedBid adGroupEstimatedBid = getAdGroupEstimatedBidByKeywords(
                currency,
                keywordAndMatchTypes,
                language,
                publisherCountries,
                targetPositionForAds
                );
			
            // Print the KeywordEstimatedBids

            if (keywordEstimatedBids != null)
            {
            	System.out.println("KeywordEstimatedBids\n");
            	
                for (KeywordEstimatedBid bid : keywordEstimatedBids.getKeywordEstimatedBids())
                {
                    if (bid == null)
                    {
                        System.out.println("The keyword is not valid.\n");
                    }
                    else
                    {
                        System.out.println(bid.getKeyword());

                        if (bid.getEstimatedBids() == null)
                        {
                            System.out.println("  There is no bid information available for the keyword.\n");
                        }
                        else
                        {
                            for (EstimatedBidAndTraffic estimatedBidAndTraffic : bid.getEstimatedBids().getEstimatedBidAndTraffics())
                            {
                            	System.out.println("    Estimated Minimum Bid: " + 
                                        currencyFmt.format(estimatedBidAndTraffic.getEstimatedMinBid()));
                                System.out.println("    Match Type: " + estimatedBidAndTraffic.getMatchType());
                                System.out.println("    Average CPC: " + 
                                        (estimatedBidAndTraffic.getAverageCPC() != null ? currencyFmt.format(estimatedBidAndTraffic.getAverageCPC()) : "null"));
                                System.out.printf("    Estimated clicks per week: %s to %s\n",
                                		estimatedBidAndTraffic.getMinClicksPerWeek(), estimatedBidAndTraffic.getMaxClicksPerWeek());
                                System.out.printf("    Estimated impressions per week: %s to %s\n",
                                		estimatedBidAndTraffic.getMinImpressionsPerWeek(), estimatedBidAndTraffic.getMaxImpressionsPerWeek());
                                System.out.printf("    Estimated cost per week: %s to %s\n",
                                    (estimatedBidAndTraffic.getMinTotalCostPerWeek() != null ? currencyFmt.format(estimatedBidAndTraffic.getMinTotalCostPerWeek()) : "null"),
                                    (estimatedBidAndTraffic.getMaxTotalCostPerWeek() != null ? currencyFmt.format(estimatedBidAndTraffic.getMaxTotalCostPerWeek()) : "null"));
                                System.out.println();
                            }
                        }
                    }
                }
            }
            
            // Print the AdGroupEstimatedBid

            if (adGroupEstimatedBid != null) {
            	System.out.println("AdGroupEstimatedBid\n");
                
                System.out.println("    Estimated Ad Group Bid: " + 
                        currencyFmt.format(adGroupEstimatedBid.getEstimatedAdGroupBid()));
                System.out.println("    Average CPC: " + 
                        (adGroupEstimatedBid.getAverageCPC() != null ? currencyFmt.format(adGroupEstimatedBid.getAverageCPC()) : "null"));
                System.out.printf("    Estimated clicks per week: %s to %s\n",
                		adGroupEstimatedBid.getMinClicksPerWeek(), adGroupEstimatedBid.getMaxClicksPerWeek());
                System.out.printf("    Estimated impressions per week: %s to %s\n",
                		adGroupEstimatedBid.getMinImpressionsPerWeek(), adGroupEstimatedBid.getMaxImpressionsPerWeek());
                System.out.printf("    Estimated cost per week: %s to %s\n",
                    (adGroupEstimatedBid.getMinTotalCostPerWeek() != null ? currencyFmt.format(adGroupEstimatedBid.getMinTotalCostPerWeek()) : "null"),
                    (adGroupEstimatedBid.getMaxTotalCostPerWeek() != null ? currencyFmt.format(adGroupEstimatedBid.getMaxTotalCostPerWeek()) : "null"));
                System.out.println();
             }

        // Ad Intelligence service operations can throw AdApiFaultDetail.
        } catch (AdApiFaultDetail_Exception ex) {
            System.out.println("The operation failed with the following faults:\n");

            for (AdApiError error : ex.getFaultInfo().getErrors().getAdApiErrors())
            {
                System.out.printf("AdApiError\n");
                System.out.printf("Code: %d\nError Code: %s\nMessage: %s\n\n", error.getCode(), error.getErrorCode(), error.getMessage());
            }
        
        // Ad Intelligence service operations can throw ApiFaultDetail.
        } catch (ApiFaultDetail_Exception ex) {
            System.out.println("The operation failed with the following faults:\n");

            for (BatchError error : ex.getFaultInfo().getBatchErrors().getBatchErrors())
            {
                System.out.printf("BatchError at Index: %d\n", error.getIndex());
                System.out.printf("Code: %d\nMessage: %s\n\n", error.getCode(), error.getMessage());
            }

            for (OperationError error : ex.getFaultInfo().getOperationErrors().getOperationErrors())
            {
                System.out.printf("OperationError\n");
                System.out.printf("Code: %d\nMessage: %s\n\n", error.getCode(), error.getMessage());
            }
        } catch (RemoteException ex) {
            System.out.println("Service communication error encountered: ");
            System.out.println(ex.getMessage());
            ex.printStackTrace();
        } catch (Exception ex) {
             System.out.println("Error encountered: ");
             System.out.println(ex.getMessage());
             ex.printStackTrace();
         }
    }
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {
      Locales.setCurrent(request);
      if (Users.getCurrent() == null) { // for a bug in websphere portal 5.1 with Domino LDAP
        Users.setCurrent((String) request.getSession().getAttribute("xava.user"));
      }
      request.getParameter("application"); // for a bug in websphere 5.1
      request.getParameter("module"); // for a bug in websphere 5.1
      Tab tab = (Tab) request.getSession().getAttribute("xava_reportTab");
      int[] selectedRowsNumber =
          (int[]) request.getSession().getAttribute("xava_selectedRowsReportTab");
      Map[] selectedKeys = (Map[]) request.getSession().getAttribute("xava_selectedKeysReportTab");
      int[] selectedRows = getSelectedRows(selectedRowsNumber, selectedKeys, tab);
      request.getSession().removeAttribute("xava_selectedRowsReportTab");
      Integer columnCountLimit =
          (Integer) request.getSession().getAttribute("xava_columnCountLimitReportTab");
      request.getSession().removeAttribute("xava_columnCountLimitReportTab");

      setDefaultSchema(request);
      String user = (String) request.getSession().getAttribute("xava_user");
      request.getSession().removeAttribute("xava_user");
      Users.setCurrent(user);
      String uri = request.getRequestURI();
      if (uri.endsWith(".pdf")) {
        InputStream is;
        JRDataSource ds;
        Map parameters = new HashMap();
        synchronized (tab) {
          tab.setRequest(request);
          parameters.put("Title", tab.getTitle());
          parameters.put("Organization", getOrganization());
          parameters.put("Date", getCurrentDate());
          for (String totalProperty : tab.getTotalPropertiesNames()) {
            parameters.put(totalProperty + "__TOTAL__", getTotal(request, tab, totalProperty));
          }
          TableModel tableModel = getTableModel(request, tab, selectedRows, false, true, null);
          tableModel.getValueAt(0, 0);
          if (tableModel.getRowCount() == 0) {
            generateNoRowsPage(response);
            return;
          }
          is = getReport(request, response, tab, tableModel, columnCountLimit);
          ds = new JRTableModelDataSource(tableModel);
        }
        JasperPrint jprint = JasperFillManager.fillReport(is, parameters, ds);
        response.setContentType("application/pdf");
        response.setHeader(
            "Content-Disposition", "inline; filename=\"" + getFileName(tab) + ".pdf\"");
        JasperExportManager.exportReportToPdfStream(jprint, response.getOutputStream());
      } else if (uri.endsWith(".csv")) {
        String csvEncoding = XavaPreferences.getInstance().getCSVEncoding();
        if (!Is.emptyString(csvEncoding)) {
          response.setCharacterEncoding(csvEncoding);
        }
        response.setContentType("text/x-csv");
        response.setHeader(
            "Content-Disposition", "inline; filename=\"" + getFileName(tab) + ".csv\"");
        synchronized (tab) {
          tab.setRequest(request);
          response
              .getWriter()
              .print(
                  TableModels.toCSV(
                      getTableModel(request, tab, selectedRows, true, false, columnCountLimit)));
        }
      } else {
        throw new ServletException(
            XavaResources.getString("report_type_not_supported", "", ".pdf .csv"));
      }
    } catch (Exception ex) {
      log.error(ex.getMessage(), ex);
      throw new ServletException(XavaResources.getString("report_error"));
    } finally {
      request.getSession().removeAttribute("xava_reportTab");
    }
  }
  private void register() throws IOException {
    Log.info("Registering with " + registrar);
    FromHeader fromHeader = getFromHeader();
    Address fromAddress = fromHeader.getAddress();

    // Request URI
    SipURI requestURI = null;
    try {
      requestURI = addressFactory.createSipURI(null, registrar);

    } catch (ParseException e) {
      throw new IOException("Bad registrar address:" + registrar + " " + e.getMessage());
    }
    // requestURI.setPort(registrarPort);

    try {
      requestURI.setTransportParam(sipProvider.getListeningPoint().getTransport());

    } catch (ParseException e) {
      throw new IOException(
          sipProvider.getListeningPoint().getTransport()
              + " is not a valid transport! "
              + e.getMessage());
    }

    CallIdHeader callIdHeader = sipProvider.getNewCallId();
    CSeqHeader cSeqHeader = null;

    try {
      cSeqHeader = headerFactory.createCSeqHeader(1, Request.REGISTER);
    } catch (ParseException e) {
      // Should never happen
      throw new IOException("Corrupt Sip Stack " + e.getMessage());
    } catch (InvalidArgumentException e) {
      // Should never happen
      throw new IOException("The application is corrupt ");
    }

    ToHeader toHeader = null;
    try {
      String proxyWorkAround = System.getProperty("com.sun.mc.softphone.REGISTRAR_WORKAROUND");

      if (proxyWorkAround != null && proxyWorkAround.toUpperCase().equals("TRUE")) {

        SipURI toURI = (SipURI) (requestURI.clone());
        toURI.setUser(System.getProperty("user.name"));

        toHeader = headerFactory.createToHeader(addressFactory.createAddress(toURI), null);
      } else {
        toHeader = headerFactory.createToHeader(fromAddress, null);
      }
    } catch (ParseException e) {
      throw new IOException(
          "Could not create a To header for address:"
              + fromHeader.getAddress()
              + " "
              + e.getMessage());
    }

    ArrayList viaHeaders = getLocalViaHeaders();
    MaxForwardsHeader maxForwardsHeader = getMaxForwardsHeader();
    Request request = null;

    try {
      request =
          messageFactory.createRequest(
              requestURI,
              Request.REGISTER,
              callIdHeader,
              cSeqHeader,
              fromHeader,
              toHeader,
              viaHeaders,
              maxForwardsHeader);
    } catch (ParseException e) {
      throw new IOException("Could not create the register request! " + e.getMessage());
    }

    ExpiresHeader expHeader = null;

    for (int retry = 0; retry < 2; retry++) {
      try {
        expHeader = headerFactory.createExpiresHeader(expires);
      } catch (InvalidArgumentException e) {
        if (retry == 0) {
          continue;
        }
        throw new IOException(
            "Invalid registrations expiration parameter - " + expires + " " + e.getMessage());
      }
    }

    request.addHeader(expHeader);
    ContactHeader contactHeader = getRegistrationContactHeader();
    request.addHeader(contactHeader);

    try {
      SipURI routeURI =
          (SipURI) addressFactory.createURI("sip:" + proxyCredentials.getProxy() + ";lr");
      RouteHeader routeHeader =
          headerFactory.createRouteHeader(addressFactory.createAddress(routeURI));
      request.addHeader(routeHeader);

    } catch (Exception e) {

      Log.error("Creating registration route error ", e);
    }

    ClientTransaction regTrans = null;
    try {
      regTrans = sipProvider.getNewClientTransaction(request);
    } catch (TransactionUnavailableException e) {
      throw new IOException(
          "Could not create a register transaction!\n"
              + "Check that the Registrar address is correct! "
              + e.getMessage());
    }

    try {
      sipCallId = callIdHeader.getCallId();
      sipServerCallback.addSipListener(sipCallId, this);
      registerRequest = request;
      regTrans.sendRequest();

      Log.debug("Sent register request " + registerRequest);

      if (expires > 0) {
        scheduleReRegistration();
      }
    } catch (Exception e) {
      throw new IOException("Could not send out the register request! " + e.getMessage());
    }

    this.registerRequest = request;
  }
Exemple #20
0
  /** Runs BLOAT on a method. */
  public static void bloatMethod(final MethodEditor m, final BloatContext context) {
    try {
      if (Main.COMPACT_ARRAY_INIT) {
        // Compact the initialization of arrays of the basic types by
        // putting the values of the array into a string in the constant
        // pool. The initialization code is replaced with a loop that
        // loads the array from the string in the constant pool.

        if (Main.TRACE) {
          System.out.println("  Compacting Arrays: " + Main.dateFormat.format(new Date()));
        }

        CompactArrayInitializer.transform(m);

        if (Main.DEBUG) {
          System.out.println("---------- After compaction:");
          m.print(System.out);
          System.out.println("---------- end print");
        }
      }

      FlowGraph cfg; // The control flow graph for a method

      if (Main.TRACE) {
        System.out.println("  Constructing CFG: " + Main.dateFormat.format(new Date()));
      }

      try {
        // Construct the control flow graph for method m
        cfg = new FlowGraph(m);
      } catch (final ClassFormatException ex) {
        System.err.println(ex.getMessage());
        context.release(m.methodInfo());
        return;
      }

      // We separate out initialization since before this the FlowGraph
      // more exactly represents the input program.
      cfg.initialize();

      if (Main.TRACE) {
        System.out.println("  Transforming to SSA: " + Main.dateFormat.format(new Date()));
      }

      SSA.transform(cfg);

      if (FlowGraph.DEBUG) {
        System.out.println("---------- After SSA:");
        cfg.print(System.out);
        System.out.println("---------- end print");
      }

      if (Main.DEBUG) {
        cfg.visit(new VerifyCFG(false));
      }

      if (!Tree.USE_STACK) {
        // Do copy propagation and value numbering first to get rid of
        // all the extra copies inserted for dups. If they're left in,
        // it really slows down value numbering.
        if (Main.PROP) {
          if (Main.DEBUG) {
            System.out.println("-----Before Copy Propagation-----");
          }

          if (Main.TRACE) {
            System.out.println("  Copy propagation: " + Main.dateFormat.format(new Date()));
          }

          final ExprPropagation copy = new ExprPropagation(cfg);
          copy.transform();

          if (Main.DEBUG) {
            cfg.visit(new VerifyCFG(false));
          }

          if (Main.DEBUG) {
            System.out.println("------After Copy Propagation-----");
            cfg.print(System.out);
          }
        }
      }

      DeadCodeElimination dce = null;

      if (Main.DCE) {

        if (Main.TRACE) {
          System.out.println("  Dead Code Elimination: " + Main.dateFormat.format(new Date()));
        }

        if (Main.DEBUG) {
          System.out.println("---Before Dead Code Elimination--");
        }

        dce = new DeadCodeElimination(cfg);
        dce.transform();

        if (Main.DEBUG) {
          cfg.visit(new VerifyCFG(false));
        }

        if (Main.DEBUG) {
          System.out.println("---After Dead Code Elimination---");
          cfg.print(System.out);
        }
      }

      if (Main.INFER) {

        if (Main.DEBUG) {
          System.out.println("---------Doing type inference--------");
        }

        if (Main.TRACE) {
          System.out.println("  Type Inferencing: " + Main.dateFormat.format(new Date()));
        }

        TypeInference.transform(cfg, context.getHierarchy());
      }

      if (Main.NUMBER) {

        if (Main.TRACE) {
          System.out.println("  Value Numbering: " + Main.dateFormat.format(new Date()));
        }

        if (Main.DEBUG) {
          System.out.println("--------Doing value numbering--------");
        }

        (new ValueNumbering()).transform(cfg);
      }

      if (Main.FOLD) {
        if (Main.DEBUG) {
          System.out.println("--------Before Value Folding---------");
        }

        if (Main.TRACE) {
          System.out.println("  Value Folding: " + Main.dateFormat.format(new Date()));
        }

        (new ValueFolding()).transform(cfg);

        if (Main.DEBUG) {
          cfg.visit(new VerifyCFG());
        }

        if (Main.DEBUG) {
          System.out.println("---------After Value Folding---------");
          cfg.print(System.out);
        }
      }

      if (Main.PRE) {
        if (Main.DEBUG) {
          System.out.println("-------------Before SSAPRE-----------");
        }

        if (Main.TRACE) {
          System.out.println("  SSAPRE: " + Main.dateFormat.format(new Date()));
        }

        final SSAPRE pre = new SSAPRE(cfg, context);
        pre.transform();

        if (Main.DEBUG) {
          cfg.visit(new VerifyCFG());
        }

        if (Main.DEBUG) {
          System.out.println("-------------After SSAPRE------------");
          cfg.print(System.out);
        }
      }

      if (Main.FOLD) {
        if (Main.DEBUG) {
          System.out.println("--------Before Value Folding---------");
        }

        if (Main.TRACE) {
          System.out.println("  Value Folding: " + Main.dateFormat.format(new Date()));
        }

        (new ValueFolding()).transform(cfg);

        if (Main.DEBUG) {
          cfg.visit(new VerifyCFG());
        }

        if (Main.DEBUG) {
          System.out.println("---------After Value Folding---------");
          cfg.print(System.out);
        }
      }

      if (Main.PROP) {
        if (Main.DEBUG) {
          System.out.println("-------Before Copy Propagation-------");
        }

        if (Main.TRACE) {
          System.out.println("  Copy Propagation " + Main.dateFormat.format(new Date()));
        }

        final ExprPropagation copy = new ExprPropagation(cfg);
        copy.transform();

        if (Main.DEBUG) {
          cfg.visit(new VerifyCFG());
        }

        if (Main.DEBUG) {
          System.out.println("--------After Copy Propagation-------");
          cfg.print(System.out);
        }
      }

      // make sure we've done at least one thing since the last DCE
      if (Main.DCE && (Main.INFER || Main.NUMBER || Main.FOLD || Main.PRE || Main.PROP)) {
        if (Main.DEBUG) {
          System.out.println("-----Before Dead Code Elimination----");
        }

        if (Main.TRACE) {
          System.out.println("  Dead Code Elimination: " + Main.dateFormat.format(new Date()));
        }

        dce = new DeadCodeElimination(cfg);
        dce.transform();

        if (Main.DEBUG) {
          cfg.visit(new VerifyCFG());
        }

        if (Main.DEBUG) {
          System.out.println("-----After Dead Code Elimination-----");
          cfg.print(System.out);
        }
      }

      if (Main.PERSIST) {
        (new PersistentCheckElimination()).transform(cfg);
      }

      if (Main.DIVA) {
        if (Main.DEBUG) {
          System.out.println("-----Before DIVA------");
        }

        if (Main.TRACE) {
          System.out.println("  DIVA: " + Main.dateFormat.format(new Date()));
        }

        (new InductionVarAnalyzer()).transform(cfg);

        if (Main.DEBUG) {
          System.out.println("-----After DIVA-----");
          cfg.print(System.out);
        }
      }

      /*
       * if (STACK_ALLOC) { if (DEBUG) {
       * System.out.println("------------Before StackPRE----------"); }
       *
       * StackPRE pre = new StackPRE(cfg); pre.transform();
       *
       * if (DEBUG) { cfg.visit(new VerifyCFG()); }
       *
       * if (DEBUG) { System.out.println("------------After
       * StackPRE-----------"); cfg.print(System.out); } }
       */

      // Do the new stack optimization
      if (Main.OPT_STACK_2) {

        if (Main.TRACE) {
          System.out.println("  New stack optimization: " + Main.dateFormat.format(new Date()));
        }

        // generate code without doing liveness or register allocation
        final CodeGenerator codegen = new CodeGenerator(m);
        codegen.replacePhis(cfg);
        m.clearCode2();
        cfg.visit(codegen);
        // do stack optimization on the bytecode

        final StackOpt so = new StackOpt();
        so.transform(m);

        // convert it back to a cfg
        cfg = new FlowGraph(m);
        cfg.initialize();

        // convert it back to SSA
        SSA.transform(cfg);

        // do more dead code elimination (eliminate stores)
        dce = new DeadCodeElimination(cfg);
        dce.transform();
      }

      if (Main.TRACE) {
        System.out.println("  Register allocation: " + Main.dateFormat.format(new Date()));
      }

      if (Main.VERIFY) {
        try {
          cfg.visit(new VerifyCFG());
        } catch (final IllegalArgumentException ee) {
          System.out.println(
              " NOTE: CFG did not verify while "
                  + "bloating "
                  + m.name()
                  + " after all optimizations. Exception: "
                  + ee);
        }
      }

      // We're all done performing optimizations. Let's generate some code
      // and go home.

      // Perform liveness analysis of variables in the method.
      // Assign local variables ("registers") to expression values.
      final Liveness liveness = new Liveness(cfg);
      final RegisterAllocator alloc = new RegisterAllocator(cfg, liveness);

      // Gather information which can be used to optimize use of the stack
      if (CodeGenerator.OPT_STACK) {
        if (Main.TRACE) {
          System.out.println("  Old stack optimization: " + Main.dateFormat.format(new Date()));
        }
        StackOptimizer.optimizeCFG(cfg);
      }

      if (Main.TRACE) {
        System.out.println("  Code Generation: " + Main.dateFormat.format(new Date()));
      }

      // Start the code generation process.
      final CodeGenerator codegen = new CodeGenerator(m);
      codegen.replacePhis(cfg);

      if (Main.DEBUG) {
        System.out.println("After fixing Phis------------------------");
        cfg.print(System.out);
        System.out.println("End print--------------------------------");
      }

      codegen.simplifyControlFlow(cfg);
      codegen.allocReturnAddresses(cfg, alloc);

      if (Main.DEBUG) {
        System.out.println("After removing empty blocks--------------");
        cfg.print(System.out);
        System.out.println("End print--------------------------------");
      }

      // Clear the old contents of the bytecode store and generate new
      // code.
      // Code is generated using a visitor pattern on the CFG.
      m.clearCode();
      cfg.visit(codegen);

      Peephole.transform(m);

      // Commit any changes that have been made to the method
      context.commit(m.methodInfo());

    } catch (final Exception ex99) {
      final String msg =
          "** Exception while optimizing "
              + m.name()
              + m.type()
              + " of class "
              + m.declaringClass().name();
      System.err.println(msg);
      System.err.println(ex99.getMessage());
      ex99.printStackTrace(System.err);
      System.exit(1);
    }
  }
  public void get_wallet_balance() { // **********************

    System.out.println("Get Balance...");

    rpcurl = lm.carbon_settings[10];

    rpcaddress = lm.rpcaddress_confirm;

    rpcuser = lm.carbon_settings[12];
    rpcpassword = lm.carbon_settings[13];

    System.out.println(rpcuser);
    System.out.println(rpcpassword);
    System.out.println(rpcaddress);

    String line = new String();
    String line2 = new String();

    String url1 =
        new String(
            "https://blockchain.info/merchant/"
                + rpcuser
                + "/address_balance?password="******"&address="
                + rpcaddress
                + "&confirmations=6");

    try {

      // Sets the authenticator that will be used by the networking code
      // when a proxy or an HTTP server asks for authentication.

      // Authenticator.setDefault(new CustomAuthenticator());
      System.out.println("GO0");

      URL url = new URL(url1);
      HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

      System.out.println("GO1");

      // read text returned by server
      BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      // BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
      // BufferedReader in = new BufferedReader(null);

      while ((line = in.readLine()) != null) {

        System.out.println(line);
        line2 = line2 + line;
      }

      in.close();

      JSONParser parser = new JSONParser();

      try {

        Object obj = parser.parse(line2);

        JSONObject jsonObject = (JSONObject) obj;

        String address = (String) jsonObject.get("address");
        System.out.println(address);

        String balance = (String) jsonObject.get("balance").toString();
        System.out.println(balance);
        lm.wallet_value_confirm = (long) Long.parseLong(balance);
        System.out.println("lm.wallet_value_confirm " + lm.wallet_value_confirm);

      } // try
      catch (ParseException e) {
        e.printStackTrace();
      }

    } // try
    catch (MalformedURLException e) {
      System.out.println("Malformed URL: " + e.getMessage());
    } catch (IOException e) {
      System.out.println("I/O Error: " + e.getMessage());
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  } // ***************test_for_sales()
Exemple #22
0
  // Process the request
  private String processRequest(HttpServletRequest request, HttpServletResponse response) {
    String command = request.getParameter("command");
    String id = request.getParameter("id");
    String description = request.getParameter("description");
    String status = request.getParameter("rstatus");
    status = (status != null && status.compareTo(" ") > 0) ? status : null;
    String outLine = "";
    // String nextScript = "home.jsp";
    String nextScript = request.getParameter("nextscript");
    OutputStream toClient;
    HttpSession session = request.getSession();
    boolean success = false;
    String userIDs = (String) session.getAttribute("user.id");
    long userID = Long.parseLong(userIDs);

    command = (command != null && command.compareTo(" ") > 0) ? command : "form";
    nextScript = (nextScript != null && nextScript.compareTo(" ") > 0) ? nextScript : "roles.jsp";

    //    inputstring = (inputstring != null && inputstring.compareTo(" ") > 0) ? inputstring : "";

    DbConn myConn = null;
    try {

      Context initCtx = new InitialContext();
      // String csiSchema = (String) initCtx.lookup("java:comp/env/csi-schema-path");
      String acronym = (String) initCtx.lookup("java:comp/env/SystemAcronym");
      myConn = new DbConn();
      String csiSchema = myConn.getSchemaPath();
      if (command.equals("add")) {
        Role item = new Role();
        item.setDescription(description);
        item.setStatus(status);
        getPermissions(request, item);
        getPositions(request, item);
        item.add(myConn, userID);
        GlobalMembership.refresh(myConn);
        success = true;
        outLine = "";

      } else if (command.equals("update")) {
        Role item = new Role(myConn, Long.parseLong(id));
        item.setDescription(description);
        item.setStatus(status);
        getPermissions(request, item);
        getPositions(request, item);
        item.save(myConn, userID);
        GlobalMembership.refresh(myConn);
        success = true;
        outLine = "";
      } else if (command.equals("drop")) {
        Role item = new Role(myConn, Long.parseLong(id));
        item.drop(myConn, userID);
        success = true;
        outLine = "Role " + item.getDescription() + " Removed";
      } else if (command.equals("test")) {
        outLine = "test";
      }

    } catch (IllegalArgumentException e) {
      outLine = outLine + "IllegalArgumentException caught: " + e.getMessage();
      ALog.logActivity(userID, "csi", 0, "Role error: '" + outLine + "'");
      // log(outLine);
    } catch (NullPointerException e) {
      outLine = outLine + "NullPointerException caught: " + e.getMessage();
      ALog.logActivity(userID, "csi", 0, "Role error: '" + outLine + "'");
      // log(outLine);
    }

    // catch (IOException e) {
    //    outLine = outLine + "IOException caught: " + e.getMessage();
    //    ALog.logActivity(userID, "csi", 0, "Role error: '" + outLine + "'");
    //    //log(outLine);
    // }

    catch (Exception e) {
      outLine = outLine + "Exception caught: " + e.getMessage();
      ALog.logActivity(userID, "csi", 0, "Role error: '" + outLine + "'");
      // log(outLine);
    } finally {
      try {
        generateResponse(outLine, command, nextScript, success, response);
      } catch (Exception i) {
      }

      myConn.release();
      // log("Test log message\n");
    }

    return outLine;
  }
  /** The main event handling code. */
  public void handleEvent(QueueElementIF item) {

    try {
      if (DEBUG) System.err.println("**** GOT: " + item);

      if (item instanceof GnutellaPingPacket) {
        GnutellaPingPacket ping = (GnutellaPingPacket) item;
        if (VERBOSE) System.err.println("-- Got ping: " + ping);

        if (ROUTE_PACKETS) {
          if (rememberPacket(ping)) {
            forwardPacketToAll(ping);
          }
        }

        if (SEND_PONGS) {
          GnutellaPongPacket pong = new GnutellaPongPacket(ping.getGUID(), NUM_FILES, NUM_KB);
          if (VERBOSE) System.err.println("-- Sending pong to: " + ping.getConnection());
          ping.getConnection().enqueue_lossy(pong);
        }

      } else if (item instanceof GnutellaQueryPacket) {
        GnutellaQueryPacket query = (GnutellaQueryPacket) item;
        if (VERBOSE) System.err.println("-- Got query: " + query.getSearchTerm());

        if (ROUTE_PACKETS) {
          if (rememberPacket(query)) {
            forwardPacketToAll(query);
          }
        }

      } else if (item instanceof GnutellaPongPacket) {
        GnutellaPongPacket pong = (GnutellaPongPacket) item;
        if (VERBOSE) System.err.println("-- Got pong: " + pong);
        if (ROUTE_PACKETS) forwardPacket(pong);

      } else if (item instanceof GnutellaQueryHitsPacket) {
        GnutellaQueryHitsPacket hits = (GnutellaQueryHitsPacket) item;
        if (VERBOSE) System.err.println("-- Got hits: " + hits);
        if (ROUTE_PACKETS) forwardPacket(hits);

      } else if (item instanceof GnutellaPushPacket) {
        if (VERBOSE) System.err.println("-- Dropping push packet (unimplemented)");

      } else if (item instanceof GnutellaConnection) {
        if (VERBOSE) System.err.println("-- New connection: " + item);
        num_connections++;

      } else if (item instanceof SinkClosedEvent) {
        if (VERBOSE) System.err.println("-- Connection closed: " + item);
        num_connections--;
        SinkClosedEvent sce = (SinkClosedEvent) item;

        if ((num_connections <= MIN_CONNECTIONS) && DO_CATCHER) doCatcher();

      } else if (item instanceof SinkCloggedEvent) {
        if (VERBOSE) System.err.println("-- Connection clogged: " + item);
        SinkCloggedEvent clogged = (SinkCloggedEvent) item;
        // Close down clogged connections
        GnutellaConnection gc = (GnutellaConnection) clogged.sink;
        System.err.println("GL: Closing clogged connection " + gc);
        gc.close(mySink);

      } else if (item instanceof timerEvent) {
        doTimer((timerEvent) item);
      }

    } catch (Exception e) {
      System.err.println("WORKER GOT EXCEPTION: " + e.getMessage());
      e.printStackTrace();
    }
  }
  // Process the request
  private String processRequest(HttpServletRequest request, HttpServletResponse response) {
    HttpSession session = request.getSession();
    String userIDs = (String) session.getAttribute("user.id");
    userIDs = (userIDs != null && userIDs.compareTo(" ") > 0) ? userIDs : "0";
    long userID = Long.parseLong(userIDs);
    String command = request.getParameter("command");
    String template = request.getParameter("template");
    String pageHash = request.getParameter("pagehash");
    String pageTitle = request.getParameter("pagetitle");
    String pageDescription = request.getParameter("pagedescription");

    String outLine = "";
    String nextScript = request.getParameter("nextscript");
    OutputStream toClient;
    boolean success = false;

    // System.out.println("userid=" + userID + ", id=" + id + ", command=" + command);

    command = (command != null && command.compareTo(" ") > 0) ? command : "form";
    nextScript = (nextScript != null && nextScript.compareTo(" ") > 0) ? nextScript : "simple1.jsp";

    //    inputstring = (inputstring != null && inputstring.compareTo(" ") > 0) ? inputstring : "";

    DbConn myConn = null;
    try {

      Context initCtx = new InitialContext();
      // String csiSchema = (String) initCtx.lookup("java:comp/env/csi-schema-path");
      // String acronym = (String) initCtx.lookup("java:comp/env/SystemAcronym");
      myConn = new DbConn();
      String csiSchema = myConn.getSchemaPath();
      if (userID != 0) {
        if (command.equals("add")) {
          outLine = "";
        } else if (command.equals("update")) {
          outLine = "";
        } else if (command.equals("updatepage")) {
          UHash uPage = new UHash(pageHash, myConn);
          // System.out.println("Got Here 1");
          if (template.equals("simple1")) {
            TextItem title = new TextItem(uPage.get("title"), myConn);
            title.setText(pageTitle);
            title.save(myConn);
            TextItem description = new TextItem(uPage.get("description"), myConn);
            description.setText(pageDescription);
            description.save(myConn);
          } else if (template.equals("simple2")) {
          }

        } else if (command.equals("test")) {
          outLine = "test";
        }
        success = true;
      }

    } catch (IllegalArgumentException e) {
      outLine = outLine + "IllegalArgumentException caught: " + e.getMessage();
      ALog.logActivity(userID, "csi", 0, pageHash + " error: '" + outLine + "'");
      // log(outLine);
    } catch (NullPointerException e) {
      outLine = outLine + "NullPointerException caught: " + e.getMessage();
      ALog.logActivity(userID, "csi", 0, pageHash + " error: '" + outLine + "'");
      // log(outLine);
    }

    // catch (IOException e) {
    //    outLine = outLine + "IOException caught: " + e.getMessage();
    //    ALog.logActivity(userID, "csi", 0, pageHash + " error: '" + outLine + "'");
    //    //log(outLine);
    // }

    catch (Exception e) {
      outLine = outLine + "Exception caught: " + e.getMessage();
      ALog.logActivity(userID, "csi", 0, pageHash + " error: '" + outLine + "'");
      // log(outLine);
    } finally {
      try {
        generateResponse(outLine, command, nextScript, success, response);
      } catch (Exception i) {
      }

      myConn.release();
      // log("Test log message\n");
    }

    return outLine;
  }
  /**
   * Process the specified HTTP request, and create the corresponding HTTP response (or forward to
   * another web component that will create it). Return an <code>ActionForward</code> instance
   * describing where and how control should be forwarded, or <code>null</code> if the response has
   * already been completed.
   *
   * @param mapping The ActionMapping used to select this instance
   * @param form The optional ActionForm bean for this request (if any)
   * @param request The HTTP request we are processing
   * @param response The HTTP response we are creating
   * @exception Exception if business logic throws an exception
   */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    // Extract attributes we will need
    MessageResources messages = getResources(request);

    // save errors
    ActionMessages errors = new ActionMessages();

    // START check for login (security)
    if (!SecurityService.getInstance().checkForLogin(request.getSession(false))) {
      return (mapping.findForward("welcome"));
    }
    // END check for login (security)

    // START get id of current project from either request, attribute, or cookie
    // id of project from request
    String projectId = null;
    projectId = request.getParameter("projectViewId");

    // check attribute in request
    if (projectId == null) {
      projectId = (String) request.getAttribute("projectViewId");
    }

    // id of project from cookie
    if (projectId == null) {
      projectId = StandardCode.getInstance().getCookie("projectViewId", request.getCookies());
    }

    // default project to last if not in request or cookie
    if (projectId == null) {
      java.util.List results = ProjectService.getInstance().getProjectList();

      ListIterator iterScroll = null;
      for (iterScroll = results.listIterator(); iterScroll.hasNext(); iterScroll.next()) {}
      iterScroll.previous();
      Project p = (Project) iterScroll.next();
      projectId = String.valueOf(p.getProjectId());
    }

    Integer id = Integer.valueOf(projectId);

    // END get id of current project from either request, attribute, or cookie

    // get project
    Project p = ProjectService.getInstance().getSingleProject(id);

    // get user (project manager)
    User u =
        UserService.getInstance()
            .getSingleUserRealName(
                StandardCode.getInstance().getFirstName(p.getPm()),
                StandardCode.getInstance().getLastName(p.getPm()));

    // START process pdf
    try {
      PdfReader reader = new PdfReader("C://templates/CL01_001.pdf"); // the template

      // save the pdf in memory
      ByteArrayOutputStream pdfStream = new ByteArrayOutputStream();

      // the filled-in pdf
      PdfStamper stamp = new PdfStamper(reader, pdfStream);

      // stamp.setEncryption(true, "pass", "pass", PdfWriter.AllowCopy | PdfWriter.AllowPrinting);
      AcroFields form1 = stamp.getAcroFields();
      Date cDate = new Date();
      Integer month = cDate.getMonth();
      Integer day = cDate.getDate();
      Integer year = cDate.getYear() + 1900;
      String[] monthName = {
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December"
      };

      // set the field values in the pdf form
      // form1.setField("", projectId)
      form1.setField("currentdate", monthName[month] + " " + day + ", " + year);
      form1.setField(
          "firstname", StandardCode.getInstance().noNull(p.getContact().getFirst_name()));
      form1.setField("pm", p.getPm());
      form1.setField("emailpm", u.getWorkEmail1());
      if (u.getWorkPhoneEx() != null && u.getWorkPhoneEx().length() > 0) { // ext present
        form1.setField(
            "phonepm",
            StandardCode.getInstance().noNull(u.getWorkPhone())
                + " ext "
                + StandardCode.getInstance().noNull(u.getWorkPhoneEx()));
      } else { // no ext present
        form1.setField("phonepm", StandardCode.getInstance().noNull(u.getWorkPhone()));
      }
      form1.setField("faxpm", StandardCode.getInstance().noNull(u.getLocation().getFax_number()));
      form1.setField("postalpm", StandardCode.getInstance().printLocation(u.getLocation()));

      // START add images
      //                if(u.getPicture() != null && u.getPicture().length() > 0) {
      //                    PdfContentByte over;
      //                    Image img = Image.getInstance("C:/Program Files (x86)/Apache Software
      // Foundation/Tomcat 7.0/webapps/logo/images/" + u.getPicture());
      //                    img.setAbsolutePosition(200, 200);
      //                    over = stamp.getOverContent(1);
      //                    over.addImage(img, 54, 0,0, 65, 47, 493);
      //                }
      // END add images
      form1.setField("productname", StandardCode.getInstance().noNull(p.getProduct()));
      form1.setField("project", p.getNumber() + p.getCompany().getCompany_code());
      form1.setField("description", StandardCode.getInstance().noNull(p.getProductDescription()));
      form1.setField("additional", p.getProjectRequirements());

      // get sources and targets
      StringBuffer sources = new StringBuffer("");
      StringBuffer targets = new StringBuffer("");
      if (p.getSourceDocs() != null) {
        for (Iterator iterSource = p.getSourceDocs().iterator(); iterSource.hasNext(); ) {
          SourceDoc sd = (SourceDoc) iterSource.next();
          sources.append(sd.getLanguage() + " ");
          if (sd.getTargetDocs() != null) {
            for (Iterator iterTarget = sd.getTargetDocs().iterator(); iterTarget.hasNext(); ) {
              TargetDoc td = (TargetDoc) iterTarget.next();
              if (!td.getLanguage().equals("All")) targets.append(td.getLanguage() + " ");
            }
          }
        }
      }

      form1.setField("source", sources.toString());
      form1.setField("target", targets.toString());
      form1.setField(
          "start",
          (p.getStartDate() != null)
              ? DateFormat.getDateInstance(DateFormat.SHORT).format(p.getStartDate())
              : "");
      form1.setField(
          "due",
          (p.getDueDate() != null)
              ? DateFormat.getDateInstance(DateFormat.SHORT).format(p.getDueDate())
              : "");

      if (p.getCompany().getCcurrency().equalsIgnoreCase("USD")) {

        form1.setField(
            "cost",
            (p.getProjectAmount() != null)
                ? "$ " + StandardCode.getInstance().formatDouble(p.getProjectAmount())
                : "");
      } else {
        form1.setField(
            "cost",
            (p.getProjectAmount() != null)
                ? "€ "
                    + StandardCode.getInstance()
                        .formatDouble(p.getProjectAmount() / p.getEuroToUsdExchangeRate())
                : "");
      }
      // stamp.setFormFlattening(true);
      stamp.close();

      // write to client (web browser)

      response.setHeader(
          "Content-disposition",
          "attachment; filename="
              + p.getNumber()
              + p.getCompany().getCompany_code()
              + "-Order-Confirmation"
              + ".pdf");

      OutputStream os = response.getOutputStream();
      pdfStream.writeTo(os);
      os.flush();
    } catch (Exception e) {
      System.err.println("PDF Exception:" + e.getMessage());
      throw new RuntimeException(e);
    }
    // END process pdf

    // Forward control to the specified success URI
    return (mapping.findForward("Success"));
  }
  /**
   * Process one file.
   *
   * <p>\u0040param xmlFileName Input file name to check for part of speech/lemma mismatches..
   */
  protected static void processOneFile(String xmlFileName) {
    try {
      //  Report document being processed.

      System.out.println(
          "(" + ++currentDocNumber + "/" + docsToProcess + ") " + "processing " + xmlFileName);
      //  Create filter to strip <w> and <c>
      //  elements.

      XMLFilter filter = new StripAllWordElementsFilter(XMLReaderFactory.createXMLReader());
      //  Strip path from input file name.

      String strippedFileName = FileNameUtils.stripPathName(xmlFileName);

      strippedFileName = FileNameUtils.changeFileExtension(strippedFileName, "");

      //  Generate output file name.

      String xmlOutputFileName =
          new File(outputDirectoryName, strippedFileName + ".xml").getAbsolutePath();

      //  Make sure output directory exists.

      FileUtils.createPathForFile(xmlOutputFileName);

      //  Copy input xml to output xml,
      //  stripping <w> and <c> elements.

      new FilterAdornedFile(xmlFileName, xmlOutputFileName, filter);
      //  Read it back and fix spacing.

      String fixedXML = FileUtils.readTextFile(xmlOutputFileName, "utf-8");

      fixedXML = fixedXML.replaceAll("(\\s+)", " ");

      fixedXML = fixedXML.replaceAll(" ([\\.?!,;:\\)])", "\u00241");

      fixedXML = fixedXML.replaceAll("\\( ", "(");

      fixedXML = fixedXML.replaceAll("\u00b6 ", "\u00b6");

      fixedXML = fixedXML.replaceAll("__NS1:", "");

      fixedXML = fixedXML.replaceAll("__NS1", "");
      /*
                  fixedXML    =
                      fixedXML.replaceAll
                      (
                          "</__NS1:" ,
                          ""
                      );
      */
      //  Emit unadorned XML.

      SAXBuilder builder = new SAXBuilder();

      Document document = builder.build(new StringReader(fixedXML));

      new AdornedXMLWriter(document, xmlOutputFileName);
    } catch (Exception e) {
      System.out.println("   Error: " + e.getMessage());

      e.printStackTrace();
    }
  }