/** Handles size after put. */
  private void onPut() {
    cnt.incrementAndGet();

    int c;

    while ((c = cnt.get()) > max) {
      // Decrement count.
      if (cnt.compareAndSet(c, c - 1)) {
        try {
          K key = firstEntry().getKey();

          V val;

          // Make sure that an element is removed.
          while ((val = super.remove(firstEntry().getKey())) == null) {
            // No-op.
          }

          assert val != null;

          GridInClosure2<K, V> lsnr = this.lsnr;

          // Listener notification.
          if (lsnr != null) lsnr.apply(key, val);
        } catch (NoSuchElementException e1) {
          e1.printStackTrace(); // Should never happen.

          assert false : "Internal error in grid bounded ordered set.";
        }
      }
    }
  }
  /**
   * Flushes the events.
   *
   * <p>NOTE: not threadsafe! Has to be called in the opengl thread if in opengl mode!
   */
  public void flushEvents() {
    /*
    //FIXME DEBUG TEST REMOVE!
    int count = 0;
    for (Iterator<MTInputEvent> iterator = eventQueue.iterator(); iterator.hasNext();){
    	MTInputEvent e = (MTInputEvent) iterator.next();
    	if (e instanceof MTFingerInputEvt) {
    		MTFingerInputEvt fe = (MTFingerInputEvt) e;
    		if (fe.getId() == MTFingerInputEvt.INPUT_ENDED) {
    			count++;
    		}
    	}
    }
    if (count >= 2){
    	System.out.println("--2 INPUT ENDED QUEUED!--");
    }
    int iCount = 0;
    for (IinputSourceListener listener : inputListeners){
    	if (listener.isDisabled()){
    		iCount++;
    	}
    }
    if (iCount >= inputListeners.size() && !eventQueue.isEmpty()){
    	System.out.println("--ALL INPUT PROCESSORS DISABLED!--");
    }
    */

    if (!eventQueue.isEmpty()) {
      //			System.out.print("START FLUSH CURSOR: " +
      // ((MTFingerInputEvt)eventQueue.peek()).getCursor().getId() + " Evt-ID: " +
      // ((MTFingerInputEvt)eventQueue.peek()).getId()+ " ");
      // To ensure that all global input processors of the current scene
      // get the queued events even if through the result of one event processing the scene
      // gets changed and the currents scenes processors get disabled

      // Also ensure that all queued events get flushed to the scene although
      // as a result this scenes input processors get disabled
      // TODO do this only at real scene change?
      // -> else if we disable input processors it may get delayed..

      // FIXME problem that this can get called twice - because called again in initiateScenechange
      inputProcessorsToFireTo.clear();
      for (IinputSourceListener listener : inputListeners) {
        if (!listener.isDisabled()) {
          inputProcessorsToFireTo.add(listener);
        }
      }

      while (!eventQueue.isEmpty()) {
        try {
          MTInputEvent te = eventQueue.pollFirst();
          this.fireInputEvent(te);
        } catch (NoSuchElementException e) {
          e.printStackTrace();
          // System.err.println(e.getMessage());
        }
      }
      //			System.out.println("END FLUSH");
    }
  }
