Ejemplo n.º 1
0
  protected List<AbstractSession> filterByUserPrincipal(
      Collection<AbstractSession> values, Principal userPrincipal) throws IOException {
    List<AbstractSession> res = null;

    {
      if (values != null) {
        res = new ArrayList<AbstractSession>();

        for (AbstractSession session : values) {
          expandSessionPrincipal(session);
        }

        if (userPrincipal == null) {
          for (AbstractSession session : values) {
            Principal p = session.getUserPrincipal();
            if (p == null) {
              res.add(session);
            }
          }
        } else {
          for (AbstractSession session : values) {
            Principal p = session.getUserPrincipal();
            if (PrincipalUtil.equalsIgnoreRealm(userPrincipal, p)) {
              res.add(session);
            }
          }
        }
      }
    }

    return res;
  }
Ejemplo n.º 2
0
  public List getUserListAT() {

    List<Map> list = new ArrayList<Map>();

    String[][] data = {
      {"3537255778", "Alex Chen"},
      {"2110989338", "Brian Wang"},
      {"3537640807", "David Hsieh"},
      {"5764816553", "James Yu"},
      {"3756404948", "K.C."},
      {"2110994764", "Neil Weinstock"},
      {"6797798390", "Owen Chen"},
      {"3831206627", "Randy Chen"},
      {"6312460903", "Tony Shen"},
      {"2110993498", "Yee Liaw"}
    };

    for (int i = 0; i < data.length; i++) {

      Map map = new HashMap();

      String userRef = data[i][0];
      String userName = data[i][1];

      map.put("userObjectId", userRef);
      map.put("userName", userName);

      list.add(map);
    }

    return list;
  }
Ejemplo n.º 3
0
  public JSONObject filterPlacesRandomly(
      JSONObject placesJSONObject, int finalPlacesNumberPerRequest, List<String> place_ids) {
    JSONObject initialJSON = (JSONObject) placesJSONObject.clone();
    JSONObject finalJSONObject = new JSONObject();
    int numberFields = placesJSONObject.size();
    int remainingPlaces = finalPlacesNumberPerRequest;
    int keywordsProcessed = 0;

    Set<String> keywords = initialJSON.keySet();

    for (String keyword : keywords) {
      JSONArray placesForKeyword = (JSONArray) initialJSON.get(keyword);
      JSONArray finalPlacesForKeyword = new JSONArray();
      int placesForKeywordSize = placesForKeyword.size();

      int maxPlacesToKeepInFinalJSON = remainingPlaces / (numberFields - keywordsProcessed);
      int placesToKeepInFinalJSON = Math.min(maxPlacesToKeepInFinalJSON, placesForKeywordSize);
      remainingPlaces -= placesToKeepInFinalJSON;

      for (int i = 0; i < placesToKeepInFinalJSON; i++) {
        int remainingPlacesInJSONArray = placesForKeyword.size();
        int randomElementPosInArray = (new Random()).nextInt(remainingPlacesInJSONArray);
        JSONObject temp = (JSONObject) placesForKeyword.remove(randomElementPosInArray);
        place_ids.add((String) temp.get("place_id"));
        finalPlacesForKeyword.add(temp);
      }

      finalJSONObject.put(keyword, finalPlacesForKeyword);
      keywordsProcessed++;
    }

    return finalJSONObject;
  }
Ejemplo n.º 4
0
  /**
   * Returns paths constructed by rewriting pathInfo using rules from the hosted site's mappings.
   * Paths are ordered from most to least specific match.
   *
   * @param site The hosted site.
   * @param pathInfo Path to be rewritten.
   * @param queryString
   * @return The rewritten path. May be either:
   *     <ul>
   *       <li>A path to a file in the Orion workspace, eg. <code>/ProjectA/foo/bar.txt</code>
   *       <li>An absolute URL pointing to another site, eg. <code>http://foo.com/bar.txt</code>
   *     </ul>
   *
   * @return The rewritten paths.
   * @throws URISyntaxException
   */
  private URI[] getMapped(IHostedSite site, IPath pathInfo, String queryString)
      throws URISyntaxException {
    final Map<String, List<String>> map = site.getMappings();
    final IPath originalPath = pathInfo;
    IPath path = originalPath.removeTrailingSeparator();

    List<URI> uris = new ArrayList<URI>();
    String rest = null;
    final int count = path.segmentCount();
    for (int i = 0; i <= count; i++) {
      List<String> base = map.get(path.toString());
      if (base != null) {
        rest = originalPath.removeFirstSegments(count - i).toString();
        for (int j = 0; j < base.size(); j++) {
          URI uri =
              rest.equals("") ? new URI(base.get(j)) : URIUtil.append(new URI(base.get(j)), rest);
          uris.add(
              new URI(
                  uri.getScheme(),
                  uri.getUserInfo(),
                  uri.getHost(),
                  uri.getPort(),
                  uri.getPath(),
                  queryString,
                  uri.getFragment()));
        }
      }
      path = path.removeLastSegments(1);
    }
    if (uris.size() == 0)
      // No mapping for /
      return null;
    else return uris.toArray(new URI[uris.size()]);
  }
 public MutableHttpServletRequest() {
   attributeMap = new HashMap<String, Object>();
   headerMap = new HashMap<String, String[]>();
   parameterMap = new HashMap<String, String[]>();
   fileItemMap = new HashMap<String, FileItem[]>();
   locales = new ArrayList<Locale>();
   locales.add(Locale.getDefault());
 }
 public ControllerRequest(Class<? extends Controller> controllerClass, Matcher matchedUrl) {
   this.controllerClass = controllerClass;
   if (matchedUrl.groupCount() > 0) {
     List<String> argsList = new ArrayList<String>(matchedUrl.groupCount());
     for (int i = 1; i <= matchedUrl.groupCount(); i++) {
       argsList.add(matchedUrl.group(i));
     }
     this.args = argsList;
   } else {
     this.args = new ArrayList<String>(0);
   }
 }
