public static void main(String[] args) {
    Stack s = new Stack();
    s.push(1);
    s.push(2);
    s.push(3);
    assert (s.peek().equals(3));
    s.pop();
    assert (s.peek().equals(2));
    s.pop();
    s.push(4);
    assert (s.peek().equals(4));
    s.pop();
    s.pop();
    try {
      s.pop();
      assert (false);
    } catch (NoSuchElementException e) {
      System.out.println("empty stack");
      System.out.println(e.getMessage());
    }

    s.push(0);
    s.push(-1);
    s.push(Integer.MAX_VALUE);
    assert (s.peek().equals(Integer.MAX_VALUE));
    s.pop();
    assert (s.peek().equals(-1));
    s.pop();
    assert (s.peek().equals(0));
    s.pop();
    try {
      s.pop();
      assert (false);
    } catch (NoSuchElementException e) {
      System.out.println("empty stack");
      System.out.println(e.getMessage());
    }
    s.push(0);
    assert (s.peek().equals(0));

    Queue q = new Queue();
    q.enqueue(1);
    q.enqueue(2);
    assert (q.head().equals(1));
    q.dequeue();
    assert (q.head().equals(2));
    q.dequeue();
    try {
      q.dequeue();
      assert (false);
    } catch (NoSuchElementException e) {
      System.out.println("empty queue");
      System.out.println(e.getMessage());
    }
  }
 @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);
   }
 }
  @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);
  }
Пример #5
0
 @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());
   }
 }
  @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();
    }
  }
  /**
   * 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();
    }
  }
  /**
   * Matches parentheses and square brackets. Populates the openingBracketIndex and
   * closingBracketIndex array lists in such a way that closingBracketIndex[i] is
   * the position of the bracket in the expression that closes an opening bracket
   * at position openingBracketIndex[i]. For example, if the expression is:
   * <pre>
   *    (a+(b-c))*(d+A[4])
   * </pre>
   * then the method would return true, and the array lists would be set to:
   * <pre>
   *    openingBracketIndex: [0 3 10 14]
   *    closingBracketIndex: [8 7 17 16]
   * </pe>
   *
   * See the FAQ in project description for more details.
   *
   * @return True if brackets are matched correctly, false if not
   */
  public boolean isLegallyMatched() {
    // COMPLETE THIS METHOD

    // FOLLOWING LINE ADDED TO MAKE COMPILER HAPPY

    Stack<Integer> parenContainer = new Stack<Integer>();
    Stack<Integer> bracContainer = new Stack<Integer>();
    openingBracketIndex = new ArrayList<Integer>();
    closingBracketIndex = new ArrayList<Integer>();

    for (int i = 0; i < expr.length(); i++) {
      char ch = expr.charAt(i);
      if (ch == '(') {
        parenContainer.push(i);
      } else if (ch == '[') {
        bracContainer.push(i);
      }

      if (ch == ')') {
        try {
          closingBracketIndex.add(i);
          openingBracketIndex.add(parenContainer.pop());
        } catch (NoSuchElementException e) {
          System.out.println(e.getMessage());
          return false;
        }

      } else if (ch == ']') {
        try {
          closingBracketIndex.add(i);
          openingBracketIndex.add(bracContainer.pop());
        } catch (NoSuchElementException e) {
          System.out.println(e.getMessage());
          return false;
        }
      }
    }

    if (parenContainer.isEmpty() && bracContainer.isEmpty()) {
      System.out.println(openingBracketIndex);
      System.out.println(closingBracketIndex);
      return true;
    }

    return false;
  }
Пример #9
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;
 }
  @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());
    }
  }
 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());
   }
 }
Пример #12
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);
    }
  }
Пример #13
0
  @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();
    }
  }
Пример #14
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);
   }
 }
Пример #15
0
 /**
  * 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());
   }
 }
  /**
   * @param isInterchange
   * @param id
   * @param fieldName
   * @param value
   * @return 201 when the update was successful, 404, when no rule corresponds to given id or 400
   *     when the update cannot be performed.
   */
  @PUT
  @Path("{rule-id}/{field}/{value}")
  public Response updateRule(
      @HeaderParam(X_VISION_INTERCHANGE_HEADER) final boolean isInterchange,
      @PathParam("rule-id") final String id,
      @PathParam("field") final String fieldName,
      @PathParam("value") final String value) {
    try {
      store.update(id, fieldName, value);
      update.notifyUpdate(isInterchange, id, fieldName, value);
    } catch (final NoSuchElementException e) {
      return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
    } catch (final IllegalArgumentException e) {
      return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
    }

    return toCORS(Response.ok());
  }
