Example usage for org.apache.commons.lang ArrayUtils isNotEmpty

List of usage examples for org.apache.commons.lang ArrayUtils isNotEmpty

Introduction

In this page you can find the example usage for org.apache.commons.lang ArrayUtils isNotEmpty.

Prototype

public static boolean isNotEmpty(boolean[] array) 

Source Link

Document

Checks if an array of primitive booleans is not empty or not null.

Usage

From source file:eu.europa.esig.dss.DSSUtils.java

/**
 * This method loads the issuer certificate from the given location (AIA). The certificate must be DER-encoded and may be supplied in binary or
 * printable (Base64) encoding. If the certificate is provided in Base64 encoding, it must be bounded at the beginning by -----BEGIN
 * CERTIFICATE-----, and must be bounded at the end by -----END CERTIFICATE-----. It throws an {@code DSSException} or return {@code null} when the certificate cannot be loaded.
 *
 * @param cert/* ww w . j av  a2  s  .  c om*/
 *            certificate for which the issuer should be loaded
 * @param loader
 *            the loader to use
 * @return
 */
public static CertificateToken loadIssuerCertificate(final CertificateToken cert, final DataLoader loader) {
    List<String> urls = DSSASN1Utils.getAccessLocations(cert);
    if (CollectionUtils.isEmpty(urls)) {
        logger.info("There is no AIA extension for certificate download.");
        return null;
    }

    if (loader == null) {
        logger.warn(
                "There is no DataLoader defined to load Certificates from AIA extension (urls : " + urls + ")");
        return null;
    }

    for (String url : urls) {
        logger.debug("Loading certificate from {}", url);

        byte[] bytes = loader.get(url);
        if (ArrayUtils.isNotEmpty(bytes)) {
            try {
                logger.debug("Certificate : " + Base64.encodeBase64String(bytes));

                CertificateToken issuerCert = loadCertificate(bytes);
                if (issuerCert != null) {
                    if (!cert.getIssuerX500Principal().equals(issuerCert.getSubjectX500Principal())) {
                        logger.info(
                                "There is AIA extension, but the issuer subject name and subject name does not match.");
                        logger.info("CERT ISSUER    : " + cert.getIssuerX500Principal().toString());
                        logger.info("ISSUER SUBJECT : " + issuerCert.getSubjectX500Principal().toString());
                    }
                    return issuerCert;
                }
            } catch (Exception e) {
                logger.warn("Unable to parse certficate from AIA (url:" + url + ") : " + e.getMessage());
            }
        } else {
            logger.error("Unable to read data from {}.", url);
        }
    }

    return null;
}

From source file:com.photon.phresco.service.admin.actions.components.Downloads.java

public String delete() {
    if (isDebugEnabled) {
        S_LOGGER.debug("Downloads.delete : Entry");
    }/*w  w w  .  j a  va2 s .c o m*/

    try {
        if (isDebugEnabled) {
            if (StringUtils.isEmpty(getCustomerId())) {
                S_LOGGER.warn("Downloads.update", "status=\"Bad Request\"", "message=\"Customer Id is empty\"");
                return showErrorPopup(new PhrescoException("Customer Id is empty"),
                        getText(EXCEPTION_DOWNLOADS_DELETE));
            }
            S_LOGGER.info("Downloads.update", "customerId=" + "\"" + getCustomerId() + "\"");
        }
        String[] downloadIds = getHttpRequest().getParameterValues(REQ_DOWNLOAD_ID);
        if (ArrayUtils.isNotEmpty(downloadIds)) {
            if (isDebugEnabled) {
                if (isDebugEnabled) {
                    S_LOGGER.info("Downloads.delete", "downloadIds=" + "\"" + downloadIds.toString() + "\"");
                }
            }
            for (String downloadid : downloadIds) {
                getServiceManager().deleteDownloadInfo(downloadid, getCustomerId());
            }
            addActionMessage(getText(DOWNLOAD_DELETED));
        }
    } catch (PhrescoException e) {
        if (isDebugEnabled) {
            S_LOGGER.error("Downloads.delete", "status=\"Failure\"",
                    "message=\"" + e.getLocalizedMessage() + "\"");
        }
        return showErrorPopup(e, getText(EXCEPTION_DOWNLOADS_DELETE));
    }
    if (isDebugEnabled) {
        S_LOGGER.debug("Downloads.delete : Exit");
    }

    return list();
}