Ejemplo n.º 7
0
  public List getUserList() {
    List<Map> list = new ArrayList<Map>();

    try {

      /*
      String apiUrl=rallyApiHost+"/user?query="+
      	"((TeamMemberships%20%3D%20https%3A%2F%2Frally1.rallydev.com%2Fslm%2Fwebservice%2F1.34%2Fproject%2F6169133135)%20or%20"+
      	"(TeamMemberships%20%3D%20https%3A%2F%2Frally1.rallydev.com%2Fslm%2Fwebservice%2F1.34%2Fproject%2F6083311244))"+
      	"&fetch=true&order=Name&start=1&pagesize=100";
      */

      String apiUrl =
          rallyApiHost
              + "/user?query=(Disabled%20=%20false)"
              + "&fetch=true&order=Name&start=1&pagesize=100";

      log.info("apiUrl=" + apiUrl);

      String responseXML = getRallyXML(apiUrl);

      org.jdom.input.SAXBuilder bSAX = new org.jdom.input.SAXBuilder();
      org.jdom.Document doc = bSAX.build(new StringReader(responseXML));
      Element root = doc.getRootElement();

      XPath xpath = XPath.newInstance("//Object");
      List xlist = xpath.selectNodes(root);

      Iterator iter = xlist.iterator();
      while (iter.hasNext()) {

        Map map = new HashMap();

        Element item = (Element) iter.next();

        String userRef = item.getAttribute("ref").getValue();
        String userName = item.getAttribute("refObjectName").getValue();
        String userObjectId = item.getChildText("ObjectID");

        map.put("userRef", userRef);
        map.put("userObjectId", userObjectId);
        map.put("userName", userName);

        list.add(map);
      }

    } catch (Exception ex) {
      log.error("", ex);
    }

    return list;
  }
Ejemplo n.º 8
0
 void getDomChanges(List<DomElement> result, WApplication app) {
   DomElement e = DomElement.getForUpdate(this, this.getDomElementType());
   if (!this.isStubbed() && this.flags_.get(BIT_GRID_CHANGED)) {
     DomElement newE = this.createDomElement(app);
     e.replaceWith(newE);
   } else {
     if (this.rowsChanged_ != null) {
       for (Iterator<WTableRow> i_it = this.rowsChanged_.iterator(); i_it.hasNext(); ) {
         WTableRow i = i_it.next();
         DomElement e2 = DomElement.getForUpdate(i, DomElementType.DomElement_TR);
         i.updateDom(e2, false);
         result.add(e2);
       }
       ;
       this.rowsChanged_ = null;
     }
     if (this.rowsAdded_ != 0) {
       DomElement etb =
           DomElement.getForUpdate(this.getId() + "tb", DomElementType.DomElement_TBODY);
       for (int i = 0; i < (int) this.rowsAdded_; ++i) {
         DomElement tr = this.createRow(this.getRowCount() - this.rowsAdded_ + i, true, app);
         etb.addChild(tr);
       }
       result.add(etb);
       this.rowsAdded_ = 0;
     }
     if (this.flags_.get(BIT_COLUMNS_CHANGED)) {
       for (int i = 0; i < this.columns_.size(); ++i) {
         DomElement e2 =
             DomElement.getForUpdate(this.columns_.get(i), DomElementType.DomElement_COL);
         this.columns_.get(i).updateDom(e2, false);
         result.add(e2);
       }
       this.flags_.clear(BIT_COLUMNS_CHANGED);
     }
     this.updateDom(e, false);
   }
   result.add(e);
 }
  @Test
  @Ignore
  public void showAllNonShippedOrders() throws Exception {
    orders.add(new Order("a", "b", "c"));
    orders.add(new Order("d", "e", "f"));

    when(request.getMethod()).thenReturn("GET");
    when(request.getRequestURI()).thenReturn("/orders");

    ordersController.service();

    verify(ordersView).show(orders);
  }
