Beispiel #1
0
 public static void main(String[] args) {
   try {
     getConnectionParameters(args);
     if (help) {
       printUsage();
       return;
     }
     long bTime = System.currentTimeMillis();
     connect();
     printHostProductDetails();
     long eTime = System.currentTimeMillis();
     System.out.println("Total time in milli secs to get the product line id: " + (eTime - bTime));
   } catch (IllegalArgumentException e) {
     System.out.println(e.getMessage());
     printUsage();
   } catch (SOAPFaultException sfe) {
     printSoapFaultException(sfe);
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     try {
       disconnect();
     } catch (SOAPFaultException sfe) {
       printSoapFaultException(sfe);
     } catch (Exception e) {
       System.out.println("Failed to disconnect - " + e.getMessage());
       e.printStackTrace();
     }
   }
 }
Beispiel #2
0
 public static void main(String[] args) {
   try {
     getConnectionParameters(args);
     getInputParameters(args);
     if (help) {
       printUsage();
       return;
     }
     connect();
     displayStats();
   } catch (IllegalArgumentException e) {
     System.out.println(e.getMessage());
     printUsage();
   } catch (SOAPFaultException sfe) {
     printSoapFaultException(sfe);
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     try {
       disconnect();
     } catch (SOAPFaultException sfe) {
       printSoapFaultException(sfe);
     } catch (Exception e) {
       System.out.println("Failed to disconnect - " + e.getMessage());
       e.printStackTrace();
     }
   }
 }
 public int addToTable(String line) {
   String[] a = line.split(splitToken);
   try {
     return addToTable(a);
   } catch (IllegalArgumentException e) {
     String msg = String.format("\"%s\" -> '%s'", e.getMessage(), line);
     throw new IllegalArgumentException(msg, e);
   }
 }
Beispiel #4
0
 Calendar readDate(String helptekst) {
   String datumString = readString(helptekst + "; voer datum in (dd-mm-jjjj)");
   try {
     return StringUtilities.datum(datumString);
   } catch (IllegalArgumentException exc) {
     System.out.println(exc.getMessage());
     return readDate(helptekst);
   }
 }
  /**
   * Sends a specific <tt>Request</tt> to the STUN server associated with this
   * <tt>StunCandidateHarvest</tt>.
   *
   * @param request the <tt>Request</tt> to send to the STUN server associated with this
   *     <tt>StunCandidateHarvest</tt>
   * @param firstRequest <tt>true</tt> if the specified <tt>request</tt> should be sent as the first
   *     request in the terms of STUN; otherwise, <tt>false</tt>
   * @return the <tt>TransactionID</tt> of the STUN client transaction through which the specified
   *     <tt>Request</tt> has been sent to the STUN server associated with this
   *     <tt>StunCandidateHarvest</tt>
   * @param transactionID the <tt>TransactionID</tt> of <tt>request</tt> because <tt>request</tt>
   *     only has it as a <tt>byte</tt> array and <tt>TransactionID</tt> is required for the
   *     <tt>applicationData</tt> property value
   * @throws StunException if anything goes wrong while sending the specified <tt>Request</tt> to
   *     the STUN server associated with this <tt>StunCandidateHarvest</tt>
   */
  protected TransactionID sendRequest(
      Request request, boolean firstRequest, TransactionID transactionID) throws StunException {
    if (!firstRequest && (longTermCredentialSession != null))
      longTermCredentialSession.addAttributes(request);

    StunStack stunStack = harvester.getStunStack();
    TransportAddress stunServer = harvester.stunServer;
    TransportAddress hostCandidateTransportAddress = hostCandidate.getTransportAddress();

    if (transactionID == null) {
      byte[] transactionIDAsBytes = request.getTransactionID();

      transactionID =
          (transactionIDAsBytes == null)
              ? TransactionID.createNewTransactionID()
              : TransactionID.createTransactionID(harvester.getStunStack(), transactionIDAsBytes);
    }
    synchronized (requests) {
      try {
        transactionID =
            stunStack.sendRequest(
                request, stunServer, hostCandidateTransportAddress, this, transactionID);
      } catch (IllegalArgumentException iaex) {
        if (logger.isLoggable(Level.INFO)) {
          logger.log(
              Level.INFO,
              "Failed to send "
                  + request
                  + " through "
                  + hostCandidateTransportAddress
                  + " to "
                  + stunServer,
              iaex);
        }
        throw new StunException(StunException.ILLEGAL_ARGUMENT, iaex.getMessage(), iaex);
      } catch (IOException ioex) {
        if (logger.isLoggable(Level.INFO)) {
          logger.log(
              Level.INFO,
              "Failed to send "
                  + request
                  + " through "
                  + hostCandidateTransportAddress
                  + " to "
                  + stunServer,
              ioex);
        }
        throw new StunException(StunException.NETWORK_ERROR, ioex.getMessage(), ioex);
      }

      requests.put(transactionID, request);
    }
    return transactionID;
  }
Beispiel #6
0
 /** Formats and displays today's date. */
 public void reformat() {
   Date today = new Date();
   SimpleDateFormat formatter = new SimpleDateFormat(currentPattern);
   try {
     String dateString = formatter.format(today);
     result.setForeground(Color.black);
     result.setText(dateString);
   } catch (IllegalArgumentException iae) {
     result.setForeground(Color.red);
     result.setText("Error: " + iae.getMessage());
   }
 }
 @Path("{id}/split")
 @POST
 public Response split(
     @PathParam("id") final String signupId,
     @FormParam("componentPresentationId") final Set<String> componentIds) {
   checkAuthenticated();
   try {
     String newSignupId = courseService.split(signupId, componentIds);
     return Response.status(Response.Status.CREATED).entity(newSignupId).build();
   } catch (IllegalArgumentException iae) {
     throw new CourseSignupException(iae.getMessage(), iae);
   }
 }
 /*
   Method purpose: Prompt the user for the name of the agent for editing.
   Method parameters: House data object, and int x for the object which coordinates it corresponds to.
   Return: None.
 */
 public static void editAgentName(Map<Integer, House> data, int x) {
   // Prompt for the name, only reprompts if an error occurs.
   String name = "";
   boolean valid = false;
   do {
     try {
       name = JOptionPane.showInputDialog(null, "Please enter the agents name");
       data.get(x).setAgentName(name);
       valid = true;
     } catch (IllegalArgumentException f) {
       JOptionPane.showMessageDialog(null, f.getMessage());
       valid = false;
     }
   } while (!valid);
 }
  public void compile() throws CompilerException, CacheCorruptedException {
    Application application = ApplicationManager.getApplication();
    try {
      if (!myFilesToCompile.isEmpty()) {
        if (application.isUnitTestMode()) {
          saveTestData();
        }
        compileModules(buildModuleToFilesMap(myFilesToCompile));
      }
    } catch (SecurityException e) {
      throw new CompilerException(
          CompilerBundle.message("error.compiler.process.not.started", e.getMessage()), e);
    } catch (IllegalArgumentException e) {
      throw new CompilerException(e.getMessage(), e);
    } finally {
      for (final VirtualFile file : myModuleToTempDirMap.values()) {
        if (file != null) {
          final File ioFile = new File(file.getPath());
          FileUtil.asyncDelete(ioFile);
        }
      }
      myModuleToTempDirMap.clear();
    }

    if (!myFilesToCompile.isEmpty()
        && myCompileContext.getMessageCount(CompilerMessageCategory.ERROR) == 0) {
      // package-info.java hack
      final List<TranslatingCompiler.OutputItem> outputs =
          new ArrayList<TranslatingCompiler.OutputItem>();
      ApplicationManager.getApplication()
          .runReadAction(
              new Runnable() {
                public void run() {
                  for (final VirtualFile file : myFilesToCompile) {
                    if (PACKAGE_ANNOTATION_FILE_NAME.equals(file.getName())
                        && !myProcessedPackageInfos.contains(file)) {
                      outputs.add(new OutputItemImpl(file));
                    }
                  }
                }
              });
      if (!outputs.isEmpty()) {
        mySink.add(null, outputs, VirtualFile.EMPTY_ARRAY);
      }
    }
  }
