Beispiel #1
0
 /** Convert an exception object to a Json string. */
 public static String toJsonString(final Exception e) {
   final Map<String, Object> m = new TreeMap<String, Object>();
   m.put("exception", e.getClass().getSimpleName());
   m.put("message", e.getMessage());
   m.put("javaClassName", e.getClass().getName());
   return toJsonString(RemoteException.class, m);
 }
  public LeadsIntermediateIterator(String key, String prefix, InfinispanManager imanager, int i) {
    log = LoggerFactory.getLogger(LeadsIntermediateIterator.class);
    this.imanager = imanager;
    // initialize cache
    intermediateDataCache = (Cache) imanager.getPersisentCache(prefix + ".data");
    indexSiteCache = (Cache) imanager.getPersisentCache(prefix + ".indexed");
    baseIntermKey = new ComplexIntermediateKey();
    baseIntermKey.setCounter(currentCounter);
    baseIntermKey.setKey(key);

    // read all the IndexComplexIntermediateKeys with attribute == keys
    this.list = new ArrayList<>();
    try {
      CloseableIterable<Map.Entry<String, Object>> myIterable =
          ((Cache) indexSiteCache)
              .getAdvancedCache()
              .filterEntries(new IndexedComplexIntermKeyFilter(key));
      for (Map.Entry<String, Object> entry : myIterable) {
        //        System.err.println("ADDING TO LIST key: " + entry.getKey() + " value " +
        // entry.getValue().toString());
        if (entry.getValue() instanceof IndexedComplexIntermediateKey) {
          ComplexIntermediateKey c =
              new ComplexIntermediateKey((IndexedComplexIntermediateKey) entry.getValue());
          list.add((IndexedComplexIntermediateKey) entry.getValue());
        } else {
          System.err.println("\n\nGET [B once again");
        }
      }
      // check if the number of iterations is correct //this constructor is for debugging purposes
      if (i != list.size()) {
        System.err.println(
            "iterator size "
                + key
                + " "
                + list.size()
                + " correct number: "
                + i
                + " size of cache with IndexedComplexIntermediateKey "
                + indexSiteCache.size());
      }
    } catch (Exception e) {
      System.err.println("Exception on LeadsIntermediateIterator " + e.getClass().toString());
      System.err.println("Message: " + e.getMessage());
      log.error("Exception on LeadsIntermediateIterator " + e.getClass().toString());
      log.error("Message: " + e.getMessage());
    }

    chunkIterator = list.iterator();

    if (chunkIterator.hasNext()) {
      currentChunk = chunkIterator.next();
      baseIntermKey = new ComplexIntermediateKey(currentChunk);
    } else {
      currentChunk = null;
    }
  }
 /**
  * An exception message formatter used when an exception is thrown by the post-deserialization
  * mechanism.
  *
  * @param exc The exception thrown by the underlying code.
  * @return A new ConversionException with <code>e</code> nested.
  */
 private ConversionException failDeserialize(Exception exc) {
   StringBuffer buffer = new StringBuffer();
   buffer.append("An exception of type ");
   buffer.append(exc.getClass().getName());
   buffer.append(" was thrown by an object while it was being deserialized.");
   return new ConversionException(buffer.toString(), exc);
 }
  /**
   * true if the file esists
   *
   * @param hdfsPath
   * @return
   */
  @Override
  public boolean exists(final String hdfsPath) {
    if (isRunningAsUser()) {
      return super.exists(hdfsPath);
    }
    UserGroupInformation uig = getCurrentUserGroup();
    try {
      //           if(true)    throw new UnsupportedOperationException("Uncomment when using version
      // 1.0.*");
      return uig.doAs(
          new PrivilegedExceptionAction<Boolean>() {

            public Boolean run() throws Exception {
              FileSystem fileSystem = getDFS();

              Path dst = new Path(hdfsPath);

              boolean directory = fileSystem.exists(dst);
              return directory;
            }
          });
    } catch (Exception e) {
      throw new RuntimeException(
          "Failed to copyFromFileSystem because "
              + e.getMessage()
              + " exception of class "
              + e.getClass(),
          e);
    }
    //       return false;
  }
  /**
   * write text to a remote file system
   *
   * @param hdfsPath !null remote path
   * @param content !null test content
   */
  @Override
  public void writeToFileSystem(final String hdfsPath, final String content) {
    if (isRunningAsUser()) {
      super.writeToFileSystem(hdfsPath, content);
      return;
    }
    UserGroupInformation uig = getCurrentUserGroup();
    try {
      //          if(true)    throw new UnsupportedOperationException("Uncomment when using version
      // 1.0.*");
      uig.doAs(
          new PrivilegedExceptionAction<Void>() {

            public Void run() throws Exception {
              FileSystem fs = getDFS();
              Path src = new Path(hdfsPath);
              Path parent = src.getParent();
              guaranteeDirectory(parent);
              OutputStream os = FileSystem.create(fs, src, FULL_FILE_ACCESS);
              FileUtilities.writeFile(os, content);
              return null;
            }
          });
    } catch (Exception e) {
      throw new RuntimeException(
          "Failed to writeToFileSystem because "
              + e.getMessage()
              + " exception of class "
              + e.getClass(),
          e);
    }
  }
 /**
  * @param spaceKey to get info for
  * @return spaces indexing info or null if not found.
  */
 protected SpaceIndexingInfo getLastSpaceIndexingInfo(String spaceKey) {
   SpaceIndexingInfo lastIndexing = lastSpaceIndexingInfo.get(spaceKey);
   if (lastIndexing == null && activityLogIndexName != null) {
     try {
       refreshSearchIndex(activityLogIndexName);
       SearchResponse sr =
           client
               .prepareSearch(activityLogIndexName)
               .setTypes(activityLogTypeName)
               .setPostFilter(
                   FilterBuilders.andFilter(
                       FilterBuilders.termFilter(SpaceIndexingInfo.DOCFIELD_SPACE_KEY, spaceKey),
                       FilterBuilders.termFilter(
                           SpaceIndexingInfo.DOCFIELD_RIVER_NAME, riverName().getName())))
               .setQuery(QueryBuilders.matchAllQuery())
               .addSort(SpaceIndexingInfo.DOCFIELD_START_DATE, SortOrder.DESC)
               .addField("_source")
               .setSize(1)
               .execute()
               .actionGet();
       if (sr.getHits().getTotalHits() > 0) {
         SearchHit hit = sr.getHits().getAt(0);
         lastIndexing = SpaceIndexingInfo.readFromDocument(hit.sourceAsMap());
       } else {
         logger.debug("No last indexing info found in activity log for space {}", spaceKey);
       }
     } catch (Exception e) {
       logger.warn(
           "Error during LastSpaceIndexingInfo reading from activity log ES index: {} {}",
           e.getClass().getName(),
           e.getMessage());
     }
   }
   return lastIndexing;
 }
 public FsPermission getPermissions(final Path src) {
   UserGroupInformation uig = getCurrentUserGroup();
   try {
     //           if(true)    throw new UnsupportedOperationException("Uncomment when using version
     // 1.0.*");
     return uig.doAs(
         new PrivilegedExceptionAction<FsPermission>() {
           public FsPermission run() throws Exception {
             FileSystem fs = getDFS();
             if (fs.exists(src)) {
               FileStatus fileStatus = fs.getFileStatus(src);
               return fileStatus.getPermission();
             }
             return null;
           }
         });
   } catch (Exception e) {
     throw new RuntimeException(
         "Failed to getPermissions because "
             + e.getMessage()
             + " exception of class "
             + e.getClass(),
         e);
   }
   //      return FsPermission.getDefault();
 }
  /**
   * true if the file exists
   *
   * @param hdfsPath !null path - probably of an existing file
   * @return
   */
  @Override
  public long fileLength(final String hdfsPath) {
    if (isRunningAsUser()) {
      return super.fileLength(hdfsPath);
    }
    UserGroupInformation uig = getCurrentUserGroup();
    try {
      //           if(true)    throw new UnsupportedOperationException("Uncomment when using version
      // 1.0.*");
      return uig.doAs(
          new PrivilegedExceptionAction<Long>() {

            public Long run() throws Exception {
              FileSystem fs = getDFS();

              if (!exists(hdfsPath)) return null;
              Path src = new Path(hdfsPath);
              ContentSummary contentSummary = fs.getContentSummary(src);
              if (contentSummary == null) return null;
              return contentSummary.getLength();
            }
          });
    } catch (Exception e) {
      throw new RuntimeException(
          "Failed to get fileLength because "
              + e.getMessage()
              + " exception of class "
              + e.getClass(),
          e);
    }
  }
  @Override
  public void writeToFileSystem(final String hdfsPath, final File localPath) {
    if (isRunningAsUser()) {
      super.writeToFileSystem(hdfsPath, localPath);
      return;
    }
    UserGroupInformation uig = getCurrentUserGroup();
    try {
      //           if(true)    throw new UnsupportedOperationException("Uncomment when using version
      // 1.0.*");
      uig.doAs(
          new PrivilegedExceptionAction<Void>() {

            public Void run() throws Exception {
              FileSystem fileSystem = getDFS();

              Path dst = new Path(hdfsPath);

              Path src = new Path(localPath.getAbsolutePath());

              fileSystem.copyFromLocalFile(src, dst);
              fileSystem.setPermission(dst, FULL_FILE_ACCESS);
              return null;
            }
          });
    } catch (Exception e) {
      throw new RuntimeException(
          "Failed to writeToFileSystem because "
              + e.getMessage()
              + " exception of class "
              + e.getClass(),
          e);
    }
  }
