예제 #1
0
 @Override
 public PackageConfiguration responseMessageForPackageConfiguration(String responseBody) {
   try {
     PackageConfiguration packageConfiguration = new PackageConfiguration();
     Map<String, Map> configurations;
     try {
       configurations = parseResponseToMap(responseBody);
     } catch (Exception e) {
       throw new RuntimeException("Package configuration should be returned as a map");
     }
     if (configurations == null || configurations.isEmpty()) {
       throw new RuntimeException("Empty response body");
     }
     for (String key : configurations.keySet()) {
       if (isEmpty(key)) {
         throw new RuntimeException("Package configuration key cannot be empty");
       }
       if (!(configurations.get(key) instanceof Map)) {
         throw new RuntimeException(
             format(
                 "Package configuration properties for key '%s' should be represented as a Map",
                 key));
       }
       packageConfiguration.add(toPackageMaterialProperty(key, configurations.get(key)));
     }
     return packageConfiguration;
   } catch (RuntimeException e) {
     throw new RuntimeException(
         format("Unable to de-serialize json response. %s", e.getMessage()));
   }
 }
 public void testExceptionHandling() {
   final ComponentAdapter componentAdapter =
       new ThreadLocalizing.ThreadLocalized(
           new ConstructorInjection.ConstructorInjector(
               TargetInvocationExceptionTester.class, ThrowingComponent.class, null));
   final TargetInvocationExceptionTester tester =
       (TargetInvocationExceptionTester)
           componentAdapter.getComponentInstance(null, ComponentAdapter.NOTHING.class);
   try {
     tester.throwsCheckedException();
     fail("ClassNotFoundException expected");
   } catch (final ClassNotFoundException e) {
     assertEquals("junit", e.getMessage());
   }
   try {
     tester.throwsRuntimeException();
     fail("RuntimeException expected");
   } catch (final RuntimeException e) {
     assertEquals("junit", e.getMessage());
   }
   try {
     tester.throwsError();
     fail("Error expected");
   } catch (final Error e) {
     assertEquals("junit", e.getMessage());
   }
 }
예제 #3
0
  /**
   * This function takes a perl5 regular expression as the pattern to perform pattern matching and
   * string substitution.
   *
   * <p>"s/pattern/replacement/[g][i][m][o][s][x]"
   *
   * <p>g - substitute globally (all occurence) i - case insensitive m - treat the input as
   * consisting of multiple lines o - interpolate once s - treat the input as consisting of a single
   * line x - enable extended expression syntax incorporating whitespace and comments
   *
   * <p>to perform string substitution. Unless the [g] option is specified, the dafault is to
   * replace only the first occurrence.
   *
   * @param perl5Pattern - Perl5 regular expression
   * @param input - input string
   * @return result - processed string. The original input is returned when there is no match
   * @exception - FrameworkException is thrown when either pattern or input is null
   */
  public static String substitute(String perl5Pattern, String input) throws FrameworkException {
    if ((perl5Pattern == null) || (input == null)) {
      throw new FrameworkException(
          "RegexUtil: replaceAll(): Either input or pattern is null."
              + "input = "
              + input
              + ", "
              + "pattern = "
              + perl5Pattern);
    }

    if (Debug.isLevelEnabled(Debug.MSG_STATUS)) {
      Debug.log(
          Debug.MSG_STATUS,
          "RegexUtils: replaceAll: perl5Pattern = " + perl5Pattern + " input = " + input);
    }

    Perl5Util util = new Perl5Util();
    String result = input;

    try {
      result = util.substitute(perl5Pattern, input);
    } catch (RuntimeException e) {
      throw new FrameworkException("RegexUtils: substitute: " + e.getMessage());
    }

    return result;
  }
    /*MUST be called under the WriteLock*/
    @NotNull
    private Map<Integer, SerializedStubTree> readOldData(final int key) throws StorageException {
      final Map<Integer, SerializedStubTree> result = new HashMap<Integer, SerializedStubTree>();

      IndexStorage<Integer, SerializedStubTree> indexStorage = myStorage;
      if (indexStorage instanceof MemoryIndexStorage) {
        final MemoryIndexStorage<Integer, SerializedStubTree> memIndexStorage =
            (MemoryIndexStorage<Integer, SerializedStubTree>) indexStorage;
        if (!memIndexStorage.isBufferingEnabled()) {
          // if buffering is not enabled, use backend storage to make sure
          // the returned stub tree contains no data corresponding to unsaved documents.
          // This will ensure that correct set of old keys is used for update
          indexStorage = memIndexStorage.getBackendStorage();
        }
      }
      try {
        final ValueContainer<SerializedStubTree> valueContainer = indexStorage.read(key);
        if (valueContainer.size() != 1) {
          LOG.assertTrue(valueContainer.size() == 0);
          return result;
        }

        result.put(key, valueContainer.getValueIterator().next());
        return result;
      } catch (RuntimeException e) {
        final Throwable cause = e.getCause();
        if (cause instanceof IOException) {
          throw new StorageException(cause);
        }
        throw e;
      }
    }
 public void setMetricsReportingDisabled() {
   try {
     metricReportingService.setMetricsReportingDisabled();
   } catch (RuntimeException e) {
     throw new ConfigurationException("Error enabling metric reporting: " + e.getMessage(), e);
   }
 }