Exemplo n.º 3
0
  public static void main(String[] args) {
    System.out.println("WFS Demo");
    try {
      //            URL url = new
      // URL("http://www2.dmsolutions.ca/cgi-bin/mswfs_gmap?version=1.0.0&request=getcapabilities&service=wfs");
      URL url = new URL("http://www.refractions.net:8080/geoserver/wfs?REQUEST=GetCapabilities");

      Map m = new HashMap();
      m.put(WFSDataStoreFactory.URL.key, url);
      m.put(WFSDataStoreFactory.TIMEOUT.key, new Integer(10000));
      m.put(WFSDataStoreFactory.PROTOCOL.key, Boolean.FALSE);

      DataStore wfs = (new WFSDataStoreFactory()).createNewDataStore(m);
      Query query = new DefaultQuery(wfs.getTypeNames()[1]);
      FeatureReader<SimpleFeatureType, SimpleFeature> ft =
          wfs.getFeatureReader(query, Transaction.AUTO_COMMIT);
      int count = 0;
      while (ft.hasNext()) if (ft.next() != null) count++;
      System.out.println("Found " + count + " features");
    } catch (IOException e) {
      e.printStackTrace();
    } catch (NoSuchElementException e) {
      e.printStackTrace();
    } catch (IllegalAttributeException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 4
0
 /**
  * Reads a file and appends the data contained in the file to this Histogram. The format of the
  * file is bins \t occurences. Lines beginning with # and empty lines are ignored.
  *
  * @param inputPathName A pathname string.
  * @exception java.io.IOException Description of the Exception
  */
 public void read(String inputPathName) throws java.io.IOException {
   java.io.BufferedReader reader =
       new java.io.BufferedReader(new java.io.FileReader(inputPathName));
   String s = null;
   while ((s = reader.readLine()) != null) {
     s = s.trim();
     if (s.equals("") || (s.charAt(0) == '#')) { // ignore empty lines and lines beginning with #
       continue;
     }
     try {
       java.util.StringTokenizer st = new java.util.StringTokenizer(s, "\t");
       int binNumber = Integer.parseInt(st.nextToken());
       double numberOfOccurences = Double.parseDouble(st.nextToken());
       Double priorOccurences = (Double) bins.get(new Integer(binNumber));
       if (priorOccurences == null) { // first occurence for this bin
         bins.put(new Integer(binNumber), new Double(numberOfOccurences));
       } else {
         numberOfOccurences +=
             priorOccurences.doubleValue(); // increase occurences for bin by priorOccurences
         bins.put(new Integer(binNumber), new Double(numberOfOccurences));
       }
       ymax = Math.max(numberOfOccurences, ymax);
       xmin = Math.min(binNumber * binWidth + binOffset, xmin);
       xmax = Math.max(binNumber * binWidth + binWidth + binOffset, xmax);
     } catch (java.util.NoSuchElementException nsee) {
       nsee.printStackTrace();
     } catch (NumberFormatException nfe) {
       nfe.printStackTrace();
     }
   }
   dataChanged = true;
 }
Exemplo n.º 5
0
 @Override
 public void run() {
   String in = null;
   while (scanning) {
     try {
       in = input.nextLine();
     } catch (java.util.NoSuchElementException e) {
       e.printStackTrace();
     }
     // juste une idée pour que les clients de Syn puissent faire des commandes console à partir de
     // leur ptite app
     // if(externalIn.lenght != 0){
     //	in = externalIn;
     // }
     Syn.d("CS: input: " + in, Ansi.Color.YELLOW);
     // Commandes normales
     if (in.startsWith("@@")) {
       if (in.equals("@@exit")) {
         System.exit(0);
       } else if (in.equals("@@stopscan")) {
         Syn.w("Scanner stopped", null);
         break;
       }
     } else
     // Commandes de réponse à une question (Ex pour créer une nouvelle table sql)
     if (in.startsWith("!!") && question.length() > 0) {
       if (in.equals("yes")) {
         answerYes();
       } else if (in.equals("no")) {
         answerNo();
       }
     }
   }
   t.interrupt();
 }
Exemplo n.º 6
0
 // see DbFile.java for javadocs
 public DbFileIterator iterator(TransactionId tid) {
   try {
     return new HeapFileIterator(tid, this);
   } catch (DbException dbe) {
     dbe.printStackTrace();
   } catch (TransactionAbortedException transe) {
     transe.printStackTrace();
   } catch (NoSuchElementException nosuche) {
     nosuche.printStackTrace();
   }
   return null;
 }
  static <T extends Comparable<? super T>> void union(List<T> a, List<T> b, List<T> out) {
    ListIterator<T> aIterator = a.listIterator();
    ListIterator<T> bIterator = b.listIterator();
    int aIndex = 0;
    int bIndex = 0;
    try {
      T aTemp = aIterator.next();
      T bTemp = bIterator.next();

      while (aIndex + 1 <= a.size() && bIndex + 1 <= b.size()) {
        {
          if (aTemp.compareTo(bTemp) == 0) {
            out.add(aTemp);
            aIndex++;
            bIndex++;
            if (aIterator.hasNext()) aTemp = aIterator.next();
            if (bIterator.hasNext()) bTemp = bIterator.next();
          } else if (aTemp.compareTo(bTemp) < 0) {
            aIndex++;
            out.add(aTemp);
            if (aIterator.hasNext()) aTemp = aIterator.next();

          } else {
            bIndex++;
            out.add(bTemp);
            if (bIterator.hasNext()) bTemp = bIterator.next();
          }
        }

        if (a.size() >= aIndex + 1 && bIndex + 1 > b.size()) {
          out.add(aTemp);
          aIndex++;
          while (aIterator.hasNext()) {
            aTemp = aIterator.next();
            out.add(aTemp);
          }
        } else if (b.size() >= bIndex + 1 && aIndex + 1 > a.size()) {
          bIndex++;
          out.add(bTemp);
          while (bIterator.hasNext()) {
            bTemp = bIterator.next();
            out.add(bTemp);
          }
        }
      }

    } catch (NoSuchElementException ex) {
      System.out.println("The input array(s) is/are empty. Please check!!");
      ex.printStackTrace();
    }
  }
Exemplo n.º 8
0
 /**
  * 获取所有专辑
  *
  * @return
  */
 public synchronized ArrayList<Category> getAlbums() {
   ArrayList<Category> albums = new ArrayList<Category>();
   if (mAudioCategory != null) {
     Collection<Category> collection = mAudioCategory.values();
     if (collection != null && !collection.isEmpty()) {
       try {
         albums.addAll(collection);
       } catch (NoSuchElementException ex) {
         ex.printStackTrace();
       }
     }
   }
   return albums;
 }
Exemplo n.º 9
0
 /**
  * 获取所有视频文件夹
  *
  * @return
  */
 public synchronized ArrayList<Category> getVideoPaths() {
   ArrayList<Category> paths = new ArrayList<Category>();
   if (mVideoCategory != null) {
     Collection<Category> collection = mVideoCategory.values();
     if (collection != null && !collection.isEmpty()) {
       try {
         paths.addAll(collection);
       } catch (NoSuchElementException ex) {
         ex.printStackTrace();
       }
     }
   }
   return paths;
 }
Exemplo n.º 10
0
 private String receive() {
   response = null;
   try {
     while (response == null) {
       if (in.hasNextLine()) {
         // Continue trying to recieve message until response is stored
         response = in.nextLine();
       }
     }
   } catch (NoSuchElementException e) {
     e.printStackTrace();
   }
   return response;
 }
Exemplo n.º 11
0
  protected static Dimension stringToDimension(String value) {
    Dimension dim = null;
    StringTokenizer tok;

    if (value != null) {
      try {
        tok = new StringTokenizer(value);
        dim = new Dimension(Integer.parseInt(tok.nextToken()), Integer.parseInt(tok.nextToken()));
      } catch (NoSuchElementException e1) {
        e1.printStackTrace();
      } catch (NumberFormatException e2) {
        e2.printStackTrace();
      }
    }
    return dim;
  }
Exemplo n.º 12
0
  protected static Point stringToPoint(String value) {
    Point pt = null;
    StringTokenizer tok;

    if (value != null) {
      try {
        tok = new StringTokenizer(value);
        pt = new Point(Integer.parseInt(tok.nextToken()), Integer.parseInt(tok.nextToken()));
      } catch (NoSuchElementException e1) {
        e1.printStackTrace();
      } catch (NumberFormatException e2) {
        e2.printStackTrace();
      }
    }
    return pt;
  }
Exemplo n.º 13
0
 public static String take() {
   String message = null;
   if (GameModeType.SERVER == mode) {
     message = getInput("QUERY");
     if (message.equals("error")) {
       message = "exit";
     }
   } else {
     Scanner input = null;
     try {
       input = new Scanner(System.in);
       message = input.nextLine();
     } catch (NoSuchElementException nsee) {
       nsee.printStackTrace();
     } catch (IllegalStateException ise) {
       ise.printStackTrace();
     }
   }
   return message;
 }
Exemplo n.º 14
0
    public Object[] formatLink(String modLink, String modName) throws NoSuchElementException {
      try {
        String fixedLink = modLink.replace(modName, "modname").replace(".jar", "");
        String mcVersion = getPartOfString(fixedLink, 4, " ");
        mcVersion = mcVersion.replace("[", "");
        mcVersion = mcVersion.replace("]", "");

        String modVersion = getPartOfString(fixedLink, 2, " ").replace("v", "");

        return new String[] {
          modName,
          modVersion,
          mcVersion,
          fixedLink.contains("alpha") ? "a" : fixedLink.contains("beta") ? "b" : ""
        };
      } catch (NoSuchElementException e) {
        e.printStackTrace();
        return null;
      }
    }
Exemplo n.º 15
0
  /**
   * Create a HeapPage from a set of bytes of data read from disk. The format of a HeapPage is a set
   * of header bytes indicating the slots of the page that are in use, some number of tuple slots.
   * Specifically, the number of tuples is equal to:
   *
   * <p>floor((BufferPool.PAGE_SIZE*8) / (tuple size * 8 + 1))
   *
   * <p>where tuple size is the size of tuples in this database table, which can be determined via
   * {@link Catalog#getTupleDesc}. The number of 8-bit header words is equal to:
   *
   * <p>ceiling(no. tuple slots / 8)
   *
   * <p>
   *
   * @see Database#getCatalog
   * @see Catalog#getTupleDesc
   * @see BufferPool#PAGE_SIZE
   */
  public HeapPage(HeapPageId id, byte[] data) throws IOException {
    this.pid = id;
    this.td = Database.getCatalog().getTupleDesc(id.getTableId());
    this.numSlots = getNumTuples();
    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));

    // allocate and read the header slots of this page
    header = new byte[getHeaderSize()];
    for (int i = 0; i < header.length; i++) header[i] = dis.readByte();

    try {
      // allocate and read the actual records of this page
      tuples = new Tuple[numSlots];
      for (int i = 0; i < tuples.length; i++) tuples[i] = readNextTuple(dis, i);
    } catch (NoSuchElementException e) {
      e.printStackTrace();
    }
    dis.close();

    setBeforeImage();
  }
