java.lang.reflect.UndeclaredThrowableException#getCause ( )源码实例Demo

下面列出了java.lang.reflect.UndeclaredThrowableException#getCause ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: cxf   文件: HeaderClientServerTest.java
@Test
public void testRPCInOutHeader() throws Exception {
    URL wsdl = getClass().getResource("/wsdl/soapheader_rpc.wsdl");
    assertNotNull(wsdl);

    SOAPRPCHeaderService service
        = new SOAPRPCHeaderService(wsdl,
            new QName("http://apache.org/header_test/rpc", "SOAPRPCHeaderService"));
    assertNotNull(service);
    TestRPCHeader proxy = service.getSoapRPCHeaderPort();
    try {
        HeaderMessage header = new HeaderMessage();
        Holder<HeaderMessage> holder = new Holder<>(header);

        for (int idx = 0; idx < 2; idx++) {
            holder.value.setHeaderVal("header" + idx);
            String returnVal = proxy.testInOutHeader("part" + idx, holder);

            assertNotNull(returnVal);
            assertEquals("header" + idx, returnVal);
            assertEquals("part" + idx, holder.value.getHeaderVal());
        }
    } catch (UndeclaredThrowableException ex) {
        throw (Exception)ex.getCause();
    }
}
 
源代码2 项目: visualvm   文件: RemoteHostOverview.java
public double getSystemLoadAverage() {
    if (loadAverageAvailable) {
        checkJmxApp();
        if (jmxApp == null) {
            return -1;
        }
        try {
            return osMXBean.getSystemLoadAverage();
        } catch (UndeclaredThrowableException ex) {
            if (ex.getCause() instanceof ConnectException) {
                jmxApp = null;
                return getSystemLoadAverage();
            }
            throw ex;
        }
    }
    return -1;
}
 
源代码3 项目: cxf   文件: ClientServerWebSocketTest.java
@Test
public void testBasicConnection() throws Exception {

    SOAPService service = new SOAPService();

    Greeter greeter = service.getPort(portName, Greeter.class);
    updateGreeterAddress(greeter, PORT);

    try {
        String reply = greeter.greetMe("test");
        assertNotNull("no response received from service", reply);
        assertEquals("Hello test", reply);

        reply = greeter.sayHi();
        assertNotNull("no response received from service", reply);
        assertEquals("Bonjour", reply);
    } catch (UndeclaredThrowableException ex) {
        throw (Exception)ex.getCause();
    }
    BindingProvider bp = (BindingProvider)greeter;
    Map<String, Object> responseContext = bp.getResponseContext();
    Integer responseCode = (Integer) responseContext.get(Message.RESPONSE_CODE);
    assertEquals(200, responseCode.intValue());
}
 
源代码4 项目: cxf   文件: ClientServerVersioningTest.java
@Test
public void testVersionBasedRouting() throws Exception {

    SOAPService service = new SOAPService();
    assertNotNull(service);

    try {
        Greeter greeter = service.getPort(portName, Greeter.class);
        updateAddressPort(greeter, PORT);

        GreetMe1 request = new GreetMe1();
        request.setRequestType("Bonjour");
        GreetMeResponse greeting = greeter.greetMe(request);
        assertNotNull("no response received from service", greeting);
        assertEquals("Hello Bonjour version1", greeting.getResponseType());

        String reply = greeter.sayHi();
        assertNotNull("no response received from service", reply);
        assertEquals("Bonjour version2", reply);
    } catch (UndeclaredThrowableException ex) {
        throw (Exception)ex.getCause();
    }
}
 
源代码5 项目: cxf   文件: ClientServerMiscTest.java
@Test
public void testMinOccursAndNillableJAXBElement() throws Exception {

    JaxbElementTest_Service service = new JaxbElementTest_Service();
    assertNotNull(service);
    JaxbElementTest port = service.getPort(JaxbElementTest.class);
    updateAddressPort(port, PORT);

    try {

        String response = port.newOperation("hello");
        assertNotNull(response);
        assertEquals("in=hello", response);

        response = port.newOperation(null);
        assertNotNull(response);
        assertEquals("in=null", response);

    } catch (UndeclaredThrowableException ex) {
        throw (Exception) ex.getCause();
    }
}
 
