Example usage for java.lang NullPointerException getMessage

List of usage examples for java.lang NullPointerException getMessage

Introduction

In this page you can find the example usage for java.lang NullPointerException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.dtolabs.rundeck.core.resources.TestURLResourceModelSource.java

public void testConfigureProperties() throws Exception {
    final URLResourceModelSource provider = new URLResourceModelSource(getFrameworkInstance());
    try {//from   w w w . j  a  v a2  s . c om
        provider.configure(null);
        fail("Should throw NPE");
    } catch (NullPointerException e) {
        e.printStackTrace();
    }

    Properties props = new Properties();
    try {
        provider.configure(props);
        fail("shouldn't succeed");
    } catch (ConfigurationException e) {
        assertEquals("project is required", e.getMessage());
    }

    props.setProperty("project", PROJ_NAME);
    try {
        provider.configure(props);
        fail("shouldn't succeed");
    } catch (ConfigurationException e) {
        assertEquals("url is required", e.getMessage());
    }
    props.setProperty("url", "blah");
    try {
        provider.configure(props);
        fail("shouldn't succeed");
    } catch (ConfigurationException e) {
        assertTrue(e.getMessage().startsWith("url is malformed"));
    }

    props.setProperty("url", "ftp://example.com/blah");
    try {
        provider.configure(props);
        fail("shouldn't succeed");
    } catch (ConfigurationException e) {
        assertTrue(e.getMessage().startsWith("url protocol not allowed: "));
    }

    props.setProperty("url", "http://example.com/test");
    provider.configure(props);
    assertNotNull(provider.configuration.nodesUrl);
    assertEquals("http://example.com/test", provider.configuration.nodesUrl.toExternalForm());

    assertEquals(PROJ_NAME, provider.configuration.project);

    props.setProperty("url", "https://example.com/test");
    provider.configure(props);
    assertNotNull(provider.configuration.nodesUrl);
    assertEquals("https://example.com/test", provider.configuration.nodesUrl.toExternalForm());

    props.setProperty("url", "file://some/file");
    provider.configure(props);
    assertNotNull(provider.configuration.nodesUrl);
    assertEquals("file://some/file", provider.configuration.nodesUrl.toExternalForm());

    props.setProperty("timeout", "notanumber");
    try {
        provider.configure(props);
        fail("shouldn't succeed");
    } catch (ConfigurationException e) {
        assertTrue(e.getMessage().startsWith("timeout is invalid: "));
    }

    props.setProperty("timeout", "12345");
    provider.configure(props);
    assertEquals(12345, provider.configuration.timeout);

    assertEquals(true, provider.configuration.useCache);
    props.setProperty("cache", "false");
    provider.configure(props);
    assertEquals(false, provider.configuration.useCache);
}

