コード例 #1
1
 /*
  * (non-Javadoc)
  *
  * @see
  * it.geosolutions.geofence.gui.server.service.IInstancesManagerService#
  * saveInstance(it.geosolutions.geofence.gui.client.model.Instance)
  */
 public void saveInstance(GSInstance instance) {
   it.geosolutions.geofence.core.model.GSInstance remote_instance = null;
   if (instance.getId() >= 0) {
     try {
       remote_instance = geofenceRemoteService.getInstanceAdminService().get(instance.getId());
       remote_instance.setName(instance.getName());
       remote_instance.setDateCreation(instance.getDateCreation());
       remote_instance.setDescription(instance.getDescription());
       remote_instance.setBaseURL(instance.getBaseURL());
       remote_instance.setPassword(instance.getPassword());
       remote_instance.setUsername(instance.getUsername());
       geofenceRemoteService.getInstanceAdminService().update(remote_instance);
     } catch (NotFoundServiceEx e) {
       logger.error(e.getLocalizedMessage(), e.getCause());
       throw new ApplicationException(e.getLocalizedMessage(), e.getCause());
     }
   } else {
     try {
       remote_instance = new it.geosolutions.geofence.core.model.GSInstance();
       remote_instance.setName(instance.getName());
       remote_instance.setDateCreation(instance.getDateCreation());
       remote_instance.setDescription(instance.getDescription());
       remote_instance.setBaseURL(instance.getBaseURL());
       remote_instance.setPassword(instance.getPassword());
       remote_instance.setUsername(instance.getUsername());
       geofenceRemoteService.getInstanceAdminService().insert(remote_instance);
     } catch (Exception e) {
       logger.error(e.getLocalizedMessage(), e.getCause());
       throw new ApplicationException(e.getLocalizedMessage(), e.getCause());
     }
   }
 }
コード例 #2
0
 protected void onPostExecute(String result) {
   try {
     JSONObject jsonObject = new JSONObject(result);
     JSONArray fileArray;
     Object status = jsonObject.get("estado");
     Object message = jsonObject.get("mensaje");
     if (status.equals("ok")) {
       Toast.makeText(getApplicationContext(), message.toString(), Toast.LENGTH_LONG).show();
       Log.i("Search", message.toString());
       Utility.appendToInfoLog("Search", message.toString());
       Log.d("Search", jsonObject.toString());
       Utility.appendToDebugLog("Search", jsonObject.toString());
       if (jsonObject.has("archivos")) {
         fileArray = jsonObject.getJSONArray("archivos");
         for (int i = 0; i < fileArray.length(); i++) {
           String filePath = fileArray.getString(i);
           String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
           filesList.add(fileName);
         }
       } else {
         filesList.add("No results for your search");
       }
       ArrayAdapter<String> files =
           new ArrayAdapter<>(getApplicationContext(), R.layout.list_item, filesList);
       lv.setAdapter(files);
     } else {
       Toast.makeText(getApplicationContext(), message.toString(), Toast.LENGTH_LONG).show();
       Log.e("Search", message.toString());
       Utility.appendToErrorLog("Search", message.toString());
     }
   } catch (Exception e) {
     Log.e("Search", e.getLocalizedMessage());
     Utility.appendToErrorLog("Search", e.getLocalizedMessage());
   }
 }
コード例 #3
0
 public String getSearchFiles(String URL) {
   StringBuilder stringBuilder = new StringBuilder();
   HttpClient httpClient = new DefaultHttpClient();
   HttpGet httpGet = new HttpGet(URL);
   JSONObject json = new JSONObject();
   try {
     json.put("mail", email);
     httpGet.setEntity(new StringEntity(json.toString(), "UTF-8"));
     httpGet.setHeader("Content-Type", "application/json");
     httpGet.setHeader("Accept-Encoding", "application/json");
     HttpResponse response = httpClient.execute(httpGet);
     StatusLine statusLine = response.getStatusLine();
     int statusCode = statusLine.getStatusCode();
     if (statusCode == 200) {
       HttpEntity entity = response.getEntity();
       InputStream inputStream = entity.getContent();
       BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
       String line;
       while ((line = reader.readLine()) != null) {
         stringBuilder.append(line);
       }
       inputStream.close();
     } else {
       Log.e("Search", "status code: " + statusCode);
       Utility.appendToErrorLog("Search", "status code: " + statusCode);
     }
   } catch (Exception e) {
     Log.e("Search", e.getLocalizedMessage());
     Utility.appendToErrorLog("Search", e.getLocalizedMessage());
   }
   return stringBuilder.toString();
 }
