Example usage for org.apache.commons.lang3.reflect FieldUtils readField

List of usage examples for org.apache.commons.lang3.reflect FieldUtils readField

Introduction

In this page you can find the example usage for org.apache.commons.lang3.reflect FieldUtils readField.

Prototype

public static Object readField(final Object target, final String fieldName, final boolean forceAccess)
        throws IllegalAccessException 

Source Link

Document

Reads the named Field .

Usage

From source file:nl.xs4all.home.freekdb.b52reader.gui.MainGuiTest.java

private void checkArticlesInGui(FilterTestType testType, MainGui mainGui, int tableRowCount)
        throws IllegalAccessException {
    int expectedRowCount = mockConfiguration.useSpanTable() ? 2 : 1;

    if (testType == NO_MATCHES) {
        expectedRowCount = 0;/*from w w w.  j av a  2s.co m*/
    } else if (testType == REMOVE_TEXT) {
        expectedRowCount = 5;
    }

    assertEquals(expectedRowCount, tableRowCount);

    Object filteredArticlesField = FieldUtils.readField(mainGui, "filteredArticles", true);

    assertTrue(filteredArticlesField instanceof List);
    List filteredArticles = (List) filteredArticlesField;

    if (testType == INSERT_TEXT) {
        assertEquals("u1", ((Article) filteredArticles.get(0)).getUrl());
    } else if (testType == CHANGE_TEXT) {
        assertEquals("u2", ((Article) filteredArticles.get(0)).getUrl());
    } else if (testType == REMOVE_TEXT) {
        IntStream.range(0, filteredArticles.size()).forEach(index -> {
            // Test article 3 (with index 2) is archived and should be filtered out: u1, u2, u4, u5, and u6.
            String expectedUrl = "u" + (index + (index < 2 ? 1 : 2));
            assertEquals(expectedUrl, ((Article) filteredArticles.get(index)).getUrl());
        });
    }
}

From source file:org.apache.drill.exec.udf.dynamic.TestDynamicUDFSupport.java

@Test
public void testLazyInit() throws Exception {
    thrown.expect(UserRemoteException.class);
    thrown.expectMessage(containsString("No match found for function signature custom_lower(<CHARACTER>)"));
    test("select custom_lower('A') from (values(1))");

    copyDefaultJarsToStagingArea();/* ww w  . j  a  v  a 2s.  c  o  m*/
    test("create function using jar '%s'", defaultBinaryJar);
    testBuilder().sqlQuery("select custom_lower('A') as res from (values(1))").unOrdered()
            .baselineColumns("res").baselineValues("a").go();

    Path localUdfDirPath = hadoopToJavaPath((org.apache.hadoop.fs.Path) FieldUtils
            .readField(getDrillbitContext().getFunctionImplementationRegistry(), "localUdfDir", true));

    assertTrue("Binary should exist in local udf directory",
            localUdfDirPath.resolve(defaultBinaryJar).toFile().exists());
    assertTrue("Source should exist in local udf directory",
            localUdfDirPath.resolve(defaultSourceJar).toFile().exists());
}

From source file:org.apache.drill.exec.udf.dynamic.TestDynamicUDFSupport.java

@Test
public void testDropFunction() throws Exception {
    copyDefaultJarsToStagingArea();/*from www .j  a  v a  2s.  c o m*/
    test("create function using jar '%s'", defaultBinaryJar);
    test("select custom_lower('A') from (values(1))");

    Path localUdfDirPath = hadoopToJavaPath((org.apache.hadoop.fs.Path) FieldUtils
            .readField(getDrillbitContext().getFunctionImplementationRegistry(), "localUdfDir", true));

    assertTrue("Binary should exist in local udf directory",
            localUdfDirPath.resolve(defaultBinaryJar).toFile().exists());
    assertTrue("Source should exist in local udf directory",
            localUdfDirPath.resolve(defaultSourceJar).toFile().exists());

    String summary = "The following UDFs in jar %s have been unregistered:\n"
            + "[custom_lower(VARCHAR-REQUIRED)]";

    testBuilder().sqlQuery("drop function using jar '%s'", defaultBinaryJar).unOrdered()
            .baselineColumns("ok", "summary").baselineValues(true, String.format(summary, defaultBinaryJar))
            .go();

    thrown.expect(UserRemoteException.class);
    thrown.expectMessage(containsString("No match found for function signature custom_lower(<CHARACTER>)"));
    test("select custom_lower('A') from (values(1))");

    RemoteFunctionRegistry remoteFunctionRegistry = getDrillbitContext().getRemoteFunctionRegistry();
    Path registryPath = hadoopToJavaPath(remoteFunctionRegistry.getRegistryArea());

    assertEquals("Remote registry should be empty",
            remoteFunctionRegistry.getRegistry(new DataChangeVersion()).getJarList().size(), 0);

    assertFalse("Binary should not be present in registry area",
            registryPath.resolve(defaultBinaryJar).toFile().exists());
    assertFalse("Source should not be present in registry area",
            registryPath.resolve(defaultSourceJar).toFile().exists());

    assertFalse("Binary should not be present in local udf directory",
            localUdfDirPath.resolve(defaultBinaryJar).toFile().exists());
    assertFalse("Source should not be present in local udf directory",
            localUdfDirPath.resolve(defaultSourceJar).toFile().exists());
}