From source file:com.androguide.apkreator.MainActivity.java

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
@Override/*from   ww  w.  ja v a2s .  c om*/
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setContentView(R.layout.activity_main);

    /**
     * Before anything we need to check if the config files exist to avoid
     * FC is they don't
     *
     * @see #checkIfConfigExists()
     */
    checkIfConfigExists();

    /**
     * Now it's all good because if no configuration was found we have
     * copied a default one over.
     *
     * @see #checkIfConfigExists()
     */
    setAppConfigInPrefs();

    headers = getPluginTabs();

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);

    /*
       * set a custom shadow that overlays the main content when the drawer
     * opens
     */
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

    /* set up the drawer's list view with items and click listener */
    ArrayAdapter<String> pimpAdapter = new ArrayAdapter<String>(this, R.layout.drawer_list_item,
            mDrawerHeaders);
    mDrawerList.setAdapter(pimpAdapter);
    Log.e("FIRST POS", mDrawerList.getFirstVisiblePosition() + "");
    Log.e("LAST POS", mDrawerList.getLastVisiblePosition() + "");
    View child = mDrawerList.getChildAt(mDrawerList.getFirstVisiblePosition());
    if (child != null && android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
        child.setBackground(getColouredTouchFeedback());
    mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

    /** Set the user-defined ActionBar icon */
    File file = new File(getFilesDir() + "/.APKreator/icon.png");
    if (file.exists()) {
        try {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setHomeButtonEnabled(true);
            Uri iconUri = Uri.fromFile(new File(getFilesDir() + "/.APKreator/icon.png"));
            Bitmap icon = BitmapFactory.decodeFile(iconUri.getPath());
            Drawable ic = new BitmapDrawable(icon);
            getSupportActionBar().setIcon(ic);
        } catch (NullPointerException e) {
            Log.e("NPE", e.getMessage());
        }
    }
    /*
     * ActionBarDrawerToggle ties together the proper interactions between
    * the sliding drawer and the action bar app icon
    */
    mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
            mDrawerLayout, /* DrawerLayout object */
            R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
            R.string.app_name, /* "open drawer" description for accessibility */
            R.string.app_name /* "close drawer" description for accessibility */
    ) {
        public void onDrawerClosed(View view) {
            invalidateOptionsMenu(); /*
                                     * creates call to
                                     * onPrepareOptionsMenu()
                                     */

        }

        public void onDrawerOpened(View drawerView) {
            invalidateOptionsMenu(); /*
                                     * creates call to
                                     * onPrepareOptionsMenu()
                                     */
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    /** Tabs adapter using the PagerSlidingStrip library */
    tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
    ViewPager pager = (ViewPager) findViewById(R.id.pager);
    MyPagerAdapter adapter = new MyPagerAdapter(this.getSupportFragmentManager());
    pager.setAdapter(adapter);
    pager.setOnPageChangeListener(new OnPageChangeListener() {

        @Override
        public void onPageSelected(int arg0) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    });

    final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4,
            getResources().getDisplayMetrics());
    pager.setPageMargin(pageMargin);

    tabs.setViewPager(pager);
    tabs.setOnPageChangeListener(this);

    changeColor(Color.parseColor(getPluginColor()));
    pager.setOffscreenPageLimit(5);
}

From source file:de.teamgrit.grit.entities.Exercise.java

/**
 * Cleanup when stopping a task. Delete all generated files.
 */// w w  w  .  j a v  a 2s . c  o m
private void cleanup() {
    // Delete binaries, temporary files and fetched sources.
    try {
        FileUtils.deleteDirectory(context.getBinPath().toFile());
        FileUtils.deleteDirectory(context.getTempPdfPath().toFile());
        FileUtils.deleteDirectory(context.getFetchPath().toFile());

    } catch (NullPointerException e) {
        LOGGER.severe("Error while trying to clean up: " + "Couldn't delete nonexistent directory: "
                + e.getMessage());
    } catch (IOException e) {
        LOGGER.severe("Error while trying to clean up: " + e.getMessage());
    }
}

From source file:io.hops.hopsworks.api.zeppelin.rest.InterpreterRestApi.java

/**
 * Get a setting//from w w w  . ja va  2 s  .co m
 */
@GET
@Path("setting/{settingId}")
public Response getSetting(@PathParam("settingId") String settingId) {
    try {
        InterpreterSetting setting = this.interpreterSettingManager.get(settingId);
        if (setting == null) {
            return new JsonResponse<>(Status.NOT_FOUND).build();
        } else {
            return new JsonResponse<>(Status.OK, "", setting).build();
        }
    } catch (NullPointerException e) {
        logger.error("Exception in InterpreterRestApi while creating ", e);
        return new JsonResponse<>(Status.INTERNAL_SERVER_ERROR, e.getMessage(), ExceptionUtils.getStackTrace(e))
                .build();
    }
}

From source file:org.wso2.carbon.apimgt.gateway.mediators.DigestAuthMediator.java

/**
 * This method performs the overall mediation for digest authentication
 *
 * @param messageContext This message context will contain the context of the 401 response received from the
 *                       backend after the first request from the client. It also contains some properties set
 *                       from the synapse configuration of the api as well, such as POSTFIX, BACKEND_URL,
 *                       HTTP_METHOD etc.
 * @return A boolean value.True if successful and false if not.
 *//*from w  w w .  j  a  va  2  s  .co  m*/
