Example usage for java.lang Package getPackage

List of usage examples for java.lang Package getPackage

Introduction

In this page you can find the example usage for java.lang Package getPackage.

Prototype

@CallerSensitive
@Deprecated(since = "9")
@SuppressWarnings("deprecation")
public static Package getPackage(String name) 

Source Link

Document

Finds a package by name in the caller's class loader and its ancestors.

Usage

From source file:org.openflexo.sg.generator.SGJavaClassGenerator.java

public void addImport(Class<?> neededImport) {
    if (!neededImport.isPrimitive() && neededImport.getPackage() != Package.getPackage("java.lang")) {
        addImport(neededImport.getName());
    }/*w  w  w. j a v a  2 s .com*/
}

From source file:com.mockey.plugin.PluginStore.java

/**
 * Looks to the default plug-in directory location to initialize this store
 *///from   w w w  . jav  a2  s  . c o m
public void initializeOrUpdateStore() {

    try {
        List<PackageInfo> list = PackageInfoPeerClassFinder.findPackageInfo();
        for (PackageInfo pi : list) {
            for (String className : pi.getClassList()) {

                try {
                    // If we don't have the class
                    Class<?> o = Class.forName(className);
                    if (o == null) {
                        throw new Exception("Class not available");
                    }
                } catch (NoClassDefFoundError ncdfe) {
                    // By Design: gobbling up this error to reduce the
                    // non-needed noise upon startup. If there is a real
                    // issue, then it will bubble up somewhere else.
                } catch (Exception e) {
                    // Explicitly load classes from packages that have
                    // package-info
                    try {
                        ClassLoader.getSystemClassLoader().loadClass(className);
                    } catch (java.lang.NoClassDefFoundError ncdfe) {
                        // By Design: gobbling up this error to reduce the
                        // non-needed noise upon startup. If there is a real
                        // issue, then it will bubble up somewhere else.
                    }
                }

                Package packageItem = Package.getPackage(pi.getName());
                if (null != packageItem.getAnnotation(MockeyRequestInspector.class)) {
                    Class<?> x = doesThisImplementIRequestInspector(className);
                    if (x != null && !this.reqInspectorClassNameList.contains(x)) {
                        this.reqInspectorClassNameList.add(x);
                        logger.debug("Plugin added: " + className);
                    }
                }
            }
        }

    } catch (Exception e) {
        logger.error("Found a Mockey.jar, but unable read mockey jar", e);
    }
}

From source file:com.cpjit.swagger4j.util.ReflectUtils.java

/**
 * ?????// www .  j  a  va 2 s  . co  m
 * <p>
 * package-info.java?{@code null}
 * </p>
 * @since 1.2.2
 */
private static Package getPackage(final String packageName)
        throws FileNotFoundException, IllegalArgumentException {
    Package pkg = Package.getPackage(packageName);
    if (pkg == null) { // ?package-info.class
        pkg = scanClazzName(packageName).stream().map(clazzName -> {
            try {
                return Class.forName(clazzName).getPackage();
            } catch (ClassNotFoundException e) {
                return null;
            }
        }).filter(pk -> pk != null).findFirst().get();
    }
    return pkg;
}

From source file:wordnice.utils.JavaUtils.java

public static void loadPackages(Collection<Package> out, Collection<String> in) throws Throwable {
    Iterator<String> it = in.iterator();
    while (it.hasNext()) {
        out.add(Package.getPackage(it.next()));
    }/*from  w  ww.jav a 2 s  . com*/
}

From source file:com.gooddata.GoodData.java

private String getUserAgent() {
    final Package pkg = Package.getPackage("com.gooddata");
    final String clientVersion = pkg != null && pkg.getImplementationVersion() != null
            ? pkg.getImplementationVersion()
            : UNKNOWN_VERSION;//from  www .  ja va 2 s  .  co m

    final VersionInfo vi = loadVersionInfo("org.apache.http.client", HttpClientBuilder.class.getClassLoader());
    final String apacheVersion = vi != null ? vi.getRelease() : UNKNOWN_VERSION;

    return String.format("%s/%s (%s; %s) %s/%s", "GoodData-Java-SDK", clientVersion,
            System.getProperty("os.name"), System.getProperty("java.specification.version"),
            "Apache-HttpClient", apacheVersion);
}

From source file:org.aitools.programd.Core.java

/**
 * Initializes and starts up the Core.//from  w  ww.j a  v  a  2  s.co  m
 */
