Example usage for java.lang.reflect Constructor setAccessible

List of usage examples for java.lang.reflect Constructor setAccessible

Introduction

In this page you can find the example usage for java.lang.reflect Constructor setAccessible.

Prototype

@Override
@CallerSensitive
public void setAccessible(boolean flag) 

Source Link

Document

A SecurityException is also thrown if this object is a Constructor object for the class Class and flag is true.

Usage

From source file:org.apache.nifi.toolkit.tls.util.TlsHelperTest.java

@Before
public void setup() throws Exception {
    days = 360;//from  w ww  . ja  va2s.  co  m
    keySize = 2048;
    keyPairAlgorithm = "RSA";
    signingAlgorithm = "SHA1WITHRSA";
    keyPairGenerator = KeyPairGenerator.getInstance(keyPairAlgorithm);
    keyPairGenerator.initialize(keySize);
    Constructor<KeyStore> keyStoreConstructor = KeyStore.class.getDeclaredConstructor(KeyStoreSpi.class,
            Provider.class, String.class);
    keyStoreConstructor.setAccessible(true);
    keyStore = keyStoreConstructor.newInstance(keyStoreSpi, keyStoreProvider, "faketype");
    keyStore.load(null, null);
    file = File.createTempFile("keystore", "file");
    when(outputStreamFactory.create(file)).thenReturn(tmpFileOutputStream);
}

From source file:com.novartis.opensource.yada.format.AbstractResponse.java

/**
 * Derives the default converter using the format and protocol values.
 * @param yqr the result container//from   w  ww  .  ja  v  a2 s. c  o  m
 * @return the default Converter
 * @throws YADARequestException when the default converter cannot be instantiated
 * @throws YADAConverterException when result reformatting fails
 * @throws YADAQueryConfigurationException 
 */
protected Converter getDefaultConverter(YADAQueryResult yqr)
        throws YADARequestException, YADAConverterException, YADAQueryConfigurationException {
    Converter converter = null;
    String format = yqr.getYADAQueryParamValue(YADARequest.PS_FORMAT);
    String type = "";
    String className = "";
    try {
        if (yqr.isFormatStructured()) {
            format = format.toUpperCase();
        } else {
            format = DELIMITED;
        }

        if (getProtocol().equals(Parser.JDBC)) {
            type = RESULTSET_RESULT;
        } else if (getProtocol().equals(Parser.SOAP)) {
            type = SOAP_RESULT;
        } else if (getProtocol().equals(Parser.REST)) {
            type = REST_RESULT;
        } else if (getProtocol().equals(Parser.FILE)) {
            type = FILESYSTEM_RESULT;
        } else {
            String msg = "The converter you are attempting to instantiate requires a protocol or class that is not supported.  This could be a configuration issue.";
            throw new YADAQueryConfigurationException(msg);
        }
        className = FORMAT_PKG + type + format + CONVERTER;
        Constructor<?> c = Class.forName(className).getConstructor(new Class[] { YADAQueryResult.class });
        c.setAccessible(true);
        converter = (AbstractConverter) c.newInstance(new Object[] { yqr });
    } catch (InstantiationException e) {
        String msg = "Could not instantiate Converter.";
        throw new YADARequestException(msg, e);
    } catch (IllegalAccessException e) {
        String msg = "Could not access Converter class.";
        throw new YADARequestException(msg, e);
    } catch (ClassNotFoundException e) {
        String msg = "Could not find Converter class";
        throw new YADARequestException(msg, e);
    } catch (NoSuchMethodException e) {
        String msg = "There appears to be no Converter constructor accepting a YADAQueryResult parameter.";
        throw new YADARequestException(msg, e);
    } catch (SecurityException e) {
        String msg = "There appears to be no public Converter constructor accepting a YADAQueryResult parameter.";
        throw new YADARequestException(msg, e);
    } catch (IllegalArgumentException e) {
        String msg = "There appears to be no public Converter constructor accepting a YADAQueryResult parameter.";
        throw new YADARequestException(msg, e);
    } catch (InvocationTargetException e) {
        String msg = "There appears to be no public Converter constructor accepting a YADAQueryResult parameter.";
        throw new YADARequestException(msg, e);
    }
    return converter;
}

