Example usage for java.io File toURL

List of usage examples for java.io File toURL

Introduction

In this page you can find the example usage for java.io File toURL.

Prototype

@Deprecated
public URL toURL() throws MalformedURLException 

Source Link

Document

Converts this abstract pathname into a file: URL.

Usage

From source file:org.talend.designer.documentation.generation.HTMLDocGenerator.java

@Override
public void generateHTMLFile(ExportFileResource resource, String cssFile) {
    try {//w  ww  .  j a  va 2s.c  om

        // Store all pictures' path.
        List<URL> picList = new ArrayList<URL>(5);

        String jobName = resource.getItem().getProperty().getLabel();

        String jobVersion = resource.getItem().getProperty().getVersion();

        String tempFolderPath = checkTempDirIsExists(resource);

        handleXMLFile(resource, tempFolderPath);

        String picFolderPath = checkPicDirIsExists(resource, tempFolderPath);

        final Bundle b = Platform.getBundle(IHTMLDocConstants.REPOSITORY_PLUG_IN_ID);

        final URL xslFileUrl = FileLocator
                .toFileURL(FileLocator.find(b, new Path(IHTMLDocConstants.MAIN_XSL_FILE_PATH), null));
        // final URL logoFileUrl = FileLocator.toFileURL(FileLocator.find(b,
        // new Path(IHTMLDocConstants.LOGO_FILE_PATH), null));

        File logoFile = new File(picFolderPath + File.separatorChar + IHTMLDocConstants.TALEND_LOGO_FILE_NAME);
        saveLogoImage(SWT.IMAGE_JPEG, logoFile);

        String xslFilePath = xslFileUrl.getPath();
        // String logoFilePath = logoFileUrl.getPath();
        // FileCopyUtils.copy(logoFilePath, picFolderPath + File.separatorChar
        // + IHTMLDocConstants.TALEND_LOGO_FILE_NAME);

        // if import a css template, generate a new xsl file
        String temXslPath = null;
        File file = new File(xslFilePath);
        temXslPath = HTMLDocUtils.getTmpFolder() + File.separator + file.getName();
        generateXslFile(xslFilePath, temXslPath, cssFile, tempFolderPath);
        // if no new xls generated, use default xsl
        File temFile = new File(temXslPath);
        if (!temFile.exists()) {
            temXslPath = null;
        }
        if (temXslPath == null) {
            temXslPath = xslFilePath;
        }

        picList.add(logoFile.toURL());

        Set keySet = picFilePathMap.keySet();
        for (Object key : keySet) {
            String value = picFilePathMap.get(key);
            FileCopyUtils.copy(value, picFolderPath + File.separatorChar + key);
            picList.add(new File(picFolderPath + File.separatorChar + key).toURL());
        }

        byte[] innerContent = null;
        ProcessType processType = null;
        if (resource.getItem() instanceof ProcessItem) {
            processType = ((ProcessItem) resource.getItem()).getProcess();
            innerContent = (byte[]) processType.getScreenshots().get("process"); //$NON-NLS-1$
        } else if (resource.getItem() instanceof JobletProcessItem) {
            processType = ((JobletProcessItem) resource.getItem()).getJobletProcess();
            innerContent = (byte[]) processType.getScreenshots().get("process"); //$NON-NLS-1$
        }

        if (innerContent != null) {
            ImageDescriptor imagedesc = ImageUtils.createImageFromData(innerContent);
            String picName = jobName + "_" + jobVersion + IHTMLDocConstants.JOB_PREVIEW_PIC_SUFFIX; //$NON-NLS-1$
            ImageUtils.save(imagedesc.createImage(), picFolderPath + File.separatorChar + picName,
                    SWT.IMAGE_PNG);
            picList.add(new File(picFolderPath + File.separatorChar + picName).toURL());
        }
        for (NodeType node : (List<NodeType>) processType.getNode()) {
            String uniqueName = ""; //$NON-NLS-1$
            for (Object o : node.getElementParameter()) {
                if (o instanceof ElementParameterType) {
                    if ("UNIQUE_NAME".equals(((ElementParameterType) o).getName())) { //$NON-NLS-1$
                        uniqueName = ((ElementParameterType) o).getValue();
                        break;
                    }
                }
            }
            byte[] screenshot = (byte[]) processType.getScreenshots().get(uniqueName);
            if (screenshot != null && screenshot.length != 0) {
                ImageDescriptor imagedesc = ImageUtils.createImageFromData(screenshot);
                String picName = IHTMLDocConstants.EXTERNAL_NODE_PREVIEW + uniqueName
                        + IHTMLDocConstants.JOB_PREVIEW_PIC_SUFFIX;
                ImageUtils.save(imagedesc.createImage(), picFolderPath + File.separatorChar + picName,
                        SWT.IMAGE_PNG);
                picList.add(new File(picFolderPath + File.separatorChar + picName).toURL());
            }
        }

        List<URL> resultFiles = parseXML2HTML(tempFolderPath, jobName + "_" + jobVersion, temXslPath); //$NON-NLS-1$

        addResources(resource, resultFiles);

        resource.addResources(IHTMLDocConstants.PIC_FOLDER_NAME, picList);

        // List<URL> externalList = getExternalHtmlPath();
        // resource.addResources(IHTMLDocConstants.EXTERNAL_FOLDER_NAME, externalList);

    } catch (Exception e) {
        e.printStackTrace();
        ExceptionHandler.process(e);

    }

    targetConnectionMap = null;
    sourceConnectionMap = null;
}

From source file:com.neusou.bioroid.image.ImageLoader.java