Beispiel #10
0
 // User defined finders/Buscadores definidos por el usuario
 public static Size findById(int id) throws javax.ejb.ObjectNotFoundException {
   if (XavaPreferences.getInstance().isJPAPersistence()) {
     javax.persistence.Query query =
         org.openxava.jpa.XPersistence.getManager()
             .createQuery("from Size as o where o.id = :arg0");
     query.setParameter("arg0", new Integer(id));
     try {
       return (Size) query.getSingleResult();
     } catch (Exception ex) {
       // In this way in order to work with Java pre 5
       if (ex.getClass().getName().equals("javax.persistence.NoResultException")) {
         throw new javax.ejb.ObjectNotFoundException(
             XavaResources.getString("object_not_found", "Size"));
       } else {
         ex.printStackTrace();
         throw new RuntimeException(ex.getMessage());
       }
     }
   } else {
     org.hibernate.Query query =
         org.openxava.hibernate.XHibernate.getSession()
             .createQuery("from Size as o where o.id = :arg0");
     query.setParameter("arg0", new Integer(id));
     Size r = (Size) query.uniqueResult();
     if (r == null) {
       throw new javax.ejb.ObjectNotFoundException(
           XavaResources.getString("object_not_found", "Size"));
     }
     return r;
   }
 }
Beispiel #11
0
  private synchronized void init() throws SQLException {
    if (isClosed) return;

    // do tables exists?
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery(TABLE_NAMES_SELECT_STMT);

    ArrayList<String> missingTables = new ArrayList(TABLES.keySet());
    while (rs.next()) {
      String tableName = rs.getString("name");
      missingTables.remove(tableName);
    }

    for (String missingTable : missingTables) {
      try {
        Statement createStmt = conn.createStatement();
        // System.out.println("Adding table "+ missingTable);
        createStmt.executeUpdate(TABLES.get(missingTable));
        createStmt.close();

      } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
      }
    }
  }
  protected HDFWithNameAccessor(final String host, final int port, final String user) {
    super(host, port, user);
    if (port <= 0) throw new IllegalArgumentException("bad port " + port);
    String connectString = "hdfs://" + host + ":" + port + "/";
    final String userDir = "/user/" + user;

    UserGroupInformation uig = getCurrentUserGroup();
    try {
      //          if(true)    throw new UnsupportedOperationException("Uncomment when using version
      // 1.0.*");

      uig.doAs(
          new PrivilegedExceptionAction<Void>() {

            public Void run() throws Exception {
              getDFS();
              return null;
            }
          });
    } catch (Exception e) {
      throw new RuntimeException(
          "Failed to connect on "
              + connectString
              + " because "
              + e.getMessage()
              + " exception of class "
              + e.getClass(),
          e);
    }
  }