예제 #6
0
 void setFormData(WObject.FormData formData) {
   if (!(formData.values.length == 0)) {
     List<String> attributes = new ArrayList<String>();
     attributes = new ArrayList<String>(Arrays.asList(formData.values[0].split(";")));
     if (attributes.size() == 6) {
       try {
         this.volume_ = Double.parseDouble(attributes.get(0));
       } catch (RuntimeException e) {
         this.volume_ = -1;
       }
       try {
         this.current_ = Double.parseDouble(attributes.get(1));
       } catch (RuntimeException e) {
         this.current_ = -1;
       }
       try {
         this.duration_ = Double.parseDouble(attributes.get(2));
       } catch (RuntimeException e) {
         this.duration_ = -1;
       }
       this.playing_ = attributes.get(3).equals("0");
       this.ended_ = attributes.get(4).equals("1");
       try {
         this.readyState_ = intToReadyState(Integer.parseInt(attributes.get(5)));
       } catch (RuntimeException e) {
         throw new WException(
             "WAbstractMedia: error parsing: " + formData.values[0] + ": " + e.toString());
       }
     } else {
       throw new WException("WAbstractMedia: error parsing: " + formData.values[0]);
     }
   }
 }
예제 #7
0
  private synchronized void updateAlarms() {
    //        activeAlarms.clear();
    for (TagBlankEntity tagBlankEntity : deviceEntity.getTagBlankEntities()) {
      for (AlarmBlank alarmBlank : tagBlankEntity.getAlarmBlanks()) {
        StringBuffer sb = new StringBuffer();

        try {
          sb.append(values.get(tagBlankEntity.getTagDescr()).getRegister());
          sb.append(alarmBlank.getCondition());
          String script = sb.toString();
          Boolean res = (Boolean) AlarmUtil.getInstance().getScriptEngine().eval(script);
          Alarm alarm = new Alarm(alarmBlank);
          if (res == true) {
            if (activeAlarms.contains(alarm)) {
              continue;
            } else {
              activeAlarms.add(alarm);
              AlarmEntity alarmEntity = new AlarmEntity();
              alarmEntity.setAlarmBlank(alarmBlank);
              alarmEntity.setAlarmTime(alarm.getStartTime());
              DataHelper.getInstance().saveAlarm(alarmEntity);
            }
          } else {
            if (activeAlarms.contains(alarm)) {
              activeAlarms.remove(alarm);
            }
          }
        } catch (RuntimeException ex) {
          ex.printStackTrace();
        } catch (ScriptException e) {
          e.printStackTrace();
        }
      }
    }
  }
  @Test
  public void testGetTemporaryFilesThrowsIfCompletingAfterObsoletion() throws Throwable {
    ColumnFamilyStore cfs = MockSchema.newCFS(KEYSPACE);
    File dataFolder = new Directories(cfs.metadata).getDirectoryForNewSSTables();
    SSTableReader sstable = sstable(dataFolder, cfs, 0, 128);

    LogTransaction logs = new LogTransaction(OperationType.COMPACTION);
    assertNotNull(logs);

    LogTransaction.SSTableTidier tidier = logs.obsoleted(sstable);

    sstable.markObsolete(tidier);
    sstable.selfRef().release();

    LogTransaction.waitForDeletions();

    try {
      // This should race with the asynchronous deletion of txn log files
      // it should throw because we are violating the requirement that a transaction must
      // finish before deleting files (i.e. releasing sstables)
      getTemporaryFiles(dataFolder);
      fail("Expected runtime exception");
    } catch (RuntimeException e) {
      // pass as long as the cause is not an assertion
      assertFalse(e.getCause() instanceof AssertionError);
    }

    logs.finish();
  }
 public void setMetricsReportingStmtDisabled(String statementName) {
   try {
     metricReportingService.setMetricsReportingStmtDisabled(statementName);
   } catch (RuntimeException e) {
     throw new ConfigurationException(
         "Error enabling metric reporting for statement: " + e.getMessage(), e);
   }
 }
 public void setMetricsReportingInterval(String stmtGroupName, long newInterval) {
   try {
     metricReportingService.setMetricsReportingInterval(stmtGroupName, newInterval);
   } catch (RuntimeException e) {
     throw new ConfigurationException(
         "Error updating interval for metric reporting: " + e.getMessage(), e);
   }
 }