源代码6 项目: cxf   文件: TrivialSOAPHandlerTest.java
@Test
public void testInvocation() throws Exception {

    GreeterService service = new GreeterService();
    assertNotNull(service);

    try {
        Greeter greeter = service.getGreeterPort();
        setAddress(greeter, address);

        String greeting = greeter.greetMe("Bonjour");
        assertNotNull("no response received from service", greeting);
        assertEquals("BONJOUR", greeting);

    } catch (UndeclaredThrowableException ex) {
        throw (Exception)ex.getCause();
    }
}
 
源代码7 项目: cxf   文件: ClientServerWebSocketTest.java
@Test
public void testBasicConnection2() throws Exception {
    URL wsdl = getClass().getResource("/wsdl/hello_world.wsdl");
    assertNotNull(wsdl);

    SOAPService service = new SOAPService(wsdl, serviceName);

    //getPort only passing in SEI
    Greeter greeter = service.getPort(Greeter.class);
    updateGreeterAddress(greeter, PORT);

    String response1 = new String("Hello Milestone-");
    String response2 = new String("Bonjour");
    try {
        for (int idx = 0; idx < 5; idx++) {
            String greeting = greeter.greetMe("Milestone-" + idx);
            assertNotNull("no response received from service", greeting);
            String exResponse = response1 + idx;
            assertEquals(exResponse, greeting);

            String reply = greeter.sayHi();
            assertNotNull("no response received from service", reply);
            assertEquals(response2, reply);

            greeter.greetMeOneWay("Milestone-" + idx);
        }
    } catch (UndeclaredThrowableException ex) {
        throw (Exception)ex.getCause();
    }
}
 
源代码8 项目: cxf   文件: ClientServerXMLTest.java
@Test
public void testXMLBindingOfSoapHeaderWSDL() throws Exception {
    XMLHeaderService service = new XMLHeaderService();
    HeaderTester port = service.getXMLPort9000();
    updateAddressPort(port, REG_PORT);
    try {
        verifyInHeader(port);
        verifyInOutHeader(port);
        verifyOutHeader(port);
    } catch (UndeclaredThrowableException ex) {
        throw (Exception) ex.getCause();
    }
}
 
源代码9 项目: hadoop   文件: TimelineClientImpl.java
private ClientResponse doPosting(final Object obj, final String path)
    throws IOException, YarnException {
  ClientResponse resp;
  try {
    resp = authUgi.doAs(new PrivilegedExceptionAction<ClientResponse>() {
      @Override
      public ClientResponse run() throws Exception {
        return doPostingObject(obj, path);
      }
    });
  } catch (UndeclaredThrowableException e) {
      throw new IOException(e.getCause());
  } catch (InterruptedException ie) {
    throw new IOException(ie);
  }
  if (resp == null ||
      resp.getClientResponseStatus() != ClientResponse.Status.OK) {
    String msg =
        "Failed to get the response from the timeline server.";
    LOG.error(msg);
    if (LOG.isDebugEnabled() && resp != null) {
      String output = resp.getEntity(String.class);
      LOG.debug("HTTP error code: " + resp.getStatus()
          + " Server response : \n" + output);
    }
    throw new YarnException(msg);
  }
  return resp;
}
 
源代码10 项目: cxf   文件: ClientServerWebSocketTest.java
@Test
public void testBasicConnectionAndOneway() throws Exception {
    URL wsdl = getClass().getResource("/wsdl/hello_world.wsdl");
    assertNotNull(wsdl);

    SOAPService service = new SOAPService(wsdl, serviceName);

    Greeter greeter = service.getPort(portName, Greeter.class);
    updateGreeterAddress(greeter, PORT);

    String response1 = new String("Hello Milestone-");
    String response2 = new String("Bonjour");
    try {
        for (int idx = 0; idx < 1; idx++) {
            String greeting = greeter.greetMe("Milestone-" + idx);
            assertNotNull("no response received from service", greeting);
            String exResponse = response1 + idx;
            assertEquals(exResponse, greeting);

            String reply = greeter.sayHi();
            assertNotNull("no response received from service", reply);
            assertEquals(response2, reply);

            greeter.greetMeOneWay("Milestone-" + idx);



        }
    } catch (UndeclaredThrowableException ex) {
        throw (Exception)ex.getCause();
    }
}
 