Пример #17
0
 @ApiOperation(value = "Cancel LunchMenu.", notes = "Returns NO_CONTENT if cancel 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."),
     })
 @PreAuthorize("hasAuthority('ADMIN')")
 @RequestMapping(value = "/{id}/cancel", method = RequestMethod.PUT)
 @ResponseStatus(HttpStatus.NO_CONTENT)
 public void cancelLunchMenu(
     @ApiParam(value = "ID of LunchMenu from DB", required = true) @PathVariable Long id) {
   LOGGER.debug("Cancel LunchMenu {} ", id);
   try {
     lunchMenusService.cancelLunchMenu(id);
   } catch (NoSuchElementException exception) {
     throw new ExceptionLunchMenuNotFound(exception.getMessage());
   }
 }
  /** @return True if the failure was handled and should be treated as success. */
  boolean dispatchFailure(ClientContext<TM, TC> context, Throwable throwable) {
    final Optional<AsyncExceptions.AsyncWebServiceError> serviceErrorOption =
        AsyncExceptions.asWebServiceError(throwable);
    if (serviceErrorOption.isPresent()) {
      errorCode = serviceErrorOption.get().getCode();
      errorMessage = serviceErrorOption.get().getMessage();
      return false;
    }

    final NoSuchElementException ex2 =
        Exceptions.findCause(throwable, NoSuchElementException.class);
    if (ex2 != null) {
      errorMessage = ex2.getMessage();
      return false;
    }

    LOG.error("Eucalyptus client error", throwable);
    return false;
  }
Пример #19
0
  /** Parses an OBJ (ends with ".obj") or MTL file (ends with ".mtl"). */
  protected void parseFile(String filename) throws IOException {
    // get the file relative to the source path
    File file = new File(path, filename);
    BufferedReader reader = new BufferedReader(new FileReader(file));

    // get the parser based on the file extention
    LineParser parser = null;
    int extIndex = filename.lastIndexOf('.');
    if (extIndex != -1) {
      String ext = filename.substring(extIndex + 1);
      parser = (LineParser) parsers.get(ext.toLowerCase());
    }
    if (parser == null) {
      parser = (LineParser) parsers.get("obj");
    }

    // parse every line in the file
    while (true) {
      String line = reader.readLine();
      // no more lines to read
      if (line == null) {
        reader.close();
        return;
      }

      line = line.trim();

      // ignore blank lines and comments
      if (line.length() > 0 && !line.startsWith("#")) {
        // interpret the line
        try {
          parser.parseLine(line);
        } catch (NumberFormatException ex) {
          throw new IOException(ex.getMessage());
        } catch (NoSuchElementException ex) {
          throw new IOException(ex.getMessage());
        }
      }
    }
  }
Пример #20
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
  }
Пример #21
0
  @SuppressWarnings("unchecked")
  @Test
  public void testHardwareWithImageIdPredicateOnlyDoesntImage() {

    Hardware hardware =
        new HardwareBuilder()
            .id("hardwareId")
            .supportsImage(ImagePredicates.idEquals("differentImageId"))
            .build();

    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(hardware));
    Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
    Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
    TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);

    expect(optionsProvider.get()).andReturn(new TemplateOptions());

    replay(defaultTemplate, optionsProvider, templateBuilderProvider);

    TemplateBuilderImpl template =
        createTemplateBuilder(
            image, locations, images, hardwares, region, optionsProvider, templateBuilderProvider);
    try {
      template.imageId(getProviderFormatId("imageId")).build();
      fail("Expected NoSuchElementException");
    } catch (NoSuchElementException e) {
      // make sure message is succinct
      assertEquals(
          e.getMessage(),
          "no hardware profiles support images matching params: idEquals(differentImageId)");
      verify(defaultTemplate, optionsProvider, templateBuilderProvider);
    }
  }