public boolean mediate(MessageContext messageContext) {

    String realm;
    String serverNonce;
    String qop;
    String opaque;
    String algorithm;

    if (log.isDebugEnabled()) {
        log.debug("Digest authorization header creation mediator is activated...");
    }

    try {

        org.apache.axis2.context.MessageContext axis2MC = ((Axis2MessageContext) messageContext)
                .getAxis2MessageContext();

        String postFix = (String) messageContext.getProperty(DigestAuthConstants.POSTFIX);
        String backendURL = (String) messageContext.getProperty(DigestAuthConstants.BACKEND_URL);
        URI backendUri = new URI(backendURL);
        String path = backendUri.getPath();

        if (path.endsWith("/") && postFix.startsWith("/")) {
            postFix = postFix.substring(1);
        }

        String digestUri = path + postFix;

        if (log.isDebugEnabled()) {
            log.debug("digest-uri value is : " + digestUri);
        }

        //Take the WWW-Authenticate header from the message context
        Map transportHeaders = (Map) axis2MC
                .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
        String wwwHeader = (String) transportHeaders.get(HttpHeaders.WWW_AUTHENTICATE);

        if (log.isDebugEnabled()) {
            log.debug("WWW-Authentication header is :" + wwwHeader);
        }
        //This step can throw a NullPointerException if a WWW-Authenticate header is not received.
        String[] wwwHeaderSplits = wwwHeader.split("Digest");

        //Happens only if the WWW-Authenticate header supports digest authentication.
        if (wwwHeaderSplits.length > 1 && wwwHeaderSplits[1] != null) {

            //extracting required header information from the WWW-Authenticate header
            String[] headerAttributes = splitDigestHeader(wwwHeaderSplits);
            realm = headerAttributes[0];
            serverNonce = headerAttributes[1];
            qop = headerAttributes[2];
            opaque = headerAttributes[3];
            algorithm = headerAttributes[4];

            if (log.isDebugEnabled()) {
                log.debug("Server nonce value : " + serverNonce);
                log.debug("realm : " + realm);
            }

            //get username password given by the client
            String userNamePassword = (String) messageContext.getProperty(DigestAuthConstants.UNAMEPASSWORD);

            byte[] valueDecoded = Base64.decodeBase64(userNamePassword.getBytes(DigestAuthConstants.CHARSET));
            String decodedString = new String(valueDecoded, DigestAuthConstants.CHARSET);
            String[] splittedArrayOfUserNamePassword = decodedString.split(":");

            String userName = splittedArrayOfUserNamePassword[0];
            String passWord = splittedArrayOfUserNamePassword[1];

            if (log.isDebugEnabled()) {
                log.debug("Username : " + userName);
                log.debug("Password : " + passWord);
            }

            //get the Http method (GET, POST, PUT or DELETE etc.)
            String httpMethod = (String) messageContext.getProperty(DigestAuthConstants.HTTP_METHOD);

            if (log.isDebugEnabled()) {
                log.debug("HTTP method of request is : " + httpMethod);
            }

            //generate clientNonce
            String clientNonce = generateClientNonce();

            //calculate hash1
            String ha1 = calculateHA1(userName, realm, passWord, algorithm, serverNonce, clientNonce);

            if (log.isDebugEnabled()) {
                log.debug("Value of hash 1 is : " + ha1);
            }

            //calculate hash2
            String ha2 = calculateHA2(qop, httpMethod, digestUri, messageContext);

            if (log.isDebugEnabled()) {
                log.debug("Value of hash 2 is : " + ha2);
            }

            //getting the previous NonceCount
            String prevNonceCount = (String) messageContext.getProperty(DigestAuthConstants.NONCE_COUNT);

            if (prevNonceCount == null) {
                messageContext.setProperty(DigestAuthConstants.NONCE_COUNT,
                        DigestAuthConstants.INIT_NONCE_COUNT);
                prevNonceCount = (String) messageContext.getProperty(DigestAuthConstants.NONCE_COUNT);
            }

            //generate the final hash (serverResponse)
            String[] serverResponseArray = generateResponseHash(ha1, ha2, serverNonce, qop, prevNonceCount,
                    clientNonce);

            //setting the NonceCount after incrementing
            messageContext.setProperty(DigestAuthConstants.NONCE_COUNT, serverResponseArray[1]);

            String serverResponse = serverResponseArray[0];

            if (log.isDebugEnabled()) {
                log.debug("Value of server response  is : " + serverResponse);
            }

            //Construct the authorization header
            StringBuilder header = constructAuthHeader(userName, realm, serverNonce, digestUri,
                    serverResponseArray, qop, opaque, clientNonce, algorithm);

            if (log.isDebugEnabled()) {
                log.debug("Processed Authorization header to be sent in the request is : " + header);
            }

            //set the AuthHeader field in the message context
            messageContext.setProperty(DigestAuthConstants.AUTH_HEADER, header.toString());

            return true;

        } else {
            //This is not digest auth protected api. let it go. Might be basic auth or NTLM protected.
            //Here we receive a www-authenticate header but it is not for Digest authentication.
            return true;
        }
    } catch (NullPointerException ex) {
        log.error("The endpoint does not support digest authentication : " + ex.getMessage(), ex);
        return false;
    } catch (Exception e) {
        log.error("Exception has occurred while performing Digest Auth class mediation : " + e.getMessage(), e);
        return false;
    }

}