Ejemplo n.º 10
0
 /**
  * Procesa los llamados a listar marcas
  *
  * @param
  * @return
  * @throws IOException
  * @throws ServletException
  */
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   BrandRepository brands = (BrandRepository) context.getBean("brandRepository");
   Collection data_brands = brands.findAllBrand();
   List param_brands = new ArrayList();
   Iterator itr = data_brands.iterator();
   while (itr.hasNext()) {
     Brand brand = (Brand) itr.next();
     BrandDTO dto = BrandAssembler.Create(brand);
     param_brands.add(dto);
   }
   request.setAttribute("brands", param_brands);
   forward("/ListBrands.jsp", request, response);
 }
Ejemplo n.º 11
0
  /**
   * Gets values referenced by sequential keys, e.g. {@code key1...keyN}.
   *
   * @param keyPrefix Key prefix, e.g. {@code key} for {@code key1...keyN}.
   * @param params Parameters map.
   * @return Values.
   */
  @Nullable
  protected List<Object> values(String keyPrefix, Map<String, Object> params) {
    assert keyPrefix != null;

    List<Object> vals = new LinkedList<>();

    for (int i = 1; ; i++) {
      String key = keyPrefix + i;

      if (params.containsKey(key)) vals.add(params.get(key));
      else break;
    }

    return vals;
  }
  @Test
  @Ignore
  public void theControllerWillShipAnOrder() throws Exception {
    Order order = new Order("5555", "_", "_");
    orders.add(order);

    when(request.getMethod()).thenReturn("POST");
    when(request.getRequestURI()).thenReturn("/orders/shipped");
    when(request.getParameter("order_code")).thenReturn("5555");

    ordersController.service();

    assertEquals("controller should set shipped", true, order.isShipped());
    verify(ordersView).refresh();
  }
Ejemplo n.º 13
0
 private void expand(int row, int column, int rowSpan, int columnSpan) {
   int newRowCount = Math.max(this.getRowCount(), row + rowSpan);
   int newColumnCount = Math.max(this.getColumnCount(), column + columnSpan);
   int extraRows = newRowCount - this.getRowCount();
   int extraColumns = newColumnCount - this.getColumnCount();
   if (extraColumns > 0) {
     for (int a_row = 0; a_row < this.getRowCount(); ++a_row) {
       {
         int insertPos = this.grid_.items_.get(a_row).size();
         for (int ii = 0; ii < (extraColumns); ++ii)
           this.grid_.items_.get(a_row).add(insertPos + ii, new Grid.Item());
       }
       ;
     }
     {
       int insertPos = this.grid_.columns_.size();
       for (int ii = 0; ii < (extraColumns); ++ii)
         this.grid_.columns_.add(insertPos + ii, new Grid.Section());
     }
     ;
   }
   if (extraRows > 0) {
     {
       int insertPos = this.grid_.items_.size();
       for (int ii = 0; ii < (extraRows); ++ii)
         this.grid_.items_.add(insertPos + ii, new ArrayList<Grid.Item>());
     }
     ;
     for (int i = 0; i < extraRows; ++i) {
       final List<Grid.Item> items =
           this.grid_.items_.get(this.grid_.items_.size() - extraRows + i);
       {
         int insertPos = items.size();
         for (int ii = 0; ii < (newColumnCount); ++ii) items.add(insertPos + ii, new Grid.Item());
       }
       ;
     }
     {
       int insertPos = this.grid_.rows_.size();
       for (int ii = 0; ii < (extraRows); ++ii)
         this.grid_.rows_.add(insertPos + ii, new Grid.Section());
     }
     ;
   }
 }
Ejemplo n.º 14
0
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   ProfesorRepository profesores = (ProfesorRepository) context.getBean("profesorRepository");
   try {
     Collection lista = profesores.findAllProfesor();
     List data = new ArrayList();
     Iterator itr = lista.iterator();
     while (itr.hasNext()) {
       Profesor prof = (Profesor) itr.next();
       ProfesorDTO dto = ProfesorAssembler.Create(prof);
       data.add(dto);
     }
     request.setAttribute("profesores", data);
     forward("/listaProfesores.jsp", request, response);
   } catch (Exception e) {
     request.setAttribute("mensaje", e.getMessage());
     forward("/paginaError.jsp", request, response);
   }
 }