Пример #22
0
 /** Read an InputStream that contains a list of servers to restore. */
 protected boolean restoreServers(InputStream inputStream) throws SplatException {
   XMLDecoder decoder = new XMLDecoder(inputStream);
   boolean ok = true;
   SSAPRegResource server = null;
   while (true) {
     try {
       server = (SSAPRegResource) decoder.readObject();
       String name = server.getShortName();
       if (name == null || name.length() == 0) name = "<>";
       serverList.put(name, server);
       selectionList.put(name, true);
     } catch (ArrayIndexOutOfBoundsException e) {
       break; // End of list.
     } catch (NoSuchElementException e) {
       System.out.println(
           "Failed to read server list " + " (old-style or invalid):  '" + e.getMessage() + "'");
       ok = false;
       break;
     }
   }
   decoder.close();
   return ok;
 }
Пример #23
0
  protected ServiceStats trackAvailabilityOfProcessOnNode(
      Statement process, String processName, NodeMetadata node) {
    ServiceStats stats = new ServiceStats();
    Stopwatch watch = Stopwatch.createStarted();
    ExecResponse exec =
        client.runScriptOnNode(node.getId(), process, runAsRoot(false).wrapInInitScript(false));
    stats.backgroundProcessMilliseconds = watch.elapsed(TimeUnit.MILLISECONDS);
    watch.reset().start();

    HostAndPort socket = null;
    try {
      socket = openSocketFinder.findOpenSocketOnNode(node, 8080, 600, TimeUnit.SECONDS);
    } catch (NoSuchElementException e) {
      throw new NoSuchElementException(
          format("%s%n%s%s", e.getMessage(), exec.getOutput(), exec.getError()));
    }

    stats.socketOpenMilliseconds = watch.elapsed(TimeUnit.MILLISECONDS);

    getAnonymousLogger()
        .info(format("<< %s on node(%s)[%s] %s", processName, node.getId(), socket, stats));
    return stats;
  }
Пример #24
0
  /**
   * Adds a Data Line to the yData- and the xData - puffer
   *
   * @param s The feature to be added to the XYPAIRSandPEAKTABLEdataLine attribute
   * @exception NumberFormatException Description of the Exception
   */
  private final void addXYPAIRSandPEAKTABLEdataLine(String s) throws NumberFormatException {
    double xDataDummy = 0;
    double yDataDummy = 0;

    if (!separatorStandardChecked) {
      // entscheide ob , als Trennung oder fuer FlieSkommazahl verwendet wird !;-((
      int kommaIndex = s.indexOf(",", 0);
      int pointIndex = s.indexOf(".", 0);
      int spaceIndex = s.indexOf(" ", 0);
      int tabulatorIndex = s.indexOf("\t", 0);

      if (pointIndex == -1) {
        // bei schlechtem Standard, kann auch Komma Fuer FlieSkommazahlen
        // vorkommen und darf NICHT als Trennzeichen interpretiert werden
        // Was fuer ein Mist, gibts, aber !!!
        if ((kommaIndex != -1) && (spaceIndex != -1)) {
          if (kommaIndex < spaceIndex) {
            if ((s.charAt(kommaIndex + 1) >= '0') && (s.charAt(kommaIndex + 1) <= '9')) {
              // s=s.replace(',','.');
              standardSeparator = false;
            }
          }
        } else if ((kommaIndex != -1) && (tabulatorIndex != -1)) {
          if (kommaIndex < tabulatorIndex) {
            if ((s.charAt(kommaIndex + 1) >= '0') && (s.charAt(kommaIndex + 1) <= '9')) {
              // s=s.replace(',','.');
              standardSeparator = false;
            }
          }
        }
      }

      separatorStandardChecked = true;
    }

    if (!standardSeparator) {
      s = s.replace(',', '.');
    }

    StringTokenizer dataLine = new StringTokenizer(s, " \t,");
    String s1 = "";

    try {
      s1 = dataLine.nextToken();
    } catch (NoSuchElementException e) {
      logger.error("The data line \"" + s + "\" is skipped. It contains" + " no valid data.");

      return;
    }

    try {
      // println("x "+s1);
      xDataDummy = (new Double(s1)).doubleValue();
    } catch (NumberFormatException e) {
      logger.error("The data line \"" + s + "\" is skipped. It contains" + " not a valid X value.");

      return;
    }

    xDataDummy = xDataDummy * xFactor;
    xData.add(new Double(xDataDummy));

    try {
      s1 = dataLine.nextToken();
    } catch (NoSuchElementException e) {
      logger.error(e.getMessage());
    }

    try {
      // println("y "+s1);
      yDataDummy = (new Double(s1)).doubleValue();
    } catch (NumberFormatException e) {
      logger.error("The data line \"" + s + "\" is skipped. It contains" + " not a valid Y value.");

      return;
    }

    yDataDummy = yDataDummy * yFactor;
    yData.add(new Double(yDataDummy));
  }