源代码11 项目: cxf   文件: ClientServerWebSocketTest.java
@Test
public void testBasicAuth() throws Exception {
    URL wsdl = getClass().getResource("/wsdl/hello_world.wsdl");
    assertNotNull(wsdl);

    SOAPService service = new SOAPService(wsdl, serviceName);
    Greeter greeter = service.getPort(portName, Greeter.class);
    updateGreeterAddress(greeter, PORT);

    try {
        //try the jaxws way
        BindingProvider bp = (BindingProvider)greeter;
        bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "BJ");
        bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "pswd");
        String s = greeter.greetMe("secure");
        assertEquals("Hello BJ", s);
        bp.getRequestContext().remove(BindingProvider.USERNAME_PROPERTY);
        bp.getRequestContext().remove(BindingProvider.PASSWORD_PROPERTY);
        ((Closeable)greeter).close();

        greeter = service.getPort(portName, Greeter.class);
        updateGreeterAddress(greeter, PORT);
        //try setting on the conduit directly
        Client client = ClientProxy.getClient(greeter);
        HTTPConduit httpConduit = (HTTPConduit)client.getConduit();
        AuthorizationPolicy policy = new AuthorizationPolicy();
        policy.setUserName("BJ2");
        policy.setPassword("pswd");
        httpConduit.setAuthorization(policy);

        s = greeter.greetMe("secure");
        ((Closeable)greeter).close();
        assertEquals("Hello BJ2", s);
    } catch (UndeclaredThrowableException ex) {
        throw (Exception)ex.getCause();
    }
}
 
源代码12 项目: hadoop   文件: MockAM.java
public AllocateResponse doAllocateAs(UserGroupInformation ugi,
    final AllocateRequest req) throws Exception {
  req.setResponseId(++responseId);
  try {
    return ugi.doAs(new PrivilegedExceptionAction<AllocateResponse>() {
      @Override
      public AllocateResponse run() throws Exception {
        return amRMProtocol.allocate(req);
      }
    });
  } catch (UndeclaredThrowableException e) {
    throw (Exception) e.getCause();
  }
}
 
源代码13 项目: cxf   文件: ClientServerTest.java
@Test
public void testBasicConnection2() throws Exception {
    URL wsdl = getClass().getResource("/wsdl/hello_world.wsdl");
    assertNotNull(wsdl);

    SOAPService service = new SOAPService(wsdl, serviceName);
    assertNotNull(service);

    //getPort only passing in SEI
    Greeter greeter = service.getPort(Greeter.class);
    ((BindingProvider)greeter).getRequestContext()
        .put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
             "http://localhost:" + PORT + "/SoapContext/SoapPort");

    String response1 = new String("Hello Milestone-");
    String response2 = new String("Bonjour");
    try {
        for (int idx = 0; idx < 5; idx++) {
            String greeting = greeter.greetMe("Milestone-" + idx);
            assertNotNull("no response received from service", greeting);
            String exResponse = response1 + idx;
            assertEquals(exResponse, greeting);

            String reply = greeter.sayHi();
            assertNotNull("no response received from service", reply);
            assertEquals(response2, reply);

            greeter.greetMeOneWay("Milestone-" + idx);



        }
    } catch (UndeclaredThrowableException ex) {
        throw (Exception)ex.getCause();
    }
}
 
源代码14 项目: cxf   文件: MAPTestBase.java
@Test
public void testOneway() throws Exception {
    try {
        greeter.greetMeOneWay("implicit_oneway1");
        checkVerification();
    } catch (UndeclaredThrowableException ex) {
        throw (Exception)ex.getCause();
    }
}
 
