List of usage examples for java.security PrivilegedAction PrivilegedAction
PrivilegedAction
From source file:org.apache.accumulo.tserver.replication.AccumuloReplicaSystem.java
protected Status replicateLogs(ClientContext peerContext, final HostAndPort peerTserver, final ReplicationTarget target, final Path p, final Status status, final long sizeLimit, final String remoteTableId, final TCredentials tcreds, final ReplicaSystemHelper helper, final UserGroupInformation accumuloUgi) throws TTransportException, AccumuloException, AccumuloSecurityException { log.debug("Replication WAL to peer tserver"); final Set<Integer> tids; final DataInputStream input; Span span = Trace.start("Read WAL header"); span.data("file", p.toString()); try {//from w w w .ja v a 2s . co m input = getWalStream(p); } catch (LogHeaderIncompleteException e) { log.warn( "Could not read header from {}, assuming that there is no data present in the WAL, therefore replication is complete", p); Status newStatus; // Bump up the begin to the (infinite) end, trying to be accurate if (status.getInfiniteEnd()) { newStatus = Status.newBuilder(status).setBegin(Long.MAX_VALUE).build(); } else { newStatus = Status.newBuilder(status).setBegin(status.getEnd()).build(); } span = Trace.start("Update replication table"); try { helper.recordNewStatus(p, newStatus, target); } catch (TableNotFoundException tnfe) { log.error("Tried to update status in replication table for {} as {}, but the table did not exist", p, ProtobufUtil.toString(newStatus), e); throw new RuntimeException("Replication table did not exist, will retry", e); } finally { span.stop(); } return newStatus; } catch (IOException e) { log.error("Could not create stream for WAL", e); // No data sent (bytes nor records) and no progress made return status; } finally { span.stop(); } log.debug("Skipping unwanted data in WAL"); span = Trace.start("Consume WAL prefix"); span.data("file", p.toString()); try { // We want to read all records in the WAL up to the "begin" offset contained in the Status message, // building a Set of tids from DEFINE_TABLET events which correspond to table ids for future mutations tids = consumeWalPrefix(target, input, p, status, sizeLimit); } catch (IOException e) { log.warn("Unexpected error consuming file."); return status; } finally { span.stop(); } log.debug("Sending batches of data to peer tserver"); Status lastStatus = status, currentStatus = status; final AtomicReference<Exception> exceptionRef = new AtomicReference<>(); while (true) { // Set some trace info span = Trace.start("Replicate WAL batch"); span.data("Batch size (bytes)", Long.toString(sizeLimit)); span.data("File", p.toString()); span.data("Peer instance name", peerContext.getInstance().getInstanceName()); span.data("Peer tserver", peerTserver.toString()); span.data("Remote table ID", remoteTableId); ReplicationStats replResult; try { // Read and send a batch of mutations replResult = ReplicationClient.executeServicerWithReturn(peerContext, peerTserver, new WalClientExecReturn(target, input, p, currentStatus, sizeLimit, remoteTableId, tcreds, tids)); } catch (Exception e) { log.error("Caught exception replicating data to {} at {}", peerContext.getInstance().getInstanceName(), peerTserver, e); throw e; } finally { span.stop(); } // Catch the overflow long newBegin = currentStatus.getBegin() + replResult.entriesConsumed; if (newBegin < 0) { newBegin = Long.MAX_VALUE; } currentStatus = Status.newBuilder(currentStatus).setBegin(newBegin).build(); log.debug("Sent batch for replication of {} to {}, with new Status {}", p, target, ProtobufUtil.toString(currentStatus)); // If we got a different status if (!currentStatus.equals(lastStatus)) { span = Trace.start("Update replication table"); try { if (null != accumuloUgi) { final Status copy = currentStatus; accumuloUgi.doAs(new PrivilegedAction<Void>() { @Override public Void run() { try { helper.recordNewStatus(p, copy, target); } catch (Exception e) { exceptionRef.set(e); } return null; } }); Exception e = exceptionRef.get(); if (null != e) { if (e instanceof TableNotFoundException) { throw (TableNotFoundException) e; } else if (e instanceof AccumuloSecurityException) { throw (AccumuloSecurityException) e; } else if (e instanceof AccumuloException) { throw (AccumuloException) e; } else { throw new RuntimeException("Received unexpected exception", e); } } } else { helper.recordNewStatus(p, currentStatus, target); } } catch (TableNotFoundException e) { log.error( "Tried to update status in replication table for {} as {}, but the table did not exist", p, ProtobufUtil.toString(currentStatus), e); throw new RuntimeException("Replication table did not exist, will retry", e); } finally { span.stop(); } log.debug("Recorded updated status for {}: {}", p, ProtobufUtil.toString(currentStatus)); // If we don't have any more work, just quit if (!StatusUtil.isWorkRequired(currentStatus)) { return currentStatus; } else { // Otherwise, let it loop and replicate some more data lastStatus = currentStatus; } } else { log.debug("Did not replicate any new data for {} to {}, (state was {})", p, target, ProtobufUtil.toString(lastStatus)); // otherwise, we didn't actually replicate (likely because there was error sending the data) // we can just not record any updates, and it will be picked up again by the work assigner return status; } } }
From source file:org.apache.hadoop.tools.mapred.TestCopyMapper.java
@Test(timeout = 40000) public void testSkipCopyNoPerms() { try {// ww w. jav a 2 s . c om deleteState(); createSourceData(); UserGroupInformation tmpUser = UserGroupInformation.createRemoteUser("guest"); final CopyMapper copyMapper = new CopyMapper(); final StubContext stubContext = tmpUser.doAs(new PrivilegedAction<StubContext>() { @Override public StubContext run() { try { return new StubContext(getConfiguration(), null, 0); } catch (Exception e) { LOG.error("Exception encountered ", e); throw new RuntimeException(e); } } }); final Mapper<Text, CopyListingFileStatus, Text, Text>.Context context = stubContext.getContext(); EnumSet<DistCpOptions.FileAttribute> preserveStatus = EnumSet.allOf(DistCpOptions.FileAttribute.class); preserveStatus.remove(DistCpOptions.FileAttribute.ACL); preserveStatus.remove(DistCpOptions.FileAttribute.XATTR); preserveStatus.remove(DistCpOptions.FileAttribute.TIMES); context.getConfiguration().set(DistCpConstants.CONF_LABEL_PRESERVE_STATUS, DistCpUtils.packAttributes(preserveStatus)); touchFile(SOURCE_PATH + "/src/file"); touchFile(TARGET_PATH + "/src/file"); cluster.getFileSystem().setPermission(new Path(SOURCE_PATH + "/src/file"), new FsPermission(FsAction.READ, FsAction.READ, FsAction.READ)); cluster.getFileSystem().setPermission(new Path(TARGET_PATH + "/src/file"), new FsPermission(FsAction.READ, FsAction.READ, FsAction.READ)); final FileSystem tmpFS = tmpUser.doAs(new PrivilegedAction<FileSystem>() { @Override public FileSystem run() { try { return FileSystem.get(configuration); } catch (IOException e) { LOG.error("Exception encountered ", e); Assert.fail("Test failed: " + e.getMessage()); throw new RuntimeException("Test ought to fail here"); } } }); tmpUser.doAs(new PrivilegedAction<Integer>() { @Override public Integer run() { try { copyMapper.setup(context); copyMapper.map(new Text("/src/file"), new CopyListingFileStatus(tmpFS.getFileStatus(new Path(SOURCE_PATH + "/src/file"))), context); Assert.assertEquals(stubContext.getWriter().values().size(), 1); Assert.assertTrue(stubContext.getWriter().values().get(0).toString().startsWith("SKIP")); Assert.assertTrue(stubContext.getWriter().values().get(0).toString() .contains(SOURCE_PATH + "/src/file")); } catch (Exception e) { throw new RuntimeException(e); } return null; } }); } catch (Exception e) { LOG.error("Exception encountered ", e); Assert.fail("Test failed: " + e.getMessage()); } }
From source file:org.acmsl.commons.regexpplugin.RegexpManager.java
/** * Retrieves the stream associated to the resource * whose name is given, using a concrete class loader. * @param loader the class loader.//from w ww.j av a2 s .co m * @param name the resource name. * @return the stream. */ @Nullable protected InputStream getResourceAsStream(@Nullable final ClassLoader loader, @NotNull final String name) { return AccessController.doPrivileged(new PrivilegedAction<InputStream>() { public InputStream run() { final InputStream result; if (loader != null) { result = loader.getResourceAsStream(name); } else { result = ClassLoader.getSystemResourceAsStream(name); } return result; } }); }
From source file:org.apache.axis2.util.Utils.java
/** * This method will provide the logic needed to retrieve an Object's classloader * in a Java 2 Security compliant manner. *//*from w ww. j a v a 2s. c om*/ public static ClassLoader getObjectClassLoader(final Object object) { if (object == null) { return null; } else { return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return object.getClass().getClassLoader(); } }); } }
From source file:org.apache.ranger.plugin.store.rest.ServiceRESTStore.java
@Override public ServicePolicies getServicePoliciesIfUpdated(final String serviceName, final Long lastKnownVersion) throws Exception { if (LOG.isDebugEnabled()) { LOG.debug("==> ServiceRESTStore.getServicePoliciesIfUpdated(" + serviceName + ", " + lastKnownVersion + ")"); }/* w w w . j a v a 2 s .com*/ ServicePolicies ret = null; ClientResponse response = null; if (MiscUtil.getUGILoginUser() != null && UserGroupInformation.isSecurityEnabled()) { LOG.info("Checking Service policy if updated as user : " + MiscUtil.getUGILoginUser()); PrivilegedAction<ClientResponse> action = new PrivilegedAction<ClientResponse>() { public ClientResponse run() { WebResource secureWebResource = createWebResource( REST_URL_POLICY_GET_FOR_SECURE_SERVICE_IF_UPDATED + serviceName + "/" + lastKnownVersion); return secureWebResource.accept(REST_MIME_TYPE_JSON).get(ClientResponse.class); }; }; response = MiscUtil.getUGILoginUser().doAs(action); } else { WebResource webResource = createWebResource( REST_URL_POLICY_GET_FOR_SERVICE_IF_UPDATED + serviceName + "/" + lastKnownVersion); response = webResource.accept(REST_MIME_TYPE_JSON).get(ClientResponse.class); } if (response != null && response.getStatus() == 200) { ret = response.getEntity(ServicePolicies.class); } else if (!(response != null && response.getStatus() == 304)) { RESTResponse resp = RESTResponse.fromClientResponse(response); throw new Exception(resp.getMessage()); } if (LOG.isDebugEnabled()) { LOG.debug("<== ServiceRESTStore.getServicePoliciesIfUpdated(" + serviceName + ", " + lastKnownVersion + "): " + ret); } return ret; }
From source file:com.inmobi.conduit.distcp.tools.mapred.TestCopyMapper.java
@Test public void testSkipCopyNoPerms() { try {/*from w w w. j av a 2 s . c om*/ deleteState(); createSourceData(); final InMemoryWriter writer = new InMemoryWriter(); UserGroupInformation tmpUser = UserGroupInformation.createRemoteUser("guest"); final CopyMapper copyMapper = new CopyMapper(); final Mapper<Text, FileStatus, NullWritable, Text>.Context context = tmpUser .doAs(new PrivilegedAction<Mapper<Text, FileStatus, NullWritable, Text>.Context>() { @Override public Mapper<Text, FileStatus, NullWritable, Text>.Context run() { try { StatusReporter reporter = new StubStatusReporter(); return getMapperContext(copyMapper, reporter, writer); } catch (Exception e) { LOG.error("Exception encountered ", e); throw new RuntimeException(e); } } }); EnumSet<DistCpOptions.FileAttribute> preserveStatus = EnumSet.allOf(DistCpOptions.FileAttribute.class); context.getConfiguration().set(DistCpConstants.CONF_LABEL_PRESERVE_STATUS, DistCpUtils.packAttributes(preserveStatus)); touchFile(SOURCE_PATH + "/src/file.gz"); touchFile(TARGET_PATH + "/src/file.gz"); cluster.getFileSystem().setPermission(new Path(SOURCE_PATH + "/src/file.gz"), new FsPermission(FsAction.READ, FsAction.READ, FsAction.READ)); cluster.getFileSystem().setPermission(new Path(TARGET_PATH + "/src/file.gz"), new FsPermission(FsAction.READ, FsAction.READ, FsAction.READ)); final FileSystem tmpFS = tmpUser.doAs(new PrivilegedAction<FileSystem>() { @Override public FileSystem run() { try { return FileSystem.get(configuration); } catch (IOException e) { LOG.error("Exception encountered ", e); Assert.fail("Test failed: " + e.getMessage()); throw new RuntimeException("Test ought to fail here"); } } }); tmpUser.doAs(new PrivilegedAction<Integer>() { @Override public Integer run() { try { copyMapper.setup(context); copyMapper.map(new Text("/src/file.gz"), tmpFS.getFileStatus(new Path(SOURCE_PATH + "/src/file.gz")), context); } catch (Exception e) { throw new RuntimeException(e); } return null; } }); } catch (Exception e) { LOG.error("Exception encountered ", e); Assert.fail("Test failed: " + e.getMessage()); } }
From source file:org.apache.axis2.deployment.util.Utils.java
/** * Modules can contain services in some cases. This method will deploy all the services * for a given AxisModule into the current AxisConfiguration. * <p>/* ww w . ja v a2 s .c om*/ * The code looks for an "aars/" directory inside the module (either .mar or exploded), * and an "aars.list" file inside that to figure out which services to deploy. Note that all * services deployed this way will have access to the Module's classes. * </p> * * @param module the AxisModule to search for services * @param configCtx ConfigurationContext in which to deploy */ public static void deployModuleServices(AxisModule module, ConfigurationContext configCtx) throws AxisFault { try { AxisConfiguration axisConfig = configCtx.getAxisConfiguration(); ArchiveReader archiveReader = new ArchiveReader(); PhasesInfo phasesInfo = axisConfig.getPhasesInfo(); final ClassLoader moduleClassLoader = module.getModuleClassLoader(); ArrayList services = new ArrayList(); final InputStream in = (InputStream) org.apache.axis2.java.security.AccessController .doPrivileged(new PrivilegedAction() { public Object run() { return moduleClassLoader.getResourceAsStream("aars/aars.list"); } }); if (in != null) { BufferedReader input; try { input = new BufferedReader((InputStreamReader) org.apache.axis2.java.security.AccessController .doPrivileged(new PrivilegedAction() { public Object run() { return new InputStreamReader(in); } })); String line; while ((line = input.readLine()) != null) { line = line.trim(); if (line.length() > 0 && line.charAt(0) != '#') { services.add(line); } } input.close(); } catch (IOException ex) { ex.printStackTrace(); } } if (services.size() > 0) { for (Object service1 : services) { final String servicename = (String) service1; if (servicename == null || "".equals(servicename)) { continue; } InputStream fin = (InputStream) org.apache.axis2.java.security.AccessController .doPrivileged(new PrivilegedAction() { public Object run() { return moduleClassLoader.getResourceAsStream("aars/" + servicename); } }); if (fin == null) { throw new AxisFault("No service archive found : " + servicename); } File inputFile = Utils.createTempFile(servicename, fin, (File) axisConfig.getParameterValue(Constants.Configuration.ARTIFACTS_TEMP_DIR)); DeploymentFileData filedata = new DeploymentFileData(inputFile); filedata.setClassLoader(false, moduleClassLoader, (File) axisConfig.getParameterValue(Constants.Configuration.ARTIFACTS_TEMP_DIR), axisConfig.isChildFirstClassLoading()); HashMap wsdlservice = archiveReader.processWSDLs(filedata); if (wsdlservice != null && wsdlservice.size() > 0) { Iterator servicesitr = wsdlservice.values().iterator(); while (servicesitr.hasNext()) { AxisService service = (AxisService) servicesitr.next(); Iterator operations = service.getOperations(); while (operations.hasNext()) { AxisOperation axisOperation = (AxisOperation) operations.next(); phasesInfo.setOperationPhases(axisOperation); } } } AxisServiceGroup serviceGroup = new AxisServiceGroup(axisConfig); serviceGroup.setServiceGroupClassLoader(filedata.getClassLoader()); ArrayList serviceList = archiveReader.processServiceGroup(filedata.getAbsolutePath(), filedata, serviceGroup, false, wsdlservice, configCtx); for (Object aServiceList : serviceList) { AxisService axisService = (AxisService) aServiceList; Parameter moduleService = new Parameter(); moduleService.setValue("true"); moduleService.setName(AxisModule.MODULE_SERVICE); axisService.addParameter(moduleService); serviceGroup.addService(axisService); } axisConfig.addServiceGroup(serviceGroup); fin.close(); } } } catch (IOException e) { throw AxisFault.makeFault(e); } }
From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractAuthenticationController.java
@RequestMapping(value = "/reset_password", method = RequestMethod.POST, params = "username") public String requestReset(@RequestParam(value = "username", required = true) final String username, HttpServletRequest request, ModelMap map) { logger.debug("###Entering in requestReset(username,request) method @POST"); String showSuffixControl = "false"; if (config.getValue(Names.com_citrix_cpbm_username_duplicate_allowed).equals("true")) { showSuffixControl = "true"; map.addAttribute("useSmallCss", "true"); }/* ww w . j av a2s . c o m*/ map.addAttribute("showSuffixControl", showSuffixControl); try { User user = privilegeService.runAsPortal(new PrivilegedAction<User>() { @Override public User run() { return userService.getUserByParam("username", username, false); } }); if (user.isEmailVerified()) { userService.sendResetPasswordMail(user, "reset.password", user.getUsername()); } } catch (NoSuchUserException ex) { // no indication to user that this failed. return "auth.request_reset_success"; } logger.debug("###Exiting requestReset(username,request) method @POST"); return "auth.request_reset_success"; }
From source file:org.apache.axiom.om.util.StAXUtils.java
private static XMLOutputFactory newXMLOutputFactory(final ClassLoader classLoader, final StAXWriterConfiguration configuration) { return (XMLOutputFactory) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { ClassLoader savedClassLoader; if (classLoader == null) { savedClassLoader = null; } else { savedClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(classLoader); }/*w ww. j a v a2 s .com*/ try { XMLOutputFactory factory = XMLOutputFactory.newInstance(); factory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.FALSE); Map props = loadFactoryProperties("XMLOutputFactory.properties"); if (props != null) { for (Iterator it = props.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); factory.setProperty((String) entry.getKey(), entry.getValue()); } } StAXDialect dialect = StAXDialectDetector.getDialect(factory.getClass()); if (configuration != null) { factory = configuration.configure(factory, dialect); } return new ImmutableXMLOutputFactory(dialect.normalize(dialect.makeThreadSafe(factory))); } finally { if (savedClassLoader != null) { Thread.currentThread().setContextClassLoader(savedClassLoader); } } } }); }
From source file:org.apache.hadoop.tools.mapred.TestCopyMapper.java
@Test(timeout = 40000) public void testFailCopyWithAccessControlException() { try {/* w ww . ja v a 2 s. c o m*/ deleteState(); createSourceData(); UserGroupInformation tmpUser = UserGroupInformation.createRemoteUser("guest"); final CopyMapper copyMapper = new CopyMapper(); final StubContext stubContext = tmpUser.doAs(new PrivilegedAction<StubContext>() { @Override public StubContext run() { try { return new StubContext(getConfiguration(), null, 0); } catch (Exception e) { LOG.error("Exception encountered ", e); throw new RuntimeException(e); } } }); EnumSet<DistCpOptions.FileAttribute> preserveStatus = EnumSet.allOf(DistCpOptions.FileAttribute.class); preserveStatus.remove(DistCpOptions.FileAttribute.ACL); preserveStatus.remove(DistCpOptions.FileAttribute.XATTR); final Mapper<Text, CopyListingFileStatus, Text, Text>.Context context = stubContext.getContext(); context.getConfiguration().set(DistCpConstants.CONF_LABEL_PRESERVE_STATUS, DistCpUtils.packAttributes(preserveStatus)); touchFile(SOURCE_PATH + "/src/file"); OutputStream out = cluster.getFileSystem().create(new Path(TARGET_PATH + "/src/file")); out.write("hello world".getBytes()); out.close(); cluster.getFileSystem().setPermission(new Path(SOURCE_PATH + "/src/file"), new FsPermission(FsAction.READ, FsAction.READ, FsAction.READ)); cluster.getFileSystem().setPermission(new Path(TARGET_PATH + "/src/file"), new FsPermission(FsAction.READ, FsAction.READ, FsAction.READ)); final FileSystem tmpFS = tmpUser.doAs(new PrivilegedAction<FileSystem>() { @Override public FileSystem run() { try { return FileSystem.get(configuration); } catch (IOException e) { LOG.error("Exception encountered ", e); Assert.fail("Test failed: " + e.getMessage()); throw new RuntimeException("Test ought to fail here"); } } }); tmpUser.doAs(new PrivilegedAction<Integer>() { @Override public Integer run() { try { copyMapper.setup(context); copyMapper.map(new Text("/src/file"), new CopyListingFileStatus(tmpFS.getFileStatus(new Path(SOURCE_PATH + "/src/file"))), context); Assert.fail("Didn't expect the file to be copied"); } catch (AccessControlException ignore) { } catch (Exception e) { // We want to make sure the underlying cause of the exception is // due to permissions error. The exception we're interested in is // wrapped twice - once in RetriableCommand and again in CopyMapper // itself. if (e.getCause() == null || e.getCause().getCause() == null || !(e.getCause().getCause() instanceof AccessControlException)) { throw new RuntimeException(e); } } return null; } }); } catch (Exception e) { LOG.error("Exception encountered ", e); Assert.fail("Test failed: " + e.getMessage()); } }