From source file:com.belle.yitiansystem.merchant.service.impl.MerchantServiceNewImpl.java

/**
 * ??//from w w w .java 2 s.com
 * 
 * @param supplier
 * @param bankNoHidden
 * @param catNameHidden
 */
private void bulidSupplierBrandCat(SupplierVo supplier, String bankNoHidden, String catNameHidden) {
    // ?|
    if (StringUtils.isNotBlank(bankNoHidden)) { // bankNoHidden:[Hfjt;POwu;CMs6]
        // ??
        List<BrandVo> _brand_list = new ArrayList<BrandVo>();
        // ?
        List<CatVo> _cat_list = new ArrayList<CatVo>();
        // ??
        List<BrandCatRelation> _brandcat_list = new ArrayList<BrandCatRelation>();

        String[] _arraybank = bankNoHidden.split(";");

        Map<String, String> brankNoIdMap = new HashMap<String, String>();
        Map<String, String> catStructNameIdMap = new HashMap<String, String>();
        if (ArrayUtils.isNotEmpty(_arraybank)) {
            BrandVo _temp_brand = null;
            for (String _brandNo : _arraybank) {
                _temp_brand = new BrandVo();
                _temp_brand.setId(UUIDGenerator.getUUID());
                _temp_brand.setSupplyId(supplier.getId());
                _temp_brand.setBrandNo(_brandNo);

                _brand_list.add(_temp_brand);
                // ??IdNo
                brankNoIdMap.put(_brandNo, _temp_brand.getId());
            }
            supplier.setBrandVos(_brand_list);
        }

        // 
        // [brand_no;struct_name_brand_no;struct_name_brand_no;struct_name]
        if (StringUtils.isNotBlank(catNameHidden)) {
            Set<String> catSet = new HashSet<String>();
            String[] catNameStr = catNameHidden.split("_");
            for (String string : catNameStr) {
                String[] catStr = string.split(";");
                catSet.add(catStr[1]);
            }
            if (CollectionUtils.isNotEmpty(catSet)) {
                CatVo _temp_cat = null;
                for (String set : catSet) {
                    _temp_cat = new CatVo();
                    _temp_cat.setId(UUIDGenerator.getUUID());
                    _temp_cat.setSupplyId(supplier.getId());
                    _temp_cat.setStructName(set);
                    Category c = commodityBaseApiService.getCategoryByStructName(set);
                    _temp_cat.setCatNo(c.getCatNo());

                    _cat_list.add(_temp_cat);
                    // ?Idstructname
                    catStructNameIdMap.put(set, _temp_cat.getId());
                }
                supplier.setCatVos(_cat_list);
            }

            BrandCatRelation relation = null;
            for (String string : catNameStr) {
                String[] catStr = string.split(";");
                relation = new BrandCatRelation();
                relation.setId(UUIDGenerator.getUUID());
                relation.setBrandId(brankNoIdMap.get(catStr[0]));
                relation.setCatId(catStructNameIdMap.get(catStr[1]));
                _brandcat_list.add(relation);
            }
            if (CollectionUtils.isNotEmpty(_brandcat_list)) {
                supplier.setBrandcatRelations(_brandcat_list);
            }
        }
    }
}

From source file:jef.database.DbClientBuilder.java