Пример #25
0
  @Override
  public WOResponse handleRequest(WORequest request) {
    int bufferSize = 16384;

    WOApplication application = WOApplication.application();
    application.awake();
    try {
      WOContext context = application.createContextForRequest(request);
      WOResponse response = application.createResponseInContext(context);

      String sessionIdKey = application.sessionIdKey();
      String sessionId = (String) request.formValueForKey(sessionIdKey);
      if (sessionId == null) {
        sessionId = request.cookieValueForKey(sessionIdKey);
      }
      context._setRequestSessionID(sessionId);
      if (context._requestSessionID() != null) {
        application.restoreSessionWithID(sessionId, context);
      }

      try {
        final WODynamicURL url = request._uriDecomposed();
        final String requestPath = url.requestHandlerPath();
        final Matcher idMatcher = Pattern.compile("^id/(\\d+)/").matcher(requestPath);

        final Integer requestedAttachmentID;
        String requestedWebPath;

        final boolean requestedPathContainsAnAttachmentID = idMatcher.find();
        if (requestedPathContainsAnAttachmentID) {
          requestedAttachmentID = Integer.valueOf(idMatcher.group(1));
          requestedWebPath = idMatcher.replaceFirst("/");
        } else {
          // MS: This is kind of goofy because we lookup by path, your web path needs to
          // have a leading slash on it.
          requestedWebPath = "/" + requestPath;
          requestedAttachmentID = null;
        }

        try {
          InputStream attachmentInputStream;
          String mimeType;
          String fileName;
          long length;
          String queryString = url.queryString();
          boolean proxyAsAttachment =
              (queryString != null && queryString.contains("attachment=true"));

          EOEditingContext editingContext = ERXEC.newEditingContext();
          editingContext.lock();

          try {
            ERAttachment attachment =
                fetchAttachmentFor(editingContext, requestedAttachmentID, requestedWebPath);

            if (_delegate != null && !_delegate.attachmentVisible(attachment, request, context)) {
              throw new SecurityException("You are not allowed to view the requested attachment.");
            }
            mimeType = attachment.mimeType();
            length = attachment.size().longValue();
            fileName = attachment.originalFileName();
            ERAttachmentProcessor<ERAttachment> attachmentProcessor =
                ERAttachmentProcessor.processorForType(attachment);
            if (!proxyAsAttachment) {
              proxyAsAttachment = attachmentProcessor.proxyAsAttachment(attachment);
            }
            InputStream rawAttachmentInputStream =
                attachmentProcessor.attachmentInputStream(attachment);
            attachmentInputStream = new BufferedInputStream(rawAttachmentInputStream, bufferSize);
          } finally {
            editingContext.unlock();
          }

          response.setHeader(mimeType, "Content-Type");
          response.setHeader(String.valueOf(length), "Content-Length");

          if (proxyAsAttachment) {
            response.setHeader("attachment; filename=\"" + fileName + "\"", "Content-Disposition");
          }

          response.setStatus(200);
          response.setContentStream(attachmentInputStream, bufferSize, length);
        } catch (SecurityException e) {
          NSLog.out.appendln(e);
          response.setContent(e.getMessage());
          response.setStatus(403);
        } catch (NoSuchElementException e) {
          NSLog.out.appendln(e);
          response.setContent(e.getMessage());
          response.setStatus(404);
        } catch (FileNotFoundException e) {
          NSLog.out.appendln(e);
          response.setContent(e.getMessage());
          response.setStatus(404);
        } catch (IOException e) {
          NSLog.out.appendln(e);
          response.setContent(e.getMessage());
          response.setStatus(500);
        }

        return response;
      } finally {
        if (context._requestSessionID() != null) {
          WOApplication.application().saveSessionForContext(context);
        }
      }
    } finally {
      application.sleep();
    }
  }
