类org.apache.http.conn.HttpHostConnectException源码实例Demo

下面列出了怎么用org.apache.http.conn.HttpHostConnectException的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: JerryMouse   文件: ServerLifeCycleTest.java
@Test(expected = HttpHostConnectException.class)
public void testServerStartAndStop() throws Exception {
    int availablePort = NetUtils.getAvailablePort();
    HttpServer httpSever = new HttpServer("/tmp/static");
    List<Context> contexts = httpSever.getContexts();
    Context context = contexts.get(0);
    context.setPort(availablePort);
    httpSever.start();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet("http://localhost:" + availablePort + "/");
    CloseableHttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    String responseStr = EntityUtils.toString(entity);
    assertEquals("/", responseStr);
    httpSever.destroy();
    httpclient.execute(httpget);
}
 
@Override
	public boolean neadRetry(Exception exception, BulkCommand bulkCommand) {
		if (exception instanceof HttpHostConnectException     //NoHttpResponseException 重试
				|| exception instanceof ConnectTimeoutException //连接超时重试
				|| exception instanceof UnknownHostException
				|| exception instanceof NoHttpResponseException
				|| exception instanceof NoServerElasticSearchException
//              || exception instanceof SocketTimeoutException    //响应超时不重试,避免造成业务数据不一致
		) {

			return true;
		}

		if(exception instanceof SocketException){
			String message = exception.getMessage();
			if(message != null && message.trim().equals("Connection reset")) {
				return true;
			}
		}

		return false;
	}
 
@Test(timeout = 10_000L)
public void testConnectTimeout() {
  // Apache HttpClient doesn't appear to behave correctly on windows
  assumeTrue(!isWindows());

  HttpTransport httpTransport = new ApacheHttpTransport();
  GenericUrl url = new GenericUrl("http://google.com:81");
  try {
    httpTransport.createRequestFactory().buildGetRequest(url).setConnectTimeout(100).execute();
    fail("should have thrown an exception");
  } catch (HttpHostConnectException | ConnectTimeoutException expected) {
    // expected
  } catch (IOException e) {
    fail("unexpected IOException: " + e.getClass().getName());
  }
}
 
源代码4 项目: esigate   文件: HttpErrorPage.java
public static CloseableHttpResponse generateHttpResponse(Exception exception) {
    if (exception instanceof HttpHostConnectException) {
        return generateHttpResponse(HttpStatus.SC_BAD_GATEWAY, "Connection refused");
    } else if (exception instanceof ConnectionPoolTimeoutException) {
        return generateHttpResponse(HttpStatus.SC_GATEWAY_TIMEOUT, "Connection pool timeout");
    } else if (exception instanceof ConnectTimeoutException) {
        return generateHttpResponse(HttpStatus.SC_GATEWAY_TIMEOUT, "Connect timeout");
    } else if (exception instanceof SocketTimeoutException) {
        return generateHttpResponse(HttpStatus.SC_GATEWAY_TIMEOUT, "Socket timeout");
    } else if (exception instanceof SocketException) {
        return generateHttpResponse(HttpStatus.SC_BAD_GATEWAY, "Socket Exception");
    } else if (exception instanceof ClientProtocolException) {
        String message = exception.getMessage();
        if (message == null && exception.getCause() != null) {
            message = exception.getCause().getMessage();
        }
        return generateHttpResponse(HttpStatus.SC_BAD_GATEWAY, "Protocol error: " + message);
    } else {
        LOG.error("Error retrieving URL", exception);
        return generateHttpResponse(HttpStatus.SC_BAD_GATEWAY, "Error retrieving URL");
    }
}
 