From source file:org.echocat.jomon.maven.boot.ArtifactFactory.java

@Nonnull
protected Object createCliRequest(@Nonnull ClassWorld classWorld, @Nonnull Class<?> cliRequestClass)
        throws Exception {
    final Constructor<?> constructor = cliRequestClass.getDeclaredConstructor(String[].class, ClassWorld.class);
    constructor.setAccessible(true);
    return constructor.newInstance(new String[0], classWorld);
}

From source file:org.apache.olingo.client.core.communication.request.AbstractODataRequest.java

/**
 * Gets an empty response that can be initialized by a stream.
 * <br/>// ww w  . j  a v a 2  s .  co m
 * This method has to be used to build response items about a batch request.
 *
 * @param <V> ODataResponse type.
 * @return empty OData response instance.
 */
@SuppressWarnings("unchecked")
public <V extends ODataResponse> V getResponseTemplate() {
    for (Class<?> clazz : this.getClass().getDeclaredClasses()) {
        if (ODataResponse.class.isAssignableFrom(clazz)) {
            try {
                final Constructor<?> constructor = clazz.getDeclaredConstructor(this.getClass(),
                        ODataClient.class, HttpClient.class, HttpResponse.class);
                constructor.setAccessible(true);
                return (V) constructor.newInstance(this, odataClient, httpClient, null);
            } catch (Exception e) {
                LOG.error("Error retrieving response class template instance", e);
            }
        }
    }

    throw new IllegalStateException("No response class template has been found");
}

From source file:com.arpnetworking.steno.LogValueMapFactoryTest.java

@Test
public void testPrivateConstructor() throws Exception {
    final Constructor<LogValueMapFactory> constructor = LogValueMapFactory.class.getDeclaredConstructor();
    Assert.assertNotNull(constructor);//from w w w .  ja  v a2  s .c  o m
    try {
        constructor.newInstance();
        Assert.fail("Static helper class should have private no-args constructor");
    } catch (final IllegalAccessException e) {
        constructor.setAccessible(true);
        final LogValueMapFactory logValueMapFactory = constructor.newInstance();
        Assert.assertNotNull(logValueMapFactory);
    }
}

From source file:com.smartitengineering.emailq.service.impl.EmailServiceImpl.java

@Inject
public void initSendMailCron() {
    if (!cronEnabled.booleanValue()) {
        return;//from w  w  w  .ja v  a  2s.co m
    }
    try {
        transport = session.getTransport("smtp");
    } catch (Exception ex) {
        logger.error("Could not initialize SMTP transport", ex);
        throw new IllegalStateException(ex);
    }
    try {
        scheduler = StdSchedulerFactory.getDefaultScheduler();
        JobDetail detail = new JobDetail("sendEmailJob", "sendEmailPoll", SendEmailJob.class);
        Trigger trigger = new DateIntervalTrigger("sendEmailTrigger", "sendEmailPoll",
                DateIntervalTrigger.IntervalUnit.SECOND, period.intValue());
        scheduler.setJobFactory(new JobFactory() {

            public Job newJob(TriggerFiredBundle bundle) throws SchedulerException {
                try {
                    Class<? extends Job> jobClass = bundle.getJobDetail().getJobClass();
                    if (EmailServiceImpl.class.equals(jobClass.getEnclosingClass())) {
                        Constructor<? extends Job> constructor = (Constructor<? extends Job>) jobClass
                                .getDeclaredConstructors()[0];
                        constructor.setAccessible(true);
                        Job job = constructor.newInstance(EmailServiceImpl.this);
                        return job;
                    } else {
                        return jobClass.newInstance();
                    }
                } catch (Exception ex) {
                    throw new SchedulerException(ex);
                }
            }
        });
        scheduler.start();
        scheduler.scheduleJob(detail, trigger);
    } catch (Exception ex) {
        logger.error("Could not start cron job!", ex);
        throw new IllegalStateException(ex);
    }
}

From source file:com.google.apphosting.vmruntime.VmApiProxyDelegate.java