コード例 #4
0
  @Override
  protected IStatus run(IProgressMonitor monitor) {

    try {
      File file = new File(getJobParameters().get(FILE_NAME));
      FileInputStream fin = new FileInputStream(file);
      BufferedInputStream bis = new BufferedInputStream(fin);
      BufferedReader br = new BufferedReader(new InputStreamReader(bis));

      ArrayList<String> filenames = new ArrayList<String>();

      String filename = br.readLine();
      // if there is nothing there, throw an exception here to let the user know
      if (filename == null) {
        throw new IOException("No File Specified in drop location");
      }

      // otherwise try to load in all the image filenames
      while (filename != null) {
        filenames.add(filename);
        filename = br.readLine();
      }

      processFile(filenames);

    } catch (Exception e) {
      setStatus(e.getLocalizedMessage());
      return new Status(IStatus.INFO, Activator.PLUGIN_ID, e.getLocalizedMessage());
    }

    setStatus("OK");
    return Status.OK_STATUS;
  }
コード例 #5
0
ファイル: PropertyDescriptor.java プロジェクト: mbarbero/emf
 public String isValid(Object object) {
   Object value;
   try {
     value =
         eDataType
             .getEPackage()
             .getEFactoryInstance()
             .createFromString(eDataType, (String) object);
   } catch (Exception exception) {
     String message = exception.getClass().getName();
     int index = message.lastIndexOf('.');
     if (index >= 0) {
       message = message.substring(index + 1);
     }
     if (exception.getLocalizedMessage() != null) {
       message = message + ": " + exception.getLocalizedMessage();
     }
     return message;
   }
   Diagnostic diagnostic = Diagnostician.INSTANCE.validate(eDataType, value);
   if (diagnostic.getSeverity() == Diagnostic.OK) {
     return null;
   } else {
     return (diagnostic.getChildren().get(0))
         .getMessage()
         .replaceAll("'", "''")
         .replaceAll("\\{", "'{'"); // }}
   }
 }
コード例 #6
0
    @Override
    protected String doInBackground(Void... params) {
      HttpClient httpClient = new DefaultHttpClient();
      HttpContext localContext = new BasicHttpContext();
      HttpPost httpPost = new HttpPost("http://54.235.91.254:8080/get_bus_location");
      String text = null;

      try { // for get_bus_location
        JSONObject json = new JSONObject();
        httpPost.setHeader("Content-Type", "application/json");
        json.put("user_id", uname); // change to uname
        json.put("route_id", "12");
        httpPost.setEntity(new ByteArrayEntity(json.toString().getBytes()));
      } catch (Exception e) {
        return e.getLocalizedMessage();
      }

      try { // to capture response into String
        HttpResponse response = httpClient.execute(httpPost, localContext);
        HttpEntity entity = response.getEntity();
        text = getASCIIContentFromEntity(entity);
      } catch (Exception e) {
        return e.getLocalizedMessage();
      }

      try {
        set_locations(text);
      } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

      return text;
    }
コード例 #7
0
ファイル: Jails.java プロジェクト: Battleroar/Essentials
		@EventHandler(priority = EventPriority.HIGHEST)
		public void onPlayerJoin(final PlayerJoinEvent event)
		{
			final User user = ess.getUser(event.getPlayer());
			if (!user.isJailed() || user.getJail() == null || user.getJail().isEmpty())
			{
				return;
			}

			try
			{
				sendToJail(user, user.getJail());
			}
			catch (Exception ex)
			{
				if (ess.getSettings().isDebug())
				{
					LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex);
				}
				else
				{
					LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()));
				}
			}
			user.sendMessage(_("jailMessage"));
		}
コード例 #8
0
  @Override
  public boolean performFinish() {
    // finish work in each page
    page.finish(new NullProgressMonitor());
    outgoingPage.finish(new NullProgressMonitor());

    String bundleFile = page.getBundleFile();

    // only use a target rev if checkbox was selected
    ChangeSet cs = outgoingPage.isRevisionSelected() ? outgoingPage.getRevision() : null;

    // base will be null if nothing was selected or checkbox is not selected
    ChangeSet base = page.getBaseRevision();

    // can be null or empty
    String repo = page.getUrlText();

    // create operation
    BundleOperation op = new BundleOperation(getContainer(), root, cs, base, bundleFile, repo);
    try {
      // and run it...
      getContainer().run(true, true, op);
    } catch (Exception e) {
      MercurialEclipsePlugin.logError(e);
      page.setErrorMessage(e.getLocalizedMessage());
      outgoingPage.setErrorMessage(e.getLocalizedMessage());
    }
    return super.performFinish();
  }
コード例 #9
0
ファイル: JdbcBatchDao.java プロジェクト: gspandy/AMI_FEP
 public void batchUpdate() {
   if (executing) return;
   synchronized (batchDaoLock) {
     // 数据库不可用,则直接退出批量保存。
     DbState ds = DbMonitor.getInstance().getMonitor(dataSource);
     if (null != ds && !ds.isAvailable()) return;
     if (null != executeThreadName) {
       log.error("BatchDao[key=" + key + "] has already been executed by : " + executeThreadName);
     }
     executeThreadName = Thread.currentThread().getName();
     // 取消保存成功标志判断,以免保存异常后临时保存队列无法清空
     // boolean success = false;
     try {
       executing = true;
       _doBatchUpdate();
       // success = true;
     } catch (CannotGetJdbcConnectionException e) {
       // 数据库连接异常,通知监控模块
       tracer.trace("batch dao1 exception: CannotGetJdbcConnectionException");
       if (null != ds) ds.setAvailable(false);
     } catch (BadSqlGrammarException e) {
       // 语法错误,必须纠正。正确情况下,系统不应该打印此错误信息
       tracer.trace("batch dao1 exception:" + e.getLocalizedMessage(), e);
     } catch (Exception e) {
       tracer.trace("batch dao1 exception:" + e.getLocalizedMessage(), e);
       log.warn("batch dao1 exception:" + e.getLocalizedMessage(), e);
     } finally {
       executing = false;
     }
     executeThreadName = null;
   }
 }