Exemplo n.º 16
0
  /**
   * Helper constructor to create a heap page to be used as buffer.
   *
   * @param data - Data to be put in tmp page
   * @param td - Tuple description for the corresponding table.
   * @throws IOException
   */
  private HeapPage(byte[] data, TupleDesc td) throws IOException {
    this.pid =
        null; // No need of a pid here as this page serves as a dummy buffer page and is meant to be
              // used independent of BufferManager.
    this.td = td;
    this.numSlots = (BufferPool.PAGE_SIZE * 8) / ((td.getSize() * 8) + 1);

    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));
    this.header = new Header(dis);

    try {
      // allocate and read the actual records of this page
      tuples = new Tuple[numSlots];
      for (int i = 0; i < numSlots; i++) {
        tuples[i] = readNextTuple(dis, i);
      }
    } catch (NoSuchElementException e) {
      e.printStackTrace();
    }

    dis.close();
  }
Exemplo n.º 17
0
  private static void computeVariants(
      final MoJo mojo, final IMethod im, final MethodInfo nfo, final String outDir)
      throws IllegalArgumentException, FileNotFoundException, CancelException, PDGFormatException,
          WalaException {
    final boolean ignoreExceptions = true;
    final Aliasing minMax = mojo.computeMinMaxAliasing(im);

    computeAliasVariants(mojo, minMax, im, ignoreExceptions, outDir + File.separator + "minmax");

    if (nfo.hasIFCStmts()) {
      int num = 0;
      for (IFCStmt ifc : nfo.getIFCStmts()) {
        num++;

        if (ifc.hasAliasStmt()) {
          try {
            final Aliasing stmtAlias = mojo.computeMayAliasGraphs(nfo, ifc);

            computeAliasVariants(
                mojo, stmtAlias, im, ignoreExceptions, outDir + File.separator + "ifc" + num);
          } catch (AliasGraphException exc) {
            System.err.println("Could not compute alias graph for " + nfo);
            System.err.println(exc.getMessage());
            exc.printStackTrace();
          } catch (NoSuchElementException exc) {
            System.err.println("Could not compute alias graph for " + nfo);
            System.err.println(exc.getMessage());
            exc.printStackTrace();
          } catch (FlowAstException exc) {
            System.err.println("Could not compute alias graph for " + nfo);
            System.err.println(exc.getMessage());
            exc.printStackTrace();
          }
        }
      }
    }

    // TODO do pair method param alias
  }