Пример #26
0
 /**
  * Returns the unique result from the database that exactly matches <code>example</code>. The
  * differences between this method and {@link #getUnique(Object)} are:
  *
  * <ol>
  *   <li>{@link #getUnique(Object)} uses <i><code>enableLike</code></i> match and this method does
  *       not. <i><code>enableLike</code></i> criteria trips hibernate when special characters are
  *       involved. So it has been replaced by exact "=" (equals to)
  *   <li>Unique result logic is correctly implemented in this method. If the query returns more
  *       than one result, this method correctly throws an exception wrapping <code>
  *       NonUniqueResultException</code>. {@link #getUnique(Object)} does not throw an exception
  *       in this case and returns a result as long as it finds one or more matching results
  *       (because of the following properties set on the query: <code>setMaxResults(1)</code>,
  *       <code>setFetchSize(1)</code> and <code>setFirstResult(0)</code>)
  * </ol>
  *
  * @param example
  * @return
  * @throws EucalyptusCloudException
  */
 @SuppressWarnings("unchecked")
 public <T> T getUniqueEscape(final T example) throws EucalyptusCloudException {
   try {
     Object id = null;
     try {
       id =
           this.getEntityManager()
               .getEntityManagerFactory()
               .getPersistenceUnitUtil()
               .getIdentifier(example);
     } catch (final Exception ex) {
     }
     if (id != null) {
       final T res = (T) this.getEntityManager().find(example.getClass(), id);
       if (res == null) {
         throw new NoSuchElementException("@Id: " + id);
       } else {
         return res;
       }
     } else if ((example instanceof HasNaturalId)
         && (((HasNaturalId) example).getNaturalId() != null)) {
       final String natId = ((HasNaturalId) example).getNaturalId();
       final T ret =
           (T)
               this.createCriteria(example.getClass())
                   .setLockMode(LockMode.NONE)
                   .setCacheable(true)
                   .add(Restrictions.naturalId().set("naturalId", natId))
                   .uniqueResult();
       if (ret == null) {
         throw new NoSuchElementException("@NaturalId: " + natId);
       }
       return ret;
     } else {
       final T ret =
           (T)
               this.createCriteria(example.getClass())
                   .setLockMode(LockMode.NONE)
                   .setCacheable(true)
                   .add(Example.create(example))
                   .uniqueResult();
       if (ret == null) {
         throw new NoSuchElementException("example: " + LogUtil.dumpObject(example));
       }
       return ret;
     }
   } catch (final NonUniqueResultException ex) {
     throw new EucalyptusCloudException(
         "Get unique failed for "
             + example.getClass().getSimpleName()
             + " because "
             + ex.getMessage(),
         ex);
   } catch (final NoSuchElementException ex) {
     throw new EucalyptusCloudException(
         "Get unique failed for "
             + example.getClass().getSimpleName()
             + " using "
             + ex.getMessage(),
         ex);
   } catch (final Exception ex) {
     final Exception newEx = PersistenceExceptions.throwFiltered(ex);
     throw new EucalyptusCloudException(
         "Get unique failed for "
             + example.getClass().getSimpleName()
             + " because "
             + newEx.getMessage(),
         newEx);
   }
 }