コード例 #10
0
ファイル: JSocket.java プロジェクト: gspandy/AMI_FEP
 private void _handleBuffer() {
   while (readBuffer.hasRemaining()) {
     if (null == message) {
       message = messageCreator.create();
     }
     boolean down = false;
     try {
       down = message.read(readBuffer);
     } catch (Exception e) {
       log.warn("消息对象读取数据异常:" + e.getLocalizedMessage(), e);
       message = null;
       break;
     }
     if (down) { // 消息已经完整读取。
       try {
         message.setSource(JSocket.this);
         message.setIoTime(System.currentTimeMillis());
         message.setTxfs(txfs);
         // 终端上行的MessageZj对象的peerAddr,保存的是终端本身的IP。
         // 下面的判断是正确的,别修改为错误代码。
         if (null == message.getPeerAddr() || 0 == message.getPeerAddr().length()) {
           message.setPeerAddr(peerAddr);
         }
         listener.onReceive(JSocket.this, message);
       } catch (Exception e) {
         log.error(e.getLocalizedMessage(), e);
       }
       message = null;
     } else break;
   }
   if (readBuffer.hasRemaining()) readBuffer.compact();
   else readBuffer.clear();
 }
コード例 #11
0
  @RequestMapping(
      value = "",
      method = {RequestMethod.PUT})
  @ResponseBody
  public StreamingRequest updateStreamingConfig(@RequestBody StreamingRequest streamingRequest)
      throws JsonProcessingException {
    StreamingConfig streamingConfig = deserializeSchemalDesc(streamingRequest);
    KafkaConfig kafkaConfig = deserializeKafkaSchemalDesc(streamingRequest);

    if (streamingConfig == null) {
      return streamingRequest;
    }
    try {
      streamingConfig = streamingService.updateStreamingConfig(streamingConfig);
    } catch (AccessDeniedException accessDeniedException) {
      throw new ForbiddenException("You don't have right to update this StreamingConfig.");
    } catch (Exception e) {
      logger.error("Failed to deal with the request:" + e.getLocalizedMessage(), e);
      throw new InternalErrorException(
          "Failed to deal with the request: " + e.getLocalizedMessage());
    }
    try {
      kafkaConfig = kafkaConfigService.updateKafkaConfig(kafkaConfig);
    } catch (AccessDeniedException accessDeniedException) {
      throw new ForbiddenException("You don't have right to update this KafkaConfig.");
    } catch (Exception e) {
      logger.error("Failed to deal with the request:" + e.getLocalizedMessage(), e);
      throw new InternalErrorException(
          "Failed to deal with the request: " + e.getLocalizedMessage());
    }

    streamingRequest.setSuccessful(true);

    return streamingRequest;
  }
コード例 #12
0
ファイル: JSocket.java プロジェクト: gspandy/AMI_FEP
 private int _doReceive() {
   try {
     int len = readBuffer.remaining();
     if (len == 0) {
       readBuffer.position(0);
       log.warn("缓冲区满,不能接收数据。dump=" + HexDump.hexDumpCompact(readBuffer));
       readBuffer.clear();
       len = readBuffer.remaining();
     }
     byte[] in = readBuffer.array();
     int off = readBuffer.position();
     int n = socket.getInputStream().read(in, off, len);
     if (n <= 0) return -1;
     lastReadTime = System.currentTimeMillis();
     readBuffer.position(off + n);
     readBuffer.flip();
   } catch (SocketTimeoutException te) {
     return 0;
   } catch (IOException ioe) {
     log.warn("client IO exception," + ioe.getLocalizedMessage() + ",peer=" + getPeerAddr());
     return -2;
   } catch (Exception e) {
     log.warn("client socket[" + getPeerAddr() + "] _doReceive:" + e.getLocalizedMessage(), e);
     return -3;
   }
   try {
     _handleBuffer();
   } catch (Exception e) {
     log.error(e.getLocalizedMessage(), e);
     return 0; // 处理异常,非通信异常。
   }
   return 0; // 成功
 }