源代码5 项目: celos   文件: JettyServerTest.java
@Test(expected = HttpHostConnectException.class)
public void testServerStopsSpecifyPort() throws Exception {
    int port = getFreePort();

    JettyServer jettyServer = new JettyServer();
    jettyServer.start(port);

    HttpClient httpClient = new DefaultHttpClient();
    HttpGet workflowListGet = new HttpGet("http://localhost:" + port);
    HttpResponse response = httpClient.execute(workflowListGet);

    Assert.assertEquals(response.getStatusLine().getStatusCode(), 403);
    EntityUtils.consume(response.getEntity());
    jettyServer.stop();

    httpClient.execute(workflowListGet);
}
 
源代码6 项目: dropwizard-experiment   文件: HealthChecker.java
public boolean check() throws InterruptedException {
    try {
        HttpResponse<String> health = Unirest.get(url + "/admin/healthcheck")
                .basicAuth("test", "test")
                .asString();

        if (health.getStatus() == 200) {
            log.info("Healthy with {}", health.getBody());
            return true;
        } else {
            log.error("Unhealthy with {}", health.getBody());
            return false;
        }
    } catch (UnirestException e) {
        if (e.getCause() instanceof HttpHostConnectException && duration < maxDuration) {
            log.info("Unable to connect, retrying...");
            duration = duration + DELAY;
            Thread.sleep(TimeUnit.SECONDS.toMillis(DELAY));
            return check();
        }
        log.error("Unable to connect.", e);
        return false;
    }
}
 
源代码7 项目: activiti6-boot2   文件: ActivitiClientService.java
public ActivitiServiceException wrapException(Exception e, HttpUriRequest request) {
	if (e instanceof HttpHostConnectException) {
		return new ActivitiServiceException("Unable to connect to the Activiti server.");
	} else if (e instanceof ConnectTimeoutException) {
		return new ActivitiServiceException("Connection to the Activiti server timed out.");
	} else {
		// Use the raw exception message
		return new ActivitiServiceException(e.getClass().getName() + ": " + e.getMessage());
	}
}
 
源代码8 项目: cos-java-sdk-v5   文件: ExceptionUtils.java
public static CosClientException createClientException(IOException ex) {
    String errorCode = ClientExceptionConstants.UNKNOWN;
    if (ex instanceof ConnectTimeoutException) {
        errorCode = ClientExceptionConstants.CONNECTION_TIMEOUT;
    } else if (ex instanceof UnknownHostException) {
        errorCode = ClientExceptionConstants.UNKNOWN_HOST;
    } else if (ex instanceof HttpHostConnectException) {
        errorCode = ClientExceptionConstants.HOST_CONNECT;
    } else if (ex instanceof SocketTimeoutException) {
        errorCode = ClientExceptionConstants.SOCKET_TIMEOUT;
    }

    return new CosClientException(ex.getMessage(), errorCode, ex);
}
 
源代码9 项目: 2017-highload-kv   文件: StartStopTest.java
@Test
public void stop() throws Exception {
    storage.stop();
    try {
        // Should not respond after stop
        status();
    } catch (SocketTimeoutException | HttpHostConnectException e) {
        // Do nothing
    }
}
 
@Test
public void stop_hasNoHttpEndpointRunning() {
  subject.start(metricsSession);
  subject.stop(metricsSession);

  HttpGet request = new HttpGet("http://localhost:9000/");

  Throwable thrown = catchThrowable(() -> HttpClientBuilder.create().build().execute(request));

  assertThat(thrown).isInstanceOf(HttpHostConnectException.class);
}
 