Пример #27
0
  /**
   * Decodes XYDATA. Only the uncompressed ASDF format is supported. The compressed AFFN format is
   * not supported.
   *
   * @exception JCAMPException Description of the Exception
   * @exception NumberFormatException Description of the Exception
   */
  private void decodeXYDATA() throws JCAMPException, NumberFormatException {
    LabelData set = new LabelData();
    int begin;
    int end = 0;
    String s1 = "";
    String s2 = "";

    set = getParameter("DELTAX");

    if (set == null) {
      logger.warn("The label DELTAX is missing. Now its calculated !;-)");
      calculatedDeltaXneeded = true;
    }

    deltaX = getDouble(set);

    set = getParameter("LASTX");

    if (set == null) {
      String add = "";

      if (!calculatedDeltaXneeded) {
        add = ". The label DELTAX is missing and " + "can not be calculated";
      }

      throw new JCAMPException("The label LASTX is missing" + add);
    }

    lastX = getDouble(set);

    set = getParameter("FIRSTX");

    if (set == null) {
      String add = "";

      if (!calculatedDeltaXneeded) {
        add = ". The label DELTAX is missing and " + "can not be calculated";
      }

      throw new JCAMPException("The label FIRSTX is missing" + add);
    }

    firstX = getDouble(set);

    set = getParameter("NPOINTS");

    if (set == null) {
      String add = "";

      if (!calculatedDeltaXneeded) {
        add = ". The label NPOINTS is missing and DELTAX" + "can not be calculated";
        throw new JCAMPException("The label FIRSTX is missing" + add);
      }

      logger.warn("The label NPOINTS is missing. Now its estimated");
      estimatedNPointsNeeded = true;
    }

    nPoints = getDouble(set);

    // Berechnung von deltaX;
    if (calculatedDeltaXneeded) {
      deltaX = (lastX - firstX) / (nPoints - 1);
    } else {
      double dummy = 0;

      if (!estimatedNPointsNeeded && (nPoints != 0)) {
        // einfach nochmals zur Kontrolle von deltaX. Eigentlich unnoetig !
        dummy = (lastX - firstX) / (nPoints - 1);

        if (Math.abs(dummy - deltaX) > DELTAX_DIFFERENCE_WARNING_VALUE) {
          logger.warn(
              "The calculated DELTAX="
                  + dummy
                  + " (original DELTAX="
                  + deltaX
                  + ") shows a difference above "
                  + DELTAX_DIFFERENCE_WARNING_VALUE);
        }
      }
    }

    set = getParameter("XFACTOR");

    if (set == null) {
      throw new JCAMPException("The label XFACTOR is missing");
    }

    xFactor = getDouble(set);

    set = getParameter("YFACTOR");

    if (set == null) {
      throw new JCAMPException("The label YFACTOR is missing");
    }

    yFactor = getDouble(set);

    // beginne Dekodierung
    set = getParameter("XYPAIRS");

    // if (set == null)
    // {
    // }
    //    if(dataType==XYPAIRS){
    //      end=set.getData().indexOf("\n",0);
    //      if (end==-1)throw new JCAMPException("Carriage return after \"=\" is not allowed");
    //      s1=set.getData().substring(0, end).trim();
    //    }
    //    else
    if (dataType == XYDATA_X_YY) {
      set = getParameter("XYDATA");

      //            if (set == null)
      //            {
      //            }
      end = set.getData().indexOf("\n", 0);

      if (end == -1) {
        throw new JCAMPException("Carriage return" + " after \"=\" is not allowed");
      }

      s1 = set.getData().substring(0, end).trim();
    }

    s1 = set.getData().substring(end + 1, set.getData().indexOf("\n", end + 1));

    // s1=s1.trim();
    // hier findet keine Unterscheidung zwischen AFFN (ungepackt) oder ASDF (gepackt) statt
    // Pseudo-digits or ASDF forms
    // ASCII digits          0 1 2 3 4 5 6 7 8 9
    // Positive SQZ digits   @ A B C D E F G H I
    // Negative SQZ digits     a b c d e f g h i
    // Positive DIF digits   % J K L M N O P Q R
    // Negative DIF digits     j k l m n o p q r
    // Positive DUP digits     S T U V W X Y Z s
    StringTokenizer isAFFN =
        new StringTokenizer(s1, "@ABCDEFGHIabcdefghi%JKLMNOPQRjklmnopqrSTUVWXYZs");

    try {
      s2 = isAFFN.nextToken();

      if (s1.equals(s2)) {
        // ist ein Token enthalten, so ist s1 ungleich s2
        // OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
        // nur AFFN !!!
        // OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
        // wieviele Datenpunkte sind es denn etwa ?
        //                StringTokenizer dataValue = new StringTokenizer(s1, " \t");
        // ruhig groS waehlen, da sie nachher eh geloescht werden.
        //            int dataPerLine=100;
        // Anzahl der Datenwerte ist NPOINTS/countTokens
        // dataPerLine=Math.max(dataValue.countTokens(), 100);
        //            yData= new Vector((int)nPoints, dataPerLine);
        //            xData= new Vector((int)nPoints, dataPerLine);
        xData = new LinkedList();
        yData = new LinkedList();

        begin = 0;
        begin = set.getData().indexOf("\n", begin);
        begin++;

        do {
          end = set.getData().indexOf("\n", begin);

          if (set.getData().indexOf(";", begin) != -1) {
            end = Math.min(end, set.getData().indexOf(";", begin));
          }

          if (end == -1) {
            break;
          }

          s1 = set.getData().substring(begin, end).trim();

          // dataLine
          // println("s1:"+parameterSaetze[1].substring(begin,end));
          addXYDATADataLine(s1);
          begin = end + 1;
        } while (true);

        sendDataToDoubleArray();

        return;
      } else {
        throw new JCAMPException("Compressed data in ASDF format is not supported ");
      }
    } catch (NoSuchElementException e) {
      logger.error(e.getMessage());
    }
  }
  /** Attempt to establish a database connection. */
  public synchronized Connection getConnection(String username, String password)
      throws SQLException {
    if (isNew) {
      throw new SQLException(
          "Must set the ConnectionPoolDataSource "
              + "through setDataSourceName or setConnectionPoolDataSource"
              + " before calling getConnection.");
    }

    getConnectionCalled = true;
    Map pools = (Map) dsInstanceMap.get(instanceKey);
    PoolKey key = getPoolKey(username);
    Object pool = pools.get(key);
    if (pool == null) {
      try {
        registerPool(username, password);
        pool = pools.get(key);
      } catch (Exception e) {
        e.printStackTrace();
        throw new SQLException(e.getMessage());
      }
    }

    PooledConnectionAndInfo info = null;
    if (pool instanceof ObjectPool) {
      try {
        info = (PooledConnectionAndInfo) ((ObjectPool) pool).borrowObject();
      } catch (NoSuchElementException e) {
        closeDueToException(info);
        throw new SQLException(e.getMessage());
      } catch (RuntimeException e) {
        closeDueToException(info);
        throw e;
      } catch (SQLException e) {
        closeDueToException(info);
        throw e;
      } catch (Exception e) {
        closeDueToException(info);
        throw new SQLException(e.getMessage());
      }
    } else {
      // assume KeyedObjectPool
      try {
        UserPassKey upkey = getUserPassKey(username, password);
        info = (PooledConnectionAndInfo) ((KeyedObjectPool) pool).borrowObject(upkey);
      } catch (NoSuchElementException e) {
        closeDueToException(info);
        throw new SQLException(e.getMessage());
      } catch (RuntimeException e) {
        closeDueToException(info);
        throw e;
      } catch (SQLException e) {
        closeDueToException(info);
        throw e;
      } catch (Exception e) {
        closeDueToException(info);
        throw new SQLException(e.getMessage());
      }
    }
    if (!(null == password ? null == info.getPassword() : password.equals(info.getPassword()))) {
      closeDueToException(info);
      throw new SQLException(
          "Given password did not match password used " + "to create the PooledConnection.");
    }
    PooledConnection pc = info.getPooledConnection();

    boolean defaultAutoCommit = isDefaultAutoCommit();
    if (username != null) {
      Boolean userMax = getPerUserDefaultAutoCommit(username);
      if (userMax != null) {
        defaultAutoCommit = userMax.booleanValue();
      }
    }

    boolean defaultReadOnly = isDefaultReadOnly();
    if (username != null) {
      Boolean userMax = getPerUserDefaultReadOnly(username);
      if (userMax != null) {
        defaultReadOnly = userMax.booleanValue();
      }
    }

    Connection con = pc.getConnection();
    con.setAutoCommit(defaultAutoCommit);
    con.setReadOnly(defaultReadOnly);
    return con;
  }