コード例 #13
0
  /** Attempts to revert the working copy. In case of failure it just logs the error. */
  public void safeRevertWorkingCopy() {
    try {
      revertWorkingCopy();
    } catch (Exception e) {
      debuggingLogger.log(Level.FINE, "Failed to revert working copy", e);
      log("Failed to revert working copy: " + e.getLocalizedMessage());
      Throwable cause = e.getCause();
      if (!(cause instanceof SVNException)) {
        return;
      }
      SVNException svnException = (SVNException) cause;
      if (svnException.getErrorMessage().getErrorCode() == SVNErrorCode.WC_LOCKED) {
        // work space locked attempt cleanup and try to revert again
        try {
          cleanupWorkingCopy();
        } catch (Exception unlockException) {
          debuggingLogger.log(Level.FINE, "Failed to cleanup working copy", e);
          log("Failed to cleanup working copy: " + e.getLocalizedMessage());
          return;
        }

        try {
          revertWorkingCopy();
        } catch (Exception revertException) {
          log("Failed to revert working copy on the 2nd attempt: " + e.getLocalizedMessage());
        }
      }
    }
  }
コード例 #14
0
ファイル: DefExpressionTest.java プロジェクト: ewillink/ocl
  public void test_duplicateDefinition_operation() {
    helper.setContext(apple);

    try {
      // same signature as existing operation (note different param name)
      helper.defineOperation(
          "preferredLabel(s : String) : String = "
              + "if s.oclIsUndefined() then 'foo' else s endif");

      fail("Should not have parsed");
    } catch (Exception e) {
      // success
      System.out.println("Got expected error: " + e.getLocalizedMessage());
    }

    try {
      // same signature as existing operation (note different return type)
      helper.defineOperation(
          "preferredLabel(s : String) : Integer = "
              + "if s.oclIsUndefined() then 0 else s.size() endif");

      fail("Should not have parsed");
    } catch (Exception e) {
      // success
      System.out.println("Got expected error: " + e.getLocalizedMessage());
    }

    try {
      // same name but different signature is OK
      helper.defineOperation(
          "preferredLabel(text : Integer) : String = " + "if text > 0 then 'foo' else 'bar' endif");
    } catch (Exception e) {
      fail("Failed to parse: " + e.getLocalizedMessage());
    }
  }
コード例 #15
0
 @Path("/resubmitasync")
 @POST
 @Consumes("application/xml")
 @Produces("application/xml")
 public MessageResponse submitRecoverJobAsync(Message message) {
   MessageResponse response = new MessageResponse();
   String messageXML = MessageUtil.readRequestMessage(message);
   String expID = message.getHeader().getExperimentid();
   log.info(
       "Async Resuest recived from client at :"
           + new Date()
           + " : and assigned experiment id :"
           + expID
           + "with message "
           + messageXML);
   try {
     submitAsyncRequest(message);
   } catch (Exception e) {
     try {
       response.setMessage("Failed to submit job to gfac");
     } catch (Exception e1) {
       response.setStatus(ServiceConstants.ERROR);
       response.setMessage(e1.getLocalizedMessage());
     }
     response.setStatus(ServiceConstants.ERROR);
     response.setMessage(e.getLocalizedMessage());
   }
   response.setExperimentid(message.getHeader().getExperimentid());
   return response;
 }
コード例 #16
0
  @Override
  protected void doHandle(CommandContext ctx) {

    ModelControllerClient client = ctx.getModelControllerClient();
    ParsedArguments args = ctx.getParsedArguments();
    boolean l = this.l.isPresent(args);
    if (!args.hasArguments() || l) {
      printList(ctx, Util.getDeployments(client), l);
      return;
    }

    final String name = this.name.getValue(ctx.getParsedArguments());

    if (name == null) {
      printList(ctx, Util.getDeployments(client), l);
      return;
    }

    DefaultOperationRequestBuilder builder;

    // undeploy
    builder = new DefaultOperationRequestBuilder();
    builder.setOperationName("undeploy");
    builder.addNode("deployment", name);

    ModelNode result;
    try {
      ModelNode request = builder.buildRequest();
      result = client.execute(request);
    } catch (Exception e) {
      ctx.printLine("Failed to undeploy: " + e.getLocalizedMessage());
      return;
    }

    // TODO undeploy may fail if the content failed to deploy but remove should still be executed
    if (!Util.isSuccess(result)) {
      ctx.printLine("Undeploy failed: " + Util.getFailureDescription(result));
      return;
    }

    // remove
    builder = new DefaultOperationRequestBuilder();
    builder.setOperationName("remove");
    builder.addNode("deployment", name);
    try {
      ModelNode request = builder.buildRequest();
      result = client.execute(request);
    } catch (Exception e) {
      ctx.printLine(
          "Failed to remove the deployment content from the repository: "
              + e.getLocalizedMessage());
      return;
    }
    if (!Util.isSuccess(result)) {
      ctx.printLine("Remove failed: " + Util.getFailureDescription(result));
      return;
    }

    ctx.printLine("Successfully undeployed " + name + ".");
  }