源代码11 项目: whirlpool   文件: UpDownService.java
@Override
protected void collectData(Gson gson, String user, List<String> subscriptions) {
    Map<String, String> subscriptionData = new HashMap<>();
    for (String url : subscriptions) {
        try (CloseableHttpClient httpClient = HttpClientHelper.buildHttpClient()) {
            HttpUriRequest query = RequestBuilder.get()
                    .setUri(url)
                    .build();
            try (CloseableHttpResponse queryResponse = httpClient.execute(query)) {
                HttpEntity entity = queryResponse.getEntity();
                if (entity != null) {
                    String data = EntityUtils.toString(entity);
                    if (data != null && data.length() > 0) {
                        if (data.contains("www.dnsrsearch.com")) {
                            subscriptionData.put(url, "not found");
                        } else {
                            subscriptionData.put(url, "up");
                        }
                    } else {
                        subscriptionData.put(url, "down");
                    }
                } else {
                    subscriptionData.put(url, "down");
                }
            }
        } catch (HttpHostConnectException hhce) {
            subscriptionData.put(url, "down");
        } catch (Throwable throwable) {
            logger.error(throwable.getMessage(), throwable);
            subscriptionData.put(url, "down");
        }
    }

    DataResponse response = new DataResponse();
    response.setType("UpDownResponse");
    response.setId(user);
    response.setResult(MessageConstants.SUCCESS);
    response.setSubscriptionData(subscriptionData);
    responseQueue.add(gson.toJson(response));
}
 
源代码12 项目: apollo   文件: RetryableRestTemplate.java
private boolean canRetry(Throwable e, HttpMethod method) {
  Throwable nestedException = e.getCause();
  if (method == HttpMethod.GET) {
    return nestedException instanceof SocketTimeoutException
           || nestedException instanceof HttpHostConnectException
           || nestedException instanceof ConnectTimeoutException;
  }
  return nestedException instanceof HttpHostConnectException
         || nestedException instanceof ConnectTimeoutException;
}
 
源代码13 项目: apollo   文件: RetryableRestTemplateTest.java
@Before
public void init() {
  socketTimeoutException.initCause(new SocketTimeoutException());

  httpHostConnectException
      .initCause(new HttpHostConnectException(new ConnectTimeoutException(), new HttpHost(serviceOne, 80)));
  connectTimeoutException.initCause(new ConnectTimeoutException());
}
 
源代码14 项目: sdk   文件: AviRestUtils.java
/**
 * This method sets a custom HttpRequestRetryHandler in order to enable a custom
 * exception recovery mechanism.
 * 
 * @return A HttpRequestRetryHandler representing handling of the retryHandler.
 */
private static HttpRequestRetryHandler retryHandler(AviCredentials creds) {
	return (exception, executionCount, context) -> {

		if (executionCount >= creds.getNumApiRetries()) {
			// Do not retry if over max retry count
			return false;
		}
		if (exception instanceof InterruptedIOException) {
			// Timeout
			return false;
		}
		if (exception instanceof UnknownHostException) {
			// Unknown host
			return false;
		}
		if (exception instanceof SSLException) {
			// SSL handshake exception
			return false;
		}
		if (exception instanceof HttpHostConnectException) {
			return true;
		}
		HttpClientContext clientContext = HttpClientContext.adapt(context);
		HttpRequest request = clientContext.getRequest();
		boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
		if (idempotent) {
			// Retry if the request is considered idempotent
			return true;
		}
		return false;
	};
}
 
源代码15 项目: netcrusher-java   文件: HttpClientTest.java
@Test
public void testClosed() throws Exception {
    HttpUriRequest request = composeRequest();

    crusher.close();

    try {
        http.execute(request);
        Assert.fail("Exception is expected");
    } catch (HttpHostConnectException e) {
        LOGGER.debug("Exception dump", e);
    }
}
 
@Test
public void stop_hasNoHttpEndpointRunning() {
  subject.start(metricsSession);
  subject.stop(metricsSession);

  HttpGet request = new HttpGet("http://localhost:9000/");

  Throwable thrown = catchThrowable(() -> HttpClientBuilder.create().build().execute(request));

  assertThat(thrown).isInstanceOf(HttpHostConnectException.class);
}
 
源代码17 项目: java-sdk   文件: OptimizelyHttpClientTest.java
@Test(expected = HttpHostConnectException.class)
public void testProxySettings() throws IOException {
    OptimizelyHttpClient optimizelyHttpClient = OptimizelyHttpClient.builder().build();

    // If this request succeeds then the proxy config was not picked up.
    HttpGet get = new HttpGet("https://www.optimizely.com");
    optimizelyHttpClient.execute(get);
}
 