From source file:org.apache.drill.exec.udf.dynamic.TestDynamicUDFSupport.java

@Test
public void testLazyInitConcurrent() throws Exception {
    FunctionImplementationRegistry functionImplementationRegistry = spyFunctionImplementationRegistry();
    copyDefaultJarsToStagingArea();/*from w  ww  .  jav  a 2  s  . c o  m*/
    test("create function using jar '%s'", defaultBinaryJar);

    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);

    final String query = "select custom_lower('A') from (values(1))";

    doAnswer(invocation -> {
        latch1.await();
        boolean result = (boolean) invocation.callRealMethod();
        assertTrue("syncWithRemoteRegistry() should return true", result);
        latch2.countDown();
        return true;
    }).doAnswer(invocation -> {
        latch1.countDown();
        latch2.await();
        boolean result = (boolean) invocation.callRealMethod();
        assertTrue("syncWithRemoteRegistry() should return true", result);
        return true;
    }).when(functionImplementationRegistry).syncWithRemoteRegistry(anyLong());

    SimpleQueryRunner simpleQueryRunner = new SimpleQueryRunner(query);
    Thread thread1 = new Thread(simpleQueryRunner);
    Thread thread2 = new Thread(simpleQueryRunner);

    thread1.start();
    thread2.start();

    thread1.join();
    thread2.join();

    verify(functionImplementationRegistry, times(2)).syncWithRemoteRegistry(anyLong());
    LocalFunctionRegistry localFunctionRegistry = (LocalFunctionRegistry) FieldUtils
            .readField(functionImplementationRegistry, "localFunctionRegistry", true);
    assertEquals("Sync function registry version should match", 1L, localFunctionRegistry.getVersion());
}

From source file:org.apache.drill.exec.udf.dynamic.TestDynamicUDFSupport.java

@Test
public void testLazyInitNoReload() throws Exception {
    FunctionImplementationRegistry functionImplementationRegistry = spyFunctionImplementationRegistry();
    copyDefaultJarsToStagingArea();/*  w w w  . j  a  v a 2  s . c  o m*/
    test("create function using jar '%s'", defaultBinaryJar);

    doAnswer(invocation -> {
        boolean result = (boolean) invocation.callRealMethod();
        assertTrue("syncWithRemoteRegistry() should return true", result);
        return true;
    }).doAnswer(invocation -> {
        boolean result = (boolean) invocation.callRealMethod();
        assertFalse("syncWithRemoteRegistry() should return false", result);
        return false;
    }).when(functionImplementationRegistry).syncWithRemoteRegistry(anyLong());

    test("select custom_lower('A') from (values(1))");

    try {
        test("select unknown_lower('A') from (values(1))");
        fail();
    } catch (UserRemoteException e) {
        assertThat(e.getMessage(),
                containsString("No match found for function signature unknown_lower(<CHARACTER>)"));
    }

    verify(functionImplementationRegistry, times(2)).syncWithRemoteRegistry(anyLong());
    LocalFunctionRegistry localFunctionRegistry = (LocalFunctionRegistry) FieldUtils
            .readField(functionImplementationRegistry, "localFunctionRegistry", true);
    assertEquals("Sync function registry version should match", 1L, localFunctionRegistry.getVersion());
}

From source file:org.apache.servicecomb.metrics.prometheus.TestPrometheusPublisher.java