コード例 #17
0
ファイル: DefExpressionTest.java プロジェクト: ewillink/ocl
  public void test_undefine_operation_152018() {
    helper.setContext(getMetaclass("Classifier"));

    Operation operation = null;

    try {
      // define some additional property
      operation =
          helper.defineOperation(
              "other(x : Integer) : Classifier = "
                  + "if general->size() >= x then general->asSequence()->at(x) else null endif");
    } catch (Exception e) {
      fail("Failed to parse: " + e.getLocalizedMessage());
    }

    assertNotNull(operation);

    // now, undefine this operation
    ocl.getEnvironment().undefine(operation);

    assertNull(operation.eContainer());
    assertNull(operation.eResource());

    try {
      // try to define this property again.  We should succeed
      operation =
          helper.defineOperation(
              "other(x : Integer) : Classifier = "
                  + "if general->size() >= x then general->asSequence()->at(x) else null endif");
    } catch (Exception e) {
      fail("Failed to parse: " + e.getLocalizedMessage());
    }
  }
コード例 #18
0
ファイル: FeedbackService.java プロジェクト: eletto/fra2015
  /**
   * Load All feedbacks related to the Latest review / ReviewEditing. The feedback is loaded only if
   * his timestamp is > to the LastContributorSubmission field stored in the survey status
   *
   * @param user
   * @param survey
   * @param question
   * @param harmonized
   * @return
   * @throws BadRequestServiceEx
   */
  public List<Feedback> loadFeedback(User user, SurveyInstance survey, Long question)
      throws BadRequestServiceEx {

    List<Feedback> list = new ArrayList<Feedback>();
    List<Feedback> harmonizedList = new ArrayList<Feedback>();
    try {

      Search search = new Search();
      if (user != null) {
        search.addFilterEqual("user", user);
      }
      search.addFilterEqual("harmonized", false);
      search.addFilterEqual("survey", survey);
      search.addFilterEqual("entry.question.id", question);

      // search.addFilterGreaterThan("timestamp", survey.getStatus().getLastSurveyReview());
      search.addFilterGreaterThan("timestamp", survey.getStatus().getLastPendingFixSubmit());

      list = feedbackDAO.search(search);
    } catch (Exception e) {

      LOGGER.error(e.getLocalizedMessage());
      throw new BadRequestServiceEx(e.getLocalizedMessage());
    }
    list.addAll(harmonizedList);
    return list;
  }
コード例 #19
0
ファイル: FeedbackService.java プロジェクト: eletto/fra2015
  /**
   * Load the feedbacks that are saved between the previous editor submission and the latest in
   * order to allow the reviewer to see their previous comment for each entry.
   *
   * @param user
   * @param survey
   * @param question
   * @param harmonized
   * @return
   * @throws BadRequestServiceEx
   */
  public List<Feedback> loadPreviousReviewFeedbacks(User user, SurveyInstance survey, Long question)
      throws BadRequestServiceEx {

    List<Feedback> list = new ArrayList<Feedback>();
    try {

      Search search = new Search();
      search.addFilterEqual("user", user);
      search.addFilterEqual("survey", survey);
      search.addFilterEqual("entry.question.id", question);
      Long prev =
          (survey.getStatus().getPreviousPendingFix() != null)
              ? survey.getStatus().getPreviousPendingFix()
              : 0;

      // Long last = (survey.getStatus().getLastSurveyReview() !=
      // null)?survey.getStatus().getLastSurveyReview():0;
      Long last =
          (survey.getStatus().getLastPendingFixSubmit() != null)
              ? survey.getStatus().getLastPendingFixSubmit()
              : 0;

      search.addFilterGreaterThan("timestamp", prev);
      search.addFilterLessThan("timestamp", last);
      list = feedbackDAO.search(search);
    } catch (Exception e) {

      LOGGER.error(e.getLocalizedMessage());
      throw new BadRequestServiceEx(e.getLocalizedMessage());
    }
    return list;
  }
コード例 #20
0
  @ExceptionHandler(value = {SolrException.class, SolrServerException.class})
  public void handleException(
      Exception ex, HttpServletRequest request, HttpServletResponse response) throws IOException {

    String msg;

    if (ex instanceof SolrException) {
      msg = ex.getLocalizedMessage();
      // Don't send the request as part of error msg
      int requestStart = msg.indexOf("request:");
      if (requestStart > 0) {
        msg = msg.substring(0, requestStart);
      }
    } else if (ex instanceof SolrServerException) {
      msg = appContext.getMessage("oai.solr.unavailable", null, Locale.getDefault());
    } else {
      msg = ex.getLocalizedMessage();
    }

    if (clientXsltHandler != null) {
      clientXsltHandler.sendErrorXml(response, msg, request.getRequestURL().toString());
      ex.printStackTrace();
    } else {
      response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, msg);
    }
  }