Ejemplo n.º 15
0
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   GrupoRepository grupos = (GrupoRepository) context.getBean("grupoRepository");
   try {
     Collection lista = grupos.findAllGrupo();
     List data = new ArrayList();
     Iterator itr = lista.iterator();
     while (itr.hasNext()) {
       Grupo grupo = (Grupo) itr.next();
       GrupoDTO dto = GrupoAssembler.CreateDTO(grupo);
       data.add(dto);
     }
     request.setAttribute("grupos", data);
     forward("/listaGrupos.jsp", request, response);
   } catch (Exception e) {
     request.setAttribute("mensaje", e.getMessage());
     forward("/paginaError.jsp", request, response);
   }
 }
Ejemplo n.º 16
0
  public static List getOfflineList2(List stationList, Map data) {
    List list = new ArrayList();

    int i, stationNum = 0;
    String station_id = null;
    List tmp = null;
    Map m = null;
    stationNum = stationList.size();
    for (i = 0; i < stationNum; i++) {
      m = (Map) stationList.get(i);
      station_id = (String) m.get("station_id");

      tmp = (List) data.get(station_id);
      if (tmp != null) {
        list.add(m);
      }
    }

    return list;
  }
  private static void addChild(UIComponent parent, String prevId, UIComponent child) {
    if (parent != null) {
      List<UIComponent> children = parent.getChildren();
      int size = children.size();
      boolean hasPrev = prevId == null;

      int i = 0;
      for (; i < size; i++) {
        UIComponent oldChild = children.get(i);

        if (hasPrev && oldChild.getId() != null) {
          children.add(i, child);

          return;
        } else if (prevId != null && prevId.equals(oldChild.getId())) hasPrev = true;
      }

      parent.getChildren().add(child);
    }
  }
Ejemplo n.º 18
0
  public List getProjectList() {
    List<Map> list = new ArrayList<Map>();

    try {

      String apiUrl = rallyApiHost + "/project?" + "fetch=true&order=Name&start=1&pagesize=200";

      log.info("rallyApiUrl:" + apiUrl);

      String responseXML = getRallyXML(apiUrl);

      org.jdom.input.SAXBuilder bSAX = new org.jdom.input.SAXBuilder();
      org.jdom.Document doc = bSAX.build(new StringReader(responseXML));
      Element root = doc.getRootElement();

      XPath xpath = XPath.newInstance("//Object");
      List xlist = xpath.selectNodes(root);

      Iterator iter = xlist.iterator();
      while (iter.hasNext()) {

        Map map = new HashMap();

        Element item = (Element) iter.next();
        String objId = item.getChildText("ObjectID");
        String name = item.getChildText("Name");
        String state = item.getChildText("State");

        map.put("objId", objId);
        map.put("name", name);
        map.put("state", state);

        list.add(map);
      }

    } catch (Exception ex) {
      log.error("ERROR: ", ex);
    }

    return list;
  }
  /** Access catalog component and retrieve transportation data from the database */
  public List searchTransportation(String origin, String destination, Locale locale)
      throws HTMLActionException {
    List transportation = null;
    List transportationBean = new ArrayList();

    // call catalog component
    try {
      CatalogFacade catalogFacade = new CatalogFacade();
      transportation = catalogFacade.getTransportations(origin, destination, locale);

      // Catch catalog exceptions and re-throw them as
      // mini-app application defined exceptions.
    } catch (Exception e) {
      throw new HTMLActionException(
          "Transportation Search Exception:: Catalog Exception accessing catalog component: " + e);
    }
    for (int i = 0; i < transportation.size(); ++i) {
      transportationBean.add(
          new TransportationBean(
              ((com.sun.j2ee.blueprints.catalog.Transportation) transportation.get(i))
                  .getTransportationId(),
              ((com.sun.j2ee.blueprints.catalog.Transportation) transportation.get(i)).getName(),
              ((com.sun.j2ee.blueprints.catalog.Transportation) transportation.get(i))
                  .getDescription(),
              ((com.sun.j2ee.blueprints.catalog.Transportation) transportation.get(i))
                  .getImageURI(),
              ((com.sun.j2ee.blueprints.catalog.Transportation) transportation.get(i)).getPrice(),
              ((com.sun.j2ee.blueprints.catalog.Transportation) transportation.get(i)).getOrigin(),
              ((com.sun.j2ee.blueprints.catalog.Transportation) transportation.get(i))
                  .getDestination(),
              ((com.sun.j2ee.blueprints.catalog.Transportation) transportation.get(i)).getCarrier(),
              ((com.sun.j2ee.blueprints.catalog.Transportation) transportation.get(i))
                  .getDepartureTime(),
              ((com.sun.j2ee.blueprints.catalog.Transportation) transportation.get(i))
                  .getArrivalTime(),
              ((com.sun.j2ee.blueprints.catalog.Transportation) transportation.get(i))
                  .getTravelClass()));
    }
    return transportationBean;
  }
  public void _jspService(HttpServletRequest request, HttpServletResponse response)
      throws java.io.IOException, ServletException {

    JspFactory _jspxFactory = null;
    javax.servlet.jsp.PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;

    try {
      _jspxFactory = JspFactory.getDefaultFactory();
      response.setContentType("text/xml;charset=ISO-8859-1");
      pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true);
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\n");
      out.write("\n");

      HttpSession user = request.getSession(true);
      Notification newNotice = (Notification) user.getAttribute("newNotice");
      List exclude = new ArrayList();
      exclude.add(NotificationWizardServlet.WT_VENDOR_NAME); // Exclude WebTelemetry

      out.print(buildTree(newNotice, exclude));
      out.write("\n");
    } catch (Throwable t) {
      out = _jspx_out;
      if (out != null && out.getBufferSize() != 0) out.clearBuffer();
      if (pageContext != null) pageContext.handlePageException(t);
    } finally {
      if (_jspxFactory != null) _jspxFactory.releasePageContext(pageContext);
    }
  }