예제 #11
0
  public void appendMessages(List<AnalyzedMessage> newMessages) {
    if (newMessages.size() == 0) return;

    List<AnalyzedMessage> oldMessages = new ArrayList<>(messages);

    if (messageFilter != null) newMessages = CUtils.filter(newMessages, messageFilter);

    messages.addAll(newMessages);

    List<StyleNode> msgNodes =
        CUtils.map(
            newMessages,
            m -> {
              StyleNode n = builder.buildMessage(m);
              n.updateTree(NStyleUtils.getTemplateManager());
              return n;
            });
    rootMessageStyleNodes.addAll(msgNodes);

    List<StyleNode> appendNodes = new ArrayList<>();
    List<StyleNode> removeNodes = new ArrayList<>();

    if (oldMessages.size() > 0) {
      appendNodes.add(builder.buildTemplate("message_separator"));

      if (newMessages.size() > 0) {
        if (newMessageSeparatorNode != null) removeNodes.add(newMessageSeparatorNode);
        newMessageSeparatorNode = builder.buildTemplate("new_message_separator");
        if (newMessageSeparatorNode != null) appendNodes.add(newMessageSeparatorNode);
      }
    }

    for (int i = 0; i < msgNodes.size(); i++) {
      StyleNode n = msgNodes.get(i);
      appendNodes.add(n);

      if (i < msgNodes.size() - 1) appendNodes.add(builder.buildTemplate("message_separator"));
    }

    if (endMarginTemplateId != null) {
      if (endMarginNode != null) removeNodes.add(endMarginNode);
      endMarginNode = builder.buildTemplate(endMarginTemplateId);
      appendNodes.add(endMarginNode);
    }

    runWithNoRedraw(
        () -> {
          CUtils.forEach(removeNodes, node -> node.getParent().removeChild(node));

          getRootStyleNode().addChildAll(appendNodes);

          try {
            getRootStyleNode().updateTree(NStyleUtils.getTemplateManager());
          } catch (RuntimeException e) {
            DialogUtils.openError(null, "Script error", e.toString());
          }
        });
  }