Exemplo n.º 18
0
  /**
   * Takes a string of representing token separated properties and returns an array of parsed
   * strings. NOTE: this method currently doesn't support appropriate quoting of the token, although
   * it probably should...
   *
   * @param p properties
   * @param propName the name of the property
   * @param tok the characters separating the strings.
   * @return Array of strings between the tokens.
   */
  public static String[] stringArrayFromProperties(Properties p, String propName, String tok) {

    String[] ret = null;
    String raw = p.getProperty(propName);

    if (raw != null && raw.length() != 0) {

      try {
        StringTokenizer token = new StringTokenizer(raw, tok);
        int numPaths = token.countTokens();

        ret = new String[numPaths];
        for (int i = 0; i < numPaths; i++) {
          ret[i] = token.nextToken();
        }
        return ret;
      } catch (java.util.NoSuchElementException e) {
        e.printStackTrace();
      }
    }
    return ret;
  }
  @Test
  public void testCreateDestroySecurityGroup() {
    try {
      zone =
          Iterables.find(
              client.getZoneClient().listZones(),
              new Predicate<Zone>() {

                @Override
                public boolean apply(Zone arg0) {
                  return arg0.isSecurityGroupsEnabled();
                }
              });
      securityGroupsSupported = true;
      for (SecurityGroup securityGroup :
          client
              .getSecurityGroupClient()
              .listSecurityGroups(ListSecurityGroupsOptions.Builder.named(prefix))) {
        for (IngressRule rule : securityGroup.getIngressRules())
          assert this.jobComplete.apply(
                  client.getSecurityGroupClient().revokeIngressRule(rule.getId()))
              : rule;
        client.getSecurityGroupClient().deleteSecurityGroup(securityGroup.getId());
      }
      group = client.getSecurityGroupClient().createSecurityGroup(prefix);
      assertEquals(group.getName(), prefix);
      checkGroup(group);
      try {
        client.getSecurityGroupClient().createSecurityGroup(prefix);
        assert false;
      } catch (IllegalStateException e) {

      }
    } catch (NoSuchElementException e) {
      e.printStackTrace();
    }
  }
  /**
   * execute
   *
   * @param command
   * @param commandId
   * @return boolean
   */
  @Override
  public boolean execute(final String command, final int commandId) {
    // new Thread(){
    // public void run(){
    Map<String, Object> maps = null;
    try {

      maps = SeqlParser.parseSeql(command, configFile);

      if (maps == null) throw new BadRequestException("Command not supported!");
      return executeCommand(maps, commandId);

    } catch (BadRequestException ex) {
      ex.printStackTrace();
      if (callback != null) callback.onBadRequest(ex.getMessage());
    } catch (NoSuchElementException ex) {
      ex.printStackTrace();
      if (callback != null) callback.onNoApplet();
    } catch (NoSecureElementException ex) {
      ex.printStackTrace();
      if (callback != null) callback.onNoSecureElement();
    } catch (NoReaderException ex) {
      ex.printStackTrace();
      if (callback != null) callback.onNoReader();
    } catch (ChannelNotOpenException e) {
      e.printStackTrace();
      if (callback != null) callback.onNotConnected();
    } catch (IOException e) {
      e.printStackTrace();
      if (callback != null) callback.onIOException(e.getMessage());
    } catch (Exception e) {
      if (callback != null) callback.onBadRequest(e.getMessage());
    }
    // }
    // }.start();
    return false;
  }
  /**
   * Parses the line as a line full of wind vector pairs.
   *
   * @param input String containing the input line
   * @return
   * @throws RuntimeException
   */
  private List<Object> processLine(String input) {
    int i = 0;
    List<Object> arr = new ArrayList<Object>();

    Scanner scanner = new Scanner(input).useLocale(Locale.ENGLISH);
    scanner.useDelimiter(" ");
    try {
      while (scanner.hasNext()) {

        // Do we have the row identifier (the latitude)?
        if (i == 0) {
          arr.add(scanner.nextDouble());
          i++;
          continue;
        }

        // We should now only have some wind vectors left
        WindVector v;
        try {
          v = new WindVector(scanner.nextDouble(), scanner.nextDouble());
        } catch (NoSuchElementException e) {
          logger.error("FATAL! Input file contains a incomplete value pair!");
          e.printStackTrace();
          throw new RuntimeException("FATAL! Input file contains a incomplete value pair!");
        }

        arr.add(v);
        i++;
      }
    } catch (RuntimeException e) {
      logger.error("Runtime exception occured!");
      e.printStackTrace();
      scanner.close();
    }
    return arr;
  }