源代码15 项目: pxf   文件: SecurityServletFilter.java
/**
 * If user impersonation is configured, examines the request for the presence of the expected security headers
 * and create a proxy user to execute further request chain. If security is enabled for the configuration server
 * used for the requests, makes sure that a login UGI for the the Kerberos principal is created and cached for
 * future use.
 * Responds with an HTTP error if the header is missing or the chain processing throws an exception.
 *
 * @param request  http request
 * @param response http response
 * @param chain    filter chain
 */
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {

    // retrieve user header and make sure header is present and is not empty
    final String gpdbUser = getHeaderValue(request, USER_HEADER, true);
    final String transactionId = getHeaderValue(request, TRANSACTION_ID_HEADER, true);
    final Integer segmentId = getHeaderValueInt(request, SEGMENT_ID_HEADER, true);
    final boolean lastCallForSegment = getHeaderValueBoolean(request, LAST_FRAGMENT_HEADER, false);

    final String serverName = StringUtils.defaultIfBlank(getHeaderValue(request, SERVER_HEADER, false), "default");
    final String configDirectory = StringUtils.defaultIfBlank(getHeaderValue(request, CONFIG_HEADER, false), serverName);

    Configuration configuration = configurationFactory.initConfiguration(configDirectory, serverName, gpdbUser, null);

    boolean isUserImpersonation = secureLogin.isUserImpersonationEnabled(configuration);

    // Establish the UGI for the login user or the Kerberos principal for the given server, if applicable
    UserGroupInformation loginUser = secureLogin.getLoginUser(serverName, configDirectory, configuration);

    String serviceUser = loginUser.getUserName();

    if (!isUserImpersonation && Utilities.isSecurityEnabled(configuration)) {
        // When impersonation is disabled and security is enabled
        // we check whether the pxf.service.user.name property was provided
        // and if provided we use the value as the remote user instead of
        // the principal defined in pxf.service.kerberos.principal. However,
        // the principal will need to have proxy privileges on hadoop.
        String pxfServiceUserName = configuration.get(SecureLogin.CONFIG_KEY_SERVICE_USER_NAME);
        if (StringUtils.isNotBlank(pxfServiceUserName)) {
            serviceUser = pxfServiceUserName;
        }
    }

    String remoteUser = (isUserImpersonation ? gpdbUser : serviceUser);

    SessionId session = new SessionId(
            segmentId,
            transactionId,
            remoteUser,
            serverName,
            configuration,
            loginUser);

    final String serviceUserName = serviceUser;

    // Prepare privileged action to run on behalf of proxy user
    PrivilegedExceptionAction<Boolean> action = () -> {
        LOG.debug("Performing request for gpdb_user = {} as [remote_user = {} service_user = {} login_user ={}] with{} impersonation",
                gpdbUser, remoteUser, serviceUserName, loginUser.getUserName(), isUserImpersonation ? "" : "out");
        chain.doFilter(request, response);
        return true;
    };

    try {
        // Retrieve proxy user UGI from the UGI of the logged in user
        UserGroupInformation userGroupInformation = ugiCache
                .getUserGroupInformation(session, isUserImpersonation);

        LOG.debug("Retrieved proxy user {} for server {} and session {}", userGroupInformation, serverName, session);

        // Execute the servlet chain as that user
        userGroupInformation.doAs(action);
    } catch (UndeclaredThrowableException ute) {
        // unwrap the real exception thrown by the action
        throw new ServletException(ute.getCause());
    } catch (InterruptedException ie) {
        throw new ServletException(ie);
    } finally {
        // Optimization to cleanup the cache if it is the last fragment
        LOG.debug("Releasing proxy user for session: {}. {}",
                session, lastCallForSegment ? " Last fragment call" : "");
        try {
            ugiCache.release(session, lastCallForSegment);
        } catch (Throwable t) {
            LOG.error("Error releasing UGICache for session: {}", session, t);
        }
        if (lastCallForSegment) {
            LOG.info("Finished processing {}", session);
        }
    }
}
 
