Example #1
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;
 }
Example #2
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();
 }
Example #3
0
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    CharSequence pathInfo = request.getPathInfo();
    if (pathInfo == null) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No path");
      return;
    }
    Iterator<String> pathComponents = SLASH.split(pathInfo).iterator();
    String userID;
    List<String> itemIDsList;
    try {
      userID = pathComponents.next();
      itemIDsList = Lists.newArrayList();
      while (pathComponents.hasNext()) {
        itemIDsList.add(pathComponents.next());
      }
    } catch (NoSuchElementException nsee) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, nsee.toString());
      return;
    }

    String[] itemIDs = itemIDsList.toArray(new String[itemIDsList.size()]);
    unescapeSlashHack(itemIDs);

    OryxRecommender recommender = getRecommender();
    try {
      float[] estimates = recommender.estimatePreferences(userID, itemIDs);
      output(request, response, estimates);
    } catch (NotReadyException nre) {
      response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, nre.toString());
    }
  }
  /** 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.";
        }
      }
    }
  }
  /** @see org.geotools.data.FeatureStore#setFeatures(org.geotools.data.FeatureReader) */
  public void setFeatures(FeatureReader<SimpleFeatureType, SimpleFeature> reader)
      throws IOException {
    WFSTransactionState ts = null;

    if (trans == Transaction.AUTO_COMMIT) {
      ts = new WFSTransactionState(ds);
    } else {
      ts = (WFSTransactionState) trans.getState(ds);
    }

    ts.addAction(
        getSchema().getTypeName(), new DeleteAction(getSchema().getTypeName(), Filter.INCLUDE));

    ReferencedEnvelope bounds = null;
    while (reader.hasNext()) {

      try {
        SimpleFeature f = reader.next();
        List<AttributeDescriptor> atrs = f.getFeatureType().getAttributeDescriptors();
        for (int i = 0; i < atrs.size(); i++) {
          if (atrs.get(i) instanceof GeometryDescriptor) {
            Geometry g = (Geometry) f.getAttribute(i);
            CoordinateReferenceSystem cs =
                ((GeometryDescriptor) atrs.get(i)).getCoordinateReferenceSystem();
            if (cs != null && !cs.getIdentifiers().isEmpty())
              g.setUserData(cs.getIdentifiers().iterator().next().toString());
            if (g == null) continue;
            if (bounds == null) {
              bounds = new ReferencedEnvelope(g.getEnvelopeInternal(), cs);
            } else {
              bounds.expandToInclude(g.getEnvelopeInternal());
            }
          }
        }
        ts.addAction(getSchema().getTypeName(), new InsertAction(f));
      } catch (NoSuchElementException e) {
        WFS_1_0_0_DataStore.LOGGER.warning(e.toString());
      } catch (IllegalAttributeException e) {
        WFS_1_0_0_DataStore.LOGGER.warning(e.toString());
      }
    }

    // Fire a notification.
    // JE
    if (bounds == null) {
      // if bounds are null then send an envelope to say that features were added but
      // at an unknown location.
      bounds = new ReferencedEnvelope(getSchema().getCoordinateReferenceSystem());
      ((WFS_1_0_0_DataStore) getDataStore())
          .listenerManager.fireFeaturesRemoved(
              getSchema().getTypeName(), getTransaction(), bounds, false);
    } else {
      ((WFS_1_0_0_DataStore) getDataStore())
          .listenerManager.fireFeaturesRemoved(
              getSchema().getTypeName(), getTransaction(), bounds, false);
    }
    if (trans == Transaction.AUTO_COMMIT) {
      ts.commit();
    }
  }
 @Override
 public void initialize(AttachVolumeType msg) {
   final String instanceId = this.getRequest().getInstanceId();
   final String volumeId = this.getRequest().getVolumeId();
   final Function<String, VmInstance> funcName =
       new Function<String, VmInstance>() {
         public VmInstance apply(final String input) {
           VmInstance vm = VmInstances.lookup(instanceId);
           try {
             if (!AttachmentState.attached.equals(
                 vm.lookupVolumeAttachment(volumeId).getAttachmentState())) {
               vm.updateVolumeAttachment(volumeId, AttachmentState.attaching);
             }
           } catch (Exception ex) {
             vm.updateVolumeAttachment(volumeId, AttachmentState.attaching);
           }
           return vm;
         }
       };
   try {
     Entities.asTransaction(VmInstance.class, funcName).apply(this.getRequest().getInstanceId());
   } catch (NoSuchElementException e1) {
     LOG.error(
         "Failed to lookup volume attachment state in order to update: "
             + this.getRequest().getVolumeId()
             + " due to "
             + e1.getMessage(),
         e1);
   }
 }
  /**
   * Creates temporary avatar
   *
   * @param avatarType Type of entity where to change avatar
   * @param owningObjectId Entity id where to change avatar
   * @param filename name of file being uploaded
   * @param size size of file
   * @param request servlet request
   * @return temporary avatar cropping instructions
   * @since v5.0
   */
  @POST
  @Consumes(MediaType.WILDCARD)
  @RequiresXsrfCheck
  @Path("type/{type}/owner/{owningObjectId}/temp")
  public Response storeTemporaryAvatar(
      final @PathParam("type") String avatarType,
      final @PathParam("owningObjectId") String owningObjectId,
      final @QueryParam("filename") String filename,
      final @QueryParam("size") Long size,
      final @Context HttpServletRequest request) {
    try {
      final Avatar.Type avatarsType = Avatar.Type.getByName(avatarType);
      if (null == avatarsType) {
        throw new NoSuchElementException("avatarType");
      }

      final ApplicationUser remoteUser = authContext.getUser();

      // get from paramter!!
      Avatar.Size avatarTargetSize = Avatar.Size.LARGE;
      final Response storeTemporaryAvatarResponse =
          avatarTemporaryHelper.storeTemporaryAvatar(
              remoteUser, avatarsType, owningObjectId, avatarTargetSize, filename, size, request);

      return storeTemporaryAvatarResponse;
    } catch (NoSuchElementException x) {
      return Response.status(Response.Status.NOT_FOUND).entity(x.getMessage()).build();
    }
  }
  public static void main(String[] args) {

    int dividend = 0;
    int divider = 0;

    try (Scanner scanner = new Scanner(System.in)) {
      System.out.print("\nEnter the dividend: ");
      dividend = scanner.nextInt();

      System.out.print("\nEnter the divider: ");
      divider = scanner.nextInt();

      // divider = -divider;

      int quotient = 0;
      while (dividend >= divider) {
        dividend -= divider;
        quotient++;
      }

      System.out.print("\nQuotient: " + quotient);
      System.out.print("\n\nRemainder: " + dividend);

    } catch (NoSuchElementException e) {
      System.out.println("NoSuchElementException: " + e.toString());
    } catch (Exception e) {
      System.out.println("Exception: " + e.toString());
    }
  }
  /**
   * 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");
    }
  }
  @SuppressWarnings("unchecked")
  @Test
  public void testDefaultLocationWithUnmatchedPredicateExceptionMessageAndLocationNotCalled() {
    Supplier<Set<? extends Location>> locations =
        Suppliers.<Set<? extends Location>>ofInstance(ImmutableSet.<Location>of(region));
    Supplier<Set<? extends Image>> images =
        Suppliers.<Set<? extends Image>>ofInstance(ImmutableSet.<Image>of(image));
    Supplier<Set<? extends Hardware>> hardwares =
        Suppliers.<Set<? extends Hardware>>ofInstance(
            ImmutableSet.<Hardware>of(createMock(Hardware.class)));
    Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
    Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
    TemplateOptions defaultOptions = createMock(TemplateOptions.class);

    expect(optionsProvider.get()).andReturn(defaultOptions);

    replay(defaultOptions, optionsProvider, templateBuilderProvider);

    TemplateBuilderImpl template =
        createTemplateBuilder(
            null, locations, images, hardwares, region, optionsProvider, templateBuilderProvider);

    try {
      template.imageDescriptionMatches("notDescription").build();
      fail("Expected NoSuchElementException");
    } catch (NoSuchElementException e) {
      // make sure big data is not in the exception message
      assertEquals(
          e.getMessage(),
          "no image matched predicate: And(nullEqualToIsParentOrIsGrandparentOfCurrentLocation(),imageDescription(notDescription))");
    }

    verify(defaultOptions, optionsProvider, templateBuilderProvider);
  }
  @SuppressWarnings("unchecked")
  @Test
  public void testDefaultLocationWithNoOptionsNoSuchElement() {
    Supplier<Set<? extends Location>> locations =
        Suppliers.<Set<? extends Location>>ofInstance(ImmutableSet.<Location>of(region));
    Supplier<Set<? extends Image>> images =
        Suppliers.<Set<? extends Image>>ofInstance(ImmutableSet.<Image>of(image));
    Supplier<Set<? extends Hardware>> hardwares =
        Suppliers.<Set<? extends Hardware>>ofInstance(
            ImmutableSet.<Hardware>of(createMock(Hardware.class)));
    Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
    Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
    TemplateOptions defaultOptions = createMock(TemplateOptions.class);

    expect(optionsProvider.get()).andReturn(defaultOptions);

    replay(defaultOptions, optionsProvider, templateBuilderProvider);

    TemplateBuilderImpl template =
        createTemplateBuilder(
            null, locations, images, hardwares, region, optionsProvider, templateBuilderProvider);

    try {
      template.imageId("region/imageId2").build();
      fail("Expected NoSuchElementException");
    } catch (NoSuchElementException e) {
      // make sure big data is not in the exception message
      assertEquals(e.getMessage(), "imageId(region/imageId2) not found");
    }

    verify(defaultOptions, optionsProvider, templateBuilderProvider);
  }
 @PreAuthorize("hasAuthority('ADMIN')")
 @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
 @ResponseStatus(HttpStatus.NO_CONTENT)
 @ApiOperation(
     value = "Update new LunchMenu.",
     notes = "Returns NO_CONTENT if update was successful.")
 @ApiResponses(
     value = {
       @ApiResponse(code = 401, message = "Only authenticated access allowed."),
       @ApiResponse(code = 403, message = "Only user of ADMIN role can have access to it."),
       @ApiResponse(code = 404, message = "LunchMenu with such Id not found."),
       @ApiResponse(
           code = 400,
           message =
               "Reasons:\n1:Properties 'theDay' and 'theRestaurantId' must have value.\n"
                   + "2:value of ID different between Id in URL and lunchMenuDto .\n"
                   + "3:Other combination of lunchMenuAsDto.theDay and lunchMenuAsDto.theRestaurantId already exists.")
     })
 public void updateLunchMenu(
     @ApiParam(value = "ID of LunchMenu from DB", required = true) @PathVariable Long id,
     @ApiParam(value = "new properties of LunchMenu", required = true) @Valid @RequestBody
         LunchMenuDto lunchMenuDto) {
   LOGGER.debug("Update LunchMenu {} ", lunchMenuDto);
   checkUrlAndBodyForId(id, lunchMenuDto);
   try {
     lunchMenusService.updateLunchMenu(id, lunchMenuDto);
   } catch (NoSuchElementException exception) {
     throw new ExceptionLunchMenuNotFound(exception.getMessage());
   }
 }
Example #13
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();
    }
  }
  @POST
  @Path("type/{type}/owner/{owningObjectId}/avatar")
  public Response createAvatarFromTemporary(
      final @PathParam("type") String avatarType,
      final @PathParam("owningObjectId") String owningObjectId,
      final AvatarCroppingBean croppingInstructions) {
    try {
      final Avatar.Type avatarsType = Avatar.Type.getByName(avatarType);
      if (null == avatarsType) {
        throw new NoSuchElementException("avatarType");
      }
      final ApplicationUser remoteUser = authContext.getUser();

      final AvatarBean avatarFromTemporary =
          avatarTemporaryHelper.createAvatarFromTemporary(
              remoteUser, avatarsType, owningObjectId, croppingInstructions);

      return Response.status(Response.Status.CREATED)
          .entity(avatarFromTemporary)
          .cacheControl(never())
          .build();
    } catch (NoSuchElementException x) {
      return Response.status(Response.Status.NOT_FOUND).entity(x.getMessage()).build();
    }
  }
Example #15
0
 private static String shellRead() {
   try {
     Scanner scanner = new Scanner(System.in);
     return scanner.nextLine();
   } catch (NoSuchElementException e) {
     System.err.println(e.getMessage());
     System.exit(0);
   }
   return null;
 }
Example #16
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;
 }
  @Test
  public void getMembersWhenCallingNextWithNoMoreReference() throws Exception {
    Iterator<DocumentReference> iterator = setUpSingleUser();

    assertEquals(new DocumentReference("userwiki", "XWiki", "userpage"), iterator.next());
    try {
      iterator.next();
    } catch (NoSuchElementException expected) {
      assertEquals(
          "No more users to extract from the passed references [[userwiki:XWiki.userpage]]",
          expected.getMessage());
    }
  }
Example #18
0
  /** @see org.geotools.arcsde.session.ISessionPool#getSession(boolean) */
  public ISession getSession(final boolean transactional)
      throws IOException, UnavailableConnectionException {
    checkOpen();
    try {
      Session connection = null;
      if (transactional) {
        LOGGER.finest("Borrowing session from pool for transactional access");
        connection = (Session) pool.borrowObject();
      } else {
        synchronized (openSessionsNonTransactional) {
          try {
            if (LOGGER.isLoggable(Level.FINER)) {
              LOGGER.finer("Grabbing session from pool on " + Thread.currentThread().getName());
            }
            connection = (Session) pool.borrowObject();
            if (LOGGER.isLoggable(Level.FINER)) {
              LOGGER.finer("Got session from the pool on " + Thread.currentThread().getName());
            }
          } catch (NoSuchElementException e) {
            if (LOGGER.isLoggable(Level.FINER)) {
              LOGGER.finer("No available sessions in the pool, falling back to queued session");
            }
            connection = openSessionsNonTransactional.remove();
          }

          openSessionsNonTransactional.add(connection);

          if (LOGGER.isLoggable(Level.FINER)) {
            LOGGER.finer(
                "Got session from the in use queue on " + Thread.currentThread().getName());
          }
        }
      }

      connection.markActive();
      return connection;

    } catch (NoSuchElementException e) {
      LOGGER.log(
          Level.WARNING, "Out of connections: " + e.getMessage() + ". Config: " + this.config);
      throw new UnavailableConnectionException(config.getMaxConnections(), this.config);
    } catch (SeException se) {
      ArcSdeException sdee = new ArcSdeException(se);
      LOGGER.log(Level.WARNING, "ArcSDE error getting connection for " + config, sdee);
      throw sdee;
    } catch (Exception e) {
      LOGGER.log(Level.WARNING, "Unknown problem getting connection: " + e.getMessage(), e);
      throw (IOException)
          new IOException("Unknown problem fetching connection from connection pool").initCause(e);
    }
  }
  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();
    }
  }
 public void initializeProject(WorkItem wi) {
   // Parse the current project information
   try {
     // Get the metadata information about the project
     Field pjNameFld = wi.getField("projectName");
     Field pjTypeFld = wi.getField("projectType");
     Field pjCfgPathFld = wi.getField("fullConfigSyntax");
     Field pjChkptFld = wi.getField("lastCheckpoint");
     // Convert to our class fields
     // First obtain the project name field
     if (null != pjNameFld && null != pjNameFld.getValueAsString()) {
       projectName = pjNameFld.getValueAsString();
     } else {
       LOGGER.warning("Project info did not provide a value for the 'projectName' field!");
       projectName = "";
     }
     // Next, we'll need to know the project type
     if (null != pjTypeFld && null != pjTypeFld.getValueAsString()) {
       projectType = pjTypeFld.getValueAsString();
       if (isBuild()) {
         // Next, we'll need to know the current build checkpoint for this configuration
         Field pjRevFld = wi.getField("revision");
         if (null != pjRevFld && null != pjRevFld.getItem()) {
           projectRevision = pjRevFld.getItem().getId();
         } else {
           projectRevision = "";
           LOGGER.warning("Project info did not provide a vale for the 'revision' field!");
         }
       }
     } else {
       LOGGER.warning("Project info did not provide a value for the 'projectType' field!");
       projectType = "";
     }
     // Most important is the configuration path
     if (null != pjCfgPathFld && null != pjCfgPathFld.getValueAsString()) {
       fullConfigSyntax = pjCfgPathFld.getValueAsString();
     } else {
       LOGGER.severe("Project info did not provide a value for the 'fullConfigSyntax' field!");
       fullConfigSyntax = "";
     }
     // Finally, we'll need to store the last checkpoint to figure out differences, etc.
     if (null != pjChkptFld && null != pjChkptFld.getDateTime()) {
       lastCheckpoint = pjChkptFld.getDateTime();
     } else {
       LOGGER.warning("Project info did not provide a value for the 'lastCheckpoint' field!");
       lastCheckpoint = Calendar.getInstance().getTime();
     }
   } catch (NoSuchElementException nsee) {
     LOGGER.severe("Project info did not provide a value for field " + nsee.getMessage());
   }
 }