예제 #12
0
 private void doDisableMetadataIndexing() {
   ArchivalUnit au = getAu();
   if (au == null) return;
   try {
     disableMetadataIndexing(au, false);
   } catch (RuntimeException e) {
     log.error("Can't disable metadata indexing", e);
     errMsg = "Error: " + e.toString();
   }
 }
예제 #13
0
 private void forceReindexMetadata() {
   ArchivalUnit au = getAu();
   if (au == null) return;
   try {
     startReindexingMetadata(au, true);
   } catch (RuntimeException e) {
     log.error("Can't reindex metadata", e);
     errMsg = "Error: " + e.toString();
   }
 }
예제 #14
0
 @Override
 public boolean getBooleanProperty(String name) {
   try {
     return properties.getBooleanProperty(new SimpleString(name));
   } catch (HornetQPropertyConversionException ce) {
     throw new MessageFormatRuntimeException(ce.getMessage());
   } catch (RuntimeException e) {
     throw new JMSRuntimeException(e.getMessage());
   }
 }
예제 #15
0
 @Override
 public JMSProducer clearProperties() {
   try {
     stringPropertyNames.clear();
     properties.clear();
   } catch (RuntimeException e) {
     throw new JMSRuntimeException(e.getMessage());
   }
   return this;
 }
예제 #16
0
 private void uglyjoglhack() throws InterruptedException {
   try {
     display();
   } catch (RuntimeException e) {
     if (e.getCause() instanceof InterruptedException) {
       throw ((InterruptedException) e.getCause());
     } else {
       throw (e);
     }
   }
 }
  protected void notifyOfReject(
      Context context, BasicWorkflowItem workflowItem, EPerson e, String reason) {
    try {
      // Get the item title
      String title = getItemTitle(workflowItem);

      // Get the collection
      Collection coll = workflowItem.getCollection();

      // Get rejector's name
      String rejector = getEPersonName(e);
      Locale supportedLocale = I18nUtil.getEPersonLocale(e);
      Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "submit_reject"));

      email.addRecipient(workflowItem.getSubmitter().getEmail());
      email.addArgument(title);
      email.addArgument(coll.getName());
      email.addArgument(rejector);
      email.addArgument(reason);
      email.addArgument(getMyDSpaceLink());

      email.send();
    } catch (RuntimeException re) {
      // log this email error
      log.warn(
          LogManager.getHeader(
              context,
              "notify_of_reject",
              "cannot email user eperson_id="
                  + e.getID()
                  + " eperson_email="
                  + e.getEmail()
                  + " workflow_item_id="
                  + workflowItem.getID()
                  + ":  "
                  + re.getMessage()));

      throw re;
    } catch (Exception ex) {
      // log this email error
      log.warn(
          LogManager.getHeader(
              context,
              "notify_of_reject",
              "cannot email user eperson_id="
                  + e.getID()
                  + " eperson_email="
                  + e.getEmail()
                  + " workflow_item_id="
                  + workflowItem.getID()
                  + ":  "
                  + ex.getMessage()));
    }
  }
예제 #18
0
 protected void fireChangeListeners() {
   if (changeListeners == null) return;
   for (int a = 0; a < changeListeners.size(); a++) {
     ChangeListener l = (ChangeListener) changeListeners.get(a);
     try {
       l.stateChanged(new ChangeEvent(this));
     } catch (RuntimeException e) {
       e.printStackTrace();
     }
   }
 }
예제 #19
0
 @Override
 public JMSProducer setProperty(String name, Object value) {
   checkName(name);
   try {
     TypedProperties.setObjectProperty(new SimpleString(name), value, properties);
   } catch (HornetQPropertyConversionException hqe) {
     throw new MessageFormatRuntimeException(hqe.getMessage());
   } catch (RuntimeException e) {
     throw new JMSRuntimeException(e.getMessage());
   }
   return this;
 }
예제 #20
0
 @Override
 public void write(@SuppressWarnings("NullableProblems") byte[] bytes) {
   try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file, true))) {
     bos.write(bytes);
     bos.close();
   } catch (IOException e) {
     RuntimeException ex =
         new RuntimeException("Unable to write to file " + file.getAbsolutePath());
     ex.initCause(e);
     throw ex;
   }
 }
