コード例 #1
0
ファイル: FormulaUtil.java プロジェクト: jon4than/visad
 /** evaluate the link function */
 public static Data link(VMethod m, Object[] o) throws VisADException {
   Data ans = null;
   if (o != null) {
     for (int i = 0; i < o.length; i++) {
       // convert VRealTypes to RealTypes
       if (o[i] instanceof VRealType) {
         o[i] = ((VRealType) o[i]).getRealType();
       }
     }
   }
   try {
     ans = (Data) FormulaUtil.invokeMethod(m.getMethod(), o);
   } catch (ClassCastException exc) {
     if (FormulaVar.DEBUG) exc.printStackTrace();
     throw new VisADException("Link error: invalid linked method");
   } catch (IllegalAccessException exc) {
     if (FormulaVar.DEBUG) exc.printStackTrace();
     throw new VisADException("Link error: cannot access linked method");
   } catch (IllegalArgumentException exc) {
     if (FormulaVar.DEBUG) exc.printStackTrace();
     throw new VisADException("Link error: bad method argument");
   } catch (InvocationTargetException exc) {
     if (FormulaVar.DEBUG) exc.getTargetException().printStackTrace();
     throw new VisADException("Link error: linked method threw an exception");
   }
   if (ans == null) {
     throw new VisADException("Link error: linked method returned null data");
   }
   return ans;
 }
コード例 #2
0
ファイル: GetHostName.java プロジェクト: mikelopez/jvm
 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();
     }
   }
 }
コード例 #3
0
 public double getTimeValue(int point) throws IOException {
   Array array = null;
   try {
     array = getTime(this.getPointRange(point));
   } catch (InvalidRangeException e) {
     IllegalArgumentException iae =
         new IllegalArgumentException(
             "Point <"
                 + point
                 + "> not in valid range <0, "
                 + (this.getNumberPoints() - 1)
                 + ">: "
                 + e.getMessage());
     iae.initCause(e);
     throw iae;
   }
   if (array instanceof ArrayDouble) {
     return (array.getDouble(array.getIndex()));
   } else if (array instanceof ArrayFloat) {
     return (array.getFloat(array.getIndex()));
   } else if (array instanceof ArrayInt) {
     return (array.getInt(array.getIndex()));
   } else {
     throw new IOException(
         "Time variable not float, double, or integer <"
             + array.getElementType().toString()
             + ">.");
   }
 }
コード例 #4
0
 // @todo Make sure units are meters
 public double getElevation(int point)
     throws IOException // optional; units meters;  missing = NaN.
     {
   Array array = null;
   try {
     array = getElevation(this.getPointRange(point));
   } catch (InvalidRangeException e) {
     IllegalArgumentException iae =
         new IllegalArgumentException(
             "Point <"
                 + point
                 + "> not in valid range <0, "
                 + (this.getNumberPoints() - 1)
                 + ">: "
                 + e.getMessage());
     iae.initCause(e);
     throw iae;
   }
   if (array instanceof ArrayDouble) {
     return array.getDouble(array.getIndex());
   } else if (array instanceof ArrayFloat) {
     return array.getFloat(array.getIndex());
   } else {
     throw new IOException(
         "Elevation variable not float or double <" + array.getElementType().toString() + ">.");
   }
 }
コード例 #5
0
 // @todo Make sure units are degrees_east
 public double getLongitude(int point) throws IOException // required, units degrees_east
     {
   Array array = null;
   try {
     array = getLongitude(this.getPointRange(point));
   } catch (InvalidRangeException e) {
     IllegalArgumentException iae =
         new IllegalArgumentException(
             "Point <"
                 + point
                 + "> not in valid range <0, "
                 + (this.getNumberPoints() - 1)
                 + ">: "
                 + e.getMessage());
     iae.initCause(e);
     throw iae;
   }
   if (array instanceof ArrayDouble) {
     return (array.getDouble(array.getIndex()));
   } else if (array instanceof ArrayFloat) {
     return (array.getFloat(array.getIndex()));
   } else {
     throw new IOException(
         "Longitude variable not float or double <" + array.getElementType().toString() + ">.");
   }
 }
コード例 #6
0
ファイル: Scriptlet.java プロジェクト: WilkerDiaz/Compiere
 /**
  * Execute Script Loads environment and saves result
  *
  * @return null or Exception
  */
 public Exception execute() {
   m_result = null;
   if (m_variable == null
       || m_variable.length() == 0
       || m_script == null
       || m_script.length() == 0) {
     IllegalArgumentException e = new IllegalArgumentException("No variable/script");
     log.config(e.toString());
     return e;
   }
   Interpreter i = new Interpreter();
   loadEnvironment(i);
   try {
     log.config(m_script);
     i.eval(m_script);
   } catch (Exception e) {
     log.config(e.toString());
     return e;
   }
   try {
     m_result = i.get(m_variable);
     log.config("Result (" + m_result.getClass().getName() + ") " + m_result);
   } catch (Exception e) {
     log.config("Result - " + e);
     if (e instanceof NullPointerException)
       e = new IllegalArgumentException("Result Variable not found - " + m_variable);
     return e;
   }
   return null;
 } //  execute