Exemplo n.º 22
0
  @SuppressWarnings("unchecked")
  @Override
  public WOResponse handleRequest(WORequest request) {
    WOApplication application = WOApplication.application();
    application.awake();
    try {
      WOContext context = application.createContextForRequest(request);
      WOResponse response = application.createResponseInContext(context);

      Object output;
      try {
        String inputString = request.contentString();
        JSONObject input = new JSONObject(inputString);
        String wosid = request.cookieValueForKey("wosid");
        if (wosid == null) {
          ERXMutableURL url = new ERXMutableURL();
          url.setQueryParameters(request.queryString());
          wosid = url.queryParameter("wosid");
          if (wosid == null && input.has("wosid")) {
            wosid = input.getString("wosid");
          }
        }
        context._setRequestSessionID(wosid);
        WOSession session = null;
        if (context._requestSessionID() != null) {
          session = WOApplication.application().restoreSessionWithID(wosid, context);
        }
        if (session != null) {
          session.awake();
        }
        try {
          JSONComponentCallback componentCallback = null;

          ERXDynamicURL url = new ERXDynamicURL(request._uriDecomposed());
          String requestHandlerPath = url.requestHandlerPath();
          JSONRPCBridge jsonBridge;
          if (requestHandlerPath != null && requestHandlerPath.length() > 0) {
            String componentNameAndInstance = requestHandlerPath;
            String componentInstance;
            String componentName;
            int slashIndex = componentNameAndInstance.indexOf('/');
            if (slashIndex == -1) {
              componentName = componentNameAndInstance;
              componentInstance = null;
            } else {
              componentName = componentNameAndInstance.substring(0, slashIndex);
              componentInstance = componentNameAndInstance.substring(slashIndex + 1);
            }

            if (session == null) {
              session = context.session();
            }

            String bridgesKey =
                (componentInstance == null) ? "_JSONGlobalBridges" : "_JSONInstanceBridges";
            Map<String, JSONRPCBridge> componentBridges =
                (Map<String, JSONRPCBridge>) session.objectForKey(bridgesKey);
            if (componentBridges == null) {
              int limit =
                  ERXProperties.intForKeyWithDefault(
                      (componentInstance == null)
                          ? "er.ajax.json.globalBacktrackCacheSize"
                          : "er.ajax.json.backtrackCacheSize",
                      WOApplication.application().pageCacheSize());
              componentBridges = new LRUMap<String, JSONRPCBridge>(limit);
              session.setObjectForKey(componentBridges, bridgesKey);
            }
            jsonBridge = componentBridges.get(componentNameAndInstance);
            if (jsonBridge == null) {
              Class componentClass = _NSUtilities.classWithName(componentName);
              JSONComponent component;
              if (JSONComponent.class.isAssignableFrom(componentClass)) {
                component =
                    (JSONComponent)
                        _NSUtilities.instantiateObject(
                            componentClass,
                            new Class[] {WOContext.class},
                            new Object[] {context},
                            true,
                            false);
              } else {
                throw new SecurityException(
                    "There is no JSON component named '" + componentName + "'.");
              }
              jsonBridge =
                  createBridgeForComponent(
                      component, componentName, componentInstance, componentBridges);
            }

            componentCallback = new JSONComponentCallback(context);
            jsonBridge.registerCallback(componentCallback, WOContext.class);
          } else {
            jsonBridge = _sharedBridge;
          }

          try {
            output = jsonBridge.call(new Object[] {request, response, context}, input);
          } finally {
            if (componentCallback != null) {
              jsonBridge.unregisterCallback(componentCallback, WOContext.class);
            }
          }

          if (context._session() != null) {
            WOSession contextSession = context._session();
            // If this is a new session, then we have to force it to be a cookie session
            if (wosid == null) {
              boolean storesIDsInCookies = contextSession.storesIDsInCookies();
              try {
                contextSession.setStoresIDsInCookies(true);
                contextSession._appendCookieToResponse(response);
              } finally {
                contextSession.setStoresIDsInCookies(storesIDsInCookies);
              }
            } else {
              contextSession._appendCookieToResponse(response);
            }
          }
          if (output != null) {
            response.appendContentString(output.toString());
          }

          if (response != null) {
            response._finalizeInContext(context);
            response.disableClientCaching();
          }
        } finally {
          try {
            if (session != null) {
              session.sleep();
            }
          } finally {
            if (context._session() != null) {
              WOApplication.application().saveSessionForContext(context);
            }
          }
        }
      } catch (NoSuchElementException e) {
        e.printStackTrace();
        output =
            new JSONRPCResult(
                JSONRPCResult.CODE_ERR_NOMETHOD, null, JSONRPCResult.MSG_ERR_NOMETHOD);
      } catch (JSONException e) {
        e.printStackTrace();
        output = new JSONRPCResult(JSONRPCResult.CODE_ERR_PARSE, null, JSONRPCResult.MSG_ERR_PARSE);
      } catch (Throwable t) {
        t.printStackTrace();
        output = new JSONRPCResult(JSONRPCResult.CODE_ERR_PARSE, null, t.getMessage());
      }

      return response;
    } finally {
      application.sleep();
    }
  }