예제 #21
0
 @Override
 public String getStringProperty(String name) {
   try {
     SimpleString prop = properties.getSimpleStringProperty(new SimpleString(name));
     if (prop == null) return null;
     return prop.toString();
   } catch (HornetQPropertyConversionException ce) {
     throw new MessageFormatRuntimeException(ce.getMessage());
   } catch (RuntimeException e) {
     throw new JMSRuntimeException(e.getMessage());
   }
 }
예제 #22
0
 @Override
 protected void tearDown() throws Exception {
   try {
     super.tearDown();
   } catch (RuntimeException exception) {
     // TODO: Fix inability to free pointer for runtimejar in
     // JetWithJdkAndRuntimeLightProjectDescriptor
     if (!(exception.getMessage().contains("runtimejar")
         && exception.getMessage().contains("Virtual pointer hasn't been disposed"))) {
       throw exception;
     }
   }
 }
예제 #23
0
 @Override
 public Object getObjectProperty(String name) {
   try {
     SimpleString key = new SimpleString(name);
     Object property = properties.getProperty(key);
     if (stringPropertyNames.contains(key)) {
       property = property.toString();
     }
     return property;
   } catch (HornetQPropertyConversionException ce) {
     throw new MessageFormatRuntimeException(ce.getMessage());
   } catch (RuntimeException e) {
     throw new JMSRuntimeException(e.getMessage());
   }
 }
예제 #24
0
  @Override
  public Set<String> getPropertyNames() {
    try {
      Set<String> propNames = new HashSet<String>();

      for (SimpleString str : properties.getPropertyNames()) {
        propNames.add(str.toString());
      }
      return propNames;
    } catch (HornetQPropertyConversionException ce) {
      throw new MessageFormatRuntimeException(ce.getMessage());
    } catch (RuntimeException e) {
      throw new JMSRuntimeException(e.getMessage());
    }
  }
  public void startElement(String uri, String localName, String qName, Attributes attrs)
      throws SAXException {
    try {
      final String S_ProcName = "startElement";
      assert qName.equals("Tenant");

      CFSecuritySaxLoader saxLoader = (CFSecuritySaxLoader) getParser();
      if (saxLoader == null) {
        throw CFLib.getDefaultExceptionFactory()
            .newNullArgumentException(getClass(), S_ProcName, 0, "getParser()");
      }

      ICFSecuritySchemaObj schemaObj = saxLoader.getSchemaObj();
      if (schemaObj == null) {
        throw CFLib.getDefaultExceptionFactory()
            .newNullArgumentException(getClass(), S_ProcName, 0, "getParser().getSchemaObj()");
      }

      CFLibXmlCoreContext curContext = getParser().getCurContext();

      ICFSecurityTenantObj useTenant = saxLoader.getUseTenant();
      if (useTenant == null) {
        throw CFLib.getDefaultExceptionFactory()
            .newNullArgumentException(getClass(), S_ProcName, 0, "saxLoader.useTenant");
      }

      curContext.putNamedValue("Object", useTenant);
    } catch (RuntimeException e) {
      throw new RuntimeException(
          "Near "
              + getParser().getLocationInfo()
              + ": Caught and rethrew "
              + e.getClass().getName()
              + " - "
              + e.getMessage(),
          e);
    } catch (Error e) {
      throw new Error(
          "Near "
              + getParser().getLocationInfo()
              + ": Caught and rethrew "
              + e.getClass().getName()
              + " - "
              + e.getMessage(),
          e);
    }
  }
예제 #26
0
 public void handleElement(Element e) {
   // create family
   if (e.getName().equals("family")) {
     try {
       lexicon.add(new Family(e));
     } catch (RuntimeException exc) {
       System.err.println("Skipping family: " + e.getAttributeValue("name"));
       System.err.println(exc.toString());
     }
   }
   // save distributive attributes
   else if (e.getName().equals("distributive-features")) distrElt = e;
   // save licensing features
   else if (e.getName().equals("licensing-features")) licensingElt = e;
   // save relation sort order
   else if (e.getName().equals("relation-sorting")) relationSortingElt = e;
 }