Ejemplo n.º 21
0
 static void decodeTouches(String str, List<Touch> result) {
   if (str.length() == 0) {
     return;
   }
   List<String> s = new ArrayList<String>();
   s = new ArrayList<String>(Arrays.asList(str.split(";")));
   if (s.size() % 9 != 0) {
     logger.error(
         new StringWriter()
             .append("Could not parse touches array '")
             .append(str)
             .append("'")
             .toString());
     return;
   }
   try {
     for (int i = 0; i < s.size(); i += 9) {
       result.add(
           new Touch(
               asUInt(s.get(i + 0)),
               asInt(s.get(i + 1)),
               asInt(s.get(i + 2)),
               asInt(s.get(i + 3)),
               asInt(s.get(i + 4)),
               asInt(s.get(i + 5)),
               asInt(s.get(i + 6)),
               asInt(s.get(i + 7)),
               asInt(s.get(i + 8))));
     }
   } catch (NumberFormatException ee) {
     logger.error(
         new StringWriter()
             .append("Could not parse touches array '")
             .append(str)
             .append("'")
             .toString());
     return;
   }
 }
Ejemplo n.º 22
0
  public static List getZeroList(List stationList, Map data, String col) {
    int num = 0;
    int i, stationNum = 0;
    String station_id = null;
    List list = null;
    String ep_type = null;
    Map m = null;
    List list2 = new ArrayList();
    stationNum = stationList.size();
    for (i = 0; i < stationNum; i++) {
      m = (Map) stationList.get(i);
      station_id = (String) m.get("station_id");
      // ep_type = (String)m.get("ep_type");

      list = (List) data.get(station_id);
      // if(isZero(list,col)&&f.eq(ep_type,"1")){num++;}
      if (isZero(list, col)) {
        list2.add(m);
      }
    }

    return list2;
  }
Ejemplo n.º 23
0
  /**
   * Creates a GPX-formatted file attachment for the given entry.
   *
   * @param user
   * @param entryId
   * @param fileName
   * @param activityId
   * @param track
   * @param track
   */
  public void createAttachment(
      User user, int entryId, String fileName, String title, String activityId, GpsTrack track)
      throws DataAccessException, IOException {
    Attachment a = new Attachment();
    a.setUserName(user.getUserName());
    a.setUserId(user.getUserId());
    a.setEntryId(entryId);
    a.setFileType("map");
    a.setFileName(fileName);
    a.setActivityId(activityId);
    a.setTitle(title);

    GpxFormatter formatter = new GpxFormatter();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    List<GpsTrack> tracks = new ArrayList<GpsTrack>();
    tracks.add(track);

    formatter.format(tracks, baos);
    log.debug(new String(baos.toByteArray()));
    a.setBytes(baos.toByteArray());

    new AttachmentDao().create(a);
  }
Ejemplo n.º 24
0
  public static List getZeroListNation(List stationList, Map data, String col) {
    List list = new ArrayList();

    int i, stationNum = 0;
    String station_id = null;
    List tmp = null;
    Map m = null;

    String ep_type = null;
    stationNum = stationList.size();
    for (i = 0; i < stationNum; i++) {
      m = (Map) stationList.get(i);
      station_id = (String) m.get("station_id");
      ep_type = (String) m.get("ep_type");

      tmp = (List) data.get(station_id);
      if (isZero(tmp, col) && f.eq(ep_type, "1")) {
        list.add(m);
      }
    }

    return list;
  }