Exemplo n.º 23
0
  /*
   * methods
   */
  public void parseByColumn() {

    // TODO:  This is much slower for a low number of long columns than many columns with fewer data
    // points.
    // TODO: Find out why and optimise

    boolean hasNextLine = true;
    String thisLine = null;
    try {
      thisLine = myReader.readLine();
    } catch (IOException e) {
      System.err.println("IO Exception occured whilst reading first CSV line");
      e.printStackTrace();
    }

    if (thisLine == null) {
      System.err.println("Supplied CSV is empty!!");
      hasNextLine = false;
    } else {
      ArrayList<String> tempArray = new ArrayList<String>();
      StringTokenizer myTokenizer = new StringTokenizer(thisLine, mySeperator);
      numCols = myTokenizer.countTokens();

      colHeaders = new String[numCols];
      while (myTokenizer.hasMoreTokens()) {
        try {
          tempArray.add(myTokenizer.nextToken());
        } catch (NoSuchElementException e) {
          System.err.println("No such element - is one of the column headers blank / null?");
          e.printStackTrace();
        }
      }

      tempArray.toArray(colHeaders);
    }

    dataArray = new ArrayList[numCols];
    for (int t = 0; t < numCols; t++) {
      dataArray[t] = new ArrayList<String>();
    }

    while (hasNextLine) {
      try {
        thisLine = myReader.readLine();

      } catch (IOException e) {
        System.err.println("IO Exception occured whilst reading CSV line");
        e.printStackTrace();
      }

      hasNextLine = (thisLine != null);
      if (hasNextLine) {
        StringTokenizer myTokenizer = new StringTokenizer(thisLine, mySeperator);
        for (int i = 0; i < numCols; i++) {
          try {
            dataArray[i].add(myTokenizer.nextToken());
          } catch (NoSuchElementException e) {
            System.err.println(
                "No such element - is one of the data rows blank / null - e.g. commas only?");
            e.printStackTrace();
          }
        }
        numRows++;
      }

      contentsByColumn = new WeakHashMap<String, String[]>();
      for (int k = 0; k < numCols; k++) {
        contentsByColumn.put(colHeaders[k], dataArray[k].toArray(new String[numRows]));
      }
    }

    if (Consts.DEBUG) {
      if (Consts.DEBUG)
        System.out.println("Parsed file - " + numCols + " columns and " + numRows + " rows.");
    }
  }