コード例 #7
0
 /** Creates a DOMStorable object. */
 @Override
 public Object create(String name) {
   Object o = nameToPrototypeMap.get(name);
   if (o == null) {
     throw new IllegalArgumentException("Storable name not known to factory: " + name);
   }
   if (o instanceof Class) {
     try {
       return ((Class) o).newInstance();
     } catch (Exception e) {
       IllegalArgumentException error =
           new IllegalArgumentException("Storable class not instantiable by factory: " + name);
       error.initCause(e);
       throw error;
     }
   } else {
     try {
       return o.getClass().getMethod("clone", (Class[]) null).invoke(o, (Object[]) null);
     } catch (Exception e) {
       IllegalArgumentException error =
           new IllegalArgumentException(
               "Storable prototype not cloneable by factory. Name: " + name);
       error.initCause(e);
       throw error;
     }
   }
 }
コード例 #8
0
ファイル: VITop.java プロジェクト: mikelopez/jvm
 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();
     }
   }
 }
コード例 #9
0
ファイル: AttributesPanel.java プロジェクト: escalope/IDK
  public void setEntity(java.lang.Object ent) {
    Method[] methods = ent.getClass().getDeclaredMethods();
    box.removeAll();
    for (Method m : methods) {
      if (m.getName().toLowerCase().startsWith("get")) {
        String attName = m.getName().substring(3);
        Object result;
        try {
          result = m.invoke(ent, new Object[] {});
          String value = "null";
          if (result != null) value = result.toString();
          JPanel attPane = new JPanel(new FlowLayout(FlowLayout.LEFT));
          attPane.add(new JLabel(attName + " : " + m.getReturnType().getName() + " = " + value));
          box.add(attPane);
        } catch (IllegalArgumentException e) {

          e.printStackTrace();
        } catch (IllegalAccessException e) {

          e.printStackTrace();
        } catch (InvocationTargetException e) {

          e.printStackTrace();
        }
      }
    }
  }
コード例 #10
0
 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);
   }
 }
コード例 #11
0
ファイル: StamboomConsole.java プロジェクト: Requinard/C2j
 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);
   }
 }
コード例 #12
0
  /** Gets all Genomic Data. */
  private ProfileDataSummary getGenomicData(
      String cancerStudyId,
      HashMap<String, GeneticProfile> defaultGeneticProfileSet,
      SampleList defaultSampleSet,
      String geneListStr,
      ArrayList<SampleList> sampleList,
      HttpServletRequest request,
      HttpServletResponse response)
      throws IOException, ServletException, DaoException {

    // parse geneList, written in the OncoPrintSpec language (except for changes by XSS clean)
    double zScore =
        ZScoreUtil.getZScore(
            new HashSet<String>(defaultGeneticProfileSet.keySet()),
            new ArrayList<GeneticProfile>(defaultGeneticProfileSet.values()),
            request);
    double rppaScore = ZScoreUtil.getRPPAScore(request);

    ParserOutput theOncoPrintSpecParserOutput =
        OncoPrintSpecificationDriver.callOncoPrintSpecParserDriver(
            geneListStr,
            new HashSet<String>(defaultGeneticProfileSet.keySet()),
            new ArrayList<GeneticProfile>(defaultGeneticProfileSet.values()),
            zScore,
            rppaScore);

    ArrayList<String> geneList = new ArrayList<String>();
    geneList.addAll(theOncoPrintSpecParserOutput.getTheOncoPrintSpecification().listOfGenes());

    ArrayList<ProfileData> profileDataList = new ArrayList<ProfileData>();
    Set<String> warningUnion = new HashSet<String>();

    for (GeneticProfile profile : defaultGeneticProfileSet.values()) {
      try {
        GetProfileData remoteCall =
            new GetProfileData(
                profile, geneList, StringUtils.join(defaultSampleSet.getSampleList(), " "));
        ProfileData pData = remoteCall.getProfileData();
        warningUnion.addAll(remoteCall.getWarnings());
        profileDataList.add(pData);
      } catch (IllegalArgumentException e) {
        e.getStackTrace();
      }
    }

    ProfileMerger merger = new ProfileMerger(profileDataList);
    ProfileData mergedProfile = merger.getMergedProfile();

    ProfileDataSummary dataSummary =
        new ProfileDataSummary(
            mergedProfile,
            theOncoPrintSpecParserOutput.getTheOncoPrintSpecification(),
            zScore,
            rppaScore);
    return dataSummary;
  }