@SuppressWarnings("boxing")
protected void start() {
    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler());

    // Set up the XML parsing feature settings.
    this._xmlParserFeatureSettings = new HashMap<String, Boolean>(6);
    this._xmlParserFeatureSettings.put("http://xml.org/sax/features/use-entity-resolver2",
            this._settings.xmlParserUseEntityResolver2());
    this._xmlParserFeatureSettings.put("http://xml.org/sax/features/validation",
            this._settings.xmlParserUseValidation());
    this._xmlParserFeatureSettings.put("http://apache.org/xml/features/validation/schema",
            this._settings.xmlParserUseSchemaValidation());
    this._xmlParserFeatureSettings.put("http://apache.org/xml/features/honour-all-schemaLocations",
            this._settings.xmlParserHonourAllSchemaLocations());
    this._xmlParserFeatureSettings.put("http://apache.org/xml/features/xinclude",
            this._settings.xmlParserUseXInclude());
    this._xmlParserFeatureSettings.put("http://apache.org/xml/features/validate-annotations",
            this._settings.xmlParserValidateAnnotations());

    // Use the stdout and stderr appenders in a special way, if they are defined.
    ConsoleStreamAppender stdOutAppender = ((ConsoleStreamAppender) Logger.getLogger("programd")
            .getAppender("stdout"));
    if (stdOutAppender != null) {
        if (!stdOutAppender.isWriterSet()) {
            stdOutAppender.setWriter(new OutputStreamWriter(System.out));
        }
    }

    ConsoleStreamAppender stdErrAppender = ((ConsoleStreamAppender) Logger.getLogger("programd")
            .getAppender("stderr"));
    if (stdErrAppender != null) {
        if (!stdErrAppender.isWriterSet()) {
            stdErrAppender.setWriter(new OutputStreamWriter(System.err));
        }
    }

    // Set up an interception of calls to the JDK logging system and re-route to log4j.
    JDKLogHandler.setupInterception();

    this._logger.info(String.format("Base URL for Program D Core: \"%s\".", this._baseURL));

    this._aimlProcessorRegistry = new AIMLProcessorRegistry();

    this._graphmapper = Classes.getSubclassInstance(Graphmapper.class,
            this._settings.getGraphmapperImplementation(), "Graphmapper implementation", this);
    this._bots = new Bots();
    this._processes = new ManagedProcesses(this);

    // Get an instance of the settings-specified PredicateManager.
    this._predicateManager = Classes.getSubclassInstance(PredicateManager.class,
            this._settings.getPredicateManagerImplementation(), "PredicateManager", this);

    // Get the hostname (used occasionally).
    try {
        this._hostname = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        this._hostname = "unknown hostname";
    }

    // Load the plugin config.
    URL pluginConfigURL = this._settings.getPluginConfigURL();
    if (pluginConfigURL != null) {
        pluginConfigURL = URLTools.contextualize(this._baseURL, pluginConfigURL);
        try {
            if (pluginConfigURL.openStream() != null) {
                this._pluginConfig = JDOM.getDocument(pluginConfigURL, this._logger);
            }
        } catch (IOException e) {
            // Don't load plugin config.
        }
    }

    // TODO: Make this work even if the classes aren't in a jar.
    Package pkg = Package.getPackage("org.aitools.programd");
    this._logger.info(String.format("Starting %s version %s [%s].", pkg.getSpecificationTitle(),
            pkg.getSpecificationVersion(), pkg.getImplementationVersion()));
    this._logger.info(UserSystem.jvmDescription());
    this._logger.info(UserSystem.osDescription());
    this._logger.info(UserSystem.memoryReport());
    this._logger.info("Predicates with no values defined will return: \""
            + this._settings.getPredicateEmptyDefault() + "\".");

    try {
        // Create the AIMLWatcher if configured to do so.
        if (this._settings.useAIMLWatcher()) {
            this._aimlWatcher = new AIMLWatcher(this);
        }

        // Setup a JavaScript interpreter if supposed to.
        setupInterpreter();

        // Start the AIMLWatcher if configured to do so.
        startWatcher();

        this._logger.info("Starting up the Graphmaster.");

        // Start loading bots.
        URL botConfigURL = this._settings.getBotConfigURL();
        if (botConfigURL != null) {
            loadBotConfig(botConfigURL);
        } else {
            this._logger.warn("No bot config URL specified; no bots will be loaded.");
        }

        // Request garbage collection.
        System.gc();

        this._logger.info(UserSystem.memoryReport());

        // Start the heart, if enabled.
        startHeart();
    } catch (DeveloperError e) {
        alert("developer error", e);
    } catch (UserError e) {
        alert("user error", e);
    } catch (RuntimeException e) {
        alert("unforeseen runtime exception", e);
    } catch (Throwable e) {
        alert("unforeseen problem", e);
    }

    // Set the status indicator.
    this._status = Status.READY;

    // Exit immediately if configured to do so (for timing purposes).
    if (this._settings.exitImmediatelyOnStartup()) {
        shutdown();
    }
}