源代码16 项目: openjdk-systemtest   文件: ClassProfiler.java
private void getStatsViaProxy() {
	RuntimeMXBean runtimeBean = null;
	OperatingSystemMXBean osBean = null;
	LoggingMXBean logBean = null;
	ClassLoadingMXBean classBean = null;
	CompilationMXBean compBean = null;

	// Get the proxies for the runtime, os, log and class MXBeans
	try {
		runtimeBean = ManagementFactory.newPlatformMXBeanProxy(this.mbs, ManagementFactory.RUNTIME_MXBEAN_NAME,
				RuntimeMXBean.class);

		osBean = ManagementFactory.newPlatformMXBeanProxy(this.mbs, ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME,
				OperatingSystemMXBean.class);

		logBean = ManagementFactory.newPlatformMXBeanProxy(this.mbs, LogManager.LOGGING_MXBEAN_NAME,
				LoggingMXBean.class);

		classBean = ManagementFactory.newPlatformMXBeanProxy(this.mbs, ManagementFactory.CLASS_LOADING_MXBEAN_NAME,
				ClassLoadingMXBean.class);

		// Check the compiler is being used and get the compilation MXBean
		Map<String, String> props = runtimeBean.getSystemProperties();
		String sys_comp = props.get("java.compiler");

		if ((sys_comp != null) && (!(sys_comp.equals("")))) {
			compBean = ManagementFactory.newPlatformMXBeanProxy(this.mbs, ManagementFactory.COMPILATION_MXBEAN_NAME,
					CompilationMXBean.class);
		}
	} catch (IOException ioe) {
		Message.logOut("A communication problem occurred when accessing the MBeanServerConnection");
		ioe.printStackTrace();
		Assert.fail("A communication problem occurred when accessing the MBeanServerConnection");
	}

	try {
		Message.logOut("Starting to write data");
		// Record the environment data in the log
		this.envData.writeData(runtimeBean, osBean, logBean, false);

		// Record the number of class loaded over time in a csv and record
		// the class data in the log every 10 seconds
		int secondsCnt = 0;
		int writesCnt = 0;
		while (writesCnt < 30) {
			// Write out the threadData every 10 seconds
			if (secondsCnt == 10) {
				System.out.print(".");
				this.classData.writeData(classBean, compBean, runtimeBean, true);
				secondsCnt = 0;
				writesCnt++;
			}
			this.recordClassStats(runtimeBean, classBean);
			Thread.sleep(1000);
			secondsCnt++;
		}
	} catch (InterruptedException ie) {
		Message.logOut("The sleeping profiler was interrupted");
		ie.printStackTrace();
		Assert.fail("The sleeping profiler was interrupted");
	} catch (UndeclaredThrowableException ue) {
		Throwable cause = ue.getCause();
		Class<ConnectException> connectExcept = ConnectException.class;
		Class<UnmarshalException> unmarshalExcept = UnmarshalException.class;

		if (connectExcept.isInstance(cause) || unmarshalExcept.isInstance(cause)) {
			
			// If the exception was caused by a Connect or Unmarshal
			// Exception, assume the monitored JVM has finished. 
			this.closeCSVFile();
			Message.logOut("Exiting as JVM we are connected to has finished");
			Assert.fail("Exiting as JVM we are connected to has finished");
		} else {
			Message.logOut(ue.getMessage());
			ue.printStackTrace();
			Assert.fail(ue.getMessage());
		}
	} finally {
		this.closeCSVFile();
	}
}
 