コード例 #21
0
  private void rotateTokens(HttpServletRequest request) {
    HttpSession session = request.getSession(true);

    /** rotate master token * */
    String tokenFromSession = null;

    try {
      tokenFromSession = RandomGenerator.generateRandomId(getPrng(), getTokenLength());
    } catch (Exception e) {
      throw new RuntimeException(
          String.format("unable to generate the random token - %s", e.getLocalizedMessage()), e);
    }

    session.setAttribute(getSessionKey(), tokenFromSession);

    /** rotate page token * */
    if (isTokenPerPageEnabled()) {
      @SuppressWarnings("unchecked")
      Map<String, String> pageTokens =
          (Map<String, String>) session.getAttribute(CsrfGuard.PAGE_TOKENS_KEY);

      try {
        pageTokens.put(
            request.getRequestURI(), RandomGenerator.generateRandomId(getPrng(), getTokenLength()));
      } catch (Exception e) {
        throw new RuntimeException(
            String.format("unable to generate the random token - %s", e.getLocalizedMessage()), e);
      }
    }
  }
コード例 #22
0
ファイル: DefExpressionTest.java プロジェクト: ewillink/ocl
  public void test_undefine_property_152018() {
    helper.setContext(getMetaclass("Classifier"));

    Property property = null;

    try {
      // define some additional property
      property =
          helper.defineAttribute(
              "other : Classifier = "
                  + "if general->notEmpty() then general->asSequence()->first() else null endif");
    } catch (Exception e) {
      fail("Failed to parse: " + e.getLocalizedMessage());
    }

    assertNotNull(property);

    // now, undefine this property
    ocl.getEnvironment().undefine(property);

    assertNull(property.eContainer());
    assertNull(property.eResource());

    try {
      // try to define this property again.  We should succeed
      property =
          helper.defineAttribute(
              "other : Classifier = "
                  + "if general->notEmpty() then general->asSequence()->first() else null endif");
    } catch (Exception e) {
      fail("Failed to parse: " + e.getLocalizedMessage());
    }
  }
コード例 #23
0
ファイル: DefExpressionTest.java プロジェクト: ewillink/ocl
  public void test_malformedDefExpression_operation() {
    helper.setContext(getMetaclass("Classifier"));

    try {
      // non-conformant expression type
      helper.defineOperation("oclAllParents() : Set(Classifier) = " + "self.name");

      fail("Should not have parsed");
    } catch (Exception e) {
      // success
      System.out.println("Got expected error: " + e.getLocalizedMessage());
    }

    try {
      // missing type declaration
      helper.defineOperation(
          "bestName(s : String) = " + "if self.oclIsKindOf(Class) then self.name else s endif");

      fail("Should not have parsed");
    } catch (Exception e) {
      // success
      System.out.println("Got expected error: " + e.getLocalizedMessage());
    }

    try {
      // missing type declaration in parameter
      helper.defineOperation(
          "bestName(s) : String = " + "if self.oclIsKindOf(Class) then self.name else s endif");

      fail("Should not have parsed");
    } catch (Exception e) {
      // success
      System.out.println("Got expected error: " + e.getLocalizedMessage());
    }
  }
コード例 #24
0
 /**
  * Tell the user about, and log, an exception.
  *
  * @param except the exception in question
  * @param filename what file was being read
  */
 private void printError(final Exception except, final String filename) {
   if (except instanceof MapVersionException) {
     LOGGER.log(Level.SEVERE, "Map version in " + filename + " not acceptable to reader", except);
     printParagraph("ERROR: Map version not acceptable to reader", ERROR_COLOR);
   } else if (except instanceof FileNotFoundException || except instanceof NoSuchFileException) {
     printParagraph("ERROR: File not found", ERROR_COLOR);
     LOGGER.log(Level.SEVERE, filename + " not found", except);
   } else if (except instanceof IOException) {
     //noinspection HardcodedFileSeparator
     printParagraph("ERROR: I/O error reading file", ERROR_COLOR);
     //noinspection HardcodedFileSeparator
     LOGGER.log(Level.SEVERE, "I/O error reading " + filename, except);
   } else if (except instanceof XMLStreamException) {
     printParagraph(
         "ERROR: Malformed XML in the file" + "; see following error message for details",
         ERROR_COLOR);
     final String message =
         NullCleaner.valueOrDefault(except.getLocalizedMessage(), "(message was null)");
     printParagraph(message, ERROR_COLOR);
     LOGGER.log(Level.SEVERE, "Malformed XML in file " + filename, except);
   } else if (except instanceof SPFormatException) {
     printParagraph(
         "ERROR: SP map format error at line "
             + ((SPFormatException) except).getLine()
             + "; see following error message for details",
         ERROR_COLOR);
     final String message =
         NullCleaner.valueOrDefault(except.getLocalizedMessage(), "(message was null)");
     printParagraph(message, ERROR_COLOR);
     LOGGER.log(Level.SEVERE, "SP map format error reading " + filename, except);
   } else {
     throw new IllegalStateException("Unhandled exception class");
   }
 }