From source file:org.sakaiproject.tool.assessment.ui.bean.author.SearchQuestionBean.java

public void searchQuestionsByText(boolean andOption) {
    HashMap<String, ItemSearchResult> resultsTemp = new HashMap<>();
    questionsIOwn.clear();//from   w  w w.  j ava  2s . c om
    setResults(new HashMap<>());
    setResultsSize(0);
    HashMap<String, String> additionalSearchInformation = new HashMap<String, String>();
    additionalSearchInformation.put("group", "hash");
    additionalSearchInformation.put("scope", "own");
    additionalSearchInformation.put("subtype", "item");
    if (andOption) {
        additionalSearchInformation.put("logic", "and");
    } else {
        additionalSearchInformation.put("logic", "or");
    }
    String textToSearch = getTextToSearch();
    //Let's remove the HTML code to search only by the real text.
    Source parseSearchTerms = new Source(textToSearch);
    textToSearch = parseSearchTerms.getTextExtractor().toString();
    this.setTextToSearch(textToSearch);

    try {
        SearchResponse sr = searchService.searchResponse(textToSearch, null, 0, 0, "questions",
                additionalSearchInformation);
        log.debug("This is the search repsonse: " + sr.toString());
        Terms dedup = sr.getAggregations().get("dedup");
        // For each entry
        for (Terms.Bucket entry : dedup.getBuckets()) {

            String key = entry.getKey(); // bucket key
            long docCount = entry.getDocCount(); // Doc count
            log.debug("key [{" + key + "}], doc_count [{" + docCount + "}]");

            // We ask for top_hits for each bucket
            TopHits topHits = entry.getAggregations().get("dedup_docs");
            for (SearchHit hit : topHits.getHits().getHits()) {
                log.debug(" -> id [{" + hit.getId() + "}]");
                String typeId = hit.field("typeId").getValue();
                String qText = hit.field("qText").getValue();
                Set<String> tagsSet = getTagsFromString(hit.field("tags").getValues());
                ItemSearchResult itemTemp = new ItemSearchResult(hit.getId(), typeId, qText, tagsSet,
                        origin(hit));
                resultsTemp.put(hit.getId(), itemTemp);
                //resultIds.put(hit.getId(),origin(hit));
            }
        }

    } catch (org.sakaiproject.search.api.InvalidSearchQueryException ex) {
        log.info("Error in the search: " + ex.getMessage());
        String publish_error = ContextUtil.getLocalizedString(
                "org.sakaiproject.tool.assessment.bundle.AuthorMessages", "tag_text_error3");
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(publish_error));
    } catch (java.lang.NullPointerException e) {
        log.info("Error in the search: " + e.getMessage());
        String publish_error = ContextUtil.getLocalizedString(
                "org.sakaiproject.tool.assessment.bundle.AuthorMessages", "tag_text_error2");
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(publish_error));
    }

    for (String q : resultsTemp.keySet()) {
        try {
            if (q.startsWith("/sam_item/")) {
                ItemSearchResult item = resultsTemp.get(q);
                item.setIdString(q.substring(10));
                results.put(q.substring(10), item);
            }
        } catch (Exception ex) {
            log.debug("Error finding the indexed question: " + q);
        }
    }
    setResults(results);
    if (results == null) {
        setResultsSize(0);
    } else {
        setResultsSize(results.size());
    }
    setTagToSearch(null);
    setTagToSearchLabel("");

}