源代码17 项目: openjdk-systemtest   文件: ThreadProfiler.java
private void getStatsViaProxy() {
	RuntimeMXBean runtimeBean = null;
	OperatingSystemMXBean osBean = null;
	LoggingMXBean logBean = null;
	ThreadMXBean threadBean = null;
	int stackDepth = 8;

	// Get the runtime, os, log and thread MXBeans
	try {
		runtimeBean = ManagementFactory.newPlatformMXBeanProxy(this.mbs, 
				ManagementFactory.RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);
		osBean = ManagementFactory.newPlatformMXBeanProxy(this.mbs, 
				ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class);
		logBean = ManagementFactory.newPlatformMXBeanProxy(this.mbs, 
				LogManager.LOGGING_MXBEAN_NAME, LoggingMXBean.class);
		threadBean = ManagementFactory.newPlatformMXBeanProxy(this.mbs, 
				ManagementFactory.THREAD_MXBEAN_NAME, ThreadMXBean.class);
	} catch (IOException ioe) {
		Message.logOut("A communication problem occurred when accessing the MBeanServerConnection");
		ioe.printStackTrace();
		Assert.fail("A communication problem occurred when accessing the MBeanServerConnection");
	}

	try {
		Message.logOut("Starting to write data");
		this.envData.writeData(runtimeBean, osBean, logBean, false);
		int secondsCnt = 0;
		int writesCnt = 0;
		while (writesCnt < 30) {
			// Write out the threadData 10 seconds
			if (secondsCnt == 10) {
				System.out.print(".");
				this.threadData.writeData(threadBean, stackDepth, true);
				secondsCnt = 0;
				writesCnt++;
			}
			this.recordThreadStats(runtimeBean, threadBean);
			Thread.sleep(1000);
			secondsCnt++;
		}
	} catch (InterruptedException ie) {
		Message.logOut("The sleeping profiler was interrupted");
		ie.printStackTrace();
		Assert.fail("The sleeping profiler was interrupted");
	} catch (UndeclaredThrowableException ue) {
		// If the exception was caused by a Connect or Unmarshal Exception
		// assume the monitored JVM has finished.
		Throwable cause = ue.getCause();
		Class<ConnectException> connectExcept = ConnectException.class;
		Class<UnmarshalException> unmarshalExcept = UnmarshalException.class;

		if (connectExcept.isInstance(cause) || unmarshalExcept.isInstance(cause)) {
			this.closeCSVFile();
			Message.logOut("Exiting as JVM we are connected to has finished");
			Assert.fail("Exiting as JVM we are connected to has finished");
		} else {
			Message.logOut(ue.getMessage());
			ue.printStackTrace();
			Assert.fail(ue.getMessage());
		}
	} finally {
		this.closeCSVFile();
	}
}
 
源代码18 项目: openjdk-systemtest   文件: ThreadMonitor.java
private void getStatsViaProxy() {
	RuntimeMXBean runtimeBean = null;
	OperatingSystemMXBean osBean = null;
	LoggingMXBean logBean = null;
	ThreadMXBean threadBean = null;
	int stackDepth = 8;

	// Get the runtime, os, log and thread MXBeans
	try {
		runtimeBean = ManagementFactory.newPlatformMXBeanProxy(this.mbs, 
				ManagementFactory.RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);
		osBean = ManagementFactory.newPlatformMXBeanProxy(this.mbs, 
				ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class);
		logBean = ManagementFactory.newPlatformMXBeanProxy(this.mbs, 
				LogManager.LOGGING_MXBEAN_NAME, LoggingMXBean.class);
		threadBean = ManagementFactory.newPlatformMXBeanProxy(this.mbs, 
				ManagementFactory.THREAD_MXBEAN_NAME, ThreadMXBean.class);
	} catch (IOException ioe) {
		Message.logOut("A communication problem occurred when "
				+ "accessing the MBeanServerConnection");
		ioe.printStackTrace();
	}

	try {
		this.envData.writeData (runtimeBean, osBean, logBean, false);
		int secondsCnt = 0;
		int writesCnt = 0;
		while (writesCnt < 30) {
			// Write out the threadData 10 seconds 
			if (secondsCnt == 10) {
				Message.logOut("Writing report data ...");
				this.threadData.writeData(threadBean, stackDepth, true);
				Message.logOut(" done.");
				secondsCnt = 0;
				writesCnt++;
			}
			this.recordThreadStats(runtimeBean, threadBean);
			Thread.sleep(1000);
			secondsCnt++;
		}
	} catch (InterruptedException ie) {
		Message.logOut("The sleeping profiler was interrupted");
		ie.printStackTrace();
	} catch (UndeclaredThrowableException ue) {
		// if the exception was caused by a Connect or Unmarshal Exception assume the 
		// monitored JVM has finished.
		Throwable cause = ue.getCause();
		Class<ConnectException> connectExcept = ConnectException.class;
		Class<UnmarshalException> unmarshalExcept = UnmarshalException.class;

		if (connectExcept.isInstance(cause) || unmarshalExcept.isInstance(cause)) {
			this.closeCSVFile();
			System.exit(0);
		} else { 
			throw ue;
		}
	} finally {
		this.closeCSVFile();
	}
}
 