Ejemplo n.º 25
0
 /**
  * Move a table column from its original position to a new position.
  *
  * <p>The table expands automatically when the <code>to</code> column is beyond the current table
  * dimensions.
  *
  * <p>
  *
  * @see WTable#moveRow(int from, int to)
  */
 public void moveColumn(int from, int to) {
   if (from < 0 || from >= (int) this.columns_.size()) {
     logger.error(
         new StringWriter()
             .append("moveColumn: the from index is not a valid column index.")
             .toString());
     return;
   }
   WTableColumn from_tc = this.getColumnAt(from);
   this.columns_.remove(from_tc);
   if (to > (int) this.columns_.size()) {
     this.getColumnAt(to);
   }
   this.columns_.add(0 + to, from_tc);
   for (int i = 0; i < this.rows_.size(); i++) {
     List<WTableRow.TableData> cells = this.rows_.get(i).cells_;
     WTableRow.TableData cell = cells.get(from);
     cells.remove(0 + from);
     cells.add(0 + to, cell);
   }
   this.flags_.set(BIT_GRID_CHANGED);
   this.repaint(EnumSet.of(RepaintFlag.RepaintInnerHtml));
 }
Ejemplo n.º 26
0
  public String postFile(URLFetchService us, List<PostObj> postobjlist) throws Exception {
    int index;

    Gson gson;
    String linkID;
    List<String> linkList;
    HTTPRequest req;
    String param;

    gson = new Gson();

    linkID = createUID();
    linkList = new ArrayList<String>();
    for (index = 0; index < postobjlist.size(); index++) {
      linkList.add(postobjlist.get(index).filelink);
    }

    param =
        URLEncoder.encode("postlist", "UTF-8")
            + "="
            + URLEncoder.encode(gson.toJson(postobjlist), "UTF-8")
            + '&'
            + URLEncoder.encode("linkid", "UTF-8")
            + "="
            + URLEncoder.encode(linkID, "UTF-8")
            + '&'
            + URLEncoder.encode("linklist", "UTF-8")
            + "="
            + URLEncoder.encode(gson.toJson(linkList), "UTF-8");
    req =
        new HTTPRequest(
            new URL("http://tnfshmoe.appspot.com/postdf89ksfxsyx9sfdex09usdjksd"), HTTPMethod.POST);
    req.setPayload(param.getBytes());
    us.fetch(req);

    return linkID;
  }
Ejemplo n.º 27
0
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // get the number of workers to run
    int count = this.getRequestedCount(request, 4);
    // get the executor service
    final ServletContext sc = this.getServletContext();
    final ExecutorService executorService = (ExecutorService) sc.getAttribute("myExecutorService");
    // create work coordinator
    CountDownLatch countDownLatch = new CountDownLatch(count);

    Long t1 = System.nanoTime();
    // create the workers
    List<RunnableWorkUnit2> workers = new ArrayList<RunnableWorkUnit2>();
    for (int i = 0; i < count; i++) {
      RunnableWorkUnit2 wu =
          new RunnableWorkUnit2("RunnableTask" + String.valueOf(i + 1), countDownLatch);
      workers.add(wu);
    }
    // run the workers through the executor
    for (RunnableWorkUnit2 wu : workers) {
      executorService.execute(wu);
    }

    try {
      System.out.println("START WAITING");
      countDownLatch.await();
      System.out.println("DONE WAITING");
    } catch (InterruptedException ex) {
      ex.printStackTrace();
    }

    Long t2 = System.nanoTime();
    Writer w = response.getWriter();
    w.write(String.format("\n Request processed in %dms!", (t2 - t1) / 1000000));
    w.flush();
    w.close();
  }
Ejemplo n.º 28
0
 void getDomChanges(List<DomElement> result, WApplication app) {
   if (this.mediaId_.length() != 0) {
     DomElement media = DomElement.getForUpdate(this.mediaId_, DomElementType.DomElement_DIV);
     this.updateMediaDom(media, false);
     if (this.sourcesChanged_) {
       for (int i = 0; i < this.sourcesRendered_; ++i) {
         media.callJavaScript(
             "Wt3_2_3.remove('" + this.mediaId_ + "s" + String.valueOf(i) + "');", true);
       }
       this.sourcesRendered_ = 0;
       for (int i = 0; i < this.sources_.size(); ++i) {
         DomElement src = DomElement.createNew(DomElementType.DomElement_SOURCE);
         src.setId(this.mediaId_ + "s" + String.valueOf(i));
         this.renderSource(src, this.sources_.get(i), i + 1 >= this.sources_.size());
         media.addChild(src);
       }
       this.sourcesRendered_ = this.sources_.size();
       this.sourcesChanged_ = false;
       media.callJavaScript(this.getJsMediaRef() + ".load();");
     }
     result.add(media);
   }
   super.getDomChanges(result, app);
 }