From source file:org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptorTest.java

/** Expect errors from {@link org.codehaus.groovy.runtime.NullObject}. */
@Issue("kohsuke/groovy-sandbox #15")
@Test//from   w  w w  .ja  va  2 s . c o m
public void nullPointerException() throws Exception {
    try {
        assertEvaluate(new ProxyWhitelist(), "should be rejected", "def x = null; x.member");
    } catch (NullPointerException x) {
        assertEquals(Functions.printThrowable(x), "Cannot get property 'member' on null object",
                x.getMessage());
    }
    try {
        assertEvaluate(new ProxyWhitelist(), "should be rejected", "def x = null; x.member = 42");
    } catch (NullPointerException x) {
        assertEquals(Functions.printThrowable(x), "Cannot set property 'member' on null object",
                x.getMessage());
    }
    try {
        assertEvaluate(new ProxyWhitelist(), "should be rejected", "def x = null; x.member()");
    } catch (NullPointerException x) {
        assertEquals(Functions.printThrowable(x), "Cannot invoke method member() on null object",
                x.getMessage());
    }
}

From source file:it.acubelab.batframework.systemPlugins.AIDAAnnotator.java

@Override
public Set<ScoredAnnotation> solveSa2W(String text) throws AnnotationException {

    /* Lazy connection if the connection made by the constructor failed.*/
    if (!AidaRMIClientManager.isConnected())
        setupConnection();//from w  w  w  . j  a v  a2  s  . c  om

    Set<AIDATag> res = new HashSet<AIDATag>();
    List<String> titlesToPrefetch = new Vector<String>();

    //lastTime = Calendar.getInstance().getTimeInMillis();
    AidaParsePackage input = new AidaParsePackage(text, "" + text.hashCode(), settings);
    AidaResultsPackage result = null;
    try {
        result = AidaRMIClientManager.parse(input);
    } catch (java.lang.NullPointerException e) {
        System.out
                .println("Caught exception while processing text:\n [text beginning]\n" + text + "[text end]");
        throw e;
    } catch (Exception e) {
        System.out
                .println("Caught exception while processing text:\n [text beginning]\n" + text + "[text end]");
        e.printStackTrace();
        throw new AnnotationException(e.getMessage());
    }
    //lastTime = Calendar.getInstance().getTimeInMillis() - lastTime;
    //System.out.println(result.getOverallRunTime()+ "\t" + lastTime+"ms");

    if (result == null) {
        String noSpaceText = CharUtils.trim(text).toString();
        System.out.println("NULL RESULT: " + noSpaceText.substring(0, Math.min(10, noSpaceText.length())));
    }
    if (result != null) {
        Matcher time1 = Pattern.compile("^(\\d*)ms$").matcher(result.getOverallRunTime());
        Matcher time2 = Pattern.compile("^(\\d*)s, (\\d*)ms$").matcher(result.getOverallRunTime());
        Matcher time3 = Pattern.compile("^(\\d*)m, (\\d*)s, (\\d*)ms$").matcher(result.getOverallRunTime());
        Matcher time4 = Pattern.compile("^(\\d*)h, (\\d*)m, (\\d*)s, (\\d*)ms$")
                .matcher(result.getOverallRunTime());
        Matcher time5 = Pattern.compile("^(\\d*)d, (\\d*)h, (\\d*)m, (\\d*)s, (\\d*)ms$")
                .matcher(result.getOverallRunTime());
        if (time1.matches())
            lastTime = Integer.parseInt(time1.group(1));
        else if (time2.matches())
            lastTime = Integer.parseInt(time2.group(1)) * 1000 + Integer.parseInt(time2.group(2));
        else if (time3.matches())
            lastTime = Integer.parseInt(time3.group(1)) * 1000 * 60 + Integer.parseInt(time3.group(2)) * 1000
                    + Integer.parseInt(time3.group(3));
        else if (time4.matches())
            lastTime = Integer.parseInt(time4.group(1)) * 1000 * 60 * 60
                    + Integer.parseInt(time4.group(2)) * 1000 * 60 + Integer.parseInt(time4.group(3)) * 1000
                    + Integer.parseInt(time4.group(4));
        else if (time5.matches())
            lastTime = Integer.parseInt(time5.group(1)) * 1000 * 60 * 60 * 24
                    + Integer.parseInt(time5.group(2)) * 1000 * 60 * 60
                    + Integer.parseInt(time5.group(3)) * 1000 * 60 + Integer.parseInt(time5.group(4)) * 1000
                    + Integer.parseInt(time5.group(5));
        else
            throw new AnnotationException("Time value returned by AIDA [" + result.getOverallRunTime()
                    + "] does not match the pattern.");

        DisambiguationResults disRes = result.getDisambiguationResults();
        for (ResultMention mention : disRes.getResultMentions()) {
            ResultEntity resEntity = disRes.getBestEntity(mention);

            int position = mention.getCharacterOffset();
            int length = mention.getMention().length();
            String pageTitleEscaped = resEntity.getEntity();
            String pageTitleUnescaped = StringEscapeUtils.unescapeJava(pageTitleEscaped);
            float score = (float) resEntity.getDisambiguationScore();
            if (pageTitleEscaped.equals("--NME--")) //Aida could not identify the topic.
                break;

            res.add(new AIDATag(position, length, pageTitleUnescaped, score));
            titlesToPrefetch.add(pageTitleUnescaped);
        }
    }

    /** Prefetch wids of titles*/
    try {
        api.prefetchTitles(titlesToPrefetch);
    } catch (Exception e) {
        e.printStackTrace();
        throw new AnnotationException(e.getMessage());
    }

    /** Convert to Scored Tags*/
    Set<ScoredAnnotation> resScoredAnnotations = new HashSet<ScoredAnnotation>();
    for (AIDATag t : res) {
        int wid;
        try {
            wid = api.getIdByTitle(t.title);
        } catch (IOException e) {
            e.printStackTrace();
            throw new AnnotationException(e.getMessage());
        }
        if (wid != -1)
            resScoredAnnotations.add(new ScoredAnnotation(t.position, t.length, wid, t.score));
    }
    return resScoredAnnotations;
}