@Test
public void collect() throws IllegalAccessException, IOException {
    ArchaiusUtils.setProperty(PrometheusPublisher.METRICS_PROMETHEUS_ADDRESS, "localhost:0");
    publisher.init(globalRegistry, null, null);

    Registry registry = new DefaultRegistry(new ManualClock());
    globalRegistry.add(registry);//w w w.  j a  va2 s. c o m

    Counter counter = registry.counter("count.name", "tag1", "tag1v", "tag2", "tag2v");
    counter.increment();

    HTTPServer httpServer = (HTTPServer) FieldUtils.readField(publisher, "httpServer", true);
    com.sun.net.httpserver.HttpServer server = (HttpServer) FieldUtils.readField(httpServer, "server", true);

    URL url = new URL("http://localhost:" + server.getAddress().getPort() + "/metrics");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    try (InputStream is = conn.getInputStream()) {
        Assert.assertEquals("# HELP ServiceComb Metrics ServiceComb Metrics\n"
                + "# TYPE ServiceComb Metrics untyped\n" + "count_name{tag1=\"tag1v\",tag2=\"tag2v\",} 1.0\n",
                IOUtils.toString(is));
    }

    publisher.destroy();
}

From source file:org.apache.syncope.core.provisioning.java.MappingManagerImpl.java