public Bitmap loadImage(final String imageUri, boolean immediately) {
    if (imageUri == null || imageUri.equals("null")) {
        return null;
    }// www. ja  va 2 s  .  co m

    final String url;
    url = imageUri;

    if (url == null || url.compareTo("null") == 0) {
        return null;
    }

    Bitmap dcached;
    dcached = mBitmapMap.get(url);

    if (dcached != null || immediately) {
        if (dcached == null) {
            mBitmapMap.remove(url);
        }
        return dcached;
    }

    URL imageUrl = null;

    try {
        imageUrl = new URL(imageUri);
    } catch (MalformedURLException e) {
        return null;
    }

    File imageDir = new File(mCacheDirectoryPath);
    String bigInt = computeDigest(url);
    File cachedImageFile = new File(imageDir, bigInt);
    String ess = Environment.getExternalStorageState();
    boolean canReadImageCacheDir = false;

    if (ess.equals(Environment.MEDIA_MOUNTED)) {
        if (!imageDir.canRead()) {
            boolean createSuccess = false;
            synchronized (imageDir) {
                createSuccess = imageDir.mkdirs();
            }
            canReadImageCacheDir = createSuccess && imageDir.canRead();
        }
        canReadImageCacheDir = imageDir.canRead();
        if (cachedImageFile.canRead()) {
            try {
                Bitmap cachedBitmap = getCachedBitmap(imageUrl, cachedImageFile);
                if (cachedBitmap != null) {
                    mBitmapMap.put(imageUri, cachedBitmap);
                    return cachedBitmap;
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    HttpGet httpRequest = null;
    try {
        httpRequest = new HttpGet(imageUrl.toURI());
    } catch (URISyntaxException e) {
        e.printStackTrace();
        return null;
    }

    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = null;
    try {
        response = (HttpResponse) httpclient.execute(httpRequest);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    HttpEntity entity = response.getEntity();
    BufferedHttpEntity bufHttpEntity = null;
    try {
        bufHttpEntity = new BufferedHttpEntity(entity);
        final int bufferSize = 1024 * 50;
        BufferedInputStream imageBis = new BufferedInputStream(bufHttpEntity.getContent(), bufferSize);
        long contentLength = bufHttpEntity.getContentLength();
        Bitmap decodedBitmap = decode(imageBis);
        try {
            imageBis.close();
        } catch (IOException e1) {
        }
        encode(decodedBitmap, cachedImageFile.toURL(), CompressFormat.PNG, mImageCacheQuality);
        Calendar cal = Calendar.getInstance();
        long currentTime = cal.getTime().getTime();
        if (mUseCacheDatabase) {
            mCacheRecordDbHelper.insertCacheRecord(mDb, cachedImageFile.toURL(), currentTime, contentLength);
        }
        if (decodedBitmap != null) {
            mBitmapMap.put(url, decodedBitmap);
        }
        return decodedBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.talend.core.model.metadata.designerproperties.RepositoryToComponentProperty.java

private static Object getDatabaseValue(DatabaseConnection connection, String value, IMetadataTable table,
        String targetComponent) {

    String databaseType = connection.getDatabaseType();
    if (value.equals("TYPE")) { //$NON-NLS-1$
        String typeByProduct = getStandardDbTypeFromConnection(databaseType);
        // See bug 4565
        if (databaseType.equals(EDatabaseTypeName.ORACLEFORSID.getDisplayName())) {
            // see StatsAndLogConstants
            // This connection is Oracle_SID
            return EDatabaseTypeName.ORACLEFORSID.getXmlName();
        } else if (databaseType.equals(EDatabaseTypeName.ORACLESN.getDisplayName())) {
            // This connection is Oracle_service_name
            return EDatabaseTypeName.ORACLESN.getXmlName();
        } else if (databaseType.equals(EDatabaseTypeName.ORACLE_OCI.getDisplayName())) {
            return EDatabaseTypeName.ORACLE_OCI.getXmlName();
        } else if (databaseType.equals(EDatabaseTypeName.ORACLE_CUSTOM.getDisplayName())) {
            return EDatabaseTypeName.ORACLE_CUSTOM.getXmlName();
        } else if (databaseType.equals(EDatabaseTypeName.MSSQL.getDisplayName())) {
            return EDatabaseTypeName.MSSQL.getXMLType(); // for component
        }//from w  ww.  j ava2s  .com

        else {
            return typeByProduct;
        }
    }
    if (value.equals("FRAMEWORK_TYPE")) { //$NON-NLS-1$
        if (isContextMode(connection, databaseType)) {
            if (databaseType.equals("JavaDB Embeded")) { //$NON-NLS-1$
                return "EMBEDED"; //$NON-NLS-1$
            }
            if (databaseType.equals("JavaDB JCCJDBC")) { //$NON-NLS-1$
                return "JCCJDBC"; //$NON-NLS-1$
            }
            if (databaseType.equals("JavaDB DerbyClient")) { //$NON-NLS-1$
                return "DERBYCLIENT"; //$NON-NLS-1$
            }
        } else {
            if (databaseType.equals("JavaDB Embeded")) { //$NON-NLS-1$
                return "EMBEDED"; //$NON-NLS-1$
            }
            if (databaseType.equals("JavaDB JCCJDBC")) { //$NON-NLS-1$
                return "JCCJDBC"; //$NON-NLS-1$
            }
            if (databaseType.equals("JavaDB DerbyClient")) { //$NON-NLS-1$
                return "DERBYCLIENT"; //$NON-NLS-1$
            }
        }
    }
    if (value.equals("SERVER_NAME")) { //$NON-NLS-1$
        if (isContextMode(connection, connection.getServerName())) {
            return connection.getServerName();
        } else {
            return TalendQuoteUtils.addQuotes(connection.getServerName());
        }
    }
    if (value.equals("PORT")) { //$NON-NLS-1$
        if (isContextMode(connection, connection.getPort())) {
            return connection.getPort();
        } else {
            return TalendQuoteUtils.addQuotes(connection.getPort());
        }
    }
    if (value.equals("SID") || value.equals("DATABASE_ALIAS")) { //$NON-NLS-1$ //$NON-NLS-2$
        if (("").equals(connection.getSID()) || connection.getSID() == null) { //$NON-NLS-1$
            if (isContextMode(connection, connection.getDatasourceName())) {
                return connection.getDatasourceName();
            } else {
                return TalendQuoteUtils.addQuotes(connection.getDatasourceName());
            }
        } else {
            if (isContextMode(connection, connection.getSID())) {
                return connection.getSID();
            } else {
                return TalendQuoteUtils.addQuotes(connection.getSID());
            }
        }
    }
    if (value.equals("DATASOURCE")) { //$NON-NLS-1$
        if (isContextMode(connection, connection.getDatasourceName())) {
            return connection.getDatasourceName();
        } else {
            return TalendQuoteUtils.addQuotes(connection.getDatasourceName());
        }
    }
    if (value.equals("USERNAME")) { //$NON-NLS-1$
        if (isContextMode(connection, connection.getUsername())) {
            return connection.getUsername();
        } else {
            return TalendQuoteUtils.addQuotes(connection.getUsername());
        }
    }
    if (value.equals("PASSWORD")) { //$NON-NLS-1$
        if (isContextMode(connection, connection.getPassword())) {
            return connection.getPassword();
        } else {
            String pwd = TalendQuoteUtils.checkAndAddBackslashes(connection.getRawPassword());
            return TalendQuoteUtils.addQuotes(pwd);
        }
    }
    if (value.equals("NULL_CHAR")) { //$NON-NLS-1$
        if (isContextMode(connection, connection.getNullChar())) {
            return connection.getNullChar();
        } else {
            return TalendQuoteUtils.addQuotes(connection.getNullChar());
        }
    }
    if (value.equals("SCHEMA")) { //$NON-NLS-1$
        if (isContextMode(connection, connection.getUiSchema())) {
            return connection.getUiSchema();
        } else {
            return TalendQuoteUtils.addQuotes(connection.getUiSchema());
        }
    }
    if (value.equals("FILE")) { //$NON-NLS-1$
        if (isContextMode(connection, connection.getFileFieldName())) {
            return connection.getFileFieldName();
        } else {
            return TalendQuoteUtils.addQuotes(connection.getFileFieldName());
        }
    }
    if (value.equals("PROPERTIES_STRING")) { //$NON-NLS-1$
        if (isContextMode(connection, connection.getAdditionalParams())) {
            return connection.getAdditionalParams();
        } else {
            return TalendQuoteUtils.addQuotes(connection.getAdditionalParams());
        }
    }

    if (value.equals("CDC_MODE")) { //$NON-NLS-1$
        if (isContextMode(connection, connection.getCdcTypeMode())) {
            return connection.getCdcTypeMode();
        } else {
            return connection.getCdcTypeMode();
        }
    }

    if (value.equals("DB_VERSION")) { //$NON-NLS-1$
        String dbVersionString = connection.getDbVersionString();
        if (EDatabaseConnTemplate.ACCESS.getDBDisplayName().equals(databaseType)) {
            // @Deprecated: see bug 7262 this bug is Deprecated
            return dbVersionString;
        } else if (EDatabaseConnTemplate.MYSQL.getDBDisplayName().equals(databaseType)) {
            if (dbVersionString != null) {
                return dbVersionString.toUpperCase();
            }
        } else if (EDatabaseTypeName.HIVE.getDisplayName().equals(databaseType)) {
            return connection.getParameters().get(ConnParameterKeys.CONN_PARA_KEY_HIVE_VERSION);
        } else if (EDatabaseTypeName.HBASE.getDisplayName().equals(databaseType)) {
            return connection.getParameters().get(ConnParameterKeys.CONN_PARA_KEY_HBASE_VERSION);
        } else {
            String driverValue = EDatabaseVersion4Drivers.getDriversStr(databaseType, dbVersionString);
            if (EDatabaseConnTemplate.ORACLE_OCI.getDBDisplayName().equals(databaseType)
                    || EDatabaseConnTemplate.ORACLE_CUSTOM.getDBDisplayName().equals(databaseType)
                    || EDatabaseConnTemplate.ORACLEFORSID.getDBDisplayName().equals(databaseType)
                    || EDatabaseConnTemplate.ORACLESN.getDBDisplayName().equals(databaseType)
                    || EDatabaseConnTemplate.PLUSPSQL.getDBDisplayName().equals(databaseType)
                    || EDatabaseConnTemplate.PSQL.getDBDisplayName().equals(databaseType)
                    || EDatabaseConnTemplate.SAPHana.getDBDisplayName().equals(databaseType)) {
                if (dbVersionString != null) {
                    driverValue = dbVersionString.toUpperCase();
                }
            }
            if (isContextMode(connection, dbVersionString)) {
                return dbVersionString;
            } else if (EDatabaseTypeName.VERTICA.getXmlName().equals(databaseType)) {
                EDatabaseVersion4Drivers indexOfByVersionDisplay = EDatabaseVersion4Drivers
                        .indexOfByVersion(dbVersionString);
                if (indexOfByVersionDisplay != null) {
                    return indexOfByVersionDisplay.getVersionValue();
                }
            } else {
                return driverValue;
            }
        }
    }

    if (value.equals("CONNECTION_TYPE")) { //$NON-NLS-1$
        if (isContextMode(connection, databaseType)) {
            if (databaseType.equals(EDatabaseTypeName.ORACLEFORSID.getDisplayName())) {
                return "ORACLE_SID";
            } else if (databaseType.equals(EDatabaseTypeName.ORACLESN.getDisplayName())) {
                return "ORACLE_SERVICE_NAME";
            } else if (databaseType.equals(EDatabaseTypeName.ORACLE_OCI.getDisplayName())) {
                return "ORACLE_OCI";
            } else if (databaseType.equals(EDatabaseTypeName.ORACLE_CUSTOM.getDisplayName())) {
                return "ORACLE_RAC";
            }
        } else {
            if (databaseType.equals(EDatabaseTypeName.ORACLEFORSID.getDisplayName())) {
                return "ORACLE_SID";
            } else if (databaseType.equals(EDatabaseTypeName.ORACLESN.getDisplayName())) {
                return "ORACLE_SERVICE_NAME";
            } else if (databaseType.equals(EDatabaseTypeName.ORACLE_OCI.getDisplayName())) {
                return "ORACLE_OCI";
            } else if (databaseType.equals(EDatabaseTypeName.ORACLE_CUSTOM.getDisplayName())) {
                return "ORACLE_RAC";
            }
        }
    }

    // add new class name property
    if (value.equals("DRIVER_CLASS")) { //$NON-NLS-1$
        if (isContextMode(connection, connection.getDriverClass())) {
            return connection.getDriverClass();
        } else {
            return TalendQuoteUtils.addQuotes(connection.getDriverClass());
        }
    }

    if (value.equals("URL")) { //$NON-NLS-1$
        String url = connection.getURL();
        if (isContextMode(connection, url)) {
            return url;
        } else {
            // TDI-18737:in case the url maybe null
            if (url != null) {
                String h2Prefix = "jdbc:h2:"; //$NON-NLS-1$
                if (url.startsWith(h2Prefix)) {
                    String path = url.substring(h2Prefix.length(), url.length());
                    // TDI-23861: handle the server mode of H2 which url has more than one colon.
                    if (path.split(":").length > 2) { //$NON-NLS-1$
                        int startIndex = path.lastIndexOf(":") - 1; //$NON-NLS-1$
                        String filePath = path.substring(startIndex);
                        h2Prefix += path.substring(0, startIndex);
                        path = filePath;
                    }
                    path = PathUtils.getPortablePath(path);
                    url = h2Prefix + path;
                }
                return TalendQuoteUtils.addQuotes(url);
            }
        }
    }

    // if (value.equals("DRIVER_PATH")) {
    // if (isContextMode(connection, connection.getDriverJarPath())) {
    // return connection.getDriverJarPath();
    // } else {
    // return TalendQuoteUtils.addQuotes(connection.getDriverJarPath());
    // }
    // }

    if (value.equals("DRIVER_JAR")) { //$NON-NLS-1$
        List<Map<String, Object>> value2 = new ArrayList<Map<String, Object>>();
        if (isContextMode(connection, connection.getDriverJarPath())) {
            Map<String, Object> line = new HashMap<String, Object>();
            line.put("JAR_NAME", connection.getDriverJarPath());
            value2.add(line);
        } else {
            String userDir = System.getProperty("user.dir"); //$NON-NLS-1$
            String pathSeparator = System.getProperty("file.separator"); //$NON-NLS-1$
            String defaultPath = userDir + pathSeparator + "lib" + pathSeparator + "java"; //$NON-NLS-1$ //$NON-NLS-2$
            String jarPath = connection.getDriverJarPath();

            if (jarPath == null) {
                return null;
            }

            try {
                Character comma = ';';
                String[] jars = jarPath.split(comma.toString());
                boolean deployed = false;
                if (jars != null) {
                    for (String jar : jars) {
                        File file = Path.fromOSString(jar).toFile();
                        if (file.exists() && file.isFile()) {
                            String fileName = file.getName();
                            Map<String, Object> line = new HashMap<String, Object>();
                            line.put("JAR_NAME", fileName);
                            value2.add(line);
                            if (!new File(defaultPath + pathSeparator + fileName).exists()) {
                                // deploy this library
                                try {
                                    CoreRuntimePlugin.getInstance().getLibrariesService()
                                            .deployLibrary(file.toURL());
                                    deployed = true;
                                } catch (IOException e) {
                                    ExceptionHandler.process(e);
                                    return null;
                                }
                            }
                        } else {
                            Map<String, Object> line = new HashMap<String, Object>();
                            line.put("JAR_NAME", jar);
                            value2.add(line);
                        }
                    }
                    if (deployed) {
                        CoreRuntimePlugin.getInstance().getLibrariesService().resetModulesNeeded();
                    }
                }

            } catch (Exception e) {
                return null;
            }
        }
        return value2;

    }
    if (value.equals("CDC_TYPE_MODE")) { //$NON-NLS-1$
        return new Boolean(CDCTypeMode.LOG_MODE.getName().equals(connection.getCdcTypeMode()));
    }
    // add this for tJavaDB embeded "DB Root Path"
    if (value.equals("DIRECTORY")) {//$NON-NLS-1$
        if (isContextMode(connection, connection.getDBRootPath())) {
            return connection.getDBRootPath();
        } else {
            return TalendQuoteUtils.addQuotes(connection.getDBRootPath());
        }

    }
    // add for feature 11674
    if (value.equals("RUNNING_MODE")) {//$NON-NLS-1$       
        String runningMode = "HSQLDB_IN_MEMORY";//$NON-NLS-1$   
        if (EDatabaseTypeName.HSQLDB_IN_PROGRESS.getXmlName().equals(databaseType)) {
            runningMode = "HSQLDB_INPROGRESS_PERSISTENT";//$NON-NLS-1$   
        } else if (EDatabaseTypeName.HSQLDB_SERVER.getXmlName().equals(databaseType)) {
            runningMode = "HSQLDB_SERVER";//$NON-NLS-1$   
        } else if (EDatabaseTypeName.HSQLDB_WEBSERVER.getXmlName().equals(databaseType)) {
            runningMode = "HSQLDB_WEBSERVER";//$NON-NLS-1$   
        }
        return runningMode;
    }
    if (value.equals("DBPATH")) {//$NON-NLS-1$
        if (isContextMode(connection, connection.getDBRootPath())) {
            return connection.getDBRootPath();
        } else {
            return TalendQuoteUtils.addQuotes(connection.getDBRootPath());
        }
    }
    if (value.equals("DBNAME")) {//$NON-NLS-1$
        if (isContextMode(connection, connection.getDatasourceName())) {
            return connection.getDatasourceName();
        } else {
            return TalendQuoteUtils.addQuotes(connection.getDatasourceName());
        }
    }
    if (value.equals("RAC_URL")) {
        if (isContextMode(connection, connection.getServerName())) {
            return connection.getServerName();
        } else {
            return TalendQuoteUtils.addQuotes(connection.getServerName());
        }
    }

    if (value.equals("DISTRIBUTION")) {
        if ((databaseType).equals(EDatabaseTypeName.HBASE.getDisplayName())) {
            return connection.getParameters().get(ConnParameterKeys.CONN_PARA_KEY_HBASE_DISTRIBUTION);
        } else {
            return connection.getParameters().get(ConnParameterKeys.CONN_PARA_KEY_HIVE_DISTRIBUTION);
        }
    }

    if (value.equals("HIVE_VERSION")) {
        return connection.getParameters().get(ConnParameterKeys.CONN_PARA_KEY_HIVE_VERSION);
    }

    if (value.equals("CONNECTION_MODE")) {
        return connection.getParameters().get(ConnParameterKeys.CONN_PARA_KEY_HIVE_MODE);
    }

    if (value.equals("HBASE_DISTRIBUTION")) {
        return connection.getParameters().get(ConnParameterKeys.CONN_PARA_KEY_HBASE_DISTRIBUTION);
    }

    if (value.equals("HBASE_VERSION")) {
        return connection.getParameters().get(ConnParameterKeys.CONN_PARA_KEY_HBASE_VERSION);
    }

    if (value.equals("HIVE_SERVER")) {
        return connection.getParameters().get(ConnParameterKeys.HIVE_SERVER_VERSION);
    }

    if (value.equals("HBASE_PARAMETERS")) {
        String message = connection.getParameters().get(ConnParameterKeys.CONN_PARA_KEY_HBASE_PROPERTIES);
        return HadoopRepositoryUtil.getHadoopPropertiesFullList(connection, message, true);
    }

    if (value.equals("HADOOP_ADVANCED_PROPERTIES")) {
        String message = null;
        if (EDatabaseTypeName.HIVE.getDisplayName().equals(databaseType)) {
            message = connection.getParameters().get(ConnParameterKeys.CONN_PARA_KEY_HIVE_PROPERTIES);
        } else if (EDatabaseTypeName.HBASE.getDisplayName().equals(databaseType)) {
            message = connection.getParameters().get(ConnParameterKeys.CONN_PARA_KEY_HBASE_PROPERTIES);
        }
        return HadoopRepositoryUtil.getHadoopPropertiesFullList(connection, message, true);
    }

    if (value.equals("ADVANCED_PROPERTIES") && EDatabaseTypeName.HIVE.getDisplayName().equals(databaseType)) {
        String message = connection.getParameters().get(ConnParameterKeys.CONN_PARA_KEY_HIVE_JDBC_PROPERTIES);
        return HadoopRepositoryUtil.getHadoopPropertiesList(message, true);
    }

    if (value.equals("HADOOP_CUSTOM_JARS")) {
        if (targetComponent != null && targetComponent.startsWith("tPig")) {
            // for pig component
            String clusterID = connection.getParameters()
                    .get(ConnParameterKeys.CONN_PARA_KEY_HADOOP_CLUSTER_ID);
            if (clusterID != null) {
                if (GlobalServiceRegister.getDefault().isServiceRegistered(IHadoopClusterService.class)) {
                    IHadoopClusterService hadoopClusterService = (IHadoopClusterService) GlobalServiceRegister
                            .getDefault().getService(IHadoopClusterService.class);
                    Map<String, String> hadoopCustomLibraries = hadoopClusterService
                            .getHadoopCustomLibraries(clusterID);

                    if (EDatabaseTypeName.HBASE.getDisplayName().equals(connection.getDatabaseType())) {
                        return hadoopCustomLibraries.get(ECustomVersionGroup.PIG_HBASE.getName()) == null ? ""
                                : hadoopCustomLibraries.get(ECustomVersionGroup.PIG_HBASE.getName());
                    }
                }
            }
        }
        return connection.getParameters().get(ConnParameterKeys.CONN_PARA_KEY_HADOOP_CUSTOM_JARS);
    }

    if (value.equals(EParameterNameForComponent.PARA_NAME_FS_DEFAULT_NAME.getName())) {
        String nameNodeURL = connection.getParameters().get(ConnParameterKeys.CONN_PARA_KEY_NAME_NODE_URL);
        if (nameNodeURL == null && (databaseType).equals(EDatabaseTypeName.HBASE.getDisplayName())) {
            return nameNodeURL;
        } else if (isContextMode(connection, nameNodeURL)) {
            return nameNodeURL;
        } else {
            return TalendQuoteUtils.addQuotes(nameNodeURL);
        }
    }

    if (value.equals(EParameterNameForComponent.PARA_NAME_MAPRED_JT.getName())
            || value.equals(EParameterNameForComponent.PARA_NAME_RESOURCE_MANAGER.getName())) {
        String jobTrackerURL = connection.getParameters().get(ConnParameterKeys.CONN_PARA_KEY_JOB_TRACKER_URL);
        if (isContextMode(connection, jobTrackerURL)) {
            return jobTrackerURL;
        } else {
            return TalendQuoteUtils.addQuotes(jobTrackerURL);
        }
    }

    if (value.equals(EParameterNameForComponent.PARA_NAME_USE_YARN.getName())) {
        String useYarn = connection.getParameters().get(ConnParameterKeys.CONN_PARA_KEY_USE_YARN);
        if (isContextMode(connection, useYarn)) {
            return useYarn;
        } else {
            return Boolean.valueOf(useYarn);
        }
    }

    if (value.equals("LOCAL")) {
        return false;
    }

    if (value.equals("MAPREDUCE")) {
        return true;
    }

    if (value.equals("LOAD") || value.equals("STORE")) {
        return "HBaseStorage";
    }

    if (value.equals("PIG_VERSION")) {
        return connection.getParameters().get(ConnParameterKeys.CONN_PARA_KEY_HBASE_VERSION);
    }

    if (value.equals("USE_KRB")) {
        String useKrbValue = connection.getParameters().get(ConnParameterKeys.CONN_PARA_KEY_USE_KRB);
        if (useKrbValue == null) {
            return useKrbValue;
        } else {
            return Boolean.parseBoolean(useKrbValue);
        }
    }

    if (value.equals("MAPRED_JOB_TRACKER") || value.equals("MAPRED_RESOURCE_MANAGER")) {
        String mapredJobTracker = connection.getParameters()
                .get(ConnParameterKeys.CONN_PARA_KEY_JOB_TRACKER_URL);
        if (mapredJobTracker == null) {
            return mapredJobTracker;
        } else {
            return TalendQuoteUtils.addQuotesIfNotExist(StringUtils.trimToNull(mapredJobTracker));
        }
    }

    if (value.equals("NAMENODE_PRINCIPAL")) {
        String nameNodePrincipal = connection.getParameters()
                .get(ConnParameterKeys.CONN_PARA_KEY_NAME_NODE_PRINCIPAL);
        if (nameNodePrincipal == null) {
            return nameNodePrincipal;
        } else {
            return TalendQuoteUtils.addQuotesIfNotExist(StringUtils.trimToNull(nameNodePrincipal));
        }
    }

    if (value.equals("JOBTRACKER_PRINCIPAL")) {
        String jobTrackerPrincipal = connection.getParameters()
                .get(ConnParameterKeys.CONN_PARA_KEY_JOB_TRACKER_PRINCIPAL);
        if (jobTrackerPrincipal == null) {
            return jobTrackerPrincipal;
        } else {
            return TalendQuoteUtils.addQuotesIfNotExist(StringUtils.trimToNull(jobTrackerPrincipal));
        }
    }

    if (value.equals("ZOOKEEPER_QUORUM")) {
        if (isContextMode(connection, connection.getServerName())) {
            return connection.getServerName();
        } else {
            return TalendQuoteUtils.addQuotes(connection.getServerName());
        }
    }

    if (value.equals("ZOOKEEPER_CLIENT_PORT")) {
        if (isContextMode(connection, connection.getPort())) {
            return connection.getPort();
        } else {
            return TalendQuoteUtils.addQuotes(connection.getPort());
        }
    }

    if (value.equals("COLUMN_MAPPING")) { //$NON-NLS-1$
        return getColumnMappingValue(connection, table);
    }

    if (value.equals("HIVE_PRINCIPAL")) {
        return TalendQuoteUtils
                .addQuotes(connection.getParameters().get(ConnParameterKeys.HIVE_AUTHENTICATION_HIVEPRINCIPLA));
    }

    if (value.equals("METASTORE_JDBC_URL")) {
        return TalendQuoteUtils
                .addQuotes(connection.getParameters().get(ConnParameterKeys.HIVE_AUTHENTICATION_METASTOREURL));
    }

    if (value.equals("METASTORE_CLASSNAME")) {
        return TalendQuoteUtils
                .addQuotes(connection.getParameters().get(ConnParameterKeys.HIVE_AUTHENTICATION_DRIVERCLASS));
    }

    if (value.equals("METASTORE_USERNAME")) {
        return TalendQuoteUtils
                .addQuotes(connection.getParameters().get(ConnParameterKeys.HIVE_AUTHENTICATION_USERNAME));
    }

    if (value.equals("METASTORE_PASSWORD")) {
        return TalendQuoteUtils
                .addQuotes(connection.getParameters().get(ConnParameterKeys.HIVE_AUTHENTICATION_PASSWORD));
    }

    if (value.equals("USE_KEYTAB")) {
        String USE_KEYTAB = connection.getParameters().get(ConnParameterKeys.HIVE_AUTHENTICATION_USEKEYTAB);
        if (USE_KEYTAB != null && USE_KEYTAB.equals("true")) {
            return Boolean.TRUE;
        } else {
            return Boolean.FALSE;
        }
    }

    if (value.equals("PRINCIPAL")) {
        return TalendQuoteUtils
                .addQuotes(connection.getParameters().get(ConnParameterKeys.HIVE_AUTHENTICATION_PRINCIPLA));
    }

    if (value.equals("KEYTAB_PATH")) {
        return TalendQuoteUtils
                .addQuotes(connection.getParameters().get(ConnParameterKeys.HIVE_AUTHENTICATION_KEYTAB));
    }

    if (value.equals("IMPALA_PRINCIPAL")) {
        return TalendQuoteUtils
                .addQuotes(connection.getParameters().get(ConnParameterKeys.IMPALA_AUTHENTICATION_PRINCIPLA));
    }

    return null;

}

From source file:org.apache.maven.archetype.old.DefaultOldArchetype.java

public void createArchetype(ArchetypeGenerationRequest request, File archetypeFile)
        throws ArchetypeDescriptorException, ArchetypeTemplateProcessingException {
    Map<String, String> parameters = new HashMap<String, String>();

    parameters.put("basedir", request.getOutputDirectory());

    parameters.put(Constants.PACKAGE, request.getPackage());

    parameters.put("packageName", request.getPackage());

    parameters.put(Constants.GROUP_ID, request.getGroupId());

    parameters.put(Constants.ARTIFACT_ID, request.getArtifactId());

    parameters.put(Constants.VERSION, request.getVersion());

    // ---------------------------------------------------------------------
    // Get Logger and display all parameters used
    // ---------------------------------------------------------------------
    if (getLogger().isInfoEnabled()) {
        getLogger().info("----------------------------------------------------------------------------");

        getLogger().info("Using following parameters for creating project from Old (1.x) Archetype: "
                + request.getArchetypeArtifactId() + ":" + request.getArchetypeVersion());

        getLogger().info("----------------------------------------------------------------------------");

        for (Map.Entry<String, String> entry : parameters.entrySet()) {
            String parameterName = entry.getKey();

            String parameterValue = entry.getValue();

            getLogger().info("Parameter: " + parameterName + ", Value: " + parameterValue);
        }//from  ww w.j ava  2  s  . c  o  m
    }

    // ----------------------------------------------------------------------
    // Load the descriptor
    // ----------------------------------------------------------------------

    ArchetypeDescriptorBuilder builder = new ArchetypeDescriptorBuilder();

    ArchetypeDescriptor descriptor;

    URLClassLoader archetypeJarLoader;

    InputStream is = null;

    try {
        URL[] urls = new URL[1];

        urls[0] = archetypeFile.toURL();

        archetypeJarLoader = new URLClassLoader(urls);

        is = getStream(ARCHETYPE_DESCRIPTOR, archetypeJarLoader);

        if (is == null) {
            is = getStream(ARCHETYPE_OLD_DESCRIPTOR, archetypeJarLoader);
        }

        if (is == null) {
            throw new ArchetypeDescriptorException(
                    "The " + ARCHETYPE_DESCRIPTOR + " descriptor cannot be found.");
        }

        descriptor = builder.build(new XmlStreamReader(is));
    } catch (IOException e) {
        throw new ArchetypeDescriptorException("Error reading the " + ARCHETYPE_DESCRIPTOR + " descriptor.", e);
    } catch (XmlPullParserException e) {
        throw new ArchetypeDescriptorException("Error reading the " + ARCHETYPE_DESCRIPTOR + " descriptor.", e);
    } finally {
        IOUtil.close(is);
    }

    // ----------------------------------------------------------------------
    //
    // ----------------------------------------------------------------------

    String artifactId = request.getArtifactId();

    File parentPomFile = new File(request.getOutputDirectory(), ARCHETYPE_POM);

    File outputDirectoryFile;

    boolean creating;
    File pomFile;
    if (parentPomFile.exists() && descriptor.isAllowPartial() && artifactId == null) {
        outputDirectoryFile = new File(request.getOutputDirectory());
        creating = false;
        pomFile = parentPomFile;
    } else {
        if (artifactId == null) {
            throw new ArchetypeTemplateProcessingException(
                    "Artifact ID must be specified when creating a new project from an archetype.");
        }

        outputDirectoryFile = new File(request.getOutputDirectory(), artifactId);
        creating = true;

        if (outputDirectoryFile.exists()) {
            if (descriptor.isAllowPartial()) {
                creating = false;
            } else {
                throw new ArchetypeTemplateProcessingException("Directory " + outputDirectoryFile.getName()
                        + " already exists - please run from a clean directory");
            }
        }

        pomFile = new File(outputDirectoryFile, ARCHETYPE_POM);
    }

    if (creating) {
        if (request.getGroupId() == null) {
            throw new ArchetypeTemplateProcessingException(
                    "Group ID must be specified when creating a new project from an archetype.");
        }

        if (request.getVersion() == null) {
            throw new ArchetypeTemplateProcessingException(
                    "Version must be specified when creating a new project from an archetype.");
        }
    }

    String outputDirectory = outputDirectoryFile.getAbsolutePath();

    String packageName = request.getPackage();

    // ----------------------------------------------------------------------
    // Set up the Velocity context
    // ----------------------------------------------------------------------

    Context context = new VelocityContext();

    context.put(Constants.PACKAGE, packageName);

    for (Map.Entry<String, String> entry : parameters.entrySet()) {
        context.put(entry.getKey(), entry.getValue());
    }

    // ----------------------------------------------------------------------
    // Process the templates
    // ----------------------------------------------------------------------

    ClassLoader old = Thread.currentThread().getContextClassLoader();

    Thread.currentThread().setContextClassLoader(archetypeJarLoader);

    Model parentModel = null;
    if (creating) {
        if (parentPomFile.exists()) {
            Reader fileReader = null;

            try {
                fileReader = ReaderFactory.newXmlReader(parentPomFile);
                MavenXpp3Reader reader = new MavenXpp3Reader();
                parentModel = reader.read(fileReader);
                if (!"pom".equals(parentModel.getPackaging())) {
                    throw new ArchetypeTemplateProcessingException(
                            "Unable to add module to the current project as it is not of packaging type 'pom'");
                }
            } catch (IOException e) {
                throw new ArchetypeTemplateProcessingException("Unable to read parent POM", e);
            } catch (XmlPullParserException e) {
                throw new ArchetypeTemplateProcessingException("Unable to read parent POM", e);
            } finally {
                IOUtil.close(fileReader);
            }

            parentModel.getModules().add(artifactId);
        }
    }

    try {
        processTemplates(pomFile, outputDirectory, context, descriptor, packageName, parentModel);
    } finally {
        Thread.currentThread().setContextClassLoader(old);
    }

    if (parentModel != null) {
        /*
                // TODO: would be nice to just write out with the xpp3 writer again, except that it loses a bunch of info and
                // reformats, so the module is just baked in as a string instead.
                    FileWriter fileWriter = null;
                
                    try
                    {
        fileWriter = new FileWriter( parentPomFile );
                
        MavenXpp3Writer writer = new MavenXpp3Writer();
        writer.write( fileWriter, parentModel );
                    }
                    catch ( IOException e )
                    {
        throw new ArchetypeTemplateProcessingException( "Unable to rewrite parent POM", e );
                    }
                    finally
                    {
        IOUtil.close( fileWriter );
                    }
        */
        Reader fileReader = null;
        boolean added;
        StringWriter w = new StringWriter();
        try {
            fileReader = ReaderFactory.newXmlReader(parentPomFile);
            added = addModuleToParentPom(artifactId, fileReader, w);
        } catch (IOException e) {
            throw new ArchetypeTemplateProcessingException("Unable to rewrite parent POM", e);
        } catch (DocumentException e) {
            throw new ArchetypeTemplateProcessingException("Unable to rewrite parent POM", e);
        } finally {
            IOUtil.close(fileReader);
        }

        if (added) {
            Writer out = null;
            try {
                out = WriterFactory.newXmlWriter(parentPomFile);
                IOUtil.copy(w.toString(), out);
            } catch (IOException e) {
                throw new ArchetypeTemplateProcessingException("Unable to rewrite parent POM", e);
            } finally {
                IOUtil.close(out);
            }
        }
    }

    // ----------------------------------------------------------------------
    // Log message on OldArchetype creation
    // ----------------------------------------------------------------------
    if (getLogger().isInfoEnabled()) {
        getLogger().info("project created from Old (1.x) Archetype in dir: " + outputDirectory);
    }

}

From source file:io.hops.hopsworks.common.util.Settings.java

private void addPathToConfig(Configuration conf, File path) {
    // chain-in a new classloader
    URL fileUrl = null;/*from   w w w . j  a  v  a 2 s .c o m*/
    try {
        fileUrl = path.toURL();
    } catch (MalformedURLException e) {
        throw new RuntimeException("Erroneous config file path", e);
    }
    URL[] urls = { fileUrl };
    ClassLoader cl = new URLClassLoader(urls, conf.getClassLoader());
    conf.setClassLoader(cl);
}

From source file:org.talend.designer.documentation.generation.HTMLDocGenerator.java

@Override
public void generateDocumentation(ExportFileResource resource, String targetPath, String... jobVersion)
        throws Exception {
    // Store all pictures' path.
    List<URL> picList = new ArrayList<URL>(5);

    String jobName = resource.getItem().getProperty().getLabel();

    String jobPath = resource.getItem().getProperty().getItem().getState().getPath();

    // Used for generating/updating all jobs' documentaiton only.
    if (jobName != null && !(jobName).equals(this.repositoryObjectType.toString().toLowerCase())
            && targetPath.endsWith(this.repositoryObjectType.toString().toLowerCase())) {
        targetPath = targetPath + IPath.SEPARATOR + jobPath + IPath.SEPARATOR + jobName;
    }/*from   w ww .ja v  a 2s .co m*/
    String version = ""; //$NON-NLS-1$

    // Checks if the job's version is specified, see it on "Export documentation" Dialog:
    if (jobVersion != null && jobVersion.length == 1) {
        version = jobVersion[0];
    } else {
        version = resource.getItem().getProperty().getVersion();
    }
    targetPath = targetPath + "_" + version; //$NON-NLS-1$

    File file = new File(targetPath);

    // Delete if folde is existing.
    if (file.exists()) {
        FilesUtils.removeFolder(file, true);
    }

    file.mkdirs();

    handleXMLFile(resource, targetPath, jobVersion);

    String picFolderPath = checkPicDirIsExists(resource, targetPath);

    // Gets the "org.talend.repository" plug-in:
    final Bundle b = Platform.getBundle("org.talend.repository"); //$NON-NLS-1$

    final URL xslFileUrl = FileLocator
            .toFileURL(FileLocator.find(b, new Path(IHTMLDocConstants.MAIN_XSL_FILE_PATH), null));
    // final URL logoFileUrl = FileLocator.toFileURL(FileLocator.find(b,
    // new Path(IHTMLDocConstants.LOGO_FILE_PATH), null));

    File logoFile = new File(picFolderPath + File.separatorChar + IHTMLDocConstants.TALEND_LOGO_FILE_NAME);
    saveLogoImage(SWT.IMAGE_JPEG, logoFile);

    String xslFilePath = xslFileUrl.getPath();
    // String logoFilePath = logoFileUrl.getPath();
    // FileCopyUtils.copy(logoFilePath, picFolderPath + File.separatorChar
    // + IHTMLDocConstants.TALEND_LOGO_FILE_NAME);

    // if set css file in preference.
    boolean isCheck = CorePlugin.getDefault().getPreferenceStore()
            .getBoolean(ITalendCorePrefConstants.USE_CSS_TEMPLATE);
    String cssFile = CorePlugin.getDefault().getPreferenceStore()
            .getString(ITalendCorePrefConstants.CSS_FILE_PATH);
    String temXslPath = null;
    if (isCheck && cssFile != null && !cssFile.equals("")) { //$NON-NLS-1$
        String tempFolderPath = checkTempDirIsExists(resource);
        temXslPath = tempFolderPath + File.separator + (new File(xslFilePath)).getName();
        File temXslFile = new File(temXslPath);
        if (temXslFile.exists()) {
            temXslFile.delete();
        }
        generateXslFile(xslFilePath, temXslPath, cssFile, null);
    }
    // if no new xls generated, use default xsl
    if (temXslPath != null) {
        File temFile = new File(temXslPath);
        if (!temFile.exists()) {
            temXslPath = xslFilePath;
        }
    } else {
        temXslPath = xslFilePath;
    }

    picList.add(logoFile.toURL());
    // Property property = item.getProperty();
    // String jobName = property.getLabel();
    // String jobVersion = property.getVersion();
    byte[] innerContent = null;
    ProcessType processType = null;
    if (resource.getItem() instanceof ProcessItem) {
        processType = ((ProcessItem) resource.getItem()).getProcess();
        innerContent = (byte[]) processType.getScreenshots().get("process"); //$NON-NLS-1$
    } else if (resource.getItem() instanceof JobletProcessItem) {
        processType = ((JobletProcessItem) resource.getItem()).getJobletProcess();
        innerContent = (byte[]) processType.getScreenshots().get("process"); //$NON-NLS-1$
        ;
    }

    if (innerContent != null) {
        String picName = jobName + "_" + version + IHTMLDocConstants.JOB_PREVIEW_PIC_SUFFIX; //$NON-NLS-1$
        ImageUtils.save(innerContent, picFolderPath + File.separatorChar + picName, SWT.IMAGE_PNG);
        picList.add(new File(picFolderPath + File.separatorChar + picName).toURL());

        // need to generate another pic for pdf
        ByteArrayInputStream bais = new ByteArrayInputStream(innerContent);
        Image pdfImage = new Image(null, bais);
        int width = pdfImage.getImageData().width;
        int percent = 22 * 32 * 100 / width;
        ImageUtils.save(ImageUtils.scale(pdfImage, percent),
                picFolderPath + File.separatorChar + "pdf_" + picName, //$NON-NLS-1$
                SWT.IMAGE_PNG);
        picList.add(new File(picFolderPath + File.separatorChar + "pdf_" + picName).toURL()); //$NON-NLS-1$
        pdfImage.dispose();
    }
    for (NodeType node : (List<NodeType>) processType.getNode()) {
        String uniqueName = ""; //$NON-NLS-1$
        for (Object o : node.getElementParameter()) {
            if (o instanceof ElementParameterType) {
                if ("UNIQUE_NAME".equals(((ElementParameterType) o).getName())) { //$NON-NLS-1$
                    uniqueName = ((ElementParameterType) o).getValue();
                    break;
                }
            }
        }
        byte[] screenshot = (byte[]) processType.getScreenshots().get(uniqueName);
        if (screenshot != null && screenshot.length != 0) {
            String picName = IHTMLDocConstants.EXTERNAL_NODE_PREVIEW + uniqueName
                    + IHTMLDocConstants.JOB_PREVIEW_PIC_SUFFIX;
            ImageUtils.save(screenshot, picFolderPath + File.separatorChar + picName, SWT.IMAGE_PNG);
            picList.add(new File(picFolderPath + File.separatorChar + picName).toURL());

            // need to generate externalNode pic for pdf
            ByteArrayInputStream bais = new ByteArrayInputStream(screenshot);
            Image pdfImage = new Image(null, bais);
            int width = pdfImage.getImageData().width;
            int percent = 22 * 32 * 100 / width;
            ImageUtils.save(ImageUtils.scale(pdfImage, percent),
                    picFolderPath + File.separatorChar + "pdf_" + picName, //$NON-NLS-1$
                    SWT.IMAGE_PNG);
            picList.add(new File(picFolderPath + File.separatorChar + picName).toURL());
            pdfImage.dispose();
        }
    }

    Set keySet = picFilePathMap.keySet();
    for (Object key : keySet) {
        String value = picFilePathMap.get(key);

        FileCopyUtils.copy(value, picFolderPath + File.separatorChar + key);

        picList.add(new File(picFolderPath + File.separatorChar + key).toURL());
    }

    List<URL> resultFiles = parseXml2HtmlPdf(targetPath, jobName + "_" + version, temXslPath); //$NON-NLS-1$

    resource.addResources(resultFiles);

    resource.addResources(IHTMLDocConstants.PIC_FOLDER_NAME, picList);

    HTMLDocUtils.deleteTempFiles();

    // List<URL> externalList = getExternalHtmlPath();
    // resource.addResources(IHTMLDocConstants.EXTERNAL_FOLDER_NAME, externalList);

    targetConnectionMap = null;
    sourceConnectionMap = null;
}

From source file:org.infoglue.deliver.invokers.ComponentBasedHTMLPageInvoker.java

/**
 * This method renders the base component and all it's children.
 *///from   w  ww  . jav a2  s .c  o m

private String preProcessComponent(InfoGlueComponent component, TemplateController templateController,
        Integer repositoryId, Integer siteNodeId, Integer languageId, Integer contentId,
        Integer metainfoContentId, List sortedPageComponents) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug("\n\n**** Pre processing component ****");
        logger.debug("id: " + component.getId());
        logger.debug("contentId: " + component.getContentId());
        logger.debug("name: " + component.getName());
        logger.debug("slotName: " + component.getSlotName());
    }

    StringBuilder decoratedComponent = new StringBuilder();

    templateController.setComponentLogic(new ComponentLogic(templateController, component));
    templateController.getDeliveryContext().getUsageListeners()
            .add(templateController.getComponentLogic().getComponentDeliveryContext());

    try {
        String componentString = getComponentPreProcessingTemplateString(templateController,
                component.getContentId(), component);
        if (logger.isDebugEnabled())
            logger.debug("componentString:" + componentString);

        String componentModelClassName = getComponentModelClassName(templateController,
                component.getContentId(), component);
        if (logger.isDebugEnabled())
            logger.debug("componentModelClassName:" + componentModelClassName);

        if (componentModelClassName != null && !componentModelClassName.equals("")) {
            templateController.getDeliveryContext().getUsageListeners()
                    .add(templateController.getComponentLogic().getComponentDeliveryContext());
            try {
                Timer t = new Timer();
                DigitalAssetVO asset = templateController.getAsset(component.getContentId(), "jar");

                String path = templateController.getAssetFilePathForAssetWithId(asset.getId());
                if (logger.isDebugEnabled())
                    logger.debug("path: " + path);
                if (path != null && !path.equals("")) {
                    try {
                        File jarFile = new File(path);
                        if (logger.isDebugEnabled())
                            logger.debug("jarFile:" + jarFile.exists());
                        URL url = jarFile.toURL();
                        URLClassLoader child = new URLClassLoader(new URL[] { url },
                                this.getClass().getClassLoader());

                        Class c = child.loadClass(componentModelClassName);
                        boolean isOk = ComponentModel.class.isAssignableFrom(c);
                        if (logger.isDebugEnabled())
                            logger.debug("isOk:" + isOk + " for " + componentModelClassName);
                        if (isOk) {
                            if (logger.isDebugEnabled())
                                logger.debug("Calling prepare on '" + componentModelClassName + "'");
                            ComponentModel componentModel = (ComponentModel) c.newInstance();
                            componentModel.prepare(componentString, templateController, component.getModel());
                        }
                    } catch (Exception e) {
                        logger.error(
                                "Failed loading custom class from asset JAR. Trying normal class loader. Error:"
                                        + e.getMessage());
                        ComponentModel componentModel = (ComponentModel) Thread.currentThread()
                                .getContextClassLoader().loadClass(componentModelClassName).newInstance();
                        componentModel.prepare(componentString, templateController, component.getModel());
                    }
                } else {
                    ComponentModel componentModel = (ComponentModel) Thread.currentThread()
                            .getContextClassLoader().loadClass(componentModelClassName).newInstance();
                    componentModel.prepare(componentString, templateController, component.getModel());
                }
                if (logger.isDebugEnabled())
                    t.printElapsedTime("Invoking custome class took");
            } catch (Exception e) {
                logger.error("The component '" + component.getName() + "' stated that class: "
                        + componentModelClassName
                        + " should be used as model. An exception was thrown when it was invoked: "
                        + e.getMessage(), e);
            }
            templateController.getDeliveryContext().getUsageListeners()
                    .remove(templateController.getComponentLogic().getComponentDeliveryContext());
        }

        if (componentString != null && !componentString.equals("")) {
            templateController.getDeliveryContext().getUsageListeners()
                    .add(templateController.getComponentLogic().getComponentDeliveryContext());

            Map context = getDefaultContext();
            context.put("templateLogic", templateController);
            context.put("model", component.getModel());
            StringWriter cacheString = new StringWriter();
            PrintWriter cachedStream = new PrintWriter(cacheString);
            //Timer t = new Timer();
            new VelocityTemplateProcessor().renderTemplate(context, cachedStream, componentString, false,
                    component, " - PreTemplate");
            //t.printElapsedTime("Rendering of " + component.getName() + " took ");
            componentString = cacheString.toString();

            if (logger.isDebugEnabled())
                logger.debug("componentString:" + componentString);

            templateController.getDeliveryContext().getUsageListeners()
                    .remove(templateController.getComponentLogic().getComponentDeliveryContext());
        }

        String templateComponentString = getComponentString(templateController, component.getContentId(),
                component);
        if (logger.isDebugEnabled())
            logger.debug("templateComponentString:" + templateComponentString);

        int offset = 0;
        int slotStartIndex = templateComponentString.indexOf("<ig:slot", offset);
        int slotStopIndex = 0;

        while (slotStartIndex > -1) {
            slotStopIndex = templateComponentString.indexOf("</ig:slot>", slotStartIndex);

            String slot = templateComponentString.substring(slotStartIndex, slotStopIndex + 10);
            String id = slot.substring(slot.indexOf("id") + 4, slot.indexOf("\"", slot.indexOf("id") + 4));

            boolean inherit = true;
            int inheritIndex = slot.indexOf("inherit");
            if (inheritIndex > -1) {
                String inheritString = slot.substring(inheritIndex + 9, slot.indexOf("\"", inheritIndex + 9));
                inherit = Boolean.parseBoolean(inheritString);
            }

            List subComponents = getInheritedComponents(templateController.getDatabase(), templateController,
                    component, templateController.getSiteNodeId(), id, inherit);
            Iterator subComponentsIterator = subComponents.iterator();
            while (subComponentsIterator.hasNext()) {
                InfoGlueComponent subComponent = (InfoGlueComponent) subComponentsIterator.next();
                if (subComponent.getIsInherited()) {
                    String subComponentString = preProcessComponent(subComponent, templateController,
                            repositoryId, siteNodeId, languageId, contentId, metainfoContentId,
                            sortedPageComponents);
                }
            }

            offset = slotStopIndex;
            slotStartIndex = templateComponentString.indexOf("<ig:slot", offset);
        }
    } catch (Exception e) {
        logger.warn(
                "An component with either an empty template or with no template in the sitelanguages was found:"
                        + e.getMessage(),
                e);
    }

    templateController.getDeliveryContext().getUsageListeners()
            .remove(templateController.getComponentLogic().getComponentDeliveryContext());

    if (logger.isDebugEnabled())
        logger.debug("decoratedComponent:" + decoratedComponent.toString());

    return decoratedComponent.toString();
}

From source file:org.andromda.cartridges.gui.metafacades.GuiManageableEntityLogicImpl.java

@Override
protected Object handleGetManageableExternalOrganization() {

    if (!this.handleIsExternalOrganizationExists() || this.getName().equals("")) {

        return null;

    }//w ww  .j  av  a2  s. c  o m

    try {

        final String manual_mapping_location = String
                .valueOf(this.getConfiguredProperty(GuiGlobals.MANUAL_MAPPING_LOCATION));
        final File file = new File(
                manual_mapping_location + GuiGlobals.FILE_SEPARATOR + this.getName() + ".xml");

        // File file = new File("configuration/generation/manualMapping/" + this.getName() + ".xml");
        final List<String> attributesAndAssociations = new ArrayList<String>();

        for (final Object o : this.getManageableAttributes()) {

            if (o instanceof GuiManageableEntityAttribute) {

                attributesAndAssociations.add(((GuiManageableEntityAttribute) o).getDisplayName());

            } else {

                this.logger_.info("GetManageableExternalOrganization : The attribute "
                        + ((AttributeFacade) o).getName() + " can not be handle");

            }

        }

        for (final Object o : this.getManageableAssociationEnds()) {

            if (o instanceof GuiManageableEntityAssociationEnd) {

                attributesAndAssociations.add(((GuiManageableEntityAssociationEnd) o).getDisplayName());

            } else {

                this.logger_.info("GetManageableExternalOrganization : The association end "
                        + ((AssociationEndFacade) o).getName() + " can not be handle");

            }

        }

        final org.andromda.cartridges.gui.util.parser.Parser parser = new org.andromda.cartridges.gui.util.parser.Parser(
                file.toURL(), attributesAndAssociations);
        ViewContent viewContent = new ViewContent();

        viewContent = parser.parse();

        final List<String> exceptions = parser.getInvalidAttributes();

        if (exceptions.size() > 0) {

            final StringBuilder attributes = new StringBuilder();

            for (final String name : exceptions) {

                attributes.append(name + ", ");

            }

            this.logger_.error("The attributes " + attributes.substring(0, attributes.length() - 2)
                    + " do not exist, please check the file configuration/generation/manualMapping/"
                    + this.getName() + ".xml");

            // System.exit(1);
        }

        return viewContent;

    } catch (final MalformedURLException e) {

        e.printStackTrace();

    } catch (final DocumentException e) {

        e.printStackTrace();

    }

    return null;

}

From source file:org.lockss.plugin.PluginManager.java

protected void processOneRegistryJar(CachedUrl cu, String url, ArchivalUnit au, Map tmpMap) {
    Integer curVersion = Integer.valueOf(cu.getVersion());

    if (cuNodeVersionMap.get(url) == null) {
        cuNodeVersionMap.put(url, Integer.valueOf(-1));
    }/*w  ww  .ja  va  2  s  .  c  om*/

    // If we've already visited this CU, skip it unless the current
    // repository node is a different version (older OR newer)
    Integer oldVersion = (Integer) cuNodeVersionMap.get(url);

    if (oldVersion.equals(curVersion)) {
        log.debug2(url + ": JAR repository and map versions are identical.  Skipping...");
        return;
    }

    File blessedJar = null;
    if (cu.getContentSize() == 0) {
        log.debug("Empty plugin jar: " + cu);
        return;
    } else {
        try {
            // Validate and bless the JAR file from the CU.
            blessedJar = jarValidator.getBlessedJar(cu);
            log.debug2("Plugin jar: " + cu.getUrl() + " -> " + blessedJar);
        } catch (IOException ex) {
            log.error("Error processing jar file: " + url, ex);
            return;
        } catch (JarValidator.JarValidationException ex) {
            log.error("CachedUrl did not validate: " + cu, ex);
            return;
        }
    }

    // Update the cuNodeVersion map now that we have the blessed Jar.
    cuNodeVersionMap.put(url, curVersion);

    if (blessedJar != null) {
        // Get the list of plugins to load from this jar.
        List loadPlugins = null;
        try {
            loadPlugins = getJarPluginClasses(blessedJar);
        } catch (IOException ex) {
            log.error("Error while getting list of plugins for " + blessedJar);
            return; // skip this CU.

        }
        log.debug2("Blessed jar: " + blessedJar + ", plugins: " + loadPlugins);

        // Although this -should- never happen, it's possible.
        if (loadPlugins.size() == 0) {
            log.warning("Jar " + blessedJar + " does not contain any plugins.  Skipping...");
            return; // skip this CU.
        }

        // Load the plugin classes
        ClassLoader pluginLoader = null;
        URL blessedUrl;
        try {
            blessedUrl = blessedJar.toURL();
            URL[] urls = new URL[] { blessedUrl };
            pluginLoader = preferLoadablePlugin ? new LoadablePluginClassLoader(urls)
                    : new URLClassLoader(urls);
        } catch (MalformedURLException ex) {
            log.error("Malformed URL exception attempting to create " + "classloader for plugin JAR "
                    + blessedJar);
            return; // skip this CU.
        }

        String pluginName = null;

        for (Iterator pluginIter = loadPlugins.iterator(); pluginIter.hasNext();) {
            pluginName = (String) pluginIter.next();
            String key = pluginKeyFromName(pluginName);

            Plugin plugin;
            PluginInfo info;
            try {
                info = retrievePlugin(pluginName, pluginLoader);
                if (info == null) {
                    log.warning("Probable plugin packaging error: plugin " + pluginName + " not found in "
                            + cu.getUrl());
                    continue;
                } else {
                    info.setCuUrl(url);
                    info.setRegistryAu(au);
                    List urls = info.getResourceUrls();
                    if (urls != null && !urls.isEmpty()) {
                        String jar = urls.get(0).toString();
                        if (jar != null) {
                            // If the blessed jar path is a substring of the jar:
                            // url from which the actual plugin resource or class
                            // was loaded, then it is a loadable plugin.
                            boolean isLoadable = jar.indexOf(blessedUrl.getFile()) > 0;
                            info.setIsOnLoadablePath(isLoadable);
                        }
                    }
                    plugin = info.getPlugin();
                }
            } catch (Exception ex) {
                log.error(String.format("Unable to load plugin %s", pluginName), ex);
                continue;
            }

            PluginVersion version = null;

            try {
                version = new PluginVersion(plugin.getVersion());
                info.setVersion(version);
            } catch (IllegalArgumentException ex) {
                // Don't let this runtime exception stop the daemon.  Skip the plugin.
                log.error(String.format("Skipping plugin %s: %s", pluginName, ex.getMessage()));
                // must stop plugin to enable it to be collected
                plugin.stopPlugin();
                return;
            }

            if (pluginMap.containsKey(key)) {
                // Plugin already exists in the global plugin map.
                // Replace it with a new version if one is available.
                log.debug2("Plugin " + key + " is already in global pluginMap.");
                Plugin otherPlugin = getPlugin(key);
                PluginVersion otherVer = new PluginVersion(otherPlugin.getVersion());
                if (version.toLong() > otherVer.toLong()) {
                    if (log.isDebug2()) {
                        log.debug2("Existing plugin " + plugin.getPluginId() + ": Newer version " + version
                                + " found.");
                    }
                    tmpMap.put(key, info);
                } else {
                    if (log.isDebug2()) {
                        log.debug2("Existing plugin " + plugin.getPluginId() + ": No newer version found.");
                    }
                    // must stop plugin to enable it to be collected
                    plugin.stopPlugin();
                }
            } else if (!tmpMap.containsKey(key)) {
                // Plugin doesn't yet exist in the temporary map, add it.
                tmpMap.put(key, info);

                if (log.isDebug2()) {
                    log.debug2("Plugin " + plugin.getPluginId() + ": No previous version in temp map.");
                }
            } else {
                // Plugin already exists in the temporary map, use whichever
                // version is higher.
                PluginVersion otherVer = ((PluginInfo) tmpMap.get(key)).getVersion();

                if (version.toLong() > otherVer.toLong()) {
                    if (log.isDebug2()) {
                        log.debug2("Plugin " + plugin.getPluginId() + ": version " + version
                                + " is newer than version " + otherVer + " already in temp map, overwriting.");
                    }
                    // Overwrite old key in temp map
                    tmpMap.put(key, info);
                } else {
                    // must stop plugin to enable it to be collected
                    plugin.stopPlugin();
                }
            }
        }
    }
}

From source file:org.kitodo.services.data.ProcessService.java

/**
 * write MetsFile to given Path.//  w w  w.  j a  v  a 2s .  c om
 *
 * @param process
 *            the Process to use
 * @param targetFileName
 *            the filename where the metsfile should be written
 * @param gdzfile
 *            the FileFormat-Object to use for Mets-Writing
 */
protected boolean writeMetsFile(Process process, String targetFileName, Fileformat gdzfile,
        boolean writeLocalFilegroup) throws PreferencesException, IOException, WriteException {
    FolderInformation fi = new FolderInformation(process.getId(), process.getTitle());
    Prefs preferences = serviceManager.getRulesetService().getPreferences(process.getRuleset());
    Project project = process.getProject();
    MetsModsImportExport mm = new MetsModsImportExport(preferences);
    mm.setWriteLocal(writeLocalFilegroup);
    URI imageFolderPath = fi.getImagesDirectory();
    File imageFolder = new File(imageFolderPath);
    /*
     * before creating mets file, change relative path to absolute -
     */
    DigitalDocument dd = gdzfile.getDigitalDocument();
    if (dd.getFileSet() == null) {
        Helper.setFehlerMeldung(process.getTitle() + ": digital document does not contain images; aborting");
        return false;
    }

    /*
     * get the topstruct element of the digital document depending on anchor
     * property
     */
    DocStruct topElement = dd.getLogicalDocStruct();
    if (preferences.getDocStrctTypeByName(topElement.getType().getName()).getAnchorClass() != null) {
        if (topElement.getAllChildren() == null || topElement.getAllChildren().size() == 0) {
            throw new PreferencesException(process.getTitle()
                    + ": the topstruct element is marked as anchor, but does not have any children for "
                    + "physical docstrucs");
        } else {
            topElement = topElement.getAllChildren().get(0);
        }
    }

    /*
     * if the top element does not have any image related, set them all
     */
    if (topElement.getAllToReferences("logical_physical") == null
            || topElement.getAllToReferences("logical_physical").size() == 0) {
        if (dd.getPhysicalDocStruct() != null && dd.getPhysicalDocStruct().getAllChildren() != null) {
            Helper.setMeldung(process.getTitle()
                    + ": topstruct element does not have any referenced images yet; temporarily adding them "
                    + "for mets file creation");
            for (DocStruct mySeitenDocStruct : dd.getPhysicalDocStruct().getAllChildren()) {
                topElement.addReferenceTo(mySeitenDocStruct, "logical_physical");
            }
        } else {
            Helper.setFehlerMeldung(
                    process.getTitle() + ": could not find any referenced images, export aborted");
            return false;
        }
    }

    for (ContentFile cf : dd.getFileSet().getAllFiles()) {
        String location = cf.getLocation();
        // If the file's location string shoes no sign of any protocol,
        // use the file protocol.
        if (!location.contains("://")) {
            location = "file://" + location;
        }
        String url = new URL(location).getFile();
        File f = new File(!url.startsWith(imageFolder.toURL().getPath()) ? imageFolder : null, url);
        cf.setLocation(f.toURI().toString());
    }

    mm.setDigitalDocument(dd);

    /*
     * wenn Filegroups definiert wurden, werden diese jetzt in die
     * Metsstruktur bernommen
     */
    // Replace all paths with the given VariableReplacer, also the file
    // group paths!
    VariableReplacer vp = new VariableReplacer(mm.getDigitalDocument(), preferences, process, null);
    List<ProjectFileGroup> myFilegroups = project.getProjectFileGroups();

    if (myFilegroups != null && myFilegroups.size() > 0) {
        for (ProjectFileGroup pfg : myFilegroups) {
            // check if source files exists
            if (pfg.getFolder() != null && pfg.getFolder().length() > 0) {
                URI folder = new File(fi.getMethodFromName(pfg.getFolder())).toURI();
                if (fileService.fileExist(folder)
                        && serviceManager.getFileService().getSubUris(folder).size() > 0) {
                    VirtualFileGroup v = new VirtualFileGroup();
                    v.setName(pfg.getName());
                    v.setPathToFiles(vp.replace(pfg.getPath()));
                    v.setMimetype(pfg.getMimeType());
                    v.setFileSuffix(pfg.getSuffix());
                    mm.getDigitalDocument().getFileSet().addVirtualFileGroup(v);
                }
            } else {

                VirtualFileGroup v = new VirtualFileGroup();
                v.setName(pfg.getName());
                v.setPathToFiles(vp.replace(pfg.getPath()));
                v.setMimetype(pfg.getMimeType());
                v.setFileSuffix(pfg.getSuffix());
                mm.getDigitalDocument().getFileSet().addVirtualFileGroup(v);
            }
        }
    }

    // Replace rights and digiprov entries.
    mm.setRightsOwner(vp.replace(project.getMetsRightsOwner()));
    mm.setRightsOwnerLogo(vp.replace(project.getMetsRightsOwnerLogo()));
    mm.setRightsOwnerSiteURL(vp.replace(project.getMetsRightsOwnerSite()));
    mm.setRightsOwnerContact(vp.replace(project.getMetsRightsOwnerMail()));
    mm.setDigiprovPresentation(vp.replace(project.getMetsDigiprovPresentation()));
    mm.setDigiprovReference(vp.replace(project.getMetsDigiprovReference()));
    mm.setDigiprovPresentationAnchor(vp.replace(project.getMetsDigiprovPresentationAnchor()));
    mm.setDigiprovReferenceAnchor(vp.replace(project.getMetsDigiprovReferenceAnchor()));

    mm.setPurlUrl(vp.replace(project.getMetsPurl()));
    mm.setContentIDs(vp.replace(project.getMetsContentIDs()));

    // Set mets pointers. MetsPointerPathAnchor or mptrAnchorUrl is the
    // pointer used to point to the superordinate (anchor) file, that is
    // representing a virtual? group such as a series. Several anchors
    // pointer paths can be defined/ since it is possible to define several
    // levels of superordinate structures (such as the complete edition of
    // a daily newspaper, one year ouf of that edition, )
    String anchorPointersToReplace = project.getMetsPointerPath();
    mm.setMptrUrl(null);
    for (String anchorPointerToReplace : anchorPointersToReplace.split(Project.ANCHOR_SEPARATOR)) {
        String anchorPointer = vp.replace(anchorPointerToReplace);
        mm.setMptrUrl(anchorPointer);
    }

    // metsPointerPathAnchor or mptrAnchorUrl is the pointer used to point
    // from the (lowest) superordinate (anchor) file to the lowest level
    // file (the non-anchor file).
    String anchor = project.getMetsPointerPathAnchor();
    String pointer = vp.replace(anchor);
    mm.setMptrAnchorUrl(pointer);

    try {
        // TODO andere Dateigruppen nicht mit image Namen ersetzen
        List<URI> images = fi.getDataFiles();
        List<String> imageStrings = new ArrayList<>();
        for (URI image : images) {
            imageStrings.add(image.getPath());
        }
        int sizeOfPagination = dd.getPhysicalDocStruct().getAllChildren().size();
        int sizeOfImages = images.size();
        if (sizeOfPagination == sizeOfImages) {
            dd.overrideContentFiles(imageStrings);
        } else {
            List<String> param = new ArrayList<>();
            param.add(String.valueOf(sizeOfPagination));
            param.add(String.valueOf(sizeOfImages));
            Helper.setFehlerMeldung(Helper.getTranslation("imagePaginationError", param));
            return false;
        }
    } catch (IndexOutOfBoundsException | InvalidImagesException e) {
        logger.error(e);
    }
    mm.write(targetFileName);
    Helper.setMeldung(null, process.getTitle() + ": ", "ExportFinished");
    return true;
}