From source file:com.hsbadr.MultiSystem.MainActivity.java

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
@Override/*from   ww w .  j  a va  2s.  c om*/
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setContentView(R.layout.activity_main);

    /**
     * Before anything we need to check if the config files exist to avoid
     * FC is they don't
     *
     * @see #checkIfConfigExists()
     */
    checkIfConfigExists();

    /**
     * Now it's all good because if no configuration was found we have
     * copied a default one over.
     *
     * @see #checkIfConfigExists()
     */
    setAppConfigInPrefs();

    headers = getPluginTabs();

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);

    /*
       * set a custom shadow that overlays the main content when the drawer
     * opens
     */
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

    /* set up the drawer's list view with items and click listener */
    ArrayAdapter<String> pimpAdapter = new ArrayAdapter<String>(this, R.layout.drawer_list_item,
            mDrawerHeaders);
    mDrawerList.setAdapter(pimpAdapter);
    Log.e("FIRST POS", mDrawerList.getFirstVisiblePosition() + "");
    Log.e("LAST POS", mDrawerList.getLastVisiblePosition() + "");
    View child = mDrawerList.getChildAt(mDrawerList.getFirstVisiblePosition());
    if (child != null && android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
        child.setBackground(getColouredTouchFeedback());
    mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

    /** Set the user-defined ActionBar icon */
    File file = new File(getFilesDir() + "/.MultiSystem/icon.png");
    if (file.exists()) {
        try {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setHomeButtonEnabled(true);
            Uri iconUri = Uri.fromFile(new File(getFilesDir() + "/.MultiSystem/icon.png"));
            Bitmap icon = BitmapFactory.decodeFile(iconUri.getPath());
            Drawable ic = new BitmapDrawable(icon);
            getSupportActionBar().setIcon(ic);
        } catch (NullPointerException e) {
            Log.e("NPE", e.getMessage());
        }
    }
    /*
     * ActionBarDrawerToggle ties together the proper interactions between
    * the sliding drawer and the action bar app icon
    */
    mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
            mDrawerLayout, /* DrawerLayout object */
            R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
            R.string.app_name, /* "open drawer" description for accessibility */
            R.string.app_name /* "close drawer" description for accessibility */
    ) {
        public void onDrawerClosed(View view) {
            invalidateOptionsMenu(); /*
                                     * creates call to
                                     * onPrepareOptionsMenu()
                                     */

        }

        public void onDrawerOpened(View drawerView) {
            invalidateOptionsMenu(); /*
                                     * creates call to
                                     * onPrepareOptionsMenu()
                                     */
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    /** Tabs adapter using the PagerSlidingStrip library */
    tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
    pager = (ViewPager) findViewById(R.id.pager);
    MyPagerAdapter adapter = new MyPagerAdapter(this.getSupportFragmentManager());
    pager.setAdapter(adapter);
    pager.setOnPageChangeListener(new OnPageChangeListener() {

        @Override
        public void onPageSelected(int arg0) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    });

    final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4,
            getResources().getDisplayMetrics());
    pager.setPageMargin(pageMargin);

    tabs.setViewPager(pager);
    tabs.setOnPageChangeListener(this);

    changeColor(Color.parseColor(getPluginColor()));
    pager.setOffscreenPageLimit(5);
}