Beispiel #10
0
  public static Object invoke(Method method, Object obj, Object[] args) {
    Object result = null;
    try {
      result = method.invoke(obj, args);
    } catch (IllegalArgumentException e) {

      if (e.getMessage().equals(IAE_MESSAGE)) {
        MappingUtils.throwMappingException(prepareExceptionMessage(method, args), e);
      }
      MappingUtils.throwMappingException(e);
    } catch (IllegalAccessException e) {
      MappingUtils.throwMappingException(e);
    } catch (InvocationTargetException e) {
      MappingUtils.throwMappingException(e);
    }
    return result;
  }
  /**
   * Group search API for the new filter type search and sort criteria
   *
   * @author DiepLe
   * @param searchAndSortCriteria
   * @return
   */
  @RequestMapping(value = "/search", method = RequestMethod.POST)
  @ResponseBody
  public ApiResponse<Object> getGroupSummaryByNewFilterTypeSearchAndSortCriteria(
      @RequestBody SearchAndSortCriteria searchAndSortCriteria) {

    final ApiResponse<Object> apiResponse = new ApiResponse<>();
    List<PermissionGroupSummaryDTO> permissionGroupSummaryDTO = null;
    Long totalRecords = null;
    PermissionGroupSummariesDTO summaries = null;

    try {
      permissionGroupSummaryDTO =
          groupService.getGroupSummaryByNewSearchAndSortCriteria(searchAndSortCriteria);
      totalRecords = groupService.getTotalCountForSearchAndSortCriteria(searchAndSortCriteria);
      summaries = new PermissionGroupSummariesDTO();
      summaries.setGroupList(permissionGroupSummaryDTO);
      summaries.setTotalRecords(totalRecords);
    } catch (IllegalStateException e) {
      e.printStackTrace();
      apiResponse.setStatus("failure");
      apiResponse.setData(null);
      apiResponse.setLevel(Level.ERROR);
      apiResponse.setCode("1069");
      apiResponse.setMessage(
          messageSource.getMessage(
              "1069", new Object[] {e.getMessage()}, LocaleContextHolder.getLocale()));
      return apiResponse;
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
      apiResponse.setStatus("failure");
      apiResponse.setData(null);
      apiResponse.setLevel(Level.ERROR);
      apiResponse.setCode("1070");
      apiResponse.setMessage(
          messageSource.getMessage(
              "1070", new Object[] {e.getMessage()}, LocaleContextHolder.getLocale()));
      return apiResponse;
    } catch (Exception e) {
      throw new LucasRuntimeException(LucasRuntimeException.INTERNAL_ERROR, e);
    }

    apiResponse.setData(summaries);

    return apiResponse;
  }
  /**
   * Creates the database config service.
   *
   * @param configSnapshot is the config snapshot
   * @param schedulingService is the timer stuff
   * @param schedulingMgmtService for statement schedule management
   * @return database config svc
   */
  protected static DatabaseConfigService makeDatabaseRefService(
      ConfigurationInformation configSnapshot,
      SchedulingService schedulingService,
      SchedulingMgmtService schedulingMgmtService) {
    DatabaseConfigService databaseConfigService;

    // Add auto-imports
    try {
      ScheduleBucket allStatementsBucket = schedulingMgmtService.allocateBucket();
      databaseConfigService =
          new DatabaseConfigServiceImpl(
              configSnapshot.getDatabaseReferences(), schedulingService, allStatementsBucket);
    } catch (IllegalArgumentException ex) {
      throw new ConfigurationException("Error configuring engine: " + ex.getMessage(), ex);
    }

    return databaseConfigService;
  }
 @SuppressWarnings("unchecked")
 private void preparePreprocessors(
     Map<String, Object> indexSettings, IDocumentIndexStructureBuilder indexStructureBuilder) {
   if (indexSettings != null) {
     List<Map<String, Object>> preproclist =
         (List<Map<String, Object>>) indexSettings.get("preprocessors");
     if (preproclist != null && preproclist.size() > 0) {
       for (Map<String, Object> ppc : preproclist) {
         try {
           indexStructureBuilder.addDataPreprocessor(
               StructuredContentPreprocessorFactory.createPreprocessor(ppc, client));
         } catch (IllegalArgumentException e) {
           throw new SettingsException(e.getMessage(), e);
         }
       }
     }
   }
 }
  @Test
  public void sendShouldFailWithUnmappedName() {
    // Given
    Mapping mapping = partialMapping();
    MappedApi service = service(mapping);

    // When
    String message = null;
    try {
      service.mappedCall("a", 0L);
      fail("IllegalArgumentException expected");
    } catch (IllegalArgumentException e) {
      message = e.getMessage();
    }

    // Then
    assertEquals("no mapping for field: s2", message);
  }
  /*Method purpose: To find the file that is to be read into the program.
    Method parameters: House[] data object
    Return: String path, path of the file for re-writing purposes.
  */
  public static String chooseFile(Map<Integer, House> data, String path)
      throws FileNotFoundException {
    // Initialize all the variables
    int xCord = -1;
    int yCord = -1;
    String name = " ";
    double money = 0.0;
    int status = -1;
    int type = -1;
    Scanner in = null;
    int i = 0;
    String comma;
    try {
      in = new Scanner(new FileInputStream(path));
      while (in.hasNextLine()) {
        xCord = Integer.parseInt(in.next());
        comma = in.next();

        yCord = Integer.parseInt(in.next());
        comma = in.next();

        name = in.next();
        comma = in.next();

        money = Double.parseDouble(in.next());
        comma = in.next();

        status = Integer.parseInt(in.next());
        comma = in.next();

        type = Integer.parseInt(in.next());
        // make sure I cannot get higher than 24
        data.put(i, new House(xCord, yCord, name, money, status, type));
        i++;
      }
      in.close();
    } catch (IllegalArgumentException f) {
      JOptionPane.showMessageDialog(null, f.getMessage());
    } catch (FileNotFoundException g) {
      JOptionPane.showMessageDialog(null, "Sorry, the file was not found");
    } catch (NoSuchElementException h) {
    }
    return path;
  }
 /*
   Method purpose: Presents the user with a simple menu for property type
   Method parameters: House data object, and int x for the object which coordinates it corresponds to.
   Return: None.
 */
 public static void editPropertyType(Map<Integer, House> data, int x) {
   Object[] property = {"Single family home", "Townhouse", "Condo", "Apartment"};
   int propertyType = 0;
   try {
     propertyType =
         JOptionPane.showOptionDialog(
             null,
             "Which type of property is this home?",
             "Property edit",
             JOptionPane.YES_NO_CANCEL_OPTION,
             JOptionPane.QUESTION_MESSAGE,
             null,
             property,
             property[0]);
   } catch (IllegalArgumentException e) {
     JOptionPane.showMessageDialog(null, e.getMessage());
   }
   data.get(x).setType(propertyType);
 }
  @Override
  public DbData readData(InputStream in) throws XMLStreamException {
    XMLStreamReader sr = _staxInFactory.createXMLStreamReader(in);
    DbData result = new DbData();

    sr.nextTag();
    expectTag(FIELD_TABLE, sr);

    try {
      while (sr.nextTag() == XMLStreamReader.START_ELEMENT) {
        result.addRow(readRow(sr));
      }
    } catch (IllegalArgumentException iae) {
      throw new XMLStreamException("Data problem: " + iae.getMessage(), sr.getLocation());
    }

    sr.close();
    return result;
  }
Beispiel #18
0
  @Test
  public void
      shouldThrowAnIllegalArgumentExceptionIfTheSpecifiedImplementationDoesNotHaveANoArgsConstructor()
          throws Exception {
    // Given
    MapBuilder<String, Integer> mapBuilder = mapBuilderWithKeyValuePair("first", 1);

    try {
      // When
      mapBuilder.build(NoNoArgsConstructorMap.class);
      fail("Expected an IllegalArgumentException but got nothing.");
    } catch (IllegalArgumentException exception) {
      // Then
      assertThat(
          exception.getMessage(),
          containsString(
              "Could not instantiate instance of type NoNoArgsConstructorMap. "
                  + "Does it have a public no argument constructor?"));
    }
  }
 /*
   Method purpose: Prompt the user for the status of the house.
   Method parameters: House data object, and int x for the object which coordinates it corresponds to.
   Return: None.
 */
 public static void editStatus(Map<Integer, House> data, int x) {
   // present the user with a buttom prompt. Then simply pass the choice into the house object.
   Object[] status = {"For sale", "Sold", "N/A"};
   int propertyStatus = 0;
   try {
     propertyStatus =
         JOptionPane.showOptionDialog(
             null,
             "What is the status of this home??",
             "Property edit",
             JOptionPane.YES_NO_CANCEL_OPTION,
             JOptionPane.QUESTION_MESSAGE,
             null,
             status,
             status[0]);
   } catch (IllegalArgumentException e) {
     JOptionPane.showMessageDialog(null, e.getMessage());
   }
   data.get(x).setHouseStatus(propertyStatus);
 }
  /*
    Method purpose: Prompt the user for the price of the house.
    Method parameters: House data object, and int x for the object which coordinates it corresponds to.
    Return: None.
  */
  public static void editPrice(Map<Integer, House> data, int x) {
    double price = 0;
    boolean valid = false;

    do {
      // Prompts the user for the price, retries if an error occurs
      try {
        price = Double.parseDouble(JOptionPane.showInputDialog("Please enter the property price"));
        data.get(x).setHousePrice(price);
        valid = true;
      } catch (NumberFormatException e) {
        JOptionPane.showMessageDialog(null, "Price must be entered in a numaric format");
        valid = false;
      } catch (IllegalArgumentException f) {
        JOptionPane.showMessageDialog(null, f.getMessage());
        valid = false;
      }

    } while (!valid);
  }
 /**
  * Make a new signup for the current user.
  *
  * @param courseId the courseId of the signup
  * @param components the components to sign up to
  * @param email the email of the supervisor
  * @param message the reason for the signup
  * @param specialReq any special requirements
  * @return CourseSignup the coursesignup object created
  */
 @Path("/my/new")
 @POST
 @Produces(MediaType.APPLICATION_JSON)
 public Response signup(
     @FormParam("courseId") String courseId,
     @FormParam("components") Set<String> components,
     @FormParam("email") String email,
     @FormParam("message") String message,
     @FormParam("specialReq") String specialReq) {
   checkAuthenticated();
   try {
     CourseSignup entity = courseService.signup(courseId, components, email, message, specialReq);
     ResponseBuilder builder = Response.status(Response.Status.CREATED);
     builder.entity(entity);
     return builder.build();
   } catch (IllegalStateException e) {
     throw new WebAppBadRequestException(new FailureMessage(e.getMessage()));
   } catch (IllegalArgumentException e) {
     throw new WebAppBadRequestException(new FailureMessage(e.getMessage()));
   }
 }
  private final DbRow readRow(XMLStreamReader sr) throws XMLStreamException {
    expectTag(FIELD_ROW, sr);
    DbRow row = new DbRow();
    while (sr.nextTag() == XMLStreamReader.START_ELEMENT) {
      String elemName = sr.getLocalName();
      String value = sr.getElementText();

      try {
        if (!row.assign(elemName, value)) {
          throw new XMLStreamException(
              "Unexpected element <" + elemName + ">: not one of recognized field names");
        }
      } catch (IllegalArgumentException iae) {
        throw new XMLStreamException(
            "Typed access problem with input '" + value + "': " + iae.getMessage(),
            sr.getLocation(),
            iae);
      }
    }
    return row;
  }