Пример #29
0
  /**
   * Helper function to parse Answer Options and populate Node object
   *
   * @param langNum which language vector to populate
   * @param src The string to be parsed
   * @return true if suceeds
   */
  private boolean parseAnswerOptions(int langNum, String src) {
    /* Need to make sure that the answer type, order of answers, and internal values of answers are the same across all languages */
    if (src == null) {
      if (AUTHORABLE) {
        setParseError(triceps.get("answerOptions_column_missing"));
      } else {
        setParseError("syntax error");
      }
      return false;
    }

    StringTokenizer ans = new StringTokenizer(src, "|", true); // return '|' tokens too
    String token = "";

    // Determine the question type (first token)
    try {
      token = ans.nextToken();
    } catch (NoSuchElementException t) {
      Logger.getLogger(LoggerName).log(Level.SEVERE, "missing_display_type", t);
      if (AUTHORABLE) {
        setParseError(triceps.get("missing_display_type") + t.getMessage());
      } else {
        setParseError("syntax error");
      }
    }

    if (langNum == 0) {
      for (int z = 0; z < QUESTION_TYPES.length; ++z) {
        if (token.equalsIgnoreCase(QUESTION_TYPES[z])) {
          answerType = z;
          break;
        }
      }
    } else {
      if (!QUESTION_TYPES[answerType].equalsIgnoreCase(token)) {
        if (AUTHORABLE) {
          setParseError(triceps.get("mismatch_across_languages_in_answerType"));
        } else {
          setParseError("syntax error");
        }
      }
      // don't change the known value for answerType
    }

    if (questionOrEvalType == EVAL) {
      answerType = NOTHING; // so no further processing
    } else if (answerType == BADTYPE) {
      if (AUTHORABLE) {
        setParseError(triceps.get("invalid_answerType"));
      } else {
        setParseError("syntax error");
      }
      answerType = NOTHING;
    }

    if (datumType == Datum.INVALID) {
      /* so only if not set via datumTypeStr */
      datumType = DATA_TYPES[answerType];
    }

    switch (answerType) {
      case CHECK:
      case COMBO:
      case LIST:
      case RADIO:
      case RADIO_HORIZONTAL:
      case RADIO_HORIZONTAL2:
      case COMBO2:
      case LIST2:
        String val = null;
        String msg = null;
        int field = 0;
        Vector ansOptions = new Vector();
        Vector prevAnsOptions = null;

        if (langNum > 0) {
          prevAnsOptions = getValuesAt(answerChoicesVector, 0);
        }

        int ansPos = 0;

        while (ans.hasMoreTokens()) {
          String s = null;
          s = ans.nextToken();

          if ("|".equals(s)) {
            ++field;
            continue;
          }
          switch (field) {
            case 0:
              break; // discard the first token - answerType
            case 1:
              val = s;
              if (langNum > 0) {
                boolean err = false;
                String s2 = null; // previous answer
                try {
                  s2 = ((AnswerChoice) prevAnsOptions.elementAt(ansPos++)).getValue();
                  if (!s2.equals(val)) {
                    err = true;
                  }
                } catch (NullPointerException t) {
                  Logger.getLogger(LoggerName).log(Level.SEVERE, "", t);
                  err = true;
                } catch (ArrayIndexOutOfBoundsException t) {
                  Logger.getLogger(LoggerName).log(Level.SEVERE, "", t);
                  err = true;
                }
                if (err) {
                  if (AUTHORABLE) {
                    setParseError(
                        triceps.get(
                                "mismatch_across_languages_in_return_value_for_answerChoice_num")
                            + (ansPos - 1));
                  } else {
                    setParseError("syntax error");
                  }
                  val = s2; // reset it to the previously known return value for consistency (?)
                }
              }
              break;
            case 2:
              msg = s;
              field = 0; // so that cycle between val & msg;
              if (val == null || msg == null) {
                if (AUTHORABLE) {
                  setParseError(
                      triceps.get("missing_value_or_message_for_answerChoice_num") + (ansPos - 1));
                } else {
                  setParseError("syntax error");
                }
              } else {
                AnswerChoice ac = new AnswerChoice(val, msg);
                ansOptions.addElement(ac);

                /* check for duplicate answer choice values */
                if (langNum == 0) { // only for first pass
                  if (answerChoicesHash.put(val, ac) != null) {
                    if (AUTHORABLE) {
                      setParseError(triceps.get("answerChoice_value_already_used") + val);
                    } else {
                      setParseError("syntax error");
                    }
                  }
                }
              }
              val = null;
              msg = null;
              break;
          }
        }
        if (ansOptions.size() == 0) {
          if (AUTHORABLE) {
            setParseError(triceps.get("answerChoices_must_be_specified"));
          } else {
            setParseError("syntax error");
          }
        }
        if (field == 1) {
          if (AUTHORABLE) {
            setParseError(triceps.get("missing_message_for_answerChoice_num") + (ansPos - 1));
          } else {
            setParseError("syntax error");
          }
        }
        if (langNum > 0) {
          if (prevAnsOptions.size() != ansOptions.size()) {
            if (AUTHORABLE) {
              setParseError(
                  triceps.get("mismatch_across_languages_in_number_of_answerChoices")
                      + prevAnsOptions.size()
                      + " != "
                      + ansOptions.size());
            } else {
              setParseError("syntax error");
            }
          }
        }
        answerChoicesVector.addElement(ansOptions);
        break;
      default:
        break;
    }

    return true;
  }