コード例 #25
0
ファイル: CommonUtils.java プロジェクト: DroidDemos/REMIUI
 public static void WriteFile(String str, String str2) {
   Exception e;
   Throwable th;
   File file = new File(str);
   if (file != null) {
     FileWriter fileWriter;
     try {
       fileWriter = new FileWriter(file, false);
       try {
         fileWriter.write(str2);
         fileWriter.close();
       } catch (Exception e2) {
         e = e2;
         try {
           Log.d("ConfigNameEnum.CONFIGS.getValue()", e.getLocalizedMessage());
           fileWriter.close();
         } catch (Throwable th2) {
           th = th2;
           fileWriter.close();
           throw th;
         }
       }
     } catch (Exception e3) {
       e = e3;
       fileWriter = null;
       Log.d("ConfigNameEnum.CONFIGS.getValue()", e.getLocalizedMessage());
       fileWriter.close();
     } catch (Throwable th3) {
       th = th3;
       fileWriter = null;
       fileWriter.close();
       throw th;
     }
   }
 }
コード例 #26
0
ファイル: CalendarAjax.java プロジェクト: rmundy/dotCMS
  public Map<String, Object> deleteEvent(String identifier)
      throws PortalException, SystemException, DotDataException, DotSecurityException {
    HibernateUtil.startTransaction();
    WebContext ctx = WebContextFactory.get();
    HttpServletRequest request = ctx.getHttpServletRequest();
    List<String> eventDeleteErrors = new ArrayList<String>();
    Map<String, Object> callbackData = new HashMap<String, Object>();

    // Retrieving the current user
    User user = userAPI.getLoggedInUser(request);
    boolean respectFrontendRoles = true;

    Event ev = eventAPI.find(identifier, false, user, respectFrontendRoles);
    if (ev.isLive()) {
      try {
        contAPI.unpublish(ev, user, respectFrontendRoles);
      } catch (DotSecurityException e) {
        eventDeleteErrors.add(e.getLocalizedMessage());
      } catch (DotDataException e) {
        eventDeleteErrors.add(e.getLocalizedMessage());
      } catch (DotContentletStateException e) {
        eventDeleteErrors.add(e.getLocalizedMessage());
      }
      try {
        contAPI.archive(ev, user, respectFrontendRoles);
      } catch (Exception e) {
        eventDeleteErrors.add(e.getLocalizedMessage());
      }
    } else if (!ev.isArchived()) {
      try {
        contAPI.archive(ev, user, respectFrontendRoles);
      } catch (Exception e) {
        eventDeleteErrors.add(e.getLocalizedMessage());
      }
    }

    try {
      if (ev.isArchived()) {
        contAPI.delete(ev, user, respectFrontendRoles);
      }
    } catch (Exception e) {
      eventDeleteErrors.add(e.getLocalizedMessage());
    } finally {
      if (eventDeleteErrors.size() > 0) {
        callbackData.put("eventUnpublishErrors", eventDeleteErrors);
      }
    }
    if (eventDeleteErrors.size() <= 0) {
      HibernateUtil.commitTransaction();
    }

    // At this point we already deleted the content from the index on the delete call
    /*if(!contAPI.isInodeIndexed(ev.getInode())){
    	Logger.error(this, "Timed out while waiting for index to return");
    }*/

    return callbackData;
  }
コード例 #27
0
  @Override
  protected Integer doInBackground(String... arg0) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    Thread.currentThread().setName("SSHConnectionThread");
    try {

      JSch jsch = new JSch();
      session = jsch.getSession(arg0[1], arg0[0], 22);
      session.setPassword(arg0[2].getBytes());
      session.setConfig("StrictHostKeyChecking", "no");
      session.connect(timeout);
      System.out.println("connesso? " + session.isConnected());
      int assinged_port = session.setPortForwardingL(lhost, lport, rhost, rport);
      session.setPortForwardingL(lhost, 9001, rhost, 502);
      System.out.println("localhost:" + assinged_port + " -> " + rhost + ":" + rport);
      ConnectionManager.setSession(session);

    } catch (Exception e) {
      //			System.out.println(e.getLocalizedMessage());
      //			String errore = "";
      //			if(e instanceof JSchException) errore = "Errore SSH ";
      //			else if(e instanceof UnknownHostException) errore = "Ricontrolla il dominio o la
      // connessione internet, cè qualcosa di errato, attento agli spazi e maiscole";
      //			else if(e instanceof ConnectException) errore = "Ricontrolla i campi o la connessione cè
      // qualcosa che non va, attento agli spazi e maiscole";
      //			else errore = "Ricontrolla user, password e dominio, cè qualcosa di errato, attento agli
      // spazi e maiscole";
      //			if(isDialogActivated()){
      //				AlertMessageTask errorConnection = new AlertMessageTask();
      //				errorConnection.setActivity(getActivity());
      //				errorConnection.execute(errore);
      //			}
      if (fireEvent && !e.getLocalizedMessage().contains("PortForwardingL:")) {
        System.out.println("non è portforwarding ma " + e.getLocalizedMessage());
        if (MainActivity.handle == null) return null;
        Message msgObj = MainActivity.handle.obtainMessage();
        Bundle ba = new Bundle();
        ba.putInt("status", 0);
        msgObj.setData(ba);
        MainActivity.handle.sendMessage(msgObj);
        fireEvent = false;
      }
      return null;
    }
    if (fireEvent) {
      if (MainActivity.handle == null) return null;
      Message msgObj = MainActivity.handle.obtainMessage();
      Bundle ba = new Bundle();
      ba.putInt("status", 1);
      msgObj.setData(ba);
      MainActivity.handle.sendMessage(msgObj);
      fireEvent = false;
    }
    return null;
  };