Beispiel #23
0
  /**
   * See if we can connect to the server specified by the parameter cvsRootStr
   *
   * @param cvsrootStr
   * @return true if the connection could be made
   */
  public static TeamworkCommandResult validateConnection(String cvsrootStr) {
    TeamworkCommandResult status = null;
    Connection connection = null;

    try {
      CVSRoot cvsroot = CVSRoot.parse(cvsrootStr);
      connection = getConnection(cvsroot);

      if (connection != null) {
        connection.verify();
        status = new TeamworkCommandResult();
      }
    } catch (AuthenticationException e) {
      // problem verifying connection
      status = new TeamworkCommandError(e.getMessage(), e.getLocalizedMessage());
    } catch (IllegalArgumentException iae) {
      // problem parsing CVSRoot
      status = new TeamworkCommandError(iae.getMessage(), iae.getLocalizedMessage());
    }

    return status;
  }
  @SuppressWarnings("unchecked")
  private void evaluateOnChangeListener() {
    if (pluginBean.isReadableProperty(ON_SHUTDOWN)) {
      onShutdownListener =
          (Closure) GrailsClassUtils.getPropertyOrStaticPropertyOrFieldValue(plugin, ON_SHUTDOWN);
    }
    if (pluginBean.isReadableProperty(ON_CONFIG_CHANGE)) {
      onConfigChangeListener =
          (Closure)
              GrailsClassUtils.getPropertyOrStaticPropertyOrFieldValue(plugin, ON_CONFIG_CHANGE);
    }
    if (pluginBean.isReadableProperty(ON_CHANGE)) {
      onChangeListener =
          (Closure) GrailsClassUtils.getPropertyOrStaticPropertyOrFieldValue(plugin, ON_CHANGE);
    }

    final boolean warDeployed = Metadata.getCurrent().isWarDeployed();
    final boolean reloadEnabled = Environment.getCurrent().isReloadEnabled();

    if (!((reloadEnabled || !warDeployed) && onChangeListener != null)) {
      return;
    }

    Object referencedResources =
        GrailsClassUtils.getPropertyOrStaticPropertyOrFieldValue(plugin, WATCHED_RESOURCES);

    try {
      List resourceList = null;
      if (referencedResources instanceof String) {
        if (LOG.isDebugEnabled()) {
          LOG.debug(
              "Configuring plugin "
                  + this
                  + " to watch resources with pattern: "
                  + referencedResources);
        }
        resourceList = new ArrayList();
        resourceList.add(referencedResources.toString());
      } else if (referencedResources instanceof List) {
        resourceList = (List) referencedResources;
      }

      if (resourceList != null) {
        List<String> resourceListTmp = new ArrayList<String>();
        PluginBuildSettings pluginBuildSettings = GrailsPluginUtils.getPluginBuildSettings();

        if (pluginBuildSettings != null) {

          final Resource[] pluginDirs = pluginBuildSettings.getPluginDirectories();
          final Environment env = Environment.getCurrent();
          final String baseLocation = env.getReloadLocation();

          for (Object ref : resourceList) {
            String stringRef = ref.toString();
            if (!warDeployed) {
              for (Resource pluginDir : pluginDirs) {
                if (pluginDir != null) {
                  String pluginResources =
                      getResourcePatternForBaseLocation(
                          pluginDir.getFile().getCanonicalPath(), stringRef);
                  resourceListTmp.add(pluginResources);
                }
              }
              addBaseLocationPattern(resourceListTmp, baseLocation, stringRef);
            } else {
              addBaseLocationPattern(resourceListTmp, baseLocation, stringRef);
            }
          }

          watchedResourcePatternReferences = new String[resourceListTmp.size()];
          for (int i = 0; i < watchedResourcePatternReferences.length; i++) {
            String resRef = resourceListTmp.get(i);
            watchedResourcePatternReferences[i] = resRef;
          }

          watchedResourcePatterns =
              new WatchPatternParser()
                  .getWatchPatterns(Arrays.asList(watchedResourcePatternReferences));
        }
      }
    } catch (IllegalArgumentException e) {
      if (GrailsUtil.isDevelopmentEnv()) {
        LOG.debug(
            "Cannot load plug-in resource watch list from ["
                + ArrayUtils.toString(watchedResourcePatternReferences)
                + "]. This means that the plugin "
                + this
                + ", will not be able to auto-reload changes effectively. Try runnng grails upgrade.: "
                + e.getMessage());
      }
    } catch (IOException e) {
      if (GrailsUtil.isDevelopmentEnv()) {
        LOG.debug(
            "Cannot load plug-in resource watch list from ["
                + ArrayUtils.toString(watchedResourcePatternReferences)
                + "]. This means that the plugin "
                + this
                + ", will not be able to auto-reload changes effectively. Try runnng grails upgrade.: "
                + e.getMessage());
      }
    }
  }