源代码19 项目: big-c   文件: RMWebServices.java
@DELETE
@Path("/delegation-token")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response cancelDelegationToken(@Context HttpServletRequest hsr)
    throws AuthorizationException, IOException, InterruptedException,
    Exception {

  init();
  UserGroupInformation callerUGI;
  try {
    callerUGI = createKerberosUserGroupInformation(hsr);
  } catch (YarnException ye) {
    return Response.status(Status.FORBIDDEN).entity(ye.getMessage()).build();
  }

  Token<RMDelegationTokenIdentifier> token = extractToken(hsr);

  org.apache.hadoop.yarn.api.records.Token dToken =
      BuilderUtils.newDelegationToken(token.getIdentifier(), token.getKind()
        .toString(), token.getPassword(), token.getService().toString());
  final CancelDelegationTokenRequest req =
      CancelDelegationTokenRequest.newInstance(dToken);

  try {
    callerUGI
      .doAs(new PrivilegedExceptionAction<CancelDelegationTokenResponse>() {
        @Override
        public CancelDelegationTokenResponse run() throws IOException,
            YarnException {
          return rm.getClientRMService().cancelDelegationToken(req);
        }
      });
  } catch (UndeclaredThrowableException ue) {
    if (ue.getCause() instanceof YarnException) {
      if (ue.getCause().getCause() instanceof InvalidToken) {
        throw new BadRequestException(ue.getCause().getCause().getMessage());
      } else if (ue.getCause().getCause() instanceof org.apache.hadoop.security.AccessControlException) {
        return Response.status(Status.FORBIDDEN)
          .entity(ue.getCause().getCause().getMessage()).build();
      }
      LOG.info("Renew delegation token request failed", ue);
      throw ue;
    }
    LOG.info("Renew delegation token request failed", ue);
    throw ue;
  } catch (Exception e) {
    LOG.info("Renew delegation token request failed", e);
    throw e;
  }

  return Response.status(Status.OK).build();
}
 
源代码20 项目: big-c   文件: RMWebServices.java
/**
 * Function to submit an app to the RM
 * 
 * @param newApp
 *          structure containing information to construct the
 *          ApplicationSubmissionContext
 * @param hsr
 *          the servlet request
 * @return Response containing the status code
 * @throws AuthorizationException
 * @throws IOException
 * @throws InterruptedException
 */
@POST
@Path("/apps")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response submitApplication(ApplicationSubmissionContextInfo newApp,
    @Context HttpServletRequest hsr) throws AuthorizationException,
    IOException, InterruptedException {

  init();
  UserGroupInformation callerUGI = getCallerUserGroupInformation(hsr, true);
  if (callerUGI == null) {
    throw new AuthorizationException("Unable to obtain user name, "
        + "user not authenticated");
  }

  if (UserGroupInformation.isSecurityEnabled() && isStaticUser(callerUGI)) {
    String msg = "The default static user cannot carry out this operation.";
    return Response.status(Status.FORBIDDEN).entity(msg).build();
  }

  ApplicationSubmissionContext appContext =
      createAppSubmissionContext(newApp);
  final SubmitApplicationRequest req =
      SubmitApplicationRequest.newInstance(appContext);

  try {
    callerUGI
      .doAs(new PrivilegedExceptionAction<SubmitApplicationResponse>() {
        @Override
        public SubmitApplicationResponse run() throws IOException,
            YarnException {
          return rm.getClientRMService().submitApplication(req);
        }
      });
  } catch (UndeclaredThrowableException ue) {
    if (ue.getCause() instanceof YarnException) {
      throw new BadRequestException(ue.getCause().getMessage());
    }
    LOG.info("Submit app request failed", ue);
    throw ue;
  }

  String url = hsr.getRequestURL() + "/" + newApp.getApplicationId();
  return Response.status(Status.ACCEPTED).header(HttpHeaders.LOCATION, url)
    .build();
}