コード例 #13
0
  /**
   * 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;
  }
コード例 #14
0
ファイル: ComboBoxDemo2.java プロジェクト: aki-s/emacs.pub
 /** 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());
   }
 }
コード例 #15
0
 @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);
   }
 }
コード例 #16
0
 /*
   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);
 }
コード例 #17
0
ファイル: TableStats.java プロジェクト: tenn-cn/CS186-1
 public static void setStatsMap(HashMap<String, TableStats> s) {
   try {
     java.lang.reflect.Field statsMapF = TableStats.class.getDeclaredField("statsMap");
     statsMapF.setAccessible(true);
     statsMapF.set(null, s);
   } catch (NoSuchFieldException e) {
     e.printStackTrace();
   } catch (SecurityException e) {
     e.printStackTrace();
   } catch (IllegalArgumentException e) {
     e.printStackTrace();
   } catch (IllegalAccessException e) {
     e.printStackTrace();
   }
 }
コード例 #18
0
ファイル: RelativePath.java プロジェクト: EXMARaLDA/exmaralda
  public static String resolveRelativePath(String relativePath, String base) {
    /*System.out.println("===============");
    System.out.println(relativePath);
    System.out.println(base);*/
    // keep simple cases as they were
    if ((base == null) || (new File(relativePath).isAbsolute())) {
      // System.out.println("1");
      return relativePath;
    }
    if (base.startsWith("http")) {
      try {
        // System.out.println("2a");
        return new URI(base).resolve(relativePath).toString();
      } catch (URISyntaxException ex) {
        ex.printStackTrace();
      }
    }
    if (!(relativePath.startsWith(".."))) {
      // System.out.println("2b");
      File parentFile = new File(base).getParentFile();
      if (parentFile == null) {
        return relativePath;
      }
      URI uri2 = parentFile.toURI();
      String modRelPath = relativePath.replaceAll(" ", "%20");
      // String modRelPath = relativePath;
      try {
        URI absoluteURI = uri2.resolve(modRelPath);
        return new File(absoluteURI).getAbsolutePath();
      } catch (IllegalArgumentException use) {
        use.printStackTrace();
        return relativePath;
      }
    }

    // the relative Path starts with ..
    String UP = ".." + System.getProperty("file.separator");
    String OTHER = "../";
    if (relativePath.startsWith(UP) || relativePath.startsWith(OTHER)) {
      String newBase = new File(base).getParent();
      String newRelative = relativePath.substring(3);
      // System.out.println("3");
      return resolveRelativePath(newRelative, newBase);
    }
    // no can do
    // System.out.println("4");
    return relativePath;
  }
コード例 #19
0
 public Array getData(int point, String parameterName) throws IOException {
   try {
     return (getData(this.getPointRange(point), parameterName));
   } catch (InvalidRangeException e) {
     IllegalArgumentException iae =
         new IllegalArgumentException(
             "Point <"
                 + point
                 + "> not in valid range <0, "
                 + (this.getNumberPoints() - 1)
                 + ">: "
                 + e.getMessage());
     iae.initCause(e);
     throw iae;
   }
 }
コード例 #20
0
  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);
      }
    }
  }
コード例 #21
0
ファイル: ReflectionUtils.java プロジェクト: saden1/dozer
  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;
  }
コード例 #22
0
  /**
   * 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;
  }
コード例 #23
0
 @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);
         }
       }
     }
   }
 }
コード例 #24
0
  @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);
  }
コード例 #25
0
  /**
   * 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;
  }
コード例 #26
0
  /*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;
  }
コード例 #27
0
  @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;
  }
コード例 #28
0
 /*
   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);
 }
コード例 #29
0
 // convenience method for invoking a constructor;
 // used as a central point for exception handling for Java reflection
 // constructor calls
 private <T> T invokeConstructor(
     Class<T> clazz, Class<?>[] argumentClasses, Object[] argumentObjects) {
   try {
     Constructor<T> constructor = clazz.getConstructor(argumentClasses);
     return constructor.newInstance(argumentObjects);
   } catch (IllegalArgumentException e) {
     e.printStackTrace();
   } catch (InstantiationException e) {
     e.printStackTrace();
   } catch (IllegalAccessException e) {
     e.printStackTrace();
   } catch (InvocationTargetException e) {
     e.printStackTrace();
   } catch (SecurityException e) {
     e.printStackTrace();
   } catch (NoSuchMethodException e) {
     e.printStackTrace();
   }
   return null;
 }
コード例 #30
0
ファイル: MapBuilderTest.java プロジェクト: javafunk/funk
  @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?"));
    }
  }