@Transactional(readOnly = true)
@Override//  w  w w. ja  v a 2  s  .  co m
public List<PlainAttrValue> getIntValues(final Provision provision, final Item mapItem,
        final IntAttrName intAttrName, final Any<?> any) {

    LOG.debug("Get internal values for {} as '{}' on {}", any, mapItem.getIntAttrName(),
            provision.getResource());

    Any<?> reference = null;
    Membership<?> membership = null;
    if (intAttrName.getEnclosingGroup() == null && intAttrName.getRelatedAnyObject() == null) {
        reference = any;
    }
    if (any instanceof GroupableRelatable) {
        GroupableRelatable<?, ?, ?, ?, ?> groupableRelatable = (GroupableRelatable<?, ?, ?, ?, ?>) any;

        if (intAttrName.getEnclosingGroup() != null) {
            Group group = groupDAO.findByName(intAttrName.getEnclosingGroup());
            if (group == null || !groupableRelatable.getMembership(group.getKey()).isPresent()) {
                LOG.warn("No membership for {} in {}, ignoring", intAttrName.getEnclosingGroup(),
                        groupableRelatable);
            } else {
                reference = group;
            }
        } else if (intAttrName.getRelatedAnyObject() != null) {
            AnyObject anyObject = anyObjectDAO.findByName(intAttrName.getRelatedAnyObject());
            if (anyObject == null || groupableRelatable.getRelationships(anyObject.getKey()).isEmpty()) {
                LOG.warn("No relationship for {} in {}, ignoring", intAttrName.getRelatedAnyObject(),
                        groupableRelatable);
            } else {
                reference = anyObject;
            }
        } else if (intAttrName.getMembershipOfGroup() != null) {
            Group group = groupDAO.findByName(intAttrName.getMembershipOfGroup());
            membership = groupableRelatable.getMembership(group.getKey()).orElse(null);
        }
    }
    if (reference == null) {
        LOG.warn("Could not determine the reference instance for {}", mapItem.getIntAttrName());
        return Collections.emptyList();
    }

    List<PlainAttrValue> values = new ArrayList<>();
    boolean transform = true;

    AnyUtils anyUtils = anyUtilsFactory.getInstance(reference);
    if (intAttrName.getField() != null) {
        PlainAttrValue attrValue = anyUtils.newPlainAttrValue();

        switch (intAttrName.getField()) {
        case "key":
            attrValue.setStringValue(reference.getKey());
            values.add(attrValue);
            break;

        case "realm":
            attrValue.setStringValue(reference.getRealm().getFullPath());
            values.add(attrValue);
            break;

        case "password":
            // ignore
            break;

        case "userOwner":
        case "groupOwner":
            Mapping uMapping = provision.getAnyType().equals(anyTypeDAO.findUser()) ? provision.getMapping()
                    : null;
            Mapping gMapping = provision.getAnyType().equals(anyTypeDAO.findGroup()) ? provision.getMapping()
                    : null;

            if (reference instanceof Group) {
                Group group = (Group) reference;
                String groupOwnerValue = null;
                if (group.getUserOwner() != null && uMapping != null) {
                    groupOwnerValue = getGroupOwnerValue(provision, group.getUserOwner());
                }
                if (group.getGroupOwner() != null && gMapping != null) {
                    groupOwnerValue = getGroupOwnerValue(provision, group.getGroupOwner());
                }

                if (StringUtils.isNotBlank(groupOwnerValue)) {
                    attrValue.setStringValue(groupOwnerValue);
                    values.add(attrValue);
                }
            }
            break;

        case "suspended":
            if (reference instanceof User) {
                attrValue.setBooleanValue(((User) reference).isSuspended());
                values.add(attrValue);
            }
            break;

        case "mustChangePassword":
            if (reference instanceof User) {
                attrValue.setBooleanValue(((User) reference).isMustChangePassword());
                values.add(attrValue);
            }
            break;

        default:
            try {
                Object fieldValue = FieldUtils.readField(reference, intAttrName.getField(), true);
                if (fieldValue instanceof Date) {
                    // needed because ConnId does not natively supports the Date type
                    attrValue.setStringValue(DateFormatUtils.ISO_8601_EXTENDED_DATETIME_TIME_ZONE_FORMAT
                            .format((Date) fieldValue));
                } else if (Boolean.TYPE.isInstance(fieldValue)) {
                    attrValue.setBooleanValue((Boolean) fieldValue);
                } else if (Double.TYPE.isInstance(fieldValue) || Float.TYPE.isInstance(fieldValue)) {
                    attrValue.setDoubleValue((Double) fieldValue);
                } else if (Long.TYPE.isInstance(fieldValue) || Integer.TYPE.isInstance(fieldValue)) {
                    attrValue.setLongValue((Long) fieldValue);
                } else {
                    attrValue.setStringValue(fieldValue.toString());
                }
                values.add(attrValue);
            } catch (Exception e) {
                LOG.error("Could not read value of '{}' from {}", intAttrName.getField(), reference, e);
            }
        }
    } else if (intAttrName.getSchemaType() != null) {
        switch (intAttrName.getSchemaType()) {
        case PLAIN:
            PlainAttr<?> attr;
            if (membership == null) {
                attr = reference.getPlainAttr(intAttrName.getSchemaName()).orElse(null);
            } else {
                attr = ((GroupableRelatable<?, ?, ?, ?, ?>) reference)
                        .getPlainAttr(intAttrName.getSchemaName(), membership).orElse(null);
            }
            if (attr != null) {
                if (attr.getUniqueValue() != null) {
                    values.add(anyUtils.clonePlainAttrValue(attr.getUniqueValue()));
                } else if (attr.getValues() != null) {
                    attr.getValues().forEach(value -> values.add(anyUtils.clonePlainAttrValue(value)));
                }
            }
            break;

        case DERIVED:
            DerSchema derSchema = derSchemaDAO.find(intAttrName.getSchemaName());
            if (derSchema != null) {
                String value = membership == null ? derAttrHandler.getValue(reference, derSchema)
                        : derAttrHandler.getValue(reference, membership, derSchema);
                if (value != null) {
                    PlainAttrValue attrValue = anyUtils.newPlainAttrValue();
                    attrValue.setStringValue(value);
                    values.add(attrValue);
                }
            }
            break;

        case VIRTUAL:
            // virtual attributes don't get transformed
            transform = false;

            VirSchema virSchema = virSchemaDAO.find(intAttrName.getSchemaName());
            if (virSchema != null) {
                LOG.debug("Expire entry cache {}-{}", reference, intAttrName.getSchemaName());
                virAttrCache.expire(reference.getType().getKey(), reference.getKey(),
                        intAttrName.getSchemaName());

                List<String> virValues = membership == null ? virAttrHandler.getValues(reference, virSchema)
                        : virAttrHandler.getValues(reference, membership, virSchema);
                virValues.stream().map(value -> {
                    PlainAttrValue attrValue = anyUtils.newPlainAttrValue();
                    attrValue.setStringValue(value);
                    return attrValue;
                }).forEachOrdered(attrValue -> values.add(attrValue));
            }
            break;

        default:
        }
    }

    LOG.debug("Internal values: {}", values);

    List<PlainAttrValue> transformed = values;
    if (transform) {
        for (ItemTransformer transformer : MappingUtils.getItemTransformers(mapItem)) {
            transformed = transformer.beforePropagation(mapItem, any, transformed);
        }
        LOG.debug("Transformed values: {}", values);
    } else {
        LOG.debug("No transformation occurred");
    }

    return transformed;
}

From source file:org.apache.zeppelin.rest.GetUserList.java

/**
 * function to extract users from JDBCs/* w w  w.j  av a2 s.  co  m*/
 */