Beispiel #13
0
 private void handleException(Exception e) {
   if (INTERRUPTED_EXCEPTION_TYPES.contains(e.getClass())) {
     LOG.info("Changes feed was interrupted");
   } else {
     LOG.error("Caught exception while listening to changes feed:", e);
   }
 }
 // User defined finders/Buscadores definidos por el usuario
 public static FilterBySubfamily findBy() throws javax.ejb.ObjectNotFoundException {
   if (XavaPreferences.getInstance().isJPAPersistence()) {
     javax.persistence.Query query =
         org.openxava.jpa.XPersistence.getManager().createQuery("from FilterBySubfamily as o");
     try {
       return (FilterBySubfamily) query.getSingleResult();
     } catch (Exception ex) {
       // In this way in order to work with Java pre 5
       if (ex.getClass().getName().equals("javax.persistence.NoResultException")) {
         throw new javax.ejb.ObjectNotFoundException(
             XavaResources.getString("object_not_found", "FilterBySubfamily"));
       } else {
         ex.printStackTrace();
         throw new RuntimeException(ex.getMessage());
       }
     }
   } else {
     org.hibernate.Query query =
         org.openxava.hibernate.XHibernate.getSession().createQuery("from FilterBySubfamily as o");
     FilterBySubfamily r = (FilterBySubfamily) query.uniqueResult();
     if (r == null) {
       throw new javax.ejb.ObjectNotFoundException(
           XavaResources.getString("object_not_found", "FilterBySubfamily"));
     }
     return r;
   }
 }
  /**
   * read a remote file as text
   *
   * @param hdfsPath !null remote path to an existing file
   * @return content as text
   */
  @Override
  public String readFromFileSystem(final String hdfsPath) {
    if (isRunningAsUser()) {
      return super.readFromFileSystem(hdfsPath);
    }
    UserGroupInformation uig = getCurrentUserGroup();
    try {
      //           if(true)    throw new UnsupportedOperationException("Uncomment when using version
      // 1.0.*");
      return uig.doAs(
          new PrivilegedExceptionAction<String>() {

            public String run() throws Exception {
              FileSystem fs = getDFS();
              Path src = new Path(hdfsPath);
              InputStream is = fs.open(src);
              String ret = FileUtilities.readInFile(is);
              return ret;
            }
          });
    } catch (Exception e) {
      throw new RuntimeException(
          "Failed to readFromFileSystem because "
              + e.getMessage()
              + " exception of class "
              + e.getClass(),
          e);
    }
    //    return null;
  }
  private void guaranteeDirectory(final Path src) {
    UserGroupInformation uig = getCurrentUserGroup();
    try {
      //          if(true)    throw new UnsupportedOperationException("Uncomment when using version
      // 1.0.*");
      uig.doAs(
          new PrivilegedExceptionAction<Void>() {

            public Void run() throws Exception {
              FileSystem fs = getDFS();

              if (fs.exists(src)) return null;
              if (!fs.isFile(src)) {
                return null;
              } else {
                fs.delete(src, false); // drop a file we want a directory
              }
              fs.setPermission(src, FULL_ACCESS);
              fs.mkdirs(src, FULL_ACCESS);
              return null;
            }
          });
    } catch (Exception e) {
      throw new RuntimeException(
          "Failed to guaranteeDirectory because "
              + e.getMessage()
              + " exception of class "
              + e.getClass(),
          e);
    }
  }
 /** 删除操作 平台没有处理的异常的默认处理 */
 protected void dealOtherDeleteException(Json json, Exception e) {
   if ((e.getCause() != null
           && e.getCause().getClass().getSimpleName().equals("ConstraintViolationException"))
       || (e.getCause() != null
           && e.getCause().getCause() != null
           && e.getCause()
               .getCause()
               .getClass()
               .getSimpleName()
               .equals("ConstraintViolationException"))) {
     // 违反约束关联引发的异常
     json.put("msg", getText("exception.delete.constraintViolation"));
     json.put("e", e.getClass().getSimpleName());
   } else {
     // 其他异常
     json.put("msg", e.getMessage() != null ? e.getMessage() : e.toString());
     json.put("e", e.getClass().getSimpleName());
   }
 }
 @Koan
 public void insufficientArgumentsToStringFormatCausesAnError() {
   try {
     String.format("%s %s %s", "a", "b");
     fail("No Exception was thrown!");
   } catch (Exception e) {
     assertEquals(e.getClass(), __);
     assertEquals(e.getMessage(), __);
   }
 }