Ejemplo n.º 29
0
  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    int index;

    DatastoreService ds;
    MemcacheService ms;
    BlobstoreService bs;
    URLFetchService us;
    FileService fs;

    Map<String, List<BlobKey>> blobMap;
    BlobKey blobKey;
    BlobInfoFactory blobInfoFactory;
    BlobInfo blobInfo;

    int postCount;
    int postIndex;
    String postType;
    String postText;
    String postDelpw;
    String postShowgallery;
    DataObj dataObj;
    String filelink;

    String picUrl;
    HTTPResponse picRes;
    List<HTTPHeader> headerList;
    String picMime;
    String[] fileNamePart;
    AppEngineFile picFile;
    FileWriteChannel writeChannel;

    PostObj postObj;
    List<PostObj> postObjList;
    String linkID;

    resp.setCharacterEncoding("UTF-8");
    resp.setContentType("text/plain");

    try {
      ds = DatastoreServiceFactory.getDatastoreService();
      ms = MemcacheServiceFactory.getMemcacheService();
      bs = BlobstoreServiceFactory.getBlobstoreService();
      us = URLFetchServiceFactory.getURLFetchService();
      fs = FileServiceFactory.getFileService();
      blobInfoFactory = new BlobInfoFactory(ds);

      blobMap = bs.getUploads(req);
      postCount = Integer.valueOf(req.getParameter("input_post_count"));
      postObjList = new ArrayList<PostObj>();

      for (postIndex = 0; postIndex < postCount; postIndex++) {
        try {
          postType = req.getParameter("input_post_type_" + postIndex);
          if (postType == null) {
            continue;
          }

          postText = req.getParameter("input_post_text_" + postIndex);
          postDelpw = req.getParameter("input_post_delpw_" + postIndex);
          postShowgallery = req.getParameter("input_post_showgallery_" + postIndex);
          if (postShowgallery == null) {
            postShowgallery = "";
          }

          if (postType.equals("file") == true) {
            blobKey = blobMap.get("input_post_file_" + postIndex).get(0);
            if (blobKey == null) {
              throw new Exception();
            }

            dataObj = new DataObj();
            dataObj.fileid = createUID();
            dataObj.posttime = new Date().getTime();
            dataObj.delpw = postDelpw;
            dataObj.blobkey = blobKey;
            dataObj.putDB(ds);

            blobInfo = blobInfoFactory.loadBlobInfo(dataObj.blobkey);
            filelink =
                "http://"
                    + req.getServerName()
                    + "/down/"
                    + dataObj.fileid
                    + "/"
                    + blobInfo.getFilename();
            postObj =
                new PostObj(
                    dataObj.fileid,
                    filelink,
                    blobInfo.getSize(),
                    dataObj.posttime,
                    dataObj.delpw,
                    postShowgallery);
            postObjList.add(postObj);
          } else if (postType.equals("url") == true) {
            picUrl = postText;

            picRes = us.fetch(new URL(picUrl));
            headerList = picRes.getHeaders();
            picMime = "application/octet-stream";
            for (index = 0; index < headerList.size(); index++) {
              if (headerList.get(index).getName().compareToIgnoreCase("Content-Type") == 0) {
                picMime = headerList.get(index).getValue();
                break;
              }
            }

            fileNamePart = picUrl.split("/");

            picFile = fs.createNewBlobFile(picMime, fileNamePart[fileNamePart.length - 1]);
            writeChannel = fs.openWriteChannel(picFile, true);
            writeChannel.write(ByteBuffer.wrap(picRes.getContent()));
            writeChannel.closeFinally();

            dataObj = new DataObj();
            dataObj.fileid = createUID();
            dataObj.posttime = new Date().getTime();
            dataObj.delpw = postDelpw;
            dataObj.blobkey = fs.getBlobKey(picFile);
            dataObj.putDB(ds);

            blobInfo = blobInfoFactory.loadBlobInfo(dataObj.blobkey);
            filelink =
                "http://"
                    + req.getServerName()
                    + "/down/"
                    + dataObj.fileid
                    + "/"
                    + blobInfo.getFilename();
            postObj =
                new PostObj(
                    dataObj.fileid,
                    filelink,
                    blobInfo.getSize(),
                    dataObj.posttime,
                    dataObj.delpw,
                    postShowgallery);
            postObjList.add(postObj);
          }
        } catch (Exception e) {
        }
      }

      linkID = postFile(us, postObjList);

      if (req.getParameter("specflag") != null) {
        resp.getWriter().print("http://tnfshmoe.appspot.com/link.jsp?linkid=" + linkID);
      } else {
        resp.sendRedirect("http://tnfshmoe.appspot.com/link.jsp?linkid=" + linkID);
      }
    } catch (Exception e) {
    }
  }