コード例 #28
0
  private int processarShopping(String arquivo, int tipo) {
    BufferedReader br;
    String line;
    String fields[];
    String csvSplitBy = ";";
    int erros = 0;

    Cultura equip;

    try {

      Logger.info("Processing file: " + arquivo);
      br = new BufferedReader(new InputStreamReader(new FileInputStream(arquivo), "UTF8"));
      line = br.readLine(); // pula o cabeçalho
      while ((line = br.readLine()) != null) {
        equip = new Cultura();
        fields = line.split(csvSplitBy, -1);

        equip.setNome(fields[0]);
        equip.setDescricao(fields[1]);
        equip.setBairro(fields[2]);
        equip.setEndereco(fields[3]);
        equip.setLatitude(fields[4].replace(",", "."));
        equip.setLongitude(fields[5].replace(",", "."));
        equip.setExtraInfo(
            "Telefone: "
                + fields[6]
                + ", Site: "
                + fields[7]
                + ", Horário: "
                + fields[8]
                + ", aos domingos: "
                + fields[9]);
        equip.setTipo(tipo);

        try {
          JPA.em().persist(equip);
        } catch (Exception ex) {
          Logger.error(
              "Erro salvando equipamento cultural "
                  + equip.getNome()
                  + ": "
                  + ex.getLocalizedMessage());
          erros++;
        }
      }
      Logger.info("Success processing " + arquivo);
      br.close();
    } catch (Exception e) {
      Logger.error("Erro processando arquivo " + arquivo + ": " + e.getLocalizedMessage());
      e.printStackTrace();
      erros++;
    }
    return erros;
  }
コード例 #29
0
  // Find a host connected and powered on then refresh it
  public void vcenterClusterSelectHostOperation(
      URI vcenterId, URI vcenterDataCenterId, URI clusterId, URI[] hostUris, String stepId) {
    VcenterApiClient vcenterApiClient = null;
    try {
      WorkflowStepCompleter.stepExecuting(stepId);

      VcenterDataCenter vcenterDataCenter =
          _dbClient.queryObject(VcenterDataCenter.class, vcenterDataCenterId);
      Cluster cluster = _dbClient.queryObject(Cluster.class, clusterId);
      Vcenter vcenter = _dbClient.queryObject(Vcenter.class, vcenterId);
      Collection<Host> hosts = _dbClient.queryObject(Host.class, hostUris);

      vcenterApiClient = new VcenterApiClient(_coordinator.getPropertyInfo());
      vcenterApiClient.setup(vcenter.getIpAddress(), vcenter.getUsername(), vcenter.getPassword());

      Host hostForStorageOperations = null;
      for (Host host : hosts) {
        try {
          vcenterApiClient.checkHostConnectedPoweredOn(
              vcenterDataCenter.getLabel(), cluster.getExternalId(), host.getHostName());
          hostForStorageOperations = host;
          _log.info("Host " + host.getHostName() + " to be used for storage operations");
          break;
        } catch (Exception e) {
          _log.info(
              "Host "
                  + host.getHostName()
                  + " not valid for storage operations due to exception "
                  + e.getLocalizedMessage());
        }
      }
      if (hostForStorageOperations == null) {
        _log.error(
            "No host valid for performing storage operations thus cannot perform datastore operations");
        throw new Exception(
            "No host valid for performing storage operations thus cannot perform datastore operations");
      }
      vcenterApiClient.refreshRescanHostStorage(
          vcenterDataCenter.getLabel(),
          cluster.getExternalId(),
          hostForStorageOperations.getHostName());

      // persist hostForStorageOperations ID in wf data
      _workflowService.storeStepData(stepId, hostForStorageOperations.getId());

      WorkflowStepCompleter.stepSucceded(stepId);
    } catch (Exception e) {
      _log.error("vcenterClusterSelectHostOperation exception " + e);
      WorkflowStepCompleter.stepFailed(
          stepId, VcenterControllerException.exceptions.hostException(e.getLocalizedMessage(), e));
    } finally {
      if (vcenterApiClient != null) vcenterApiClient.destroy();
    }
  }
コード例 #30
0
ファイル: FeedbackService.java プロジェクト: eletto/fra2015
  public boolean storeFeedback(Feedback... feedback) throws BadRequestServiceEx {

    try {

      feedbackDAO.save(feedback);
    } catch (Exception e) {

      LOGGER.error(e.getLocalizedMessage());
      throw new BadRequestServiceEx(e.getLocalizedMessage());
    }
    return true;
  }