예제 #27
0
  private boolean startCrawl(ArchivalUnit au, boolean force, boolean deep)
      throws CrawlManagerImpl.NotEligibleException {
    CrawlManagerImpl cmi = (CrawlManagerImpl) crawlMgr;
    if (force) {
      RateLimiter limit = cmi.getNewContentRateLimiter(au);
      if (!limit.isEventOk()) {
        limit.unevent();
      }
    }
    cmi.checkEligibleToQueueNewContentCrawl(au);
    String delayMsg = "";
    String deepMsg = "";
    try {
      cmi.checkEligibleForNewContentCrawl(au);
    } catch (CrawlManagerImpl.NotEligibleException e) {
      delayMsg = ", Start delayed due to: " + e.getMessage();
    }
    Configuration config = ConfigManager.getCurrentConfig();
    int pri = config.getInt(PARAM_CRAWL_PRIORITY, DEFAULT_CRAWL_PRIORITY);

    CrawlReq req;
    try {
      req = new CrawlReq(au);
      req.setPriority(pri);
      if (deep) {
        int d = Integer.parseInt(formDepth);
        if (d < 0) {
          errMsg = "Illegal refetch depth: " + d;
          return false;
        }
        req.setRefetchDepth(d);
        deepMsg = "Deep (" + req.getRefetchDepth() + ") ";
      }
    } catch (NumberFormatException e) {
      errMsg = "Illegal refetch depth: " + formDepth;
      return false;
    } catch (RuntimeException e) {
      log.error("Couldn't create CrawlReq: " + au, e);
      errMsg = "Couldn't create CrawlReq: " + e.toString();
      return false;
    }
    cmi.startNewContentCrawl(req, null);
    statusMsg = deepMsg + "Crawl requested for " + au.getName() + delayMsg;
    return true;
  }
 public void revert() throws IOException {
   try {
     new WriteCommandAction(myProject, getCommandName()) {
       @Override
       protected void run(Result objectResult) throws Throwable {
         myGateway.saveAllUnsavedDocuments();
         doRevert();
         myGateway.saveAllUnsavedDocuments();
       }
     }.execute();
   } catch (RuntimeException e) {
     Throwable cause = e.getCause();
     if (cause instanceof IOException) {
       throw (IOException) cause;
     }
     throw e;
   }
 }
예제 #29
0
  /**
   * Evaluates and returns the value of the expression as an object. The EvaluatorVisitor member ev
   * is used to do the evaluation procedure. This method is useful when the type of the value is
   * unknown, or not important.
   *
   * @return The calculated value of the expression if no errors occur. Returns null otherwise.
   */
  public Object getValueAsObject() {
    Object result;

    if (topNode == null) return null;
    // evaluate the expression
    try {
      result = ev.getValue(topNode, symTab);
    } catch (ParseException e) {
      if (debug) System.out.println(e);
      errorList.addElement("Error during evaluation: " + e.getMessage());
      return null;
    } catch (RuntimeException e) {
      if (debug) System.out.println(e);
      errorList.addElement(e.getClass().getName() + ": " + e.getMessage());
      return null;
    }
    return result;
  }
예제 #30
0
  public boolean writeClasses(ConstantPool consts, ConstantPool sharedconsts) {
    ClassClass classes[] = ClassClass.getClassVector(classMaker);
    ClassClass.setTypes();

    // write out some constant pool stuff here,
    writeProlog();

    try {
      writeAllNativeTables(classes);
    } catch (RuntimeException e) {
      out.flush();
      System.out.println(e);
      e.printStackTrace(System.out);
      formatError = true;
    }
    writeEpilog();
    return (!formatError) && (!out.checkError());
  }