From source file:com.google.gsa.valve.modules.ldap.LDAPSSO.java

/**
 * /*from   w  w w.  j a v a2 s  .  com*/
 * For every credentials read at the configuration file it gets the 
 * LDAP attributes from the LDAP.
 * 
 * @param ldapconn LDAP connection
 * @param ctx LDAP context
 * @param username user id
 * @param creds user credentials
 */
public void fetchingCredentials(Ldap ldapconn, DirContext ctx, String username, Credentials creds) {

    for (int i = 0; i < repositories.size(); i++) {
        String id = repositories.elementAt(i);
        logger.debug("ID [" + id + "] found at position #" + i);

        LDAPAttrRepository attrRepository;

        //fetch credentials
        try {
            attrRepository = ldapAttributes.get(id);

            //Get User's DN
            String userDName = ldapconn.getDN(username, ctx);

            logger.info("fetching credentials for (" + id + ")");
            String usernameAttr = ldapconn.getAttributeByDN(attrRepository.getUsernameAttr(), userDName, ctx);
            String passwordAttr = null;
            if (!usernameAttr.equals(null)) {
                logger.debug("UserName id[" + id + "]: " + usernameAttr);
                passwordAttr = ldapconn.getAttributeByDN(attrRepository.getPasswordAttr(), userDName, ctx);
                //add the credentials into the "creds" object
                logger.debug("LDAP credentials were acquired OK. Adding them into the credential container");
                Credential credAttr = new Credential(id);
                credAttr.setUsername(usernameAttr);
                credAttr.setPassword(passwordAttr);
                creds.add(credAttr);
            } else {
                logger.debug("Credentials for " + id + " were not found for the user " + username);
            }
        } catch (NullPointerException e) {
            logger.warn(
                    "NullPointerException when fetching attrs in the LDAP. Probably due to the user does not have those attrs");
        } catch (Exception e) {
            logger.error("Exception fetching LDAP attributes: " + e.getMessage(), e);
        }

    }

}