public List<String> getUserList(JdbcRealm obj) {
    List<String> userlist = new ArrayList<>();
    PreparedStatement ps = null;
    ResultSet rs = null;
    DataSource dataSource = null;
    String authQuery = "";
    String retval[];
    String tablename = "";
    String username = "";
    String userquery = "";
    try {
        dataSource = (DataSource) FieldUtils.readField(obj, "dataSource", true);
        authQuery = (String) FieldUtils.readField(obj, "DEFAULT_AUTHENTICATION_QUERY", true);
        LOG.info(authQuery);
        String authQueryLowerCase = authQuery.toLowerCase();
        retval = authQueryLowerCase.split("from", 2);
        if (retval.length >= 2) {
            retval = retval[1].split("with|where", 2);
            tablename = retval[0];
            retval = retval[1].split("where", 2);
            if (retval.length >= 2)
                retval = retval[1].split("=", 2);
            else
                retval = retval[0].split("=", 2);
            username = retval[0];
        }

        if (StringUtils.isBlank(username) || StringUtils.isBlank(tablename)) {
            return userlist;
        }

        userquery = "select " + username + " from " + tablename;

    } catch (IllegalAccessException e) {
        LOG.error("Error while accessing dataSource for JDBC Realm", e);
        return null;
    }

    try {
        Connection con = dataSource.getConnection();
        ps = con.prepareStatement(userquery);
        rs = ps.executeQuery();
        while (rs.next()) {
            userlist.add(rs.getString(1).trim());
        }
    } catch (Exception e) {
        LOG.error("Error retrieving User list from JDBC Realm", e);
    } finally {
        JdbcUtils.closeResultSet(rs);
        JdbcUtils.closeStatement(ps);
    }
    return userlist;
}

From source file:org.apache.zeppelin.service.ShiroAuthenticationService.java

/** Function to extract users from JDBCs. */
private List<String> getUserList(JdbcRealm obj) {
    List<String> userlist = new ArrayList<>();
    Connection con = null;/*from   w ww  .  j  a  va2 s.c om*/
    PreparedStatement ps = null;
    ResultSet rs = null;
    DataSource dataSource = null;
    String authQuery = "";
    String retval[];
    String tablename = "";
    String username = "";
    String userquery;
    try {
        dataSource = (DataSource) FieldUtils.readField(obj, "dataSource", true);
        authQuery = (String) FieldUtils.readField(obj, "authenticationQuery", true);
        LOGGER.info(authQuery);
        String authQueryLowerCase = authQuery.toLowerCase();
        retval = authQueryLowerCase.split("from", 2);
        if (retval.length >= 2) {
            retval = retval[1].split("with|where", 2);
            tablename = retval[0];
            retval = retval[1].split("where", 2);
            if (retval.length >= 2) {
                retval = retval[1].split("=", 2);
            } else {
                retval = retval[0].split("=", 2);
            }
            username = retval[0];
        }

        if (StringUtils.isBlank(username) || StringUtils.isBlank(tablename)) {
            return userlist;
        }

        userquery = String.format("SELECT %s FROM %s", username, tablename);
    } catch (IllegalAccessException e) {
        LOGGER.error("Error while accessing dataSource for JDBC Realm", e);
        return Lists.newArrayList();
    }

    try {
        con = dataSource.getConnection();
        ps = con.prepareStatement(userquery);
        rs = ps.executeQuery();
        while (rs.next()) {
            userlist.add(rs.getString(1).trim());
        }
    } catch (Exception e) {
        LOGGER.error("Error retrieving User list from JDBC Realm", e);
    } finally {
        JdbcUtils.closeResultSet(rs);
        JdbcUtils.closeStatement(ps);
        JdbcUtils.closeConnection(con);
    }
    return userlist;
}

From source file:org.bitbucket.mlopatkin.android.liblogcat.ddmlib.AdbConnectionManager.java

private static boolean isReady(AndroidDebugBridge adb) throws DdmlibUnsupportedException {
    if (adb == null) {
        return false;
    }/*w  w  w . j ava2  s  .c o m*/
    // hack below - there is no explicit way to check if the bridge was
    // created succesfully
    try {
        return (Boolean) FieldUtils
                .readField(FieldUtils.getDeclaredField(AndroidDebugBridge.class, "mStarted", true), adb, true);
    } catch (IllegalAccessException e) {
        logger.fatal("The DDMLIB is unsupported", e);
        throw new DdmlibUnsupportedException("The DDMLIB supplied is unsupported: " + System.getenv("DDMLIB"));
    }

}