<commit_before>/*******************************************************************************
 * Copyright (c) 2015-2016 Oak Ridge National Laboratory.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/
package org.csstudio.display.builder.model.util;

import static org.csstudio.display.builder.model.ModelPlugin.logger;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.logging.Level;

import org.csstudio.display.builder.model.Preferences;
import org.csstudio.display.builder.util.ResourceUtil;

/** Helper for handling resources: File, web link.
 *  @author <NAME>
 */
@SuppressWarnings("nls")
public class ModelResourceUtil extends ResourceUtil
{
    private static int timeout_ms = Preferences.getReadTimeout();

    private static WorkspaceResourceHelper workspace_helper = initializeWRHelper();

    private static WorkspaceResourceHelper initializeWRHelper()
    {
        try
        {
            @SuppressWarnings("unchecked")
            final Class<WorkspaceResourceHelper> clazz =
                (Class<WorkspaceResourceHelper>)Class.forName(WorkspaceResourceHelper.IMPL);
            final WorkspaceResourceHelper helper = clazz.newInstance();
            logger.config("Found WorkspaceResourceHelper");
            return helper;
        }
        catch (ClassNotFoundException ex)
        {   // OK to not have a WorkspaceResourceHelperImpl
            logger.config("No WorkspaceResourceHelper");
        }
        catch (Exception ex)
        {
            logger.log(Level.SEVERE, "Cannot create WorkspaceResourceHelper", ex);
        }
        return null;
    }

    /** org.csstudio.display.builder.rcp calls this to support workspace files
     *  @param workspace_helper
     */
    public static void setWorkspaceHelper(final WorkspaceResourceHelper workspace_helper)
    {
        ModelResourceUtil.workspace_helper = workspace_helper;
    }

    // Many basic String operations since paths
    // may include " ", which URL won't handle,
    // or start with "https://", which File won't handle.

    private static boolean isURL(final String path)
    {
        return path.startsWith("http://")  ||
               path.startsWith("https://");
    }

    private static boolean isAbsolute(final String path)
    {
        return path.startsWith("/")  ||
               isURL(path);
    }

    /** Normalize a windows-type path with '\'
     *  @param path Path that may use Windows '\'
     *  @return Path with only '/'
     */
    public static String normalize(final String path)
    {
        // Pattern: '\(?!\)', i.e. backslash _not_ followed by another one.
        // Each \ is doubled as \\ to get one '\' into the string,
        // then doubled once more to tell regex that we want a '\'
        return path.replaceAll("\\\\(?!\\\\)", "/");
    }

    /** Obtain location, i.e. directory of file or URL up to the last element
     *  @param path Complete path, i.e. "/some/location/resource"
     *  @return Location, i.e. "/some/location" without trailing "/", or "."
     */
    public static String getLocation(String path)
    {
        // Remove last segment from parent_display to get path
        int sep = path.lastIndexOf('/');
        if (sep >= 0)
            return path.substring(0, sep);
        return ".";
    }

    /** @param resource_name Resource that may be relative to workspace
     *  @return Location in local file system or <code>null</code>
     */
    public static String getLocalPath(final String resource_name)
    {
        if (workspace_helper != null)
        {
            final String absolute = workspace_helper.getLocalPath(resource_name);
            if (absolute != null)<commit_msg>Model resource util: Fix NPE in getLocation<commit_after>/*******************************************************************************
 * Copyright (c) 2015-2016 Oak Ridge National Laboratory.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/
package org.csstudio.display.builder.model.util;

import static org.csstudio.display.builder.model.ModelPlugin.logger;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.logging.Level;

import org.csstudio.display.builder.model.Preferences;
import org.csstudio.display.builder.util.ResourceUtil;

/** Helper for handling resources: File, web link.
 *  @author <NAME>
 */
@SuppressWarnings("nls")
public class ModelResourceUtil extends ResourceUtil
{
    private static int timeout_ms = Preferences.getReadTimeout();

    private static WorkspaceResourceHelper workspace_helper = initializeWRHelper();

    private static WorkspaceResourceHelper initializeWRHelper()
    {
        try
        {
            @SuppressWarnings("unchecked")
            final Class<WorkspaceResourceHelper> clazz =
                (Class<WorkspaceResourceHelper>)Class.forName(WorkspaceResourceHelper.IMPL);
            final WorkspaceResourceHelper helper = clazz.newInstance();
            logger.config("Found WorkspaceResourceHelper");
            return helper;
        }
        catch (ClassNotFoundException ex)
        {   // OK to not have a WorkspaceResourceHelperImpl
            logger.config("No WorkspaceResourceHelper");
        }
        catch (Exception ex)
        {
            logger.log(Level.SEVERE, "Cannot create WorkspaceResourceHelper", ex);
        }
        return null;
    }

    /** org.csstudio.display.builder.rcp calls this to support workspace files
     *  @param workspace_helper
     */
    public static void setWorkspaceHelper(final WorkspaceResourceHelper workspace_helper)
    {
        ModelResourceUtil.workspace_helper = workspace_helper;
    }

    // Many basic String operations since paths
    // may include " ", which URL won't handle,
    // or start with "https://", which File won't handle.

    private static boolean isURL(final String path)
    {
        return path.startsWith("http://")  ||
               path.startsWith("https://");
    }

    private static boolean isAbsolute(final String path)
    {
        return path.startsWith("/")  ||
               isURL(path);
    }

    /** Normalize a windows-type path with '\'
     *  @param path Path that may use Windows '\'
     *  @return Path with only '/'
     */
    public static String normalize(final String path)
    {
        // Pattern: '\(?!\)', i.e. backslash _not_ followed by another one.
        // Each \ is doubled as \\ to get one '\' into the string,
        // then doubled once more to tell regex that we want a '\'
        return path.replaceAll("\\\\(?!\\\\)", "/");
    }

    /** Obtain location, i.e. directory of file or URL up to the last element
     *
     *  <p>For a <code>null</code> path, the location will also be <code>null</code>.
     *
     *  @param path Complete path, i.e. "/some/location/resource"
     *  @return Location, i.e. "/some/location" without trailing "/", or "."
     */
    public static String getLocation(final String path)
    {
        if (path == null)
            return null;
        // Remove last segment from parent_display to get path
        int sep = path.lastIndexOf('/');
        if (sep >= 0)
            return path.substring(0, sep);
        return ".";
    }

    /** @param resource_name Resource that may be relative to workspace
     *  @return Location in local file system or <code>null</code>
     */
    public static String getLocalPath(final String resource_name)
    {
        if (workspace_helper != null)
        {
            final String absolute = workspace_helper.getLocalPath(resource_name);
            if (absolute != null)
{'fraction_non_alphanumeric': 0.1374036461519638, 'fraction_numerical': 0.0034259145968432644, 'mean_word_length': 2.6986425339366518, 'pattern_counts': {'":': 0, '<': 18, '<?xml version=': 0, '>': 20, 'https://': 4, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6821866', 'n_tokens_mistral': 2128, 'n_tokens_neox': 2074, 'n_words': 641}