Beispiel #19
0
 @Koan
 public void insufficientArgumentsToStringFormatCausesAnError() {
   try {
     String.format("%s %s %s", "a", "b");
     fail("No Exception was thrown!");
   } catch (Exception e) {
     assertEquals(e.getClass(), java.util.MissingFormatArgumentException.class);
     assertEquals(e.getMessage(), "Format specifier 's'");
   }
 }
  public MongoDBJDBC() {
    try {
      // To connect to mongodb server
      mongoClient = new MongoClient("localhost", 27017);

      // Now connect to your databases
      db = mongoClient.getDB("highschool");
      System.out.println("Connect to database successfully");
    } catch (Exception e) {
      System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
  }
Beispiel #21
0
 /**
  * Generate an exception message
  *
  * @param aException The Exception object
  * @return A representation of the exception which is appropriate for the client type
  */
 public String generateExceptionMessage(Exception aException) {
   StringBuffer retVal = new StringBuffer("<?xml version=\"1.0\"?>\n");
   retVal.append(
       "<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.1//EN\" \"http://www.wapforum.org/DTD/wml_1.1.xml\">\n");
   retVal.append("<wml>\n");
   retVal.append("<card><p>\n");
   retVal.append("[HTTPEventTranslator Error (");
   retVal.append(aException.getClass().toString());
   retVal.append(")]\n");
   retVal.append("</p></card>\n");
   retVal.append("</wml>");
   return retVal.toString();
 }
Beispiel #22
0
 // Call a javascript function. Valid arguments can null, string and numbers.
 public void func_call(String func, Object... args) {
   try {
     _func_call(func, Arrays.asList(args));
   } catch (Exception e) {
     if (func != this.js_debug_func) {
       // Send debug information about the missed call.
       this.debug(
           1,
           "jscomm",
           "func_call() exception: '" + e.getClass().toString() + ": '" + e.getMessage() + "'");
     } else {
       // Avoid loop...
       System.out.println(
           "func_call() debug exception: '"
               + e.getClass().toString()
               + ": '"
               + e.getMessage()
               + "'");
     }
     e.printStackTrace();
   }
 }
Beispiel #23
0
  public void run() {
    // each file is processed into a local hash table and then merged with the global results
    // this will cause much less contention on the global table, but still avoids a sequential
    // update
    Hashtable<String, Integer> local_results =
        new Hashtable<String, Integer>(WordCountJ.HASH_SIZE, WordCountJ.LF);
    // grab a file to work on
    String cf;
    while ((cf = files.poll()) != null) {
      try {
        BufferedReader input = new BufferedReader(new FileReader(cf));
        String text;
        // well go line-by-line... maybe this is not the fastest
        while ((text = input.readLine()) != null) {
          // parse words
          Matcher matcher = pattern.matcher(text);
          while (matcher.find()) {
            String word = matcher.group(1);
            if (local_results.containsKey(word)) {
              local_results.put(word, 1 + local_results.get(word));
            } else {
              local_results.put(word, 1);
            }
          }
        }
        input.close();
      } catch (Exception e) {
        System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage());
        return;
      }
      // merge local hashmap with shared one,could have a
      // seperate thread do this but that might be cheating

      Iterator<Map.Entry<String, Integer>> updates = local_results.entrySet().iterator();
      while (updates.hasNext()) {
        Map.Entry<String, Integer> kv = updates.next();
        String k = kv.getKey();
        Integer v = kv.getValue();
        synchronized (results) {
          if (results.containsKey(k)) {
            results.put(k, v + results.get(k));
          } else {
            results.put(k, v);
          }
        }
      }
      local_results.clear();
    }
  }
 // ------------------- remove( tree, key, title ) --------------------------
 private static void remove(BinarySearchTree bst, String key, String title) {
   if (title != null) {
     System.out.println("---------------- " + title + " ---------------");
     System.out.println(bst.inOrderString() + "\n---\n" + bst);
   }
   System.out.println("---- Removing: " + key);
   try {
     Data d = bst.delete(key);
     if (d == null) System.out.println("********** Not found ");
     else System.out.println(bst.inOrderString() + "\n---\n" + bst);
   } catch (Exception ex) {
     System.out.println("A test failed: " + ex.getClass().getName() + ": " + ex.getMessage());
     System.out.println("+++++++++++++++++++++++++++++++++++++++++++++");
     exceptionCount++;
   }
 }
 public HGWorldlyThings(Plugin plugin, HGMessageManagement msg, HGConfig cfg) {
   this.msg = msg;
   this.cfg = cfg;
   worldlyProperties = new Properties();
   worldlyPropertiesFile = new File(HGStatics.WORLDLY_PROPERTIES);
   try {
     manageWorldlyPropertyFiles();
   } catch (Exception e) {
     msg.severe(
         (new StringBuilder("Caught "))
             .append(e.getClass().getName())
             .append(" in HGWorldlyThings().")
             .toString());
     e.printStackTrace();
   }
 }
 @Nullable
 private List<Task> getIssuesFromRepositories(
     @Nullable String request,
     int max,
     long since,
     boolean forceRequest,
     @NotNull final ProgressIndicator cancelled) {
   List<Task> issues = null;
   for (final TaskRepository repository : getAllRepositories()) {
     if (!repository.isConfigured() || (!forceRequest && myBadRepositories.contains(repository))) {
       continue;
     }
     try {
       Task[] tasks = repository.getIssues(request, max, since, cancelled);
       myBadRepositories.remove(repository);
       if (issues == null) issues = new ArrayList<Task>(tasks.length);
       if (!repository.isSupported(TaskRepository.NATIVE_SEARCH) && request != null) {
         List<Task> filteredTasks =
             TaskSearchSupport.filterTasks(request, ContainerUtil.list(tasks));
         ContainerUtil.addAll(issues, filteredTasks);
       } else {
         ContainerUtil.addAll(issues, tasks);
       }
     } catch (ProcessCanceledException ignored) {
       // OK
     } catch (Exception e) {
       String reason = "";
       // Fix to IDEA-111810
       if (e.getClass() == Exception.class) {
         // probably contains some message meaningful to end-user
         reason = e.getMessage();
       }
       //noinspection InstanceofCatchParameter
       if (e instanceof SocketTimeoutException) {
         LOG.warn("Socket timeout from " + repository);
       } else {
         LOG.warn("Cannot connect to " + repository, e);
       }
       myBadRepositories.add(repository);
       if (forceRequest) {
         notifyAboutConnectionFailure(repository, reason);
       }
     }
   }
   return issues;
 }
  /**
   * The method to be called by {@link ObjectMapper} and {@link ObjectWriter} for serializing given
   * value, using serializers that this provider has access to (via caching and/or creating new
   * serializers as need be).
   */
  public void serializeValue(JsonGenerator jgen, Object value)
      throws IOException, JsonGenerationException {
    JsonSerializer<Object> ser;
    final boolean wrap;

    if (value == null) { // no type provided; must just use the default null serializer
      ser = getDefaultNullValueSerializer();
      wrap = false; // no name to use for wrapping; can't do!
    } else {
      Class<?> cls = value.getClass();
      // true, since we do want to cache root-level typed serializers (ditto for null property)
      ser = findTypedValueSerializer(cls, true, null);

      // Ok: should we wrap result in an additional property ("root name")?
      String rootName = _config.getRootName();
      if (rootName == null) { // not explicitly specified
        // [JACKSON-163]
        wrap = _config.isEnabled(SerializationFeature.WRAP_ROOT_VALUE);
        if (wrap) {
          jgen.writeStartObject();
          jgen.writeFieldName(_rootNames.findRootName(value.getClass(), _config));
        }
      } else if (rootName.length() == 0) {
        wrap = false;
      } else { // [JACKSON-764]
        // empty String means explicitly disabled; non-empty that it is enabled
        wrap = true;
        jgen.writeStartObject();
        jgen.writeFieldName(rootName);
      }
    }
    try {
      ser.serialize(value, jgen, this);
      if (wrap) {
        jgen.writeEndObject();
      }
    } catch (IOException ioe) { // As per [JACKSON-99], pass IOException and subtypes as-is
      throw ioe;
    } catch (Exception e) { // but wrap RuntimeExceptions, to get path information
      String msg = e.getMessage();
      if (msg == null) {
        msg = "[no message for " + e.getClass().getName() + "]";
      }
      throw new JsonMappingException(msg, e);
    }
  }
 /** 获取删除操作的异常提示信息 */
 protected String getDeleteExceptionMsg(Exception e) {
   if (e instanceof PermissionDeniedException) {
     return e.getMessage() == null ? getText("exception.delete.permissionDenied") : e.getMessage();
   } else if (e instanceof InnerLimitedException) {
     return e.getMessage() == null ? getText("exception.delete.innerLimited") : e.getMessage();
   } else if (e instanceof NotExistsException) {
     return e.getMessage() == null ? getText("exception.delete.notExists") : e.getMessage();
   } else if (e instanceof ConstraintViolationException // 数据约束
       || e.getClass().getName().contains("ConstraintViolationException")
       || (e.getCause() != null
           && e.getCause().getClass().getName().contains("ConstraintViolationException"))) {
     return e.getMessage() == null
         ? getText("exception.delete.constraintViolation")
         : e.getMessage();
   } else {
     return e.getMessage();
   }
 }