private RuntimeException constructException(String exceptionClassName, String message, String packageName,
        String methodName) {//  ww w  .j av a2  s  .  c om
    try {
        Class<?> c = Class.forName(exceptionClassName);
        Constructor<?> constructor = c.getDeclaredConstructor(String.class);
        constructor.setAccessible(true);
        return (RuntimeException) constructor.newInstance(message);
    } catch (Exception e) {
        return new RPCFailedException(packageName, methodName);
    }
}

From source file:com.scaleoutsoftware.soss.hserver.hadoop.MapperWrapperMapred.java

/**
 * Runs mapper for the single split.//from   w  w  w .  j  a v  a2s .  c  o m
 *
 * @param mapOutputAccumulator mapOutputAccumulator to use
 * @param split                split ot run on
 */

@Override
@SuppressWarnings("unchecked")
public void runSplit(final MapOutputAccumulator<OUTKEY, OUTVALUE> mapOutputAccumulator, Object split,
        int splitIndex) throws IOException, ClassNotFoundException, InterruptedException {
    JobConf jobConf = new JobConf(this.jobConf); //Clone JobConf to prevent unexpected task interaction

    TaskAttemptID taskAttemptID = TaskAttemptID
            .downgrade(hadoopVersionSpecificCode.createTaskAttemptId(jobId, true, splitIndex));

    ReducerWrapperMapred.updateJobConf(jobConf, taskAttemptID, splitIndex);
    updateJobWithSplit(jobConf, split);

    InputFormat inputFormat = jobConf.getInputFormat();

    Reporter reporter = Reporter.NULL;

    //Create RecordReader
    org.apache.hadoop.mapred.RecordReader<INKEY, INVALUE> recordReader = inputFormat
            .getRecordReader((InputSplit) split, jobConf, reporter);

    //Make a mapper
    org.apache.hadoop.mapred.Mapper<INKEY, INVALUE, OUTKEY, OUTVALUE> mapper;
    try {
        mapper = (org.apache.hadoop.mapred.Mapper<INKEY, INVALUE, OUTKEY, OUTVALUE>) mapperConstructor
                .newInstance();
        mapper.configure(jobConf);
    } catch (Exception e) {
        throw new RuntimeException("Cannot instantiate mapper " + mapperConstructor.getDeclaringClass(), e);
    }

    //These are to support map only jobs which write output directly to HDFS.
    final RecordWriter outputRecordWriter;
    OutputCommitter outputCommitter = null;
    TaskAttemptContext taskAttemptContext = null;

    if (mapOnlyJob) {

        taskAttemptContext = hadoopVersionSpecificCode.createTaskAttemptContextMapred(jobConf, taskAttemptID);
        OutputFormat outputFormat = jobConf.getOutputFormat();
        FileSystem fs = FileSystem.get(jobConf);
        outputRecordWriter = (org.apache.hadoop.mapred.RecordWriter<OUTKEY, OUTVALUE>) outputFormat
                .getRecordWriter(fs, jobConf, ReducerWrapperMapred.getOutputName(splitIndex), Reporter.NULL);
        outputCommitter = jobConf.getOutputCommitter();

        //Create task object so it can handle file format initialization
        //The MapTask is private in the Hadoop 1.x so we have to go through reflection.
        try {
            Class reduceTask = Class.forName("org.apache.hadoop.mapred.MapTask");
            Constructor reduceTaskConstructor = reduceTask.getDeclaredConstructor(String.class,
                    TaskAttemptID.class, int.class, JobSplit.TaskSplitIndex.class, int.class);
            reduceTaskConstructor.setAccessible(true);
            Task task = (Task) reduceTaskConstructor.newInstance(null, taskAttemptID, splitIndex,
                    new JobSplit.TaskSplitIndex(), 0);
            task.setConf(jobConf);
            task.initialize(jobConf, jobId, Reporter.NULL, false);
        } catch (Exception e) {
            throw new IOException("Cannot initialize MapTask", e);
        }
        outputCommitter.setupTask(taskAttemptContext);
    } else {
        outputRecordWriter = null;
    }

    OutputCollector<OUTKEY, OUTVALUE> outputCollector;

    if (!mapOnlyJob) {
        outputCollector = new OutputCollector<OUTKEY, OUTVALUE>() {
            @Override
            public void collect(OUTKEY outkey, OUTVALUE outvalue) throws IOException {
                try {
                    mapOutputAccumulator.combine(outkey, outvalue);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        };
    } else {
        outputCollector = new OutputCollector<OUTKEY, OUTVALUE>() {
            @Override
            public void collect(OUTKEY outkey, OUTVALUE outvalue) throws IOException {
                outputRecordWriter.write(outkey, outvalue);
            }
        };
    }

    INKEY key = recordReader.createKey();
    INVALUE value = recordReader.createValue();

    while (recordReader.next(key, value)) {
        mapper.map(key, value, outputCollector, reporter);
    }
    mapper.close();

    recordReader.close();

    if (mapOnlyJob) {
        outputRecordWriter.close(Reporter.NULL);
        outputCommitter.commitTask(taskAttemptContext);
    }

}

From source file:org.limewire.mojito.CacheForwardTest.java

@SuppressWarnings("unchecked")
public void testGetSecurityToken() throws Exception {

    MojitoDHT dht1 = null;/*  www  .  j  a v  a  2s  .co  m*/
    MojitoDHT dht2 = null;

    try {

        // Setup the first instance so that it thinks it's bootstrapping
        dht1 = MojitoFactory.createDHT();
        dht1.bind(2000);
        dht1.start();
        Context context1 = (Context) dht1;

        UnitTestUtils.setBootstrapping(dht1, true);
        assertFalse(dht1.isBootstrapped());
        assertTrue(context1.isBootstrapping());

        // And setup the second instance so that it thinks it's bootstrapped 
        dht2 = MojitoFactory.createDHT();
        dht2.bind(3000);
        dht2.start();
        Context context2 = (Context) dht2;

        UnitTestUtils.setBootstrapped(dht2, true);
        assertTrue(dht2.isBootstrapped());
        assertFalse(context2.isBootstrapping());

        // Get the SecurityToken...
        Class clazz = Class.forName("org.limewire.mojito.manager.StoreProcess$GetSecurityTokenHandler");
        Constructor<DHTTask<Result>> con = clazz.getDeclaredConstructor(Context.class, Contact.class);
        con.setAccessible(true);

        DHTTask<Result> task = con.newInstance(context2, context1.getLocalNode());
        CallableDHTTask<Result> callable = new CallableDHTTask<Result>(task);

        try {
            Result result = callable.call();
            clazz = Class.forName("org.limewire.mojito.manager.StoreProcess$GetSecurityTokenResult");
            Method m = clazz.getDeclaredMethod("getSecurityToken", new Class[0]);
            m.setAccessible(true);

            SecurityToken securityToken = (SecurityToken) m.invoke(result, new Object[0]);
            assertNotNull(securityToken);
        } catch (ExecutionException err) {
            assertInstanceof(DHTException.class, err.getCause());
            fail("DHT-1 did not return a SecurityToken", err);
        }

    } finally {
        if (dht1 != null) {
            dht1.close();
        }
        if (dht2 != null) {
            dht2.close();
        }
    }
}

From source file:de.digiway.rapidbreeze.server.infrastructure.objectstorage.ObjectStorage.java

private <T> T loadInstance(Class<T> clazz, Map<String, String> properties) {
    try {/*  w ww.  j  a  v  a 2s .  co m*/
        // Create new object of class using default constructor:
        Constructor<T> constructor = clazz.getDeclaredConstructor();
        if (!constructor.isAccessible()) {
            constructor.setAccessible(true);
        }
        T instance = constructor.newInstance();

        // Iterate over all existing properties and fill fields of new object:
        for (Map.Entry<String, String> entrySet : properties.entrySet()) {
            for (Field field : clazz.getDeclaredFields()) {
                if (field.getName().equals(entrySet.getKey())) {
                    if (!field.isAccessible()) {
                        field.setAccessible(true);
                    }
                    field.set(instance, stringToObject(field.getType(), entrySet.getValue()));
                    break;
                }
            }
        }
        return instance;
    } catch (NoSuchMethodException ex) {
        throw new IllegalStateException("Cannot find default constructor of class " + clazz, ex);
    } catch (SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException ex) {
        throw new IllegalStateException("Error during value assignment.", ex);
    }
}