Ejemplo n.º 30
0
  private List<LicenseData> getSearchByFieldResults(
      String reseller, String parameter, String type) {

    List<LicenseData> list = new ArrayList<LicenseData>();
    Connection con = null;
    try {

      Statement pst = null;
      con = getConnectiontoDB();

      StringBuffer sql = new StringBuffer();
      if (type.equalsIgnoreCase("sno")) {
        sql.append(
            " select distinct ib.item,o.orderkey,'1',so_header.so_number,so_header.end_user,TO_CHAR(TO_TIMESTAMP(so_header.ship_date/1000), 'YYYY-MM-DD'), ");
      } else {
        sql.append(
            " select distinct so_item.item,so_item.entitlementkey,so_item.quantity,so_header.so_number,so_header.end_user,TO_CHAR(TO_TIMESTAMP(so_header.ship_date/1000), 'YYYY-MM-DD'), ");
      }
      sql.append(
          "o.hmid,	CASE TO_CHAR(TO_TIMESTAMP(o.substartdate/1000), 'YYYY-MM-DD') WHEN '1969-12-31' THEN '' WHEN TO_CHAR(TO_TIMESTAMP(o.subenddate/1000), 'YYYY-MM-DD') THEN '' ELSE TO_CHAR(TO_TIMESTAMP(o.substartdate/1000), 'YYYY-MM-DD') END, ");
      sql.append(
          "CASE TO_CHAR(TO_TIMESTAMP(o.subenddate/1000), 'YYYY-MM-DD') WHEN '1969-12-31' THEN ''  WHEN TO_CHAR(TO_TIMESTAMP(o.substartdate/1000), 'YYYY-MM-DD') THEN '' ELSE TO_CHAR(TO_TIMESTAMP(o.subenddate/1000), 'YYYY-MM-DD') END, so_header.po_check_number,so_header.reseller, ");
      sql.append(
          " CASE WHEN so_item.producttype='Support' THEN TO_CHAR(TO_TIMESTAMP(o.startdate/1000), 'YYYY-MM-DD') ELSE '' END, ");
      sql.append(
          " CASE WHEN so_item.producttype='Support' THEN TO_CHAR(TO_TIMESTAMP(o.enddate/1000), 'YYYY-MM-DD') ELSE '' END  ");
      if (type.equalsIgnoreCase("sno")) {
        sql.append(" ,ib.serialnumber");
        sql.append(
            "  from ns.so_header so_header  inner join ns.ib ib on ib.salesordernumber =so_header.so_number ");
        sql.append("  inner join orderkey_information o  on so_header.entitlement_key=o.orderkey");
        sql.append(
            " inner join ns.temp_so_item so_item on so_header.entitlement_key=so_item.entitlementkey");
      } else {
        sql.append(
            " from ns.so_header so_header inner join ns.temp_so_item so_item on so_header.entitlement_key=so_item.entitlementkey ");
        sql.append(" inner join orderkey_information o on so_header.entitlement_key=o.orderkey ");
      }

      if (type.equalsIgnoreCase("sno"))
        sql.append(" where ib.serialnumber ILIKE '%" + parameter.trim() + "%' ");
      if (type.equalsIgnoreCase("so"))
        sql.append("where so_header.so_number='" + parameter.trim() + "' ");
      if (type.equalsIgnoreCase("enduser"))
        sql.append(
            "where so_header.end_user ILIKE '%" + parameter.trim().replace("'", "''") + "%'");
      if (type.equalsIgnoreCase("ek"))
        sql.append("where so_header.entitlement_key ILIKE '%" + parameter.trim() + "%'");
      if (type.equalsIgnoreCase("po"))
        sql.append("where so_header.po_check_number ILIKE '%" + parameter.trim() + "%'");
      if (type.equalsIgnoreCase("hm"))
        sql.append("where o.hmid ILIKE '%" + parameter.trim() + "%'");
      if (reseller != null && !reseller.isEmpty() && !reseller.equalsIgnoreCase("%admin%"))
        sql.append(" and so_header.reseller ILIKE '" + reseller.trim() + "'");
      if (type.equalsIgnoreCase("sno")) sql.append(" order by so_header.so_number desc ");
      pst = con.createStatement();
      ResultSet rs = pst.executeQuery(sql.toString());

      log.info("Search Fields : SQL Query " + sql);

      while (rs.next()) {
        LicenseData data = new LicenseData();
        data.setEntitlementKey(rs.getString(2));
        data.setSku(rs.getString(1));
        data.setQuantity(rs.getString(3));
        data.setSoNumbber(rs.getString(4));
        ;
        data.setEndUser(rs.getString(5));
        data.setShipDate(rs.getString(6));
        data.setHmId(rs.getString(7));
        data.setLicenseStartDate(rs.getString(8));
        data.setLicenseEndDate(rs.getString(9));
        data.setPoNumber(rs.getString(10));
        data.setNumber(rs.getString(4));
        data.setBillingCustomer(rs.getString(11));
        data.setSupportStartDate(rs.getString(12));
        data.setSupportEndDate(rs.getString(13));
        if (type.equalsIgnoreCase("sno")) data.setSerialNumber(rs.getString(14));
        list.add(data);
      }

    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } finally {
      try {
        con.close();
      } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

    return list;
  }