Beispiel #29
0
    public void run() {
      try {
        BufferedReader br =
            new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
        if (outputFile != null) {
          bw =
              new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), charset));
        }
        String line;
        while ((line = br.readLine()) != null) {
          filePosition += line.length() + 2;
          line = line.trim();
          if (!line.startsWith("#")) {
            String[] sides = split(line);
            if ((sides != null) && !sides[0].equals("key")) {

              if (searchPHI) {
                // Search the decrypted PHI for the searchText
                sides[0] = decrypt(sides[0]);
                if (sides[0].indexOf(searchText) != -1) {
                  output(sides[0] + " = " + sides[1] + "\n");
                }
              } else {
                // Search the trial ID for the searchText
                if (sides[1].indexOf(searchText) != -1) {
                  sides[0] = decrypt(sides[0]);
                  output(sides[0] + " = " + sides[1] + "\n");
                }
              }
            }
          }
        }
        br.close();
        if (bw != null) {
          bw.flush();
          bw.close();
        }
      } catch (Exception e) {
        append("\n\n" + e.getClass().getName() + ": " + e.getMessage() + "\n");
      }
      append("\nDone.\n");
      setMessage("Ready...");
    }
  /**
   * delete a directory and all enclosed files and directories
   *
   * @param hdfsPath !null path
   * @return true on success
   */
  @Override
  public boolean expunge(final String hdfsPath) {
    if (isRunningAsUser()) {
      return super.expunge(hdfsPath);
    }
    UserGroupInformation uig = getCurrentUserGroup();
    try {
      //           if(true)    throw new UnsupportedOperationException("Uncomment when using version
      // 1.0.*");
      return uig.doAs(
          new PrivilegedExceptionAction<Boolean>() {

            public Boolean run() throws Exception {
              FileSystem fs = getDFS();

              Path src = new Path(hdfsPath);

              boolean ret = true;
              if (!fs.exists(src)) {
                return ret;
              }
              // break these out
              if (fs.getFileStatus(src).isDir()) {
                boolean doneOK = fs.delete(src, true);
                doneOK = !fs.exists(src);
                ret = doneOK;
                return ret;
              }
              if (fs.isFile(src)) {
                boolean doneOK = fs.delete(src, false);
                ret = doneOK;
                return ret;
              }
              throw new IllegalStateException("should be file of directory if it exists");
            }
          });

    } catch (Exception e) {
      throw new RuntimeException(
          "Failed to expunge because " + e.getMessage() + " exception of class " + e.getClass(), e);
    }
    //      return false;
  }