protected JefEntityManagerFactory buildSessionFactory() {
    if (instance != null)
        return instance;

    // try enahcen entity if theres 'enhancePackages'.
    if (enhancePackages != null) {
        if (!enhancePackages.equalsIgnoreCase("none")) {
            new EntityEnhancer().enhance(StringUtils.split(enhancePackages, ","));
        }/*from w w w .j  a v a2 s . co  m*/
    }
    if (enhanceScanPackages && ArrayUtils.isNotEmpty(this.packagesToScan)) {
        new EntityEnhancer().enhance(packagesToScan);
    } else if (enhanceScanPackages) {
        log.warn("EnhanceScanPackages flag was set to true. but property 'packagesToScan' was not assigned");
    }
    JefEntityManagerFactory sf;
    // check data sources.
    if (dataSource == null && dataSources == null) {
        LogUtil.info("No datasource found. Using default datasource in jef.properties.");
        sf = new JefEntityManagerFactory(null, minPoolSize, maxPoolSize, transactionMode);
    } else if (dataSource != null) {
        sf = new JefEntityManagerFactory(dataSource, minPoolSize, maxPoolSize, transactionMode);
    } else {
        RoutingDataSource rs = new RoutingDataSource(
                new MapDataSourceLookup(dataSources).setDefaultKey(this.defaultDatasource));
        sf = new JefEntityManagerFactory(rs, minPoolSize, maxPoolSize, transactionMode);
    }
    if (namedQueryFile != null) {
        sf.getDefault().setNamedQueryFilename(namedQueryFile);
    }
    if (namedQueryTable != null) {
        sf.getDefault().setNamedQueryTablename(namedQueryTable);
    }

    if (packagesToScan != null || annotatedClasses != null) {
        QuerableEntityScanner qe = new QuerableEntityScanner();
        if (transactionMode == TransactionMode.JTA) {
            // JTADDL????JTA
            qe.setCheckSequence(false);
        }
        qe.setImplClasses(DataObject.class);
        qe.setAllowDropColumn(allowDropColumn);
        qe.setAlterTable(alterTable);
        qe.setCreateTable(createTable);

        qe.setInitData(this.initData);
        qe.setEntityManagerFactory(sf, this.useDataInitTable, this.initDataCharset, this.initDataExtension,
                this.initDataRoot);
        if (annotatedClasses != null)
            qe.registeEntity(annotatedClasses);
        if (packagesToScan != null) {
            String joined = StringUtils.join(packagesToScan, ',');
            qe.setPackageNames(joined);
            LogUtil.info("Starting scan easyframe entity from package: {}", joined);
            qe.doScan();
        }
        qe.finish();
    }
    if (dynamicTables != null) {
        DbClient client = sf.getDefault();
        for (String s : StringUtils.split(dynamicTables, ",")) {
            String table = s.trim();
            registe(client, table);
        }
    }
    if (registeNonMappingTableAsDynamic) {
        DbClient client = sf.getDefault();
        try {
            for (String tableName : client.getMetaData(null).getTableNames()) {
                if (MetaHolder.lookup(null, tableName) != null) {
                    registe(client, tableName);
                }
            }
        } catch (SQLException e) {
            LogUtil.exception(e);
        }

    }
    // ??
    if (StringUtils.isNotBlank(this.dbInitHandler)) {
        for (String clzName : StringUtils.split(dbInitHandler, ',')) {
            try {
                Object initType = Class.forName(clzName).newInstance();
                if (initType instanceof DbInitHandler) {
                    ((DbInitHandler) initType).doDatabaseInit(sf.getDefault());
                }
            } catch (ClassNotFoundException e) {
                LogUtil.error("InitClass load failure: class not found - " + e.getMessage());
            } catch (InstantiationException e) {
                LogUtil.error("InitClass load failure - ", e);
            } catch (IllegalAccessException e) {
                LogUtil.error("InitClass load failure - ", e);
            }
        }
    }
    return sf;
}

From source file:com.liferay.portlet.documentlibrary.lar.DLPortletDataHandlerImpl.java