Example #21
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;
 }
Example #22
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;
 }
Example #23
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;
 }
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    CharSequence pathInfo = request.getPathInfo();
    if (pathInfo == null) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No path");
      return;
    }
    Iterator<String> pathComponents = SLASH.split(pathInfo).iterator();
    long toItemID;
    List<Long> itemIDsList = Lists.newArrayList();
    try {
      toItemID = Long.parseLong(pathComponents.next());
      while (pathComponents.hasNext()) {
        itemIDsList.add(Long.parseLong(pathComponents.next()));
      }
    } catch (NoSuchElementException nsee) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, nsee.toString());
      return;
    } catch (NumberFormatException nfe) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, nfe.toString());
      return;
    }
    if (itemIDsList.isEmpty()) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No items");
      return;
    }
    long[] itemIDs = new long[itemIDsList.size()];
    for (int i = 0; i < itemIDs.length; i++) {
      itemIDs[i] = itemIDsList.get(i);
    }

    MyrrixRecommender recommender = getRecommender();
    try {
      float[] similarities = recommender.similarityToItem(toItemID, itemIDs);
      Writer out = response.getWriter();
      for (float similarity : similarities) {
        out.write(Float.toString(similarity));
        out.write('\n');
      }
    } catch (NoSuchItemException nsie) {
      response.sendError(HttpServletResponse.SC_NOT_FOUND, nsie.toString());
    } catch (NotReadyException nre) {
      response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, nre.toString());
    } catch (TasteException te) {
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, te.toString());
      getServletContext().log("Unexpected error in " + getClass().getSimpleName(), te);
    }
  }
  @POST
  @Consumes(MediaType.MULTIPART_FORM_DATA)
  @RequiresXsrfCheck
  @Path("type/{type}/owner/{owningObjectId}/temp")
  @Produces({MediaType.TEXT_HTML})
  public Response storeTemporaryAvatarUsingMultiPart(
      final @PathParam("type") String avatarType,
      final @PathParam("owningObjectId") String owningObjectId,
      final @MultipartFormParam("avatar") FilePart filePart,
      final @Context HttpServletRequest request) {
    try {
      try {
        final Avatar.Type avatarsType = Avatar.Type.getByName(avatarType);
        if (null == avatarsType) {
          throw new NoSuchElementException("avatarType");
        }

        final ApplicationUser remoteUser = authContext.getUser();

        // get from paramter!!
        Avatar.Size avatarTargetSize = Avatar.Size.LARGE;
        final Response storeTemporaryAvatarResponse =
            avatarTemporaryHelper.storeTemporaryAvatar(
                remoteUser, avatarsType, owningObjectId, avatarTargetSize, filePart, request);

        return storeTemporaryAvatarResponse;
      } catch (NoSuchElementException x) {
        return Response.status(Response.Status.NOT_FOUND).entity(x.getMessage()).build();
      }
    } catch (RESTException x) {
      String errorMsgs = x.toString();
      String sep = "";

      return Response.status(Response.Status.OK)
          .entity(
              "<html><body>"
                  + "<textarea>"
                  + "{"
                  + "\"errorMessages\": ["
                  + errorMsgs
                  + "]"
                  + "}"
                  + "</textarea>"
                  + "</body></html>")
          .cacheControl(never())
          .build();
    }
  }