Beispiel #25
0
  // Process the request
  private String processRequest(HttpServletRequest request, HttpServletResponse response) {
    HttpSession session = request.getSession();
    String userIDs = (String) session.getAttribute("user.id");
    userIDs = (userIDs != null && userIDs.compareTo(" ") > 0) ? userIDs : "0";
    long userID = Long.parseLong(userIDs);
    String command = request.getParameter("command");
    String template = request.getParameter("template");
    String pageHash = request.getParameter("pagehash");
    String pageTitle = request.getParameter("pagetitle");
    String pageDescription = request.getParameter("pagedescription");

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

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

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

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

    DbConn myConn = null;
    try {

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

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

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

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

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

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

    return outLine;
  }
Beispiel #26
0
 public static void load(LogBlock logblock) throws DataFormatException, IOException {
   final ConfigurationSection config = logblock.getConfig();
   final Map<String, Object> def = new HashMap<String, Object>();
   def.put("version", logblock.getDescription().getVersion());
   final List<String> worldNames = new ArrayList<String>();
   for (final World world : getWorlds()) worldNames.add(world.getName());
   if (worldNames.isEmpty()) {
     worldNames.add("world");
     worldNames.add("world_nether");
     worldNames.add("world_the_end");
   }
   def.put("loggedWorlds", worldNames);
   def.put("mysql.host", "localhost");
   def.put("mysql.port", 3306);
   def.put("mysql.database", "minecraft");
   def.put("mysql.user", "username");
   def.put("mysql.password", "pass");
   def.put("consumer.delayBetweenRuns", 2);
   def.put("consumer.forceToProcessAtLeast", 200);
   def.put("consumer.timePerRun", 1000);
   def.put("consumer.fireCustomEvents", false);
   def.put("consumer.useBukkitScheduler", true);
   def.put("consumer.queueWarningSize", 1000);
   def.put("clearlog.dumpDeletedLog", false);
   def.put("clearlog.enableAutoClearLog", false);
   def.put(
       "clearlog.auto",
       Arrays.asList(
           "world \"world\" before 365 days all",
           "world \"world\" player lavaflow waterflow leavesdecay before 7 days all",
           "world world_nether before 365 days all",
           "world world_nether player lavaflow before 7 days all"));
   def.put("clearlog.autoClearLogDelay", "6h");
   def.put("logging.logCreeperExplosionsAsPlayerWhoTriggeredThese", false);
   def.put("logging.logKillsLevel", "PLAYERS");
   def.put("logging.logPlayerInfo", false);
   def.put("logging.hiddenPlayers", new ArrayList<String>());
   def.put("logging.hiddenBlocks", Arrays.asList(0));
   def.put("logging.ignoredChat", Arrays.asList("/register", "/login"));
   def.put("rollback.dontRollback", Arrays.asList(10, 11, 46, 51));
   def.put("rollback.replaceAnyway", Arrays.asList(8, 9, 10, 11, 51));
   def.put("rollback.maxTime", "2 days");
   def.put("rollback.maxArea", 50);
   def.put("lookup.defaultDist", 20);
   def.put("lookup.defaultTime", "30 minutes");
   def.put("lookup.linesPerPage", 15);
   def.put("lookup.linesLimit", 1500);
   try {
     formatter = new SimpleDateFormat(config.getString("lookup.dateFormat", "MM-dd HH:mm:ss"));
   } catch (IllegalArgumentException e) {
     throw new DataFormatException(
         "Invalid specification for  date format, please see http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html : "
             + e.getMessage());
   }
   def.put("lookup.dateFormat", "MM-dd HH:mm:ss");
   def.put("questioner.askRollbacks", true);
   def.put("questioner.askRedos", true);
   def.put("questioner.askClearLogs", true);
   def.put("questioner.askClearLogAfterRollback", true);
   def.put("questioner.askRollbackAfterBan", false);
   def.put("questioner.banPermission", "mcbans.ban.local");
   def.put("tools.tool.aliases", Arrays.asList("t"));
   def.put("tools.tool.leftClickBehavior", "NONE");
   def.put("tools.tool.rightClickBehavior", "TOOL");
   def.put("tools.tool.defaultEnabled", true);
   def.put("tools.tool.item", 270);
   def.put("tools.tool.canDrop", true);
   def.put("tools.tool.params", "area 0 all sum none limit 15 desc silent");
   def.put("tools.tool.mode", "LOOKUP");
   def.put("tools.tool.permissionDefault", "OP");
   def.put("tools.toolblock.aliases", Arrays.asList("tb"));
   def.put("tools.toolblock.leftClickBehavior", "TOOL");
   def.put("tools.toolblock.rightClickBehavior", "BLOCK");
   def.put("tools.toolblock.defaultEnabled", true);
   def.put("tools.toolblock.item", 7);
   def.put("tools.toolblock.canDrop", false);
   def.put("tools.toolblock.params", "area 0 all sum none limit 15 desc silent");
   def.put("tools.toolblock.mode", "LOOKUP");
   def.put("tools.toolblock.permissionDefault", "OP");
   def.put("safety.id.check", true);
   for (final Entry<String, Object> e : def.entrySet())
     if (!config.contains(e.getKey())) config.set(e.getKey(), e.getValue());
   logblock.saveConfig();
   url =
       "jdbc:mysql://"
           + config.getString("mysql.host")
           + ":"
           + config.getInt("mysql.port")
           + "/"
           + getStringIncludingInts(config, "mysql.database");
   user = getStringIncludingInts(config, "mysql.user");
   password = getStringIncludingInts(config, "mysql.password");
   delayBetweenRuns = config.getInt("consumer.delayBetweenRuns", 2);
   forceToProcessAtLeast = config.getInt("consumer.forceToProcessAtLeast", 0);
   timePerRun = config.getInt("consumer.timePerRun", 1000);
   fireCustomEvents = config.getBoolean("consumer.fireCustomEvents", false);
   useBukkitScheduler = config.getBoolean("consumer.useBukkitScheduler", true);
   queueWarningSize = config.getInt("consumer.queueWarningSize", 1000);
   enableAutoClearLog = config.getBoolean("clearlog.enableAutoClearLog");
   autoClearLog = config.getStringList("clearlog.auto");
   dumpDeletedLog = config.getBoolean("clearlog.dumpDeletedLog", false);
   autoClearLogDelay = parseTimeSpec(config.getString("clearlog.autoClearLogDelay").split(" "));
   logCreeperExplosionsAsPlayerWhoTriggeredThese =
       config.getBoolean("logging.logCreeperExplosionsAsPlayerWhoTriggeredThese", false);
   logPlayerInfo = config.getBoolean("logging.logPlayerInfo", true);
   try {
     logKillsLevel =
         LogKillsLevel.valueOf(config.getString("logging.logKillsLevel").toUpperCase());
   } catch (final IllegalArgumentException ex) {
     throw new DataFormatException(
         "lookup.toolblockID doesn't appear to be a valid log level. Allowed are 'PLAYERS', 'MONSTERS' and 'ANIMALS'");
   }
   hiddenPlayers = new HashSet<String>();
   for (final String playerName : config.getStringList("logging.hiddenPlayers"))
     hiddenPlayers.add(playerName.toLowerCase().trim());
   hiddenBlocks = new HashSet<Integer>();
   for (final Object blocktype : config.getList("logging.hiddenBlocks")) {
     final Material mat = Material.matchMaterial(String.valueOf(blocktype));
     if (mat != null) hiddenBlocks.add(mat.getId());
     else throw new DataFormatException("Not a valid material: '" + blocktype + "'");
   }
   ignoredChat = new HashSet<String>();
   for (String chatCommand : config.getStringList("logging.ignoredChat")) {
     ignoredChat.add(chatCommand);
   }
   dontRollback = new HashSet<Integer>(config.getIntegerList("rollback.dontRollback"));
   replaceAnyway = new HashSet<Integer>(config.getIntegerList("rollback.replaceAnyway"));
   rollbackMaxTime = parseTimeSpec(config.getString("rollback.maxTime").split(" "));
   rollbackMaxArea = config.getInt("rollback.maxArea", 50);
   defaultDist = config.getInt("lookup.defaultDist", 20);
   defaultTime = parseTimeSpec(config.getString("lookup.defaultTime").split(" "));
   linesPerPage = config.getInt("lookup.linesPerPage", 15);
   linesLimit = config.getInt("lookup.linesLimit", 1500);
   askRollbacks = config.getBoolean("questioner.askRollbacks", true);
   askRedos = config.getBoolean("questioner.askRedos", true);
   askClearLogs = config.getBoolean("questioner.askClearLogs", true);
   askClearLogAfterRollback = config.getBoolean("questioner.askClearLogAfterRollback", true);
   askRollbackAfterBan = config.getBoolean("questioner.askRollbackAfterBan", false);
   safetyIdCheck = config.getBoolean("safety.id.check", true);
   banPermission = config.getString("questioner.banPermission");
   final List<Tool> tools = new ArrayList<Tool>();
   final ConfigurationSection toolsSec = config.getConfigurationSection("tools");
   for (final String toolName : toolsSec.getKeys(false))
     try {
       final ConfigurationSection tSec = toolsSec.getConfigurationSection(toolName);
       final List<String> aliases = tSec.getStringList("aliases");
       final ToolBehavior leftClickBehavior =
           ToolBehavior.valueOf(tSec.getString("leftClickBehavior").toUpperCase());
       final ToolBehavior rightClickBehavior =
           ToolBehavior.valueOf(tSec.getString("rightClickBehavior").toUpperCase());
       final boolean defaultEnabled = tSec.getBoolean("defaultEnabled", false);
       final int item = tSec.getInt("item", 0);
       final boolean canDrop = tSec.getBoolean("canDrop", false);
       final QueryParams params = new QueryParams(logblock);
       params.prepareToolQuery = true;
       params.parseArgs(getConsoleSender(), Arrays.asList(tSec.getString("params").split(" ")));
       final ToolMode mode = ToolMode.valueOf(tSec.getString("mode").toUpperCase());
       final PermissionDefault pdef =
           PermissionDefault.valueOf(tSec.getString("permissionDefault").toUpperCase());
       tools.add(
           new Tool(
               toolName,
               aliases,
               leftClickBehavior,
               rightClickBehavior,
               defaultEnabled,
               item,
               canDrop,
               params,
               mode,
               pdef));
     } catch (final Exception ex) {
       getLogger().log(Level.WARNING, "Error at parsing tool '" + toolName + "': ", ex);
     }
   toolsByName = new HashMap<String, Tool>();
   toolsByType = new HashMap<Integer, Tool>();
   for (final Tool tool : tools) {
     toolsByType.put(tool.item, tool);
     toolsByName.put(tool.name.toLowerCase(), tool);
     for (final String alias : tool.aliases) toolsByName.put(alias, tool);
   }
   final List<String> loggedWorlds = config.getStringList("loggedWorlds");
   worldConfigs = new HashMap<String, WorldConfig>();
   if (loggedWorlds.isEmpty()) throw new DataFormatException("No worlds configured");
   for (final String world : loggedWorlds)
     worldConfigs.put(
         world,
         new WorldConfig(new File(logblock.getDataFolder(), friendlyWorldname(world) + ".yml")));
   superWorldConfig = new LoggingEnabledMapping();
   for (final WorldConfig wcfg : worldConfigs.values())
     for (final Logging l : Logging.values())
       if (wcfg.isLogging(l)) superWorldConfig.setLogging(l, true);
 }
Beispiel #27
0
  public static void goToUserMode(String ID) {
    ID = ID.trim();
    if (ID.contains(" ")) {
      printError("ID cannot contain spaces.");
      return;
    }
    User user = control.login(ID);
    if (user != null) {

      commandReader = new BufferedReader(new InputStreamReader(System.in));
      while (true) {
        String line = null;
        try {
          line = commandReader.readLine();
        } catch (IOException e) {
          printError("Could Not Read Input Line");
          continue;
        }
        if (line == null) {
          printError("Could Not Read Input Line");
          continue;
        } else if (line.isEmpty()) {
          printError("Command Sould Not Be Empty");
          continue;
        }
        tokenizer = new StringTokenizer(line, " "); // break up input line based on spaces
        String command = new String();
        if (tokenizer.hasMoreTokens()) {
          command = tokenizer.nextToken();
        } else {
          printError("Could Not Read the Command");
          continue;
        }
        if (command.compareTo("createAlbum") == 0) // works
        {
          boolean created = false;
          String albumName = new String();
          try {
            String tmp = tokenizer.nextToken("\""); // skip space
            if (tmp.compareTo(" ") != 0) // if the token was not space print error
            throw new NoSuchElementException();
            String tmp2 =
                tokenizer.nextToken(
                    "\0"); // read the rest of the token(prevents from reading after double quotes)
            if (!tmp2.endsWith("\"")) // check if it ends with quote
            throw new NoSuchElementException();
            tokenizer = new StringTokenizer(tmp2); // to read stuff before quote
            albumName = tokenizer.nextToken("\""); // read the album name
            if (tokenizer.hasMoreTokens()) throw new NoSuchElementException();
          } catch (NoSuchElementException e) {
            printError("Correct Format -createAlbum \"<albumName>\"");
            continue;
          }
          if (albumName == null) {
            printError("Could Not Create Album");
            continue;
          }
          albumName = albumName.trim();
          if (albumName.isEmpty()) {
            printError("Album name cannot be empty.");
            continue;
          }

          created = control.createAlbum(albumName);
          if (created) {
            System.out.println("created album for user " + user.getID() + ":");
            System.out.println(albumName);
          } else {
            System.out.println("album exists for user " + user.getID() + ":");
            System.out.println(albumName);
          }
        } else if (command.compareTo("deleteAlbum") == 0) // works
        {
          boolean deleted = false;
          String albumName = new String();
          try {
            String tmp = tokenizer.nextToken("\"");
            if (tmp.compareTo(" ") != 0) throw new NoSuchElementException();
            String tmp2 = tokenizer.nextToken("\0");
            if (!tmp2.endsWith("\"")) throw new NoSuchElementException();
            tokenizer = new StringTokenizer(tmp2);
            albumName = tokenizer.nextToken("\"");
            if (tokenizer.hasMoreTokens()) throw new NoSuchElementException();
          } catch (NoSuchElementException e) {
            printError("Correct Format -deleteAlbum \"<albumName>\"");
            continue;
          }
          if (albumName == null) {
            printError("Could Not Delete Album");
            continue;
          }
          albumName = albumName.trim();
          if (albumName.isEmpty()) {
            printError("Album Name Cannot be Empty.");
            continue;
          }

          deleted = control.deleteAlbum(albumName);
          if (deleted) {
            System.out.println("deleted album from user " + user.getID() + ":");
            System.out.println(albumName);
          } else {
            System.out.println("album does not exist for user " + user.getID() + ":");
            System.out.println(albumName);
          }
        } else if (command.compareTo("listAlbums") == 0) // works
        {
          if (tokenizer.hasMoreTokens()) {
            printError("Correct Format -listAlbums");
            continue;
          }
          List<Album> userAlbums = new ArrayList<Album>();
          userAlbums = control.listAlbums();
          if (userAlbums == null) {
            printError("Could not retrieve the list of albums");
            continue;
          }
          if (userAlbums.isEmpty()) {
            System.out.println("No albums exist for user " + user.getID());
          } else {
            System.out.println("Albums for user " + user.getID());
            for (int i = 0;
                i < userAlbums.size();
                i++) { // control needs methods for getting start and end dates of an album and
                       // number of photos in it
              int numOfPhotos = userAlbums.get(i).getPhotos().size();
              System.out.print(userAlbums.get(i).getName() + " number of photos: " + numOfPhotos);
              if (numOfPhotos != 0) {
                System.out.print(", " + control.getStartAndEndDate(userAlbums.get(i)));
              }
              System.out.println();
            }
          }
        } else if (command.compareTo("listPhotos") == 0) {
          String albumName = new String();
          try {
            String tmp = tokenizer.nextToken("\"");
            if (tmp.compareTo(" ") != 0) throw new NoSuchElementException();
            String tmp2 = tokenizer.nextToken("\0");
            if (!tmp2.endsWith("\"")) throw new NoSuchElementException();
            tokenizer = new StringTokenizer(tmp2);
            albumName = tokenizer.nextToken("\"");
            if (tokenizer.hasMoreTokens()) throw new NoSuchElementException();
          } catch (NoSuchElementException e) {
            printError("Correct Format -listPhotos \"<albumName>\"");
            continue;
          }
          if (albumName == null) {
            printError("Could Not List Photos.");
            continue;
          }
          albumName = albumName.trim();
          if (albumName.isEmpty()) {
            printError("Album Name Cannot Be Empty.");
            continue;
          }
          List<Photo> photos = null;
          try {
            photos = control.listPhotos(albumName);

            if (photos == null) {
              printError("Could Not List Photos");
              continue;
            }
            System.out.println("Photos for album " + albumName + ":");
            for (int i = 0; i < photos.size(); i++) {
              System.out.println(
                  photos.get(i).getFileName() + " - " + Utils.formatDate(photos.get(i).getDate()));
            }
          } catch (AlbumNotFoundException e) {
            System.out.println("Album " + albumName + " does not exist");
            continue;
          }
        } else if (command.compareTo("addPhoto") == 0) // more testing needed
        {
          String fileName = new String();
          String caption = new String();
          String albumName = new String();
          try {
            String tmp = tokenizer.nextToken("\""); // skip space
            if (tmp.compareTo(" ") != 0) throw new NoSuchElementException();
            fileName = tokenizer.nextToken("\""); // get file name
            if (fileName.compareTo(" ") == 0) throw new NoSuchElementException();
            tmp = tokenizer.nextToken("\""); // skip space
            if (tmp.compareTo(" ") != 0) throw new NoSuchElementException();
            caption = tokenizer.nextToken("\"");
            if (caption.compareTo(" ") == 0) {
              caption = "";
              String tmp2 = tokenizer.nextToken("\0");
              if (!tmp2.endsWith("\"")) throw new NoSuchElementException();
              tokenizer = new StringTokenizer(tmp2);
              albumName = tokenizer.nextToken("\"");
            } else {
              tokenizer.nextToken("\"");
              String tmp2 = tokenizer.nextToken("\0");
              if (!tmp2.endsWith("\"")) throw new NoSuchElementException();
              tokenizer = new StringTokenizer(tmp2);
              albumName = tokenizer.nextToken("\"");
            }
            if (tokenizer.hasMoreTokens()) throw new NoSuchElementException();
          } catch (NoSuchElementException e) {
            printError("Correct Format -addPhoto \"<fileName>\" \"<caption>\" \"<albumName>\"");
            continue;
          }
          if (fileName == null || caption == null || albumName == null) {
            printError(
                "Correct Format -" + "addPhoto \"<fileName>\" \"<caption>\" \"<albumName>\"");
            continue;
          }
          caption = caption.trim();
          fileName = fileName.trim();
          albumName = albumName.trim();
          if (fileName.isEmpty() || albumName.isEmpty()) {
            printError(
                "Correct Format -" + "addPhoto \"<fileName>\" \"<caption>\" \"<albumName>\"");
            continue;
          }
          fileName = fileName.trim();
          albumName = albumName.trim();
          if (!caption.isEmpty()) caption = caption.trim();
          List<Album> albs = control.listAlbums();
          boolean albumExists = false;
          if (albs != null) {
            for (int i = 0; i < albs.size(); i++) {
              if (albs.get(i).getName().compareTo(albumName) == 0) albumExists = true;
            }
          }
          if (!albumExists) {
            System.out.println("Album " + albumName + " does not exist");
            continue;
          }
          File photoFile = new File(fileName);
          if (!photoFile.exists() || photoFile.isDirectory()) {
            System.out.println("File " + photoFile.getAbsolutePath() + " does not exist");
            continue;
          }
          boolean added = false;
          try {
            added = control.addPhoto(fileName, caption, albumName);

            if (added) {
              Photo addedPhoto = control.getPhotoByFileName(fileName);
              System.out.println("Added photo " + fileName + ":");
              System.out.println(addedPhoto.getCaption() + " - Album: " + albumName);
            } else {
              System.out.println(
                  "Photo " + photoFile.getAbsolutePath() + " already exists in album " + albumName);
            }
          } catch (AlbumNotFoundException e) {
            System.out.println("Album " + albumName + " does not exist");
            continue;
          } catch (FileNotFoundException e) {
            System.out.println("File " + photoFile.getAbsolutePath() + " does not exist");
            continue;
          } catch (IllegalArgumentException e) {
            printError(e.getMessage());
            continue;
          }
        } else if (command.compareTo("movePhoto") == 0) {
          String fileName = new String();
          String oldAlbum = new String();
          String newAlbum = new String();
          try {
            String tmp = tokenizer.nextToken("\"");
            if (tmp.compareTo(" ") != 0) throw new NoSuchElementException();
            fileName = tokenizer.nextToken("\"");
            tmp = tokenizer.nextToken("\"");
            if (tmp.compareTo(" ") != 0) throw new NoSuchElementException();
            oldAlbum = tokenizer.nextToken("\"");
            tmp = tokenizer.nextToken("\"");
            if (tmp.compareTo(" ") != 0) throw new NoSuchElementException();
            String tmp2 = tokenizer.nextToken("\0");
            if (!tmp2.endsWith("\"")) throw new NoSuchElementException();
            tokenizer = new StringTokenizer(tmp2);
            newAlbum = tokenizer.nextToken("\"");
            if (tokenizer.hasMoreTokens()) throw new NoSuchElementException();
          } catch (NoSuchElementException e) {
            printError(
                "Correct Format -movePhoto \"<fileName>\" \"<oldAlbumName>\" \"<newAlbumName>\"");
            continue;
          }
          if (fileName == null || oldAlbum == null || newAlbum == null) {
            printError(
                "Correct Format -"
                    + "movePhoto \"<fileName>\" \"<oldAlbumName>\" \"<newAlbumName>\"");
            continue;
          }
          fileName = fileName.trim();
          oldAlbum = oldAlbum.trim();
          newAlbum = newAlbum.trim();
          if (fileName.isEmpty() || oldAlbum.isEmpty() || newAlbum.isEmpty()) {
            printError(
                "Correct Format -"
                    + "movePhoto \"<fileName>\" \"<oldAlbumName>\" \"<newAlbumName>\"");
            continue;
          }
          boolean moved = false;
          boolean inOldAlbum = false, oldAlbumExists = false, newAlbumExists = false;
          List<Album> albsAll = control.listAlbums();
          for (int i = 0; i < albsAll.size(); i++) {
            if (albsAll.get(i).getName().compareTo(oldAlbum) == 0) oldAlbumExists = true;
            if (albsAll.get(i).getName().compareTo(newAlbum) == 0) newAlbumExists = true;
          }
          if (!oldAlbumExists) {
            System.out.println("Album " + oldAlbum + " does not exist");
            if (!newAlbumExists) System.out.println("Album " + newAlbum + " does not exist");
            continue;
          }
          if (!newAlbumExists) {
            System.out.println("Album " + newAlbum + " does not exist");
            continue;
          }
          try {
            List<String> albs = control.listsPhotoAlbumNamesInfo(fileName);
            if (albs == null) {
              System.out.println("Photo " + fileName + " does not exist in " + oldAlbum);
              continue;
            }

            for (int i = 0; i < albs.size(); i++) {
              if (albs.get(i).compareTo(newAlbum)
                  == 0) // if the photo exists in old album do not do anything
              {
                inOldAlbum = true;
              }
            }
            if (inOldAlbum) continue;

            moved = control.movePhoto(fileName, oldAlbum, newAlbum);
            if (moved) {
              System.out.println("Moved photo " + fileName);
              System.out.println(fileName + " - From album " + oldAlbum + " to album " + newAlbum);
            } else {
              System.out.println("Photo " + fileName + " does not exist in " + oldAlbum);
            }
          } catch (AlbumNotFoundException e) {
            printError(e.getMessage());
            continue;
          } catch (PhotoNotFoundException e) {
            // TODO Auto-generated catch block
            System.out.println("Photo " + fileName + " does not exist");
            continue;
          } catch (FileNotFoundException e) {
            System.out.println("Photo " + fileName + " does not exist");
            continue;
          }
        } else if (command.compareTo("removePhoto") == 0) // works
        {
          String fileName = new String();
          String albumName = new String();
          try {
            String tmp = tokenizer.nextToken("\"");
            if (tmp.compareTo(" ") != 0) throw new NoSuchElementException();
            fileName = tokenizer.nextToken("\"");
            tmp = tokenizer.nextToken("\"");
            if (tmp.compareTo(" ") != 0) throw new NoSuchElementException();
            String tmp2 = tokenizer.nextToken("\0");
            if (!tmp2.endsWith("\"")) throw new NoSuchElementException();
            tokenizer = new StringTokenizer(tmp2);
            albumName = tokenizer.nextToken("\"");
            if (tokenizer.hasMoreTokens()) throw new NoSuchElementException();
          } catch (NoSuchElementException e) {
            printError("Correct Format -removePhoto \"<fileName>\" \"<albumName>\"");
            continue;
          }
          if (fileName == null || albumName == null) {
            printError("Correct Format -" + "removePhoto \"<fileName>\" \"<albumName>\"");
            continue;
          }
          fileName = fileName.trim();
          albumName = albumName.trim();
          if (fileName.isEmpty() || albumName.isEmpty()) {
            printError("Correct Format -" + "removePhoto \"<fileName>\" \"<albumName>\"");
            continue;
          }
          boolean albumExists = false;
          List<Album> albsAll = control.listAlbums();
          for (int i = 0; i < albsAll.size(); i++) {
            if (albsAll.get(i).getName().compareTo(albumName) == 0) albumExists = true;
          }
          if (!albumExists) {
            System.out.println("Album " + albumName + " does not exist");
            continue;
          }
          boolean removed = false;
          try {
            removed = control.removePhoto(fileName, albumName);
            if (removed) {
              System.out.println("Removed photo:");
              System.out.println(fileName + " - From album " + albumName);
            } else {
              System.out.println("Photo " + fileName + " is not in album " + albumName);
            }
          } catch (AlbumNotFoundException e) {
            System.out.println("Album " + albumName + " does not exist");
            continue;
          } catch (FileNotFoundException e) {
            System.out.println("Photo " + fileName + " does not exist");
            continue;
          }
        } else if (command.compareTo("addTag") == 0) // works
        {
          String fileName = new String();
          String tagValue = new String();
          String tagType = new String();
          try {
            String tmp = tokenizer.nextToken("\"");
            if (tmp.compareTo(" ") != 0) throw new NoSuchElementException();
            fileName = tokenizer.nextToken("\""); // file name
            tokenizer.nextToken(" ");
            tagType = tokenizer.nextToken(" :"); // tag type
            tokenizer.nextToken("\"");
            String tmp2 = tokenizer.nextToken("\0");
            if (!tmp2.endsWith("\"")) throw new NoSuchElementException();
            tokenizer = new StringTokenizer(tmp2);
            tagValue = tokenizer.nextToken("\""); // tag value
            if (tokenizer.hasMoreTokens()) throw new NoSuchElementException();
          } catch (NoSuchElementException e) {
            printError("Correct Format -addTag \"<fileName>\" <tagType>:\"<tagValue>\"");
            continue;
          }
          if (tagValue == null || fileName == null || tagType == null) {
            printError("Correct Format -addTag \"<fileName>\" <tagType>:\"<tagValue>\"");
            continue;
          }
          tagValue = tagValue.trim();
          fileName = fileName.trim();
          tagType = tagType.trim();
          if (tagValue.isEmpty() || fileName.isEmpty() || tagType.isEmpty()) {
            printError("Correct Format -addTag \"<fileName>\" <tagType>:\"<tagValue>\"");
            continue;
          }
          boolean added = false;
          try {
            added = control.addTag(fileName, tagType, tagValue);

            if (added) {
              System.out.println("Added tag:");
              System.out.println(fileName + " " + tagType + ":" + tagValue);
            } else {
              System.out.println(
                  "Tag already exists for " + fileName + " " + tagType + ":" + tagValue);
            }
          } catch (PhotoNotFoundException e) {
            // printError(e.getMessage());
            System.out.println("Photo " + fileName + " does not exist");
            continue;
          } catch (FileNotFoundException e) {
            System.out.println("Photo " + fileName + " does not exist");
            continue;
          }
        } else if (command.compareTo("deleteTag") == 0) // works
        {
          String fileName = new String();
          String tagValue = new String();
          String tagType = new String();
          try {
            String tmp = tokenizer.nextToken("\"");
            if (tmp.compareTo(" ") != 0) throw new NoSuchElementException();
            fileName = tokenizer.nextToken("\""); // file name
            tokenizer.nextToken(" ");
            tagType = tokenizer.nextToken(" :"); // tag type
            tokenizer.nextToken("\"");
            String tmp2 = tokenizer.nextToken("\0");
            if (!tmp2.endsWith("\"")) throw new NoSuchElementException();
            tokenizer = new StringTokenizer(tmp2);
            tagValue = tokenizer.nextToken("\""); // tag value
            if (tokenizer.hasMoreTokens()) throw new NoSuchElementException();
          } catch (NoSuchElementException e) {
            printError("Correct Format -deleteTag \"<fileName>\" <tagType>:\"<tagValue>\"");
            continue;
          }
          if (tagValue == null || fileName == null || tagType == null) {
            printError("Correct Format -deleteTag \"<fileName>\" <tagType>:\"<tagValue>\"");
            continue;
          }
          tagValue = tagValue.trim();
          fileName = fileName.trim();
          tagType = tagType.trim();
          if (tagValue.isEmpty() || fileName.isEmpty() || tagType.isEmpty()) {
            printError("Correct Format -deleteTag \"<fileName>\" <tagType>:\"<tagValue>\"");
            continue;
          }
          boolean deleted = false;
          try {
            deleted = control.deleteTag(fileName, tagType, tagValue);

            if (deleted) {
              System.out.println("Deleted tag");
              System.out.println(fileName + " " + tagType + ":" + tagValue);
            } else {
              System.out.println(
                  "Tag does not exist for " + fileName + " " + tagType + ":" + tagValue);
            }
          } catch (PhotoNotFoundException e) {
            System.out.println("Photo " + fileName + " does not exist");
            continue;
          } catch (FileNotFoundException e) {
            System.out.println("Photo " + fileName + " does not exist");
            continue;
          }
        } else if (command.compareTo("listPhotoInfo") == 0) // works
        {
          String fileName = new String();
          try {
            String tmp = tokenizer.nextToken("\"");
            if (tmp.compareTo(" ") != 0) throw new NoSuchElementException();
            String tmp2 = tokenizer.nextToken("\0");
            if (!tmp2.endsWith("\"")) throw new NoSuchElementException();
            tokenizer = new StringTokenizer(tmp2);
            fileName = tokenizer.nextToken("\""); // file name
            if (tokenizer.hasMoreTokens()) throw new NoSuchElementException();
          } catch (NoSuchElementException e) {
            printError("Correct Format -listPhotoInfo \"<fileName>\"");
            continue;
          }
          if (fileName == null) {
            printError("Correct Format -listPhotoInfo \"<fileName>\"");
            continue;
          }
          fileName = fileName.trim();
          if (fileName.isEmpty()) {
            printError("Correct Format -listPhotoInfo \"<fileName>\"");
            continue;
          }

          try {

            Photo temp = control.getPhotoByFileName(fileName);
            List<String> albumNames = control.listsPhotoAlbumNamesInfo(fileName);
            if (temp != null && albumNames != null) {
              System.out.println("Photo file name: " + fileName);
              System.out.print("Album: ");
              if (!albumNames.isEmpty()) {
                for (int i = 0; i < albumNames.size() - 1; i++) {
                  System.out.print("\"" + albumNames.get(i) + "\", ");
                }
                System.out.print("\"" + albumNames.get(albumNames.size() - 1) + "\"");
              }
              System.out.println();
              System.out.println("Date: " + Utils.formatDate(temp.getDate())); // does not work
              System.out.println("Caption: " + temp.getCaption());
              System.out.println("Tags:");
              List<Tag> tags = temp.getTags();
              for (int i = 0; i < tags.size(); i++) System.out.println(tags.get(i).toString());
            } else System.out.println("Photo " + fileName + " does not exist");

          } catch (FileNotFoundException e) {
            System.out.println("Photo " + fileName + " does not exist");
            continue;
          }
        } else if (command.compareTo("getPhotosByDate") == 0) {
          String startDate = new String();
          String endDate = new String();
          try {
            startDate = tokenizer.nextToken(" "); // file name
            endDate = tokenizer.nextToken(" ");
            if (tokenizer.hasMoreTokens()) throw new NoSuchElementException();
          } catch (NoSuchElementException e) {
            printError("Correct Format -getPhotosByDate <start date> <end date>");
            continue;
          }
          if (startDate == null || endDate == null) {
            printError("Could not get photos by date.");
            continue;
          }
          startDate = startDate.trim();
          endDate = endDate.trim();
          if (startDate.isEmpty() || endDate.isEmpty()) {
            printError("Start date and end date cannot be empty.");
            continue;
          }
          List<Photo> photos = null;
          try {
            photos = control.getPhotosByDate(startDate, endDate);

            if (photos == null) {
              printError("Could not get photos by date.");
              continue;
            }
            System.out.println(
                "Photos for user " + user.getID() + " in range " + startDate + " to " + endDate);
            if (!photos.isEmpty()) {
              for (int i = 0; i < photos.size(); i++) {
                System.out.print(photos.get(i).getCaption() + " - Album: ");
                List<String> albumNames =
                    control.listsPhotoAlbumNamesInfo(photos.get(i).getFileName());
                for (int n = 0; n < albumNames.size() - 1; n++) {
                  System.out.print(albumNames.get(n) + ", ");
                }
                System.out.print(albumNames.get(albumNames.size() - 1));
                System.out.println(" - Date:" + Utils.formatDate(photos.get(i).getDate()));
              }
            }
          } catch (ParseException e) {
            printError(e.getMessage());
            continue;
          } catch (FileNotFoundException e) {
            printError(e.getMessage());
            continue;
          } catch (IllegalArgumentException e) {
            printError(e.getMessage());
            continue;
          }
        } else if (command.compareTo("getPhotosByTag") == 0) {
          String searchString = new String();
          try {
            searchString = tokenizer.nextToken("\0");
          } catch (NoSuchElementException e) {
            printError(
                "Correct Format -getPhotosByTag [<tagType>:]\"<tagValue>\" [,[<tagType>:]\"<tagValue>\"]... ");
            continue;
          }
          tokenizer = new StringTokenizer(searchString);
          List<String> tags = new ArrayList<String>();
          while (tokenizer
              .hasMoreTokens()) // this breaks up the tokens into tags(with or without values)
          {
            tags.add(tokenizer.nextToken(" ,"));
          }
          if (tags.isEmpty()) {
            printError(
                "Correct Format -getPhotosByTag [<tagType>:]\"<tagValue>\" [,[<tagType>:]\"<tagValue>\"]... ");
            continue;
          }
          try {
            for (int i = 0; i < tags.size(); i++) // removes the quotes around tag value
            {
              if (!tags.get(i).endsWith("\"")) {
                throw new IllegalArgumentException();
              }
              if (!tags.get(i).contains(":")) {
                if (!tags.get(i).startsWith("\"")) throw new IllegalArgumentException();
              }
              String temp = tags.get(i);
              tags.remove(i);
              StringTokenizer tok = new StringTokenizer(temp, "\"");
              ArrayList<String> args = new ArrayList<String>();
              while (tok.hasMoreTokens()) {
                args.add(tok.nextToken());
              }
              if (args.size() == 2) {
                tags.add(i, args.get(0).concat(args.get(1)));
              } else if (args.size() == 1) {
                if (args.get(0).endsWith(":")) throw new IllegalArgumentException();
                tags.add(0, args.get(0));
              } else {
                printError("getPhotosByTag. Could Not Parse Arguments.");
                continue;
              }
            }
          } catch (IllegalArgumentException e) {
            printError(
                "Correct Format -getPhotosByTag [<tagType>:]\"<tagValue>\" [,[<tagType>:]\"<tagValue>\"]... ");
            continue;
          }

          try {
            List<Photo> photos = control.getPhotosByTag(tags);
            if (photos == null) {
              printError("getPhotosByTag. Could not retrieve photos.");
              continue;
            }
            System.out.println(
                "Photos for user " + user.getID() + " with tags " + searchString + ": ");
            for (int i = 0; i < photos.size(); i++) {
              System.out.print(photos.get(i).getCaption() + " - Album:");
              List<String> albumNames =
                  control.listsPhotoAlbumNamesInfo(photos.get(i).getFileName());
              if (!albumNames.isEmpty()) {
                for (int n = 0; n < albumNames.size() - 1; n++) {
                  System.out.print(albumNames.get(n) + ", ");
                }
                System.out.print(albumNames.get(albumNames.size() - 1));
              }
              System.out.println(" - Date: " + Utils.formatDate(photos.get(i).getDate()));
            }
          } catch (FileNotFoundException e) {
            printError(e.getMessage());
            continue;
          } catch (IllegalArgumentException e) {
            printError(e.getMessage());
            continue;
          }
        } else if (command.compareTo("logout") == 0) // works
        {
          if (tokenizer.hasMoreTokens()) {
            printError("Corect Format -logout");
            continue;
          }
          control.logout();
          break;
        } else {
          printError("Unknown Command");
        }
      }

    } else {
      System.out.println("user " + ID + " does not exist");
    }
  }
Beispiel #28
0
 private static void fillField(Field f, String value) {
   try {
     // --Permissions
     boolean accessState = true;
     if (Modifier.isFinal(f.getModifiers())) {
       log.err(LOG_TAG, "Option cannot be final: " + f);
       System.exit(ExitCode.BAD_OPTION.code);
     }
     if (!f.isAccessible()) {
       accessState = false;
       f.setAccessible(true);
     }
     // --Set Value
     Object objVal = Utils.cast(value, f.getGenericType());
     if (objVal != null) {
       if (objVal.getClass().isArray()) {
         // (case: array)
         Object[] array = (Object[]) objVal;
         // error check
         if (!f.getType().isArray()) {
           log.err(
               LOG_TAG,
               "Setting an array to a non-array field. field: "
                   + f
                   + " value: "
                   + Arrays.toString(array)
                   + " src: "
                   + value);
           System.exit(ExitCode.BAD_OPTION.code);
         }
         // create specific array
         Object toSet = Array.newInstance(f.getType().getComponentType(), array.length);
         for (int i = 0; i < array.length; i++) {
           Array.set(toSet, i, array[i]);
         }
         // set value
         f.set(null, toSet);
       } else {
         // case: not array
         f.set(null, objVal);
       }
     } else {
       log.err(
           LOG_TAG, "Cannot assign option field: " + f + " value: " + value + "; invalid type");
       System.exit(ExitCode.BAD_OPTION.code);
     }
     // --Permissions
     if (!accessState) {
       f.setAccessible(false);
     }
   } catch (IllegalArgumentException e) {
     log.err(
         LOG_TAG,
         "Cannot assign option field: "
             + f.getDeclaringClass().getCanonicalName()
             + "."
             + f.getName()
             + " value: "
             + value
             + " cause: "
             + e.getMessage());
     System.exit(ExitCode.BAD_OPTION.code);
   } catch (IllegalAccessException e) {
     log.err(
         LOG_TAG,
         "Cannot access option field: "
             + f.getDeclaringClass().getCanonicalName()
             + "."
             + f.getName());
     System.exit(ExitCode.BAD_OPTION.code);
   } catch (Exception e) {
     log.err(
         LOG_TAG,
         "Cannot assign option field: "
             + f.getDeclaringClass().getCanonicalName()
             + "."
             + f.getName()
             + " value: "
             + value
             + " cause: "
             + e.getMessage());
     System.exit(ExitCode.BAD_OPTION.code);
   }
 }
Beispiel #29
0
  @Test
  public void testParseMulti() throws ParseException, TokeniserException {
    List<Policy> pl;
    ArrayList<Warning> warnings;

    pl =
        Parser.parseMulti(
            "script-src a; script-src b, , script-src c; script-src d", "https://origin.com");
    assertEquals(2, pl.size());
    assertEquals("script-src a", pl.get(0).show());
    assertEquals("script-src c", pl.get(1).show());

    pl = Parser.parseMulti("script-src a,", URI.parse("https://origin.com"));
    assertEquals(2, pl.size());
    assertEquals("script-src a", pl.get(0).show());
    assertEquals("", pl.get(1).show());

    warnings = new ArrayList<>();
    pl = Parser.parseMulti("script-src a,", URI.parse("https://origin.com"), warnings);
    assertEquals(2, pl.size());
    assertEquals("script-src a", pl.get(0).show());
    assertEquals("", pl.get(1).show());
    assertEquals(0, warnings.size());

    warnings = new ArrayList<>();
    pl = Parser.parseMulti("script-src a, sandbox", "https://origin.com", warnings);
    assertEquals(2, pl.size());
    assertEquals("script-src a", pl.get(0).show());
    assertEquals("sandbox", pl.get(1).show());
    assertEquals(0, warnings.size());

    warnings = new ArrayList<>();
    pl =
        ParserWithLocation.parseMulti(
            "   plugin-types  a/b  , script-src 'unsafe-redirect'", "https://origin.com", warnings);
    assertEquals(2, pl.size());
    assertEquals("plugin-types a/b", pl.get(0).show());
    assertEquals("script-src 'unsafe-redirect'", pl.get(1).show());
    assertEquals(1, warnings.size());
    assertEquals(
        "1:36: 'unsafe-redirect' has been removed from CSP as of version 2.0",
        warnings.get(0).show());

    warnings = new ArrayList<>();
    pl =
        ParserWithLocation.parseMulti(
            "script-src a, frame-src b", URI.parse("https://origin.com"), warnings);
    assertEquals(2, pl.size());
    assertEquals("script-src a", pl.get(0).show());
    assertEquals("frame-src b", pl.get(1).show());
    assertEquals(1, warnings.size());
    assertEquals(
        "1:15: The frame-src directive is deprecated as of CSP version 1.1. Authors who wish to govern nested browsing contexts SHOULD use the child-src directive instead.",
        warnings.get(0).show());

    try {
      pl.clear();
      pl = Parser.parseMulti("script-src a,b", "https://origin.com");
      fail();
    } catch (IllegalArgumentException e1) {
      assertEquals(0, pl.size());
      assertEquals("Unrecognised directive name: b", e1.getMessage());
    }

    try {
      ParserWithLocation.parse(
          "script-src a, script-src b", "https://origin.com", new ArrayList<>());
      fail();
    } catch (ParseException e1) {
      assertEquals(0, pl.size());
      assertEquals("1:13: expecting end of policy but found ,", e1.getMessage());
    }

    try {
      Parser.parse("script-src a, script-src b", "https://origin.com");
      fail();
    } catch (ParseException e1) {
      assertEquals(0, pl.size());
      assertEquals("expecting end of policy but found ,", e1.getMessage());
    }

    try {
      pl.clear();
      pl = ParserWithLocation.parseMulti("allow 'none', options", "https://origin.com");
      fail();
    } catch (ParseException e1) {
      assertEquals(0, pl.size());
      assertEquals(
          "1:1: The allow directive has been replaced with default-src and is not in the CSP specification.",
          e1.getMessage());
    }

    try {
      pl.clear();
      pl = ParserWithLocation.parseMulti("allow 'none', referrer", URI.parse("https://origin.com"));
      fail();
    } catch (ParseException e1) {
      assertEquals(0, pl.size());
      assertEquals(
          "1:1: The allow directive has been replaced with default-src and is not in the CSP specification.",
          e1.getMessage());
    }

    failsToParse("script-src *, ");
  }
Beispiel #30
0
  /**
   * <span class="changed_modified_2_3">Verify</span> that the value is valid according to the Bean
   * Validation constraints. <div class="changed_added_2_0">
   *
   * <p>Obtain a {@link ValidatorFactory} instance by calling {@link
   * javax.validation.Validation#buildDefaultValidatorFactory}.
   *
   * <p>Let <em>validationGroupsArray</em> be a <code>Class []</code> representing validator groups
   * set on the component by the tag handler for this validator. The first search component
   * terminates the search for the validation groups value. If no such value is found use the class
   * name of {@link javax.validation.groups.Default} as the value of the validation groups.
   *
   * <p>Let <em>valueExpression</em> be the return from calling {@link
   * UIComponent#getValueExpression} on the argument <em>component</em>, passing the literal string
   * &#8220;value&#8221; (without the quotes) as an argument. If this application is running in an
   * environment with a Unified EL Implementation for Java EE6 or later, obtain the <code>
   * ValueReference</code> from <em>valueExpression</em> and let <em>valueBaseClase</em> be the
   * return from calling <code>ValueReference.getBase()</code> and <em>valueProperty</em> be the
   * return from calling <code>ValueReference.getProperty()</code>. If an earlier version of the
   * Unified EL is present, use the appropriate methods to inspect <em>valueExpression</em> and
   * derive values for <em>valueBaseClass</em> and <em>valueProperty</em>.
   *
   * <p>If no <code>ValueReference</code> can be obtained, take no action and return.
   *
   * <p>If <code>ValueReference.getBase()</code> return <code>null</code>, take no action and
   * return.
   *
   * <p>Obtain the {@link ValidatorContext} from the {@link ValidatorFactory}.
   *
   * <p>Decorate the {@link MessageInterpolator} returned from {@link
   * ValidatorFactory#getMessageInterpolator} with one that leverages the <code>Locale</code>
   * returned from {@link javax.faces.component.UIViewRoot#getLocale}, and store it in the <code>
   * ValidatorContext</code> using {@link ValidatorContext#messageInterpolator}.
   *
   * <p>Obtain the {@link javax.validation.Validator} instance from the <code>validatorContext
   * </code>.
   *
   * <p>Obtain a <code>javax.validation.BeanDescriptor</code> from the <code>
   * javax.validation.Validator</code>. If <code>hasConstraints()</code> on the <code>BeanDescriptor
   * </code> returns false, take no action and return. Otherwise proceed.
   *
   * <p>Call {@link javax.validation.Validator#validateValue}, passing <em>valueBaseClass</em>,
   * <em>valueProperty</em>, the <em>value</em> argument, and <em>validatorGroupsArray</em> as
   * arguments.
   *
   * <p>If the returned <code>Set&lt;{@link
   * ConstraintViolation}&gt;</code> is non-empty, for each element in the <code>Set</code>, create
   * a {@link FacesMessage} where the summary and detail are the return from calling {@link
   * ConstraintViolation#getMessage}. Capture all such <code>FacesMessage</code> instances into a
   * <code>Collection</code> and pass them to {@link
   * ValidatorException#ValidatorException(java.util.Collection)}. <span
   * class="changed_added_2_3">If the {@link #ENABLE_VALIDATE_WHOLE_BEAN_PARAM_NAME} application
   * parameter is enabled and this {@code Validator} instance has validation groups other than or in
   * addition to the {@code Default} group, record the fact that this field failed validation so
   * that any <code>&lt;f:validateWholeBean /&gt;</code> component later in the tree is able to skip
   * class-level validation for the bean for which this particular field is a property. Regardless
   * of whether or not {@link #ENABLE_VALIDATE_WHOLE_BEAN_PARAM_NAME} is set, throw the new
   * exception.</span>
   *
   * <p class="changed_added_2_3">If the returned {@code Set} is empty, the {@link
   * #ENABLE_VALIDATE_WHOLE_BEAN_PARAM_NAME} application parameter is enabled and this {@code
   * Validator} instance has validation groups other than or in addition to the {@code Default}
   * group, record the fact that this field passed validation so that any <code>
   * &lt;f:validateWholeBean /&gt;</code> component later in the tree is able to allow class-level
   * validation for the bean for which this particular field is a property. </div>
   *
   * @param context {@inheritDoc}
   * @param component {@inheritDoc}
   * @param value {@inheritDoc}
   * @throws ValidatorException {@inheritDoc}
   */
  @Override
  public void validate(FacesContext context, UIComponent component, Object value) {

    if (context == null) {
      throw new NullPointerException();
    }
    if (component == null) {
      throw new NullPointerException();
    }
    ValueExpression valueExpression = component.getValueExpression("value");
    if (valueExpression == null) {
      return;
    }

    ValidatorFactory validatorFactory;
    Object cachedObject =
        context.getExternalContext().getApplicationMap().get(VALIDATOR_FACTORY_KEY);
    if (cachedObject instanceof ValidatorFactory) {
      validatorFactory = (ValidatorFactory) cachedObject;
    } else {
      try {
        validatorFactory = Validation.buildDefaultValidatorFactory();
      } catch (ValidationException e) {
        throw new FacesException("Could not build a default Bean Validator factory", e);
      }
      context.getExternalContext().getApplicationMap().put(VALIDATOR_FACTORY_KEY, validatorFactory);
    }

    ValidatorContext validatorContext = validatorFactory.usingContext();
    MessageInterpolator jsfMessageInterpolator =
        new JsfAwareMessageInterpolator(context, validatorFactory.getMessageInterpolator());
    validatorContext.messageInterpolator(jsfMessageInterpolator);
    javax.validation.Validator beanValidator = validatorContext.getValidator();
    Class[] validationGroupsArray = parseValidationGroups(getValidationGroups());

    // PENDING(rlubke, driscoll): When EL 1.3 is present, we won't need
    // this.

    ValueExpressionAnalyzer expressionAnalyzer = new ValueExpressionAnalyzer(valueExpression);

    ValueReference valueReference = expressionAnalyzer.getReference(context.getELContext());
    if (valueReference == null) {
      return;
    }
    if (isResolvable(valueReference, valueExpression)) {
      Set<ConstraintViolation<?>> violations = null;
      try {
        //noinspection unchecked
        violations =
            beanValidator.validateValue(
                valueReference.getBaseClass(),
                valueReference.getProperty(),
                value,
                validationGroupsArray);
      } catch (IllegalArgumentException iae) {
        String failureMessage =
            "Unable to validate expression "
                + valueExpression.getExpressionString()
                + " using Bean Validation.  Unable to get value of expression. "
                + " Message from Bean Validation: "
                + iae.getMessage();
        LOGGER.fine(failureMessage);
      }

      if (violations != null && !violations.isEmpty()) {
        ValidatorException toThrow;
        if (1 == violations.size()) {
          ConstraintViolation violation = violations.iterator().next();
          toThrow =
              new ValidatorException(
                  MessageFactory.getMessage(
                      context,
                      MESSAGE_ID,
                      violation.getMessage(),
                      MessageFactory.getLabel(context, component)));
        } else {
          Set<FacesMessage> messages = new LinkedHashSet<>(violations.size());
          for (ConstraintViolation violation : violations) {
            messages.add(
                MessageFactory.getMessage(
                    context,
                    MESSAGE_ID,
                    violation.getMessage(),
                    MessageFactory.getLabel(context, component)));
          }
          toThrow = new ValidatorException(messages);
        }

        // Record the fact that this field failed validation, so that multi-field
        // validation is not attempted.
        if (MultiFieldValidationUtils.wholeBeanValidationEnabled(context, validationGroupsArray)) {
          Map<Object, Map<String, Map<String, Object>>> multiFieldCandidates =
              MultiFieldValidationUtils.getMultiFieldValidationCandidates(context, true);
          Object val = valueReference.getBase();
          Map<String, Map<String, Object>> candidate =
              multiFieldCandidates.getOrDefault(val, new HashMap<>());
          Map<String, Object> tuple = new HashMap<>();
          tuple.put("component", component);
          tuple.put("value", FAILED_FIELD_LEVEL_VALIDATION);
          candidate.put(valueReference.getProperty(), tuple);
          multiFieldCandidates.putIfAbsent(val, candidate);
        }

        throw toThrow;
      }
    }

    // Record the fact that this field passed validation, so that multi-field
    // validation can be performed if desired
    if (MultiFieldValidationUtils.wholeBeanValidationEnabled(context, validationGroupsArray)) {
      Map<Object, Map<String, Map<String, Object>>> multiFieldCandidates =
          MultiFieldValidationUtils.getMultiFieldValidationCandidates(context, true);
      Object val = valueReference.getBase();
      Map<String, Map<String, Object>> candidate =
          multiFieldCandidates.getOrDefault(val, new HashMap<>());
      Map<String, Object> tuple =
          new HashMap<>(); // new ComponentValueTuple((EditableValueHolder) component, value);
      tuple.put("component", component);
      tuple.put("value", value);
      candidate.put(valueReference.getProperty(), tuple);
      multiFieldCandidates.putIfAbsent(val, candidate);
    }
  }