public static void importFileEntry(PortletDataContext portletDataContext, Element fileEntryElement, String path)
        throws Exception {

    FileEntry fileEntry = (FileEntry) portletDataContext.getZipEntryAsObject(path);

    long userId = portletDataContext.getUserId(fileEntry.getUserUuid());

    Map<Long, Long> folderIds = (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(DLFolder.class);

    long folderId = MapUtil.getLong(folderIds, fileEntry.getFolderId(), fileEntry.getFolderId());

    long[] assetCategoryIds = null;
    String[] assetTagNames = null;

    if (portletDataContext.getBooleanParameter(_NAMESPACE, "categories")) {
        assetCategoryIds = portletDataContext.getAssetCategoryIds(DLFileEntry.class,
                fileEntry.getFileEntryId());
    }//  w  w  w  .  j a v  a2  s.co  m

    if (portletDataContext.getBooleanParameter(_NAMESPACE, "tags")) {
        assetTagNames = portletDataContext.getAssetTagNames(DLFileEntry.class, fileEntry.getFileEntryId());
    }

    ServiceContext serviceContext = portletDataContext.createServiceContext(fileEntryElement, fileEntry,
            _NAMESPACE);

    serviceContext.setAttribute("sourceFileName", "A." + fileEntry.getExtension());
    serviceContext.setUserId(userId);

    String binPath = fileEntryElement.attributeValue("bin-path");

    InputStream is = null;

    if (Validator.isNull(binPath) && portletDataContext.isPerformDirectBinaryImport()) {

        try {
            is = FileEntryUtil.getContentStream(fileEntry);
        } catch (NoSuchFileException nsfe) {
        }
    } else {
        is = portletDataContext.getZipEntryAsInputStream(binPath);
    }

    if (is == null) {
        if (_log.isWarnEnabled()) {
            _log.warn("No file found for file entry " + fileEntry.getFileEntryId());
        }

        return;
    }

    if ((folderId != DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) && (folderId == fileEntry.getFolderId())) {

        String folderPath = getImportFolderPath(portletDataContext, folderId);

        Folder folder = (Folder) portletDataContext.getZipEntryAsObject(folderPath);

        Document document = fileEntryElement.getDocument();

        Element rootElement = document.getRootElement();

        Element folderElement = (Element) rootElement
                .selectSingleNode("//folder[@path='".concat(folderPath).concat("']"));

        importFolder(portletDataContext, folderPath, folderElement, folder);

        folderId = MapUtil.getLong(folderIds, fileEntry.getFolderId(), fileEntry.getFolderId());
    }

    importMetaData(portletDataContext, fileEntryElement, serviceContext);

    FileEntry importedFileEntry = null;

    String titleWithExtension = DLUtil.getTitleWithExtension(fileEntry);
    String extension = fileEntry.getExtension();

    String dotExtension = StringPool.PERIOD + extension;

    if (portletDataContext.isDataStrategyMirror()) {
        FileEntry existingFileEntry = FileEntryUtil.fetchByUUID_R(fileEntry.getUuid(),
                portletDataContext.getScopeGroupId());

        FileVersion fileVersion = fileEntry.getFileVersion();

        if (existingFileEntry == null) {
            String fileEntryTitle = fileEntry.getTitle();

            FileEntry existingTitleFileEntry = FileEntryUtil.fetchByR_F_T(portletDataContext.getScopeGroupId(),
                    folderId, fileEntryTitle);

            if (existingTitleFileEntry != null) {
                if ((fileEntry.getGroupId() == portletDataContext.getSourceGroupId())
                        && portletDataContext.isDataStrategyMirrorWithOverwriting()) {

                    DLAppLocalServiceUtil.deleteFileEntry(existingTitleFileEntry.getFileEntryId());
                } else {
                    boolean titleHasExtension = false;

                    if (fileEntryTitle.endsWith(dotExtension)) {
                        fileEntryTitle = FileUtil.stripExtension(fileEntryTitle);

                        titleHasExtension = true;
                    }

                    for (int i = 1;; i++) {
                        fileEntryTitle += StringPool.SPACE + i;

                        titleWithExtension = fileEntryTitle + dotExtension;

                        existingTitleFileEntry = FileEntryUtil.fetchByR_F_T(
                                portletDataContext.getScopeGroupId(), folderId, titleWithExtension);

                        if (existingTitleFileEntry == null) {
                            if (titleHasExtension) {
                                fileEntryTitle += dotExtension;
                            }

                            break;
                        }
                    }
                }
            }

            serviceContext.setAttribute("fileVersionUuid", fileVersion.getUuid());
            serviceContext.setUuid(fileEntry.getUuid());
            // Modification start
            boolean damnIndexing = serviceContext.isIndexingEnabled();
            try {
                serviceContext.setIndexingEnabled(false);
                importedFileEntry = DLAppLocalServiceUtil.addFileEntry(userId,
                        portletDataContext.getScopeGroupId(), folderId, titleWithExtension,
                        fileEntry.getMimeType(), fileEntryTitle, fileEntry.getDescription(), null, is,
                        fileEntry.getSize(), serviceContext);
            } finally {
                serviceContext.setIndexingEnabled(damnIndexing);
            }
            // Modification end
        } else {
            FileVersion latestExistingFileVersion = existingFileEntry.getLatestFileVersion();

            boolean indexEnabled = serviceContext.isIndexingEnabled();

            try {
                serviceContext.setIndexingEnabled(false);

                if (!fileVersion.getUuid().equals(latestExistingFileVersion.getUuid())) {

                    DLFileVersion alreadyExistingFileVersion = DLFileVersionLocalServiceUtil
                            .getFileVersionByUuidAndGroupId(fileVersion.getUuid(),
                                    existingFileEntry.getGroupId());

                    if (alreadyExistingFileVersion != null) {
                        serviceContext.setAttribute("existingDLFileVersionId",
                                alreadyExistingFileVersion.getFileVersionId());
                    }

                    serviceContext.setUuid(fileVersion.getUuid());

                    importedFileEntry = DLAppLocalServiceUtil.updateFileEntry(userId,
                            existingFileEntry.getFileEntryId(), fileEntry.getTitle(), fileEntry.getMimeType(),
                            fileEntry.getTitle(), fileEntry.getDescription(), null, false, is,
                            fileEntry.getSize(), serviceContext);

                    // Modification start
                    String[] fileEntries = PurgeRequestThreadLocal.getFileEntriesToPurge();
                    String fileEntryId = Long.toString(importedFileEntry.getFileEntryId());
                    if (ArrayUtils.isNotEmpty(fileEntries) && fileEntries[0].indexOf(fileEntryId) == -1) {
                        fileEntries[0] = fileEntries[0] + ";" + fileEntryId;
                    }
                    // Modification end
                } else {
                    DLAppLocalServiceUtil.updateAsset(userId, existingFileEntry, latestExistingFileVersion,
                            assetCategoryIds, assetTagNames, null);

                    importedFileEntry = existingFileEntry;
                }

                if (importedFileEntry.getFolderId() != folderId) {
                    importedFileEntry = DLAppLocalServiceUtil.moveFileEntry(userId,
                            importedFileEntry.getFileEntryId(), folderId, serviceContext);
                }

                if (importedFileEntry instanceof LiferayFileEntry) {
                    LiferayFileEntry liferayFileEntry = (LiferayFileEntry) importedFileEntry;

                    Indexer indexer = IndexerRegistryUtil.getIndexer(DLFileEntry.class);

                    indexer.reindex(liferayFileEntry.getModel());
                }
            } finally {
                serviceContext.setIndexingEnabled(indexEnabled);
            }
        }
    } else {
        try {
            importedFileEntry = DLAppLocalServiceUtil.addFileEntry(userId, portletDataContext.getScopeGroupId(),
                    folderId, titleWithExtension, fileEntry.getMimeType(), fileEntry.getTitle(),
                    fileEntry.getDescription(), null, is, fileEntry.getSize(), serviceContext);
        } catch (DuplicateFileException dfe) {
            String title = fileEntry.getTitle();

            String[] titleParts = title.split("\\.", 2);

            title = titleParts[0] + PwdGenerator.getPassword();

            if (titleParts.length > 1) {
                title += StringPool.PERIOD + titleParts[1];
            }

            if (!title.endsWith(dotExtension)) {
                title += dotExtension;
            }

            importedFileEntry = DLAppLocalServiceUtil.addFileEntry(userId, portletDataContext.getScopeGroupId(),
                    folderId, title, fileEntry.getMimeType(), title, fileEntry.getDescription(), null, is,
                    fileEntry.getSize(), serviceContext);
        }
    }

    if (portletDataContext.getBooleanParameter(_NAMESPACE, "previews-and-thumbnails")) {

        DLProcessorRegistryUtil.importGeneratedFiles(portletDataContext, fileEntry, importedFileEntry,
                fileEntryElement);
    }

    Map<String, String> fileEntryTitles = (Map<String, String>) portletDataContext
            .getNewPrimaryKeysMap(DLFileEntry.class.getName() + ".title");

    fileEntryTitles.put(fileEntry.getTitle(), importedFileEntry.getTitle());

    portletDataContext.importClassedModel(fileEntry, importedFileEntry, _NAMESPACE);

}

From source file:com.seer.datacruncher.utils.generic.CommonUtils.java

public static Object getClassInstance(String className, String implementedClassName, Class<?> implementedClass,
        String sourceCode) throws Exception {
    DynamicClassLoader dynacode = DynamicClassLoader.getInstance();
    Class<?> dynaClass = dynacode.getLoadedClass(className);
    File sourceDir = new File(System.getProperty("java.io.tmpdir"), "DataCruncher/src");
    boolean createFileInTemp = false;
    if (dynaClass == null) {
        createFileInTemp = true;/*  w  w w.  jav a  2  s.co m*/
    } else {
        boolean isExist = false;
        @SuppressWarnings("rawtypes")
        Class[] interfaces = dynaClass.getInterfaces();
        if (ArrayUtils.isNotEmpty(interfaces)) {
            for (Class<?> clz : interfaces) {
                if ((clz.getName().equalsIgnoreCase(implementedClassName))) {
                    isExist = true;
                }
            }
        }
        if (!isExist) {
            createFileInTemp = true;
        }
    }
    if (createFileInTemp) {
        boolean isCreated = CommonUtils.createFileIfNotExist(className, sourceCode, sourceDir);
        if (isCreated || dynaClass == null) {
            dynacode.addSourceDir(sourceDir);
            return dynacode.newProxyInstance(implementedClass, className);
        }
    }
    return dynaClass.newInstance();

}

From source file:com.nec.harvest.controller.JisekimController.java

/**
 * Thit is function handle updating data from Jisekim screen
 * /* w ww .java2 s .c  o  m*/
 * @param orgCode
 * @param monthly
 * @param jSONListActualView
 * @return boolean status update
 * @throws ServiceException
 */
public boolean handleUpdateJisekimData(String orgCode, String monthly,
        JSONListActualViewBean jSONListActualView) throws ServiceException {
    if (StringUtils.isEmpty(orgCode)) {
        throw new IllegalArgumentException("Orginazation's code must not be null or empty");
    }

    if (StringUtils.isEmpty(monthly)) {
        throw new IllegalArgumentException("Month must not be null or empty");
    }

    if (jSONListActualView == null) {
        throw new IllegalArgumentException("Jisekim Beans object must not be null");
    }

    final Session session = HibernateSessionManager.getSession();
    Transaction tx = null;

    try {
        // 
        tx = session.beginTransaction();
        JSONActualViewBean[] salesBeans = jSONListActualView.getSalesBeans();
        if (ArrayUtils.isNotEmpty(salesBeans)) {
            boolean isUpdatedMonthlySale = monthlySalesService.updateSalesData(session, orgCode, monthly,
                    salesBeans);
            if (!isUpdatedMonthlySale) {
                if (tx != null) {
                    tx.rollback();
                }

                // An error occurred while trying to update sale on month {} for organization {}
                logger.error("An error occurred while trying to update sale on month " + monthly
                        + " for organization " + orgCode);
                return false;
            }
        }

        JSONActualViewBean[] purchaseBeans = jSONListActualView.getPurchaseBeans();
        if (ArrayUtils.isNotEmpty(purchaseBeans)) {
            boolean isUpdatedPurchase = purchaseService.updatePurchaseData(session, orgCode, monthly,
                    purchaseBeans);
            if (!isUpdatedPurchase) {
                if (tx != null) {
                    tx.rollback();
                }

                // An error occurred while trying to update sale on month {} for organization {}
                logger.error("An error occurred while trying to update purchas on month " + monthly
                        + " for organization " + orgCode);
                return false;
            }
        }

        JSONActualViewBean[] inventoryBeans = jSONListActualView.getInventoryBeans();
        if (ArrayUtils.isNotEmpty(inventoryBeans)) {
            boolean isUpdatedInventory = inventoryService.updateInventoryData(session, orgCode, monthly,
                    inventoryBeans);
            if (!isUpdatedInventory) {
                if (tx != null) {
                    tx.rollback();
                }

                // 
                logger.error("An error occurred while trying to update inventory on month " + monthly
                        + " for organization " + orgCode);
                return false;
            }
        }
        tx.commit();
        return true;
    } catch (SQLGrammarException ex) {
        if (tx != null) {
            tx.rollback();
        }
        throw new ServiceException("An error occurred while update Jisekim Datas", ex);
    } finally {
        // ?
        HibernateSessionManager.closeSession(session);
    }
}

From source file:com.yougou.api.service.impl.ApiKeyServiceImpl.java

@Override
@Transactional/*from  w w w  . ja va  2s.  co  m*/
public boolean authorizeApi(String[] apiIds, String apiKeyId, SystemmgtUser systemmgtUser, String appkey,
        String userName) throws Exception {
    // ??
    String merchantCode = (String) JDBCUtils.getInstance().uniqueResult(
            "select metadata_val from tbl_merchant_api_key_metadata where metadata_key = 'MERCHANTS' and key_id = ?",
            new Object[] { apiKeyId });
    if (StringUtils.isEmpty(userName)) {
        userName = systemmgtUser.getUsername();
    }
    StringBuilder diffSqlBuilder = new StringBuilder();
    diffSqlBuilder.append(" select ");
    diffSqlBuilder.append(" group_concat(permissions separator ';') ");
    diffSqlBuilder.append(" from ( ");
    diffSqlBuilder.append(" select ");
    diffSqlBuilder.append(" concat(t2.api_name, '(', t3.category_name, ')') as permissions ");
    diffSqlBuilder.append(" from ");
    diffSqlBuilder.append(" tbl_merchant_api_license t1 ");
    diffSqlBuilder.append(" inner join tbl_merchant_api t2 on(t1.api_id = t2.id) ");
    diffSqlBuilder.append(" inner join tbl_merchant_api_category t3 on(t2.category_id = t3.id) ");
    diffSqlBuilder.append(" inner join tbl_merchant_api_key_metadata t4 on(t1.key_id = t4.key_id) ");
    diffSqlBuilder.append(" where ");
    diffSqlBuilder.append(" t4.metadata_val = ? ");
    diffSqlBuilder.append(" group by ");
    diffSqlBuilder.append(" t2.api_name, t3.category_name ");
    diffSqlBuilder.append(" ) tmp ");
    String diffSql = diffSqlBuilder.toString();
    Object ownPermissions = JDBCUtils.getInstance().uniqueResult(diffSql, new Object[] { merchantCode });

    // ?API
    String sql = "delete from tbl_merchant_api_license where key_id = ?";
    List<Object[]> sqlParams = new ArrayList<Object[]>();
    sqlParams.add(new Object[] { apiKeyId });

    MerchantOperationLog operationLog1 = new MerchantOperationLog();
    operationLog1.setId(UUIDUtil.getUUID());
    operationLog1.setMerchantCode(appkey);
    operationLog1.setOperated(new Date());
    operationLog1.setOperationNotes("?API");
    operationLog1.setOperationType(OperationType.APPKEY_AUTH);
    operationLog1.setOperator(userName);
    merchantOperationLogService.saveMerchantOperationLog(operationLog1);

    Map<String, List<Object[]>> sqlBatchs = new LinkedHashMap<String, List<Object[]>>();
    sqlBatchs.put(sql, sqlParams);
    String licensedStr = "";
    // ???API
    if (ArrayUtils.isNotEmpty(apiIds)) {
        sql = "insert into tbl_merchant_api_license(id, api_id, key_id, licensor, licensed) values(?, ?, ?, ?, ?)";
        Date licensed = new Date();
        sqlParams = new ArrayList<Object[]>();
        for (int i = 0; i < apiIds.length; i++) {
            Api api = apiService.getApiById(apiIds[i]);
            if (api != null) {
                sqlParams.add(new Object[] { UUIDUtil.getUUID(), apiIds[i], apiKeyId, userName, licensed });
                licensedStr = licensedStr + "," + api.getApiCategory().getCategoryName() + "("
                        + api.getApiName() + ")";
            }
        }
        sqlBatchs.put(sql, sqlParams);
    }

    MerchantOperationLog operationLog2 = new MerchantOperationLog();
    operationLog2.setId(UUIDUtil.getUUID());
    operationLog2.setMerchantCode(appkey);
    operationLog2.setOperated(new Date(System.currentTimeMillis() + 1000 * 60 * 2));
    operationLog2.setOperationNotes("?API:" + licensedStr);
    operationLog2.setOperationType(OperationType.APPKEY_AUTH);
    operationLog2.setOperator(userName);
    merchantOperationLogService.saveMerchantOperationLog(operationLog2);

    boolean result = JDBCUtils.getInstance().executeBatch(sqlBatchs);

    if (result) {
        Object finalPermissions = JDBCUtils.getInstance().uniqueResult(diffSql, new Object[] { merchantCode });
        if (!ObjectUtils.equals(ownPermissions, finalPermissions)) {
            /** ? Modifier by yang.mq **/
            MerchantOperationLog operationLog = new MerchantOperationLog();
            operationLog.setId(UUIDUtil.getUUID());
            operationLog.setMerchantCode(merchantCode);
            operationLog.setOperator(userName);
            operationLog.setOperated(new Date());
            operationLog.setOperationType(OperationType.API);
            operationLog.setOperationNotes(MessageFormat.format("API??{0}?{1}",
                    ownPermissions, finalPermissions));
            merchantOperationLogService.saveMerchantOperationLog(operationLog);
        }
    }

    return result;
}

From source file:ml.shifu.shifu.util.ModelSpecLoaderUtils.java

/**
 * Find the model files for some @ModelConfig. There is a little tricky about this function.
 * If @EvalConfig is specified, try to load the models according setting in @EvalConfig,
 * or if {@link EvalConfig} is null or modelsPath is blank, Shifu will try to load models under `models`
 * directory/* www . java 2 s  .  c  om*/
 *
 * @param modelConfig
 *            - {@link ModelConfig}, need this, since the model file may exist in HDFS
 * @param evalConfig
 *            - {@link EvalConfig}, maybe null
 * @param sourceType
 *            - Where is file system
 * @return - {@link FileStatus} array for all found models
 * @throws IOException
 *             io exception to load files
 */
public static List<FileStatus> findModels(ModelConfig modelConfig, EvalConfig evalConfig, SourceType sourceType)
        throws IOException {
    FileSystem fs = ShifuFileUtils.getFileSystemBySourceType(sourceType);
    PathFinder pathFinder = new PathFinder(modelConfig);

    // If the algorithm in ModelConfig is NN, we only load NN models
    // the same as SVM, LR
    String modelSuffix = "." + modelConfig.getAlgorithm().toLowerCase();

    List<FileStatus> fileList = new ArrayList<>();
    if (null == evalConfig || StringUtils.isBlank(evalConfig.getModelsPath())) {
        Path path = new Path(pathFinder.getModelsPath(sourceType));
        fileList.addAll(Arrays.asList(fs.listStatus(path, new FileSuffixPathFilter(modelSuffix))));
    } else {
        String modelsPath = evalConfig.getModelsPath();
        FileStatus[] expandedPaths = fs.globStatus(new Path(modelsPath));
        if (ArrayUtils.isNotEmpty(expandedPaths)) {
            for (FileStatus fileStatus : expandedPaths) {
                fileList.addAll(Arrays.asList(fs.listStatus(fileStatus.getPath(), // list all files
                        new FileSuffixPathFilter(modelSuffix))));
            }
        }
    }

    return fileList;
}

From source file:it.openprj.jValidator.utils.generic.CommonUtils.java

public static Object getClassInstance(String className, String implementedClassName, Class<?> implementedClass,
        String sourceCode) throws Exception {
    DynamicClassLoader dynacode = DynamicClassLoader.getInstance();
    Class<?> dynaClass = dynacode.getLoadedClass(className);
    File sourceDir = new File(System.getProperty("java.io.tmpdir"), "jValidator/src");
    boolean createFileInTemp = false;
    if (dynaClass == null) {
        createFileInTemp = true;/*from  w  ww .  java  2  s.  co m*/
    } else {
        boolean isExist = false;
        @SuppressWarnings("rawtypes")
        Class[] interfaces = dynaClass.getInterfaces();
        if (ArrayUtils.isNotEmpty(interfaces)) {
            for (Class<?> clz : interfaces) {
                if ((clz.getName().equalsIgnoreCase(implementedClassName))) {
                    isExist = true;
                }
            }
        }
        if (!isExist) {
            createFileInTemp = true;
        }
    }
    if (createFileInTemp) {
        boolean isCreated = CommonUtils.createFileIfNotExist(className, sourceCode, sourceDir);
        if (isCreated || dynaClass == null) {
            dynacode.addSourceDir(sourceDir);
            return dynacode.newProxyInstance(implementedClass, className);
        }
    }
    return dynaClass.newInstance();

}