From source file:com.yahoo.elide.core.EntityDictionary.java

private static Package getParentPackage(Package pkg) {
    String name = pkg.getName();/*from w w w  .j a v a  2s.  c o m*/
    int idx = name.lastIndexOf('.');
    return idx == -1 ? null : Package.getPackage(name.substring(0, idx));
}

From source file:net.sf.jasperreports.engine.export.JRXlsExporter.java

@Override
protected void openWorkbook(OutputStream os) {
    XlsExporterConfiguration configuration = getCurrentConfiguration();
    String lcWorkbookTemplate = workbookTemplate == null ? configuration.getWorkbookTemplate()
            : workbookTemplate;/*  w  w w  .j  a  v  a  2s .com*/
    if (lcWorkbookTemplate == null) {
        workbook = new HSSFWorkbook();
    } else {
        InputStream templateIs = null;
        try {
            templateIs = getRepository().getInputStreamFromLocation(lcWorkbookTemplate);
            if (templateIs == null) {
                throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_TEMPLATE_NOT_FOUND,
                        new Object[] { lcWorkbookTemplate });
            } else {
                workbook = new HSSFWorkbook(new POIFSFileSystem(templateIs));
                boolean keepSheets = keepTemplateSheets == null ? configuration.isKeepWorkbookTemplateSheets()
                        : keepTemplateSheets;
                if (keepSheets) {
                    sheetIndex += workbook.getNumberOfSheets();
                } else {
                    for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                        workbook.removeSheetAt(i);
                    }
                }
            }
        } catch (JRException e) {
            throw new JRRuntimeException(e);
        } catch (IOException e) {
            throw new JRRuntimeException(e);
        } finally {
            if (templateIs != null) {
                try {
                    templateIs.close();
                } catch (IOException e) {
                }
            }
        }
    }
    emptyCellStyle = workbook.createCellStyle();
    emptyCellStyle.setFillForegroundColor(HSSFColor.HSSFColorPredefined.WHITE.getIndex());
    emptyCellStyle.setFillPattern(backgroundMode);
    dataFormat = workbook.createDataFormat();
    createHelper = workbook.getCreationHelper();
    firstPageNotSet = true;
    palette = workbook.getCustomPalette();
    customColorIndex = MIN_COLOR_INDEX;
    autofitColumns = new HashMap<HSSFSheet, List<Integer>>();
    formulaCellsMap = new HashMap<HSSFCell, String>();

    SummaryInformation summaryInformation = workbook.getSummaryInformation();
    if (summaryInformation == null) {
        workbook.createInformationProperties();
        summaryInformation = workbook.getSummaryInformation();
    }

    String application = configuration.getMetadataApplication();
    if (application == null) {
        application = "JasperReports Library version "
                + Package.getPackage("net.sf.jasperreports.engine").getImplementationVersion();
    }
    summaryInformation.setApplicationName(application);

    String title = configuration.getMetadataTitle();
    if (title != null) {
        summaryInformation.setTitle(title);
    }
    String subject = configuration.getMetadataSubject();
    if (subject != null) {
        summaryInformation.setSubject(subject);
    }
    String author = configuration.getMetadataAuthor();
    if (author != null) {
        summaryInformation.setAuthor(author);
    }
    String keywords = configuration.getMetadataKeywords();
    if (keywords != null) {
        summaryInformation.setKeywords(keywords);
    }
}

From source file:net.sf.jasperreports.engine.export.ooxml.JRDocxExporter.java

/**
 *
 *//*from   www .j  a  v a  2s . c  om*/