源代码18 项目: flowable-engine   文件: FlowableClientService.java
public FlowableServiceException wrapException(Exception e, HttpUriRequest request) {
    if (e instanceof HttpHostConnectException) {
        return new FlowableServiceException("Unable to connect to the Flowable server.");
    } else if (e instanceof ConnectTimeoutException) {
        return new FlowableServiceException("Connection to the Flowable server timed out.");
    } else {
        // Use the raw exception message
        return new FlowableServiceException(e.getClass().getName() + ": " + e.getMessage());
    }
}
 
源代码19 项目: japi   文件: JapiClientTransfer.java
private Result postValues(String url, List<String[]> datas) {
    HttpPost httpPost = new HttpPost(url);
    List<NameValuePair> valuePairs = new ArrayList<>();
    for (String[] keyValue : datas) {
        valuePairs.add(new BasicNameValuePair(keyValue[0], keyValue[1]));
    }
    Integer tryCount = 0;
    while (reties > tryCount) {
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(valuePairs, "utf-8"));
            httpPost.setHeader("token", token);
            String result = EntityUtils.toString(HTTP_CLIENT.execute(httpPost).getEntity(), Consts.UTF_8);
            Result result1 = JSON.parseObject(result, ResultImpl.class);
            if (result1.getCode() != 0) {
                throw new JapiException(result1.getMsg());
            }
            return result1;
        } catch (IOException e) {
            if (e instanceof HttpHostConnectException) {
                tryCount++;
                LOGGER.warn("try connect server " + tryCount + " count.");
                try {
                    TimeUnit.SECONDS.sleep(tryTime);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
    if (tryCount <= reties) {
        LOGGER.error("server connect failed.");
    }
    return null;
}
 
源代码20 项目: japi   文件: JapiClientTransfer.java
private Result postFile(String url, List<String[]> datas, File file) {
    if (!file.exists()) {
        throw new JapiException(file.getAbsolutePath() + " file not exist.");
    }
    HttpPost httpPost = new HttpPost(url);
    Integer tryCount = 0;
    while (reties > tryCount) {
        try {
            final MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
            multipartEntity.setCharset(Charset.forName("utf-8"));
            multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            for (String[] nameValue : datas) {
                multipartEntity.addPart(nameValue[0], new StringBody(nameValue[1], ContentType.APPLICATION_JSON));
            }
            multipartEntity.addBinaryBody("file", file);
            httpPost.setEntity(multipartEntity.build());
            httpPost.setHeader("token", token);
            String result = EntityUtils.toString(HTTP_CLIENT.execute(httpPost).getEntity());
            Result result1 = JSON.parseObject(result, ResultImpl.class);
            if (result1.getCode() != 0) {
                throw new JapiException(result1.getMsg());
            }
            return result1;
        } catch (IOException e) {
            if (e instanceof HttpHostConnectException) {
                tryCount++;
                LOGGER.warn("try connect server " + tryCount + " count.");
                try {
                    TimeUnit.SECONDS.sleep(tryTime);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
    if (tryCount <= reties) {
        LOGGER.error("server connect failed.");
    }
    return null;
}
 
源代码21 项目: athenz   文件: PrometheusPullServerTest.java
@Test(expectedExceptions = { HttpHostConnectException.class }, expectedExceptionsMessageRegExp = ".* failed: Connection refused \\(Connection refused\\)")
public void testQuit() throws IOException {
    int port = 8181;
    CollectorRegistry registry = new CollectorRegistry();
    PrometheusPullServer exporter = new PrometheusPullServer(port, registry);
    exporter.quit();

    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(String.format("http://localhost:%d/metrics", port));
    client.execute(request);
}
 
源代码22 项目: java-docs-samples   文件: ExampleIntegrationTest.java
@Test
public void helloPubSub_shouldRunWithFunctionsFramework() throws Throwable {
  String functionUrl = BASE_URL + "/helloPubsub"; // URL to your locally-running function

  // Initialize constants
  String name = UUID.randomUUID().toString();
  String nameBase64 = Base64.getEncoder().encodeToString(name.getBytes(StandardCharsets.UTF_8));

  String jsonStr = gson.toJson(Map.of("data", Map.of("data", nameBase64)));

  HttpPost postRequest =  new HttpPost(URI.create(functionUrl));
  postRequest.setEntity(new StringEntity(jsonStr));

  // The Functions Framework Maven plugin process takes time to start up
  // Use resilience4j to retry the test HTTP request until the plugin responds
  RetryRegistry registry = RetryRegistry.of(RetryConfig.custom()
      .maxAttempts(8)
      .retryExceptions(HttpHostConnectException.class)
      .intervalFunction(IntervalFunction.ofExponentialBackoff(200, 2))
      .build());
  Retry retry = registry.retry("my");

  // Perform the request-retry process
  CheckedRunnable retriableFunc = Retry.decorateCheckedRunnable(
      retry, () -> client.execute(postRequest));
  retriableFunc.run();

  // Get Functions Framework plugin process' stdout
  InputStream stdoutStream = emulatorProcess.getErrorStream();
  ByteArrayOutputStream stdoutBytes = new ByteArrayOutputStream();
  stdoutBytes.write(stdoutStream.readNBytes(stdoutStream.available()));

  // Verify desired name value is present
  assertThat(stdoutBytes.toString(StandardCharsets.UTF_8)).contains(
      String.format("Hello %s!", name));
}
 
源代码23 项目: java-docs-samples   文件: ExampleIntegrationTest.java
@Test
public void helloGcs_shouldRunWithFunctionsFramework() throws Throwable {
  String functionUrl = BASE_URL + "/helloGcs"; // URL to your locally-running function

  // Initialize constants
  String name = UUID.randomUUID().toString();
  String jsonStr = gson.toJson(Map.of(
      "data", Map.of(
          "name", name, "resourceState", "exists", "metageneration", 1),
      "context", Map.of(
          "eventType", "google.storage.object.finalize")
  ));

  HttpPost postRequest =  new HttpPost(URI.create(functionUrl));
  postRequest.setEntity(new StringEntity(jsonStr));

  // The Functions Framework Maven plugin process takes time to start up
  // Use resilience4j to retry the test HTTP request until the plugin responds
  RetryRegistry registry = RetryRegistry.of(RetryConfig.custom()
      .maxAttempts(8)
      .retryExceptions(HttpHostConnectException.class)
      .intervalFunction(IntervalFunction.ofExponentialBackoff(200, 2))
      .build());
  Retry retry = registry.retry("my");

  // Perform the request-retry process
  CheckedRunnable retriableFunc = Retry.decorateCheckedRunnable(
      retry, () -> client.execute(postRequest));
  retriableFunc.run();

  // Get Functions Framework plugin process' stdout
  InputStream stdoutStream = emulatorProcess.getErrorStream();
  ByteArrayOutputStream stdoutBytes = new ByteArrayOutputStream();
  stdoutBytes.write(stdoutStream.readNBytes(stdoutStream.available()));

  // Verify desired name value is present
  assertThat(stdoutBytes.toString(StandardCharsets.UTF_8)).contains(
      String.format("File %s uploaded.", name));
}
 
public static void waitUrlAvailable(final String url) throws InterruptedException, IOException {
    for (int i = 0; i < 50; i++) {
        Thread.sleep(100);
        try {
            if (HttpClients.createDefault().execute(new HttpGet(url)).getStatusLine().getStatusCode() > -100)
                break;
        } catch (HttpHostConnectException ex) {
        }
    }
}
 
源代码25 项目: attic-stratos   文件: NginxStatisticsReader.java
/**
 * Make a http request to http://127.0.0.1:<proxy-port>/nginx_status and find writing count.
 * @param proxyPort
 * @return
 */
private int findWritingCount(int proxyPort) {
    try {
        URL url = new URL("http", "127.0.0.1", proxyPort, "/nginx_status");
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpUriRequest request = new HttpGet(url.toURI());
        HttpResponse response = httpClient.execute(request);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("http://127.0.0.1:" + proxyPort + "/nginx_status was not found");
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                (response.getEntity().getContent())));
        String output, result = "";
        while ((output = reader.readLine()) != null) {
            result += output;
        }
        Pattern pattern = Pattern.compile("(Writing: )([0-1]*)");
        Matcher matcher = pattern.matcher(result);
        if (matcher.find()) {
            // Deduct one to remove the above request
            int writingCount = Integer.parseInt(matcher.group(2)) - 1;
            if(log.isDebugEnabled()) {
                log.debug(String.format("Writing count: [proxy] %d [value] %d", proxyPort, writingCount));
            }
            return writingCount;
        }
        throw new RuntimeException("Writing block was not found in nginx_status response");
    } catch (HttpHostConnectException ignore) {
        if(ignore.getMessage().contains("Connection refused")) {
            log.warn("Could not find in-flight request count, connection refused: " +
                    "http://127.0.0.1:" + proxyPort + "/nginx_status");
        }
    } catch (Exception e) {
        log.error("Could not find in-flight request count: http://127.0.0.1:" + proxyPort + "/nginx_status", e);
    }
    return 0;
}
 
源代码26 项目: cs-actions   文件: HttpClientExecutor.java
public CloseableHttpResponse execute() {
    CloseableHttpResponse response;
    try  {
         response = closeableHttpClient.execute(httpRequestBase, context);
    } catch (SocketTimeoutException ste) {
        throw new RuntimeException("Socket timeout: " + ste.getMessage(), ste);
    } catch (HttpHostConnectException connectEx) {
        throw new RuntimeException("Connection error: " + connectEx.getMessage(), connectEx);
    } catch (IOException e) {

        throw new RuntimeException("Error while executing http request: " + e.getMessage(), e);
    }
    return response;
}
 
源代码27 项目: celos   文件: JettyServerTest.java
@Test(expected = HttpHostConnectException.class)
public void testServerStops() throws Exception {
    JettyServer jettyServer = new JettyServer();
    int port = jettyServer.start();

    HttpClient httpClient = new DefaultHttpClient();
    HttpGet workflowListGet = new HttpGet("http://localhost:" + port);
    HttpResponse response = httpClient.execute(workflowListGet);

    Assert.assertEquals(response.getStatusLine().getStatusCode(), 403);
    EntityUtils.consume(response.getEntity());
    jettyServer.stop();

    httpClient.execute(workflowListGet);
}
 
源代码28 项目: oslits   文件: Stm3000Controller.java
/**
 * Jenkins 접속 확인
 * 
 * @param request
 * @param response
 * @param model
 * @return
 * @throws Exception
 */
@SuppressWarnings("rawtypes")
@RequestMapping(value="/stm/stm3000/stm3000/selectStm3000ConfirmConnect.do")
public ModelAndView selectStm3000ConfirmConnect(HttpServletRequest request, HttpServletResponse response, ModelMap model ) throws Exception {

	try{

		// request 파라미터를 map으로 변환
		Map<String, String> paramMap = RequestConvertor.requestParamToMapAddSelInfo(request, true);

		Map jenMap = stm3000Service.selectStm3000JenkinsInfo(paramMap);
		String userId=(String)jenMap.get("jenUsrId");
		String tokenId=(String)jenMap.get("jenUsrTok");
		
		//globals.properties에서 salt값 가져오기
		String salt = EgovProperties.getProperty("Globals.lunaops.salt");
		
		//값 복호화
		String newTokenId = CommonScrty.decryptedAria(tokenId, salt);
		
		//빈값인경우 오류
		if(newTokenId == null || "".equals(newTokenId)){
			model.addAttribute("MSG_CD", JENKINS_SETTING_WORNING);
			return new ModelAndView("jsonView");
		}

		//JENKINS SETTING
		jenkinsClient.setUser(userId);
		jenkinsClient.setPassword(newTokenId);
		
		String url =   (String)jenMap.get("jenUrl")+"/api/json";
		String content = "";

		content = jenkinsClient.excuteHttpClientJenkins(url);

		jenkinsClient.getJenkinsParser(content );

		model.addAttribute("MSG_CD", JENKINS_OK);


		return new ModelAndView("jsonView");
	}
	catch(Exception ex){
		Log.error("selectStm3000ConfirmConnect()", ex);
		if( ex instanceof HttpHostConnectException){
			model.addAttribute("MSG_CD", JENKINS_FAIL);
		}else if( ex instanceof ParseException){
			model.addAttribute("MSG_CD", JENKINS_FAIL);
		}else if( ex instanceof UserDefineException){
				model.addAttribute("MSG_CD", ex.getMessage());
		}else{
			model.addAttribute("MSG_CD", JENKINS_FAIL);
		}
		//조회실패 메시지 세팅 및 저장 성공여부 세팅			
		return new ModelAndView("jsonView");
	}
}
 
源代码29 项目: oslits   文件: Stm3000Controller.java
/**
 * job 접속 확인
 * 
 * @param request
 * @param response
 * @param model
 * @return
 * @throws Exception
 */
@SuppressWarnings("rawtypes")
@RequestMapping(value="/stm/stm3000/stm3000/selectStm3000JobConfirmConnect.do")
public ModelAndView selectStm3000JobConfirmConnect(HttpServletRequest request, HttpServletResponse response, ModelMap model ) throws Exception {
	
	try{
		
		// request 파라미터를 map으로 변환
		Map<String, String> paramMap = RequestConvertor.requestParamToMapAddSelInfo(request, true);
		
		//job 정보 조회
		Map jobMap = stm3000Service.selectStm3000JobInfo(paramMap);
		
		//정보 불러오기
		String jenUsrId=(String)jobMap.get("jenUsrId");
		String jenUsrTok=(String)jobMap.get("jenUsrTok");
		String jobTok=(String)jobMap.get("jobTok");
		String jenUrl=(String)jobMap.get("jenUrl");
		String jobId=(String)jobMap.get("jobId");
		
		//globals.properties에서 salt값 가져오기
		String salt = EgovProperties.getProperty("Globals.lunaops.salt");
		
		//값 복호화
		String deJenUsrTok = CommonScrty.decryptedAria(jenUsrTok, salt);
		String deJobTok = CommonScrty.decryptedAria(jobTok, salt);
		
		//빈값인경우 오류
		if(deJenUsrTok == null || "".equals(deJenUsrTok)){
			model.addAttribute("MSG_CD", JENKINS_SETTING_WORNING);
			return new ModelAndView("jsonView");
		}
		if(deJobTok == null || "".equals(deJobTok)){
			model.addAttribute("MSG_CD", "JOB TOKEN 값이 없습니다.");
			return new ModelAndView("jsonView");
		}
		
		//JENKINS SETTING
		jenkinsClient.setUser(jenUsrId);
		jenkinsClient.setPassword(deJenUsrTok);
		
		String url = jenUrl+"/job/"+jobId+"/config.xml";
		String settingJobTok = "";
		
		settingJobTok = jenkinsClient.excuteHttpClientJobToken(url,deJobTok);
		
		//복호화 token 값과 실제 token값 확인
		if(!deJobTok.equals(settingJobTok)){
			model.addAttribute("MSG_CD", "JOB TOKEN KEY값을 확인해주세요.");
			
			return new ModelAndView("jsonView");
		}
		
		model.addAttribute("MSG_CD", JENKINS_OK);
		
		
		return new ModelAndView("jsonView");
	}
	catch(Exception ex){
		Log.error("selectStm3000JobConfirmConnect()", ex);
		if( ex instanceof HttpHostConnectException){
			model.addAttribute("MSG_CD", JENKINS_FAIL);
		}else if( ex instanceof ParseException){
			model.addAttribute("MSG_CD", JENKINS_FAIL);
		}else if( ex instanceof UserDefineException){
			model.addAttribute("MSG_CD", ex.getMessage());
		}else{
			model.addAttribute("MSG_CD", JENKINS_FAIL);
		}
		//조회실패 메시지 세팅 및 저장 성공여부 세팅			
		return new ModelAndView("jsonView");
	}
}
 
源代码30 项目: oslits   文件: Stm3000Controller.java
/**
 * 
 * Jenkins URL 검증 + JOBList + 로컬 DB 원복 JOB List 가져오기
 * 
 * @param request
 * @param response
 * @param model
 * @return
 * @throws Exception
 */
@SuppressWarnings("rawtypes")
@RequestMapping(value="/stm/stm3000/stm3000/selectStm3000URLConnect.do")
public ModelAndView selectStm3000URLConnect(HttpServletRequest request, HttpServletResponse response, ModelMap model ) throws Exception {

	try{

		// request 파라미터를 map으로 변환
		Map<String, String> paramMap = RequestConvertor.requestParamToMapAddSelInfo(request, true);

		String userId= (String)paramMap.get("jenUsrId");
		String tokenId= (String)paramMap.get("jenUsrTok");
		
		//globals.properties에서 salt값 가져오기
		String salt = EgovProperties.getProperty("Globals.lunaops.salt");
		
		//값 복호화
		tokenId = CommonScrty.decryptedAria(tokenId, salt);
		
		//빈값인경우 오류
		if(tokenId == null || "".equals(tokenId)){
			model.addAttribute("MSG_CD", JENKINS_FAIL);
			return new ModelAndView("jsonView");
		}
		
		//JENKINS SETTING
		jenkinsClient.setUser(userId);
		jenkinsClient.setPassword(tokenId);
		
		String url =   (String)paramMap.get("jenUrl")+"/api/json";
		String content = "";

		content = jenkinsClient.excuteHttpClientJenkins(url);

		Map jenkinsMap= jenkinsClient.getJenkinsParser(content );
		List jobList =  (List) jenkinsMap.get("jobs");

		//job List
		model.addAttribute("list", jobList);
		model.addAttribute("MSG_CD", JENKINS_OK);
		
		//원복 목록 가져오기
		paramMap.put("restoreSelJobType", "03");
		
		//job restore list
		List<Map> jobRestoreList = stm3000Service.selectStm3000JobNormalList(paramMap);
		
		model.addAttribute("jobRestoreList", jobRestoreList);
		return new ModelAndView("jsonView");
	}
	catch(Exception ex){
		Log.error("selectStm3000URLConnect()", ex);
		if( ex instanceof HttpHostConnectException){
			model.addAttribute("MSG_CD", JENKINS_FAIL);
		}else if( ex instanceof ParseException){
			model.addAttribute("MSG_CD", JENKINS_FAIL);
		}else if( ex instanceof IllegalArgumentException){
			model.addAttribute("MSG_CD", JENKINS_WORNING_URL);
		}else if( ex instanceof UserDefineException){
				model.addAttribute("MSG_CD", ex.getMessage());
		}else{
			model.addAttribute("MSG_CD", JENKINS_FAIL);
		}
		//조회실패 메시지 세팅 및 저장 성공여부 세팅			
		return new ModelAndView("jsonView");
	}
}
 
 类所在包
 类方法
 同包方法