Example #26
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;
  }
Example #27
0
 public static void interactiveMode(final HashMap<String, Command> commandMap, DataBase dataBase)
     throws MultiFileMapException {
   try (Scanner scanner = new Scanner(System.in)) {
     while (true) {
       System.out.print("$ ");
       if (!scanner.hasNextLine()) {
         System.exit(0);
       }
       String command = scanner.nextLine();
       execLine(command, commandMap, dataBase);
     }
   } catch (NoSuchElementException e) {
     System.err.println(e.getMessage());
     System.exit(-1);
   }
 }
Example #28
0
 public void message(String s) {
   if (firstLine == null) firstLine = s;
   else {
     StringTokenizer st = new StringTokenizer(s, " ");
     try {
       st.nextToken();
       st.nextToken();
       st.nextToken();
       size = (new Integer(st.nextToken().trim())).longValue();
     } catch (NoSuchElementException e) {
       exception = new RunnerException(e.toString());
     } catch (NumberFormatException e) {
       exception = new RunnerException(e.toString());
     }
   }
 }
Example #29
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;
  }
 /**
  * Lets the given robot pick up and use an item.
  *
  * @param robot The robot that has to execute this command.
  * @effect The given robot picks up and use a random item on its current position, provided
  *     there is an item on the same position.
  */
 @Override
 public void execute(Robot robot)
     throws NullPointerException, IllegalArgumentException, IllegalStateException {
   try {
     Item item = robot.getBoard().getRandomItemOnPosition(robot.getPosition());
     if (item != null) robot.pickUp(item);
     robot.use(item);
   } catch (NullPointerException exc) {
     assert false;
   } catch (IllegalArgumentException exc) {
     System.err.println(exc.getMessage());
   } catch (IllegalStateException exc) {
     assert false;
   } catch (NoSuchElementException exc) {
     System.err.println(exc.getMessage());
   }
 }