protected void exportReportToStream(OutputStream os) throws JRException, IOException {
    docxZip = new DocxZip();

    docWriter = docxZip.getDocumentEntry().getWriter();

    docHelper = new DocxDocumentHelper(jasperReportsContext, docWriter);
    docHelper.exportHeader();

    relsHelper = new DocxRelsHelper(jasperReportsContext, docxZip.getRelsEntry().getWriter());
    relsHelper.exportHeader();

    appHelper = new PropsAppHelper(jasperReportsContext, docxZip.getAppEntry().getWriter());
    coreHelper = new PropsCoreHelper(jasperReportsContext, docxZip.getCoreEntry().getWriter());

    appHelper.exportHeader();

    DocxExporterConfiguration configuration = getCurrentConfiguration();

    String application = configuration.getMetadataApplication();
    if (application == null) {
        application = "JasperReports Library version "
                + Package.getPackage("net.sf.jasperreports.engine").getImplementationVersion();
    }
    appHelper.exportProperty(PropsAppHelper.PROPERTY_APPLICATION, application);

    coreHelper.exportHeader();

    String title = configuration.getMetadataTitle();
    if (title != null) {
        coreHelper.exportProperty(PropsCoreHelper.PROPERTY_TITLE, title);
    }
    String subject = configuration.getMetadataSubject();
    if (subject != null) {
        coreHelper.exportProperty(PropsCoreHelper.PROPERTY_SUBJECT, subject);
    }
    String author = configuration.getMetadataAuthor();
    if (author != null) {
        coreHelper.exportProperty(PropsCoreHelper.PROPERTY_CREATOR, author);
    }
    String keywords = configuration.getMetadataKeywords();
    if (keywords != null) {
        coreHelper.exportProperty(PropsCoreHelper.PROPERTY_KEYWORDS, keywords);
    }

    List<ExporterInputItem> items = exporterInput.getItems();

    boolean isEmbedFonts = Boolean.TRUE.equals(configuration.isEmbedFonts());

    docxFontHelper = new DocxFontHelper(jasperReportsContext, docxZip, isEmbedFonts);

    DocxStyleHelper styleHelper = new DocxStyleHelper(this, docxZip.getStylesEntry().getWriter(),
            docxFontHelper);
    styleHelper.export(exporterInput);
    styleHelper.close();

    DocxSettingsHelper settingsHelper = new DocxSettingsHelper(jasperReportsContext,
            docxZip.getSettingsEntry().getWriter());
    settingsHelper.export(jasperPrint, isEmbedFonts);
    settingsHelper.close();

    docxFontTableHelper = new DocxFontTableHelper(jasperReportsContext,
            docxZip.getFontTableEntry().getWriter());
    docxFontTableHelper.exportHeader();

    docxFontTableRelsHelper = new DocxFontTableRelsHelper(jasperReportsContext,
            docxZip.getFontTableRelsEntry().getWriter());
    docxFontTableRelsHelper.exportHeader();

    runHelper = new DocxRunHelper(jasperReportsContext, docWriter, docxFontHelper);

    pageFormat = null;
    PrintPageFormat oldPageFormat = null;

    for (reportIndex = 0; reportIndex < items.size(); reportIndex++) {
        ExporterInputItem item = items.get(reportIndex);

        setCurrentExporterInputItem(item);

        bookmarkIndex = 0;
        emptyPageState = false;

        List<JRPrintPage> pages = jasperPrint.getPages();
        if (pages != null && pages.size() > 0) {
            PageRange pageRange = getPageRange();
            startPageIndex = (pageRange == null || pageRange.getStartPageIndex() == null) ? 0
                    : pageRange.getStartPageIndex();
            endPageIndex = (pageRange == null || pageRange.getEndPageIndex() == null) ? (pages.size() - 1)
                    : pageRange.getEndPageIndex();

            JRPrintPage page = null;
            for (pageIndex = startPageIndex; pageIndex <= endPageIndex; pageIndex++) {
                if (Thread.interrupted()) {
                    throw new ExportInterruptedException();
                }

                page = pages.get(pageIndex);

                pageFormat = jasperPrint.getPageFormat(pageIndex);

                if (oldPageFormat != null && oldPageFormat != pageFormat) {
                    docHelper.exportSection(oldPageFormat, pageGridLayout, false);
                }

                exportPage(page);

                oldPageFormat = pageFormat;
            }
        }
    }

    if (oldPageFormat != null) {
        docHelper.exportSection(oldPageFormat, pageGridLayout, true);
    }

    docHelper.exportFooter();
    docHelper.close();

    //      if ((hyperlinksMap != null && hyperlinksMap.size() > 0))
    //      {
    //         for(Iterator it = hyperlinksMap.keySet().iterator(); it.hasNext();)
    //         {
    //            String href = (String)it.next();
    //            String id = (String)hyperlinksMap.get(href);
    //
    //            relsHelper.exportHyperlink(id, href);
    //         }
    //      }

    relsHelper.exportFooter();
    relsHelper.close();

    appHelper.exportFooter();
    appHelper.close();

    coreHelper.exportFooter();
    coreHelper.close();

    docxFontHelper.exportFonts();

    docxFontTableHelper.exportFooter();
    docxFontTableHelper.close();

    docxFontTableRelsHelper.exportFooter();
    docxFontTableRelsHelper.close();

    docxZip.zipEntries(os);

    docxZip.dispose();
}

From source file:org.apache.tapestry5.cdi.test.InjectTest.java

/**
 * Convert a file path to a Package//  w w  w .  j  a  v  a  2  s.c  om
 * @param path the file path
 * @return a Package
 */
private static Package toPackage(String path) {
    return Package.getPackage(path.replace(File.separator, "."));
}