Example usage for java.net MalformedURLException getClass

List of usage examples for java.net MalformedURLException getClass

Introduction

In this page you can find the example usage for java.net MalformedURLException getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:org.jwebsocket.config.JWebSocketConfig.java

/**
 *
 * @param aPath//w w  w  .j a  va  2s .co  m
 * @param aClassLoader
 * @return
 */
public static URL getURLFromPath(String aPath, ClassLoader aClassLoader) {
    URL lURL = null;
    try {
        if (isLoadConfigFromResource()) {
            lURL = aClassLoader.getResource(aPath);
        } else {
            lURL = new URL("file://" + aPath);
        }
    } catch (MalformedURLException lEx) {
        System.out.println(lEx.getClass().getSimpleName() + ": " + lEx.getMessage());
    }
    return lURL;
}

From source file:org.apache.pulsar.admin.cli.PulsarAdminTool.java

private void setupCommands() {
    try {/*w ww .ja  va  2 s  .  com*/
        URL url = new URL(serviceUrl);
        config.setAuthentication(authPluginClassName, authParams);
        PulsarAdmin admin = new PulsarAdmin(url, config);
        for (Map.Entry<String, Class> c : commandMap.entrySet()) {
            jcommander.addCommand(c.getKey(),
                    c.getValue().getConstructor(PulsarAdmin.class).newInstance(admin));
        }
    } catch (MalformedURLException e) {
        System.err.println("Invalid serviceUrl: '" + serviceUrl + "'");
        System.exit(1);
    } catch (Exception e) {
        System.err.println(e.getClass() + ": " + e.getMessage());
        System.exit(1);
    }
}

From source file:com.tune.reporting.base.service.TuneServiceProxy.java

/**
 * Post request to TUNE Service API Service
 *
 * @return Boolean True if successful posting request, else False.
 * @throws TuneSdkException If error within SDK.
 *///  w w  w  .  ja v a2s. c  o  m
protected boolean postRequest() throws TuneSdkException {
    URL url = null;
    HttpsURLConnection conn = null;

    try {
        url = new URL(this.uri);
    } catch (MalformedURLException ex) {
        throw new TuneSdkException(String.format("Problems executing request: %s: %s: '%s'", this.uri,
                ex.getClass().toString(), ex.getMessage()), ex);
    }

    try {
        // connect to the server over HTTPS and submit the payload
        conn = (HttpsURLConnection) url.openConnection();

        // Create the SSL connection
        SSLContext sc;
        sc = SSLContext.getInstance("TLS");
        sc.init(null, null, new java.security.SecureRandom());
        conn.setSSLSocketFactory(sc.getSocketFactory());

        conn.setRequestMethod("GET");
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.connect();

        // Gets the status code from an HTTP response message.
        final int responseHttpCode = conn.getResponseCode();

        // Returns an unmodifiable Map of the header fields.
        // The Map keys are Strings that represent the response-header
        // field names. Each Map value is an unmodifiable List of Strings
        // that represents the corresponding field values.
        final Map<String, List<String>> responseHeaders = conn.getHeaderFields();

        final String requestUrl = url.toString();

        // Gets the HTTP response message, if any, returned along
        // with the response code from a server.
        String responseRaw = conn.getResponseMessage();

        // Pull entire JSON raw response
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();

        responseRaw = sb.toString();

        // decode to JSON
        JSONObject responseJson = new JSONObject(responseRaw);

        this.response = new TuneServiceResponse(responseRaw, responseJson, responseHttpCode, responseHeaders,
                requestUrl.toString());
    } catch (Exception ex) {
        throw new TuneSdkException(String.format("Problems executing request: %s: '%s'",
                ex.getClass().toString(), ex.getMessage()), ex);
    }

    return true;
}

From source file:com.digitalpebble.storm.crawler.bolt.ParserBolt.java

private List<Outlink> toOutlinks(String parentURL, List<Link> links, Metadata parentMetadata) {

    List<Outlink> outlinks = new ArrayList<Outlink>(links.size());

    URL url_;/*  w w  w  .jav  a  2s .  com*/
    try {
        url_ = new URL(parentURL);
    } catch (MalformedURLException e1) {
        // we would have known by now as previous
        // components check whether the URL is valid
        LOG.error("MalformedURLException on {}", parentURL);
        eventCounter.scope("error_invalid_source_url").incrBy(1);
        return outlinks;
    }

    for (Link l : links) {
        if (StringUtils.isBlank(l.getUri())) {
            continue;
        }
        String urlOL = null;

        // build an absolute URL
        try {
            URL tmpURL = URLUtil.resolveURL(url_, l.getUri());
            urlOL = tmpURL.toExternalForm();
        } catch (MalformedURLException e) {
            LOG.debug("MalformedURLException on {}", l.getUri());
            eventCounter.scope("error_outlink_parsing_" + e.getClass().getSimpleName()).incrBy(1);
            continue;
        }

        // applies the URL filters
        if (urlFilters != null) {
            urlOL = urlFilters.filter(url_, parentMetadata, urlOL);
            if (urlOL == null) {
                eventCounter.scope("outlink_filtered").incrBy(1);
                continue;
            }
        }

        eventCounter.scope("outlink_kept").incrBy(1);

        Outlink ol = new Outlink(urlOL);
        // add the anchor
        ol.setAnchor(l.getText());

        // get the metadata for the outlink from the parent ones
        ol.setMetadata(metadataTransfer.getMetaForOutlink(urlOL, parentURL, parentMetadata));

        outlinks.add(ol);
    }
    return outlinks;
}

From source file:com.digitalpebble.stormcrawler.tika.ParserBolt.java

private List<Outlink> toOutlinks(String parentURL, List<Link> links, Metadata parentMetadata) {

    Map<String, Outlink> outlinks = new HashMap<String, Outlink>();

    URL url_;/*from w  w  w .  j  av  a2  s. c  om*/
    try {
        url_ = new URL(parentURL);
    } catch (MalformedURLException e1) {
        // we would have known by now as previous
        // components check whether the URL is valid
        LOG.error("MalformedURLException on {}", parentURL);
        eventCounter.scope("error_invalid_source_url").incrBy(1);
        return new LinkedList<Outlink>();
    }

    for (Link l : links) {
        if (StringUtils.isBlank(l.getUri())) {
            continue;
        }
        String urlOL;

        // build an absolute URL
        try {
            URL tmpURL = URLUtil.resolveURL(url_, l.getUri());
            urlOL = tmpURL.toExternalForm();
        } catch (MalformedURLException e) {
            LOG.debug("MalformedURLException on {}", l.getUri());
            eventCounter.scope("error_outlink_parsing_" + e.getClass().getSimpleName()).incrBy(1);
            continue;
        }

        // applies the URL filters
        if (urlFilters != null) {
            urlOL = urlFilters.filter(url_, parentMetadata, urlOL);
            if (urlOL == null) {
                eventCounter.scope("outlink_filtered").incrBy(1);
                continue;
            }
        }

        eventCounter.scope("outlink_kept").incrBy(1);

        Outlink ol = new Outlink(urlOL);
        // add the anchor
        ol.setAnchor(l.getText());

        // get the metadata for the outlink from the parent ones
        ol.setMetadata(metadataTransfer.getMetaForOutlink(urlOL, parentURL, parentMetadata));

        // keep only one instance of outlink per URL
        Outlink ol2 = outlinks.get(urlOL);
        if (ol2 == null) {
            outlinks.put(urlOL, ol);
        }
    }
    return new ArrayList<Outlink>(outlinks.values());
}

From source file:tangocard.sdk.service.ServiceProxy.java

/**
 * Post request.// ww w . ja  v a2  s.c  o m
 *
 * @return true, if successful
 * @throws Exception the exception
 */
protected String postRequest() throws Exception {
    if (null == this._path) {
        throw new TangoCardSdkException("Member variable '_path' is null.");
    }

    String responseJsonEncoded = null;
    URL url = null;
    HttpsURLConnection connection = null;

    try {
        url = new URL(this._path);
    } catch (MalformedURLException e) {
        throw new TangoCardSdkException("MalformedURLException", e);
    }

    if (this.mapRequest()) {
        try {
            // connect to the server over HTTPS and submit the payload
            connection = (HttpsURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-length", String.valueOf(this._str_request_json.length()));
            connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");

            // open up the output stream of the connection
            DataOutputStream output = new DataOutputStream(connection.getOutputStream());
            output.write(this._str_request_json.getBytes());
        } catch (Exception e) {
            throw new TangoCardSdkException(String.format("Problems executing request: %s: '%s'",
                    e.getClass().toString(), e.getMessage()), e);
        }

        try {
            // now read the input stream until it is closed, line by line adding to the response
            InputStream inputstream = connection.getInputStream();
            InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
            BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
            StringBuffer response = new StringBuffer();
            String line = null;
            while ((line = bufferedreader.readLine()) != null) {
                response.append(line);
            }

            responseJsonEncoded = response.toString();
        } catch (Exception e) {
            throw new TangoCardSdkException(String.format("Problems reading response: %s: '%s'",
                    e.getClass().toString(), e.getMessage()), e);
        }
    }

    return responseJsonEncoded;
}

From source file:com.gmt2001.TwitchAPIv2.java

private JSONObject GetData(request_type type, String url, String post, String oauth) {
    JSONObject j = new JSONObject();

    try {/* ww  w  .  java2 s .com*/
        URL u = new URL(url);
        HttpsURLConnection c = (HttpsURLConnection) u.openConnection();

        c.addRequestProperty("Accept", header_accept);

        if (!clientid.isEmpty()) {
            c.addRequestProperty("Client-ID", clientid);
        }

        if (!oauth.isEmpty()) {
            c.addRequestProperty("Authorization", "OAuth " + oauth);
        }

        c.setRequestMethod(type.name());

        c.setUseCaches(false);
        c.setDefaultUseCaches(false);
        c.setConnectTimeout(timeout);

        c.connect();

        if (!post.isEmpty()) {
            IOUtils.write(post, c.getOutputStream());
        }

        String content;

        if (c.getResponseCode() == 200) {
            content = IOUtils.toString(c.getInputStream(), c.getContentEncoding());
        } else {
            content = IOUtils.toString(c.getErrorStream(), c.getContentEncoding());
        }

        j = new JSONObject(content);
        j.put("_success", true);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", c.getResponseCode());
        j.put("_exception", "");
        j.put("_exceptionMessage", "");
    } catch (MalformedURLException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "MalformedURLException");
        j.put("_exceptionMessage", ex.getMessage());
    } catch (SocketTimeoutException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "SocketTimeoutException");
        j.put("_exceptionMessage", ex.getMessage());
    } catch (IOException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "IOException");
        j.put("_exceptionMessage", ex.getMessage());
    } catch (Exception ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "Exception [" + ex.getClass().getName() + "]");
        j.put("_exceptionMessage", ex.getMessage());
    }

    return j;
}

From source file:com.airbnb.deeplinkdispatch.DeepLinkProcessor.java

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    Set<Element> customAnnotations = new HashSet<>();
    for (Element annotation : annotations) {
        if (annotation.getAnnotation(DEEP_LINK_SPEC_CLASS) != null) {
            customAnnotations.add(annotation);
        }// w  ww.j  av  a  2s .c om
    }

    Map<Element, String[]> prefixes = new HashMap<>();
    Set<Element> customAnnotatedElements = new HashSet<>();
    for (Element customAnnotation : customAnnotations) {
        ElementKind kind = customAnnotation.getKind();
        if (kind != ElementKind.ANNOTATION_TYPE) {
            error(customAnnotation, "Only annotation types can be annotated with @%s",
                    DEEP_LINK_SPEC_CLASS.getSimpleName());
        }
        String[] prefix = customAnnotation.getAnnotation(DEEP_LINK_SPEC_CLASS).prefix();
        if (Utils.hasEmptyOrNullString(prefix)) {
            error(customAnnotation, "Prefix property cannot have null or empty strings");
        }
        if (prefix.length == 0) {
            error(customAnnotation, "Prefix property cannot be empty");
        }
        prefixes.put(customAnnotation, prefix);
        for (Element customAnnotatedElement : roundEnv
                .getElementsAnnotatedWith(MoreElements.asType(customAnnotation))) {
            customAnnotatedElements.add(customAnnotatedElement);
        }
    }

    Set<Element> elementsToProcess = new HashSet<>(customAnnotatedElements);
    elementsToProcess.addAll(roundEnv.getElementsAnnotatedWith(DEEP_LINK_CLASS));

    List<DeepLinkAnnotatedElement> deepLinkElements = new ArrayList<>();
    for (Element element : elementsToProcess) {
        ElementKind kind = element.getKind();
        if (kind != ElementKind.METHOD && kind != ElementKind.CLASS) {
            error(element, "Only classes and methods can be annotated with @%s",
                    DEEP_LINK_CLASS.getSimpleName());
        }

        if (kind == ElementKind.METHOD) {
            Set<Modifier> methodModifiers = element.getModifiers();
            if (!methodModifiers.contains(Modifier.STATIC)) {
                error(element, "Only static methods can be annotated with @%s",
                        DEEP_LINK_CLASS.getSimpleName());
            }
        }

        DeepLink deepLinkAnnotation = element.getAnnotation(DEEP_LINK_CLASS);
        List<String> deepLinks = new ArrayList<>();
        if (deepLinkAnnotation != null) {
            deepLinks.addAll(Arrays.asList(deepLinkAnnotation.value()));
        }
        if (customAnnotatedElements.contains(element)) {
            deepLinks.addAll(enumerateCustomDeepLinks(element, prefixes));
        }
        DeepLinkEntry.Type type = kind == ElementKind.CLASS ? DeepLinkEntry.Type.CLASS
                : DeepLinkEntry.Type.METHOD;
        for (String deepLink : deepLinks) {
            try {
                deepLinkElements.add(new DeepLinkAnnotatedElement(deepLink, element, type));
            } catch (MalformedURLException e) {
                messager.printMessage(Diagnostic.Kind.ERROR, "Malformed Deep Link URL " + deepLink);
            }
        }
    }
    Set<? extends Element> deepLinkHandlerElements = roundEnv.getElementsAnnotatedWith(DeepLinkHandler.class);
    for (Element deepLinkHandlerElement : deepLinkHandlerElements) {
        Optional<AnnotationMirror> annotationMirror = getAnnotationMirror(deepLinkHandlerElement,
                DeepLinkHandler.class);
        if (annotationMirror.isPresent()) {
            Iterable<TypeMirror> klasses = getTypeValue(annotationMirror.get(), "value");
            List<TypeElement> typeElements = FluentIterable.from(klasses)
                    .transform(new Function<TypeMirror, TypeElement>() {
                        @Override
                        public TypeElement apply(TypeMirror klass) {
                            return MoreTypes.asTypeElement(klass);
                        }
                    }).toList();
            String packageName = processingEnv.getElementUtils().getPackageOf(deepLinkHandlerElement)
                    .getQualifiedName().toString();
            try {
                generateDeepLinkDelegate(packageName, typeElements);
            } catch (IOException e) {
                messager.printMessage(Diagnostic.Kind.ERROR, "Error creating file");
            } catch (RuntimeException e) {
                messager.printMessage(Diagnostic.Kind.ERROR,
                        "Internal error during annotation processing: " + e.getClass().getSimpleName());
            }
        }
    }

    Set<? extends Element> deepLinkModuleElements = roundEnv.getElementsAnnotatedWith(DeepLinkModule.class);
    for (Element deepLinkModuleElement : deepLinkModuleElements) {
        String packageName = processingEnv.getElementUtils().getPackageOf(deepLinkModuleElement)
                .getQualifiedName().toString();
        try {
            generateDeepLinkLoader(packageName, deepLinkModuleElement.getSimpleName().toString(),
                    deepLinkElements);
        } catch (IOException e) {
            messager.printMessage(Diagnostic.Kind.ERROR, "Error creating file");
        } catch (RuntimeException e) {
            messager.printMessage(Diagnostic.Kind.ERROR,
                    "Internal error during annotation processing: " + e.getClass().getSimpleName());
        }
    }

    return false;
}

From source file:org.emoseman.aconf.AutoConfig.java

private static void readConfigFromFile(Class<? extends ConfigContainer> configContainer,
        String configFilename) {/*from  w  ww.  ja va  2  s .c  o  m*/

    configLock.writeLock().lock();

    URL fileURL = null;
    if (configFilename.startsWith("file:///")) {
        try {
            fileURL = new URL(configFilename);
        } catch (MalformedURLException e) {
            throw new RuntimeException("Failed to create URL from " + configFilename, e);
        }
    } else {
        ClassLoader cl = ClassLoader.getSystemClassLoader();
        fileURL = cl.getResource(configFilename);
    }
    if (fileURL == null) {
        throw new RuntimeException("Failed to load config file " + configFilename);
    }

    Gson gson = new Gson();
    String val;
    Field field;
    Class type;
    try {
        // read json from config file
        // TODO enforce extension?
        HashMap<String, String> tmp = gson.fromJson(new InputStreamReader(fileURL.openStream()), HashMap.class);

        // search for required keys
        ArrayList<String> missingKeys = new ArrayList<>();
        for (String k : configContainerRequiredFields.get(configContainer)) {
            if (!tmp.containsKey(k)) {
                missingKeys.add(k);
            }
        }
        if (missingKeys.size() > 0) {
            throw new RuntimeException(
                    "Properties " + StringUtils.join(missingKeys, ", ") + " are required, and missing");
        }

        // assign defaults
        for (Field f : configContainerFields.get(configContainer)) {
            ConfigElement configElement = f.getAnnotation(ConfigElement.class);
            if (configElement == null) {
                continue;
            }
            if (StringUtils.isEmpty(configElement.defaultValue())) {
                continue;
            }
            if (!tmp.containsKey(configElement.propertyName())) {
                tmp.put(configElement.propertyName(), configElement.defaultValue());
            }
        }

        // populate fields
        for (String k : tmp.keySet()) {
            if (fieldMap.get(configContainer).containsKey(k)) {
                val = tmp.get(k);
                if (val.equalsIgnoreCase("${hostname}")) {
                    val = populateMacro(val);
                }
                field = fieldMap.get(configContainer).get(k);
                field.setAccessible(true);

                type = fieldTypeMap.get(configContainer).get(k);

                if (type == String.class) {
                    field.set(configContainer, String.valueOf(val));
                } else if (type == BigInteger.class) {
                    field.set(configContainer, new BigInteger(val));
                } else if (type == Float.class || type == float.class) {
                    field.set(configContainer, Float.valueOf(val));
                } else if (type == Long.class || type == long.class) {
                    field.set(configContainer, Long.valueOf(val));
                } else if (type == Double.class || type == double.class) {
                    field.set(configContainer, Double.valueOf(val));
                } else if (type == Integer.class || type == int.class) {
                    field.set(configContainer, Integer.valueOf(val));
                } else if (type == Boolean.class || type == boolean.class) {
                    field.set(configContainer, Boolean.valueOf(val));
                } else {
                    // try to execute the method reflectively
                    try {
                        Method m = type.getDeclaredMethod("valueOf", String.class);
                        Invokable invokable = new TypeToken() {
                        }.method(m);
                        if (invokable.isStatic() && !invokable.isPrivate()) {
                            field.set(configContainer, m.invoke(type, val));
                            continue;
                        }
                    } catch (Throwable ignored) {
                        // ignored
                    }
                    try {
                        Constructor typeConstructor = type.getConstructor(String.class);
                        Invokable invokable = new TypeToken() {
                        }.constructor(typeConstructor);
                        if (!invokable.isPrivate()) {
                            field.set(configContainer, typeConstructor.newInstance(val));
                            continue;
                        }
                    } catch (Throwable ignored) {
                        // ignored
                    }

                    throw new RuntimeException(
                            "Not coded for type " + type + " and could not find a method to execute!");
                }
            }
        }
        for (ConfigChangeListener listener : listeners) {
            listener.configReloaded();
        }
    } catch (Exception e) {
        log.error(e.getClass() + "-" + e.getMessage());
        if (log.isDebugEnabled()) {
            e.printStackTrace(System.err);
        }

        shutdown.set(true);
        timedPool.shutdownNow();
        throw new RuntimeException(e);
    }

    configLock.writeLock().unlock();
}

From source file:org.opentravel.schemacompiler.repository.ProjectManager.java

/**
 * Loads the specified project file and incorporates its content into the shared model instance.
 * //from  w w  w. ja  v a2 s .  com
 * @param projectFile
 *            the file location of the project to be loaded
 * @param findings
 *            validation findings where errors/warnings from the loading operation will be
 *            reported
 * @return Project
 * @throws LibraryLoaderException
 *             thrown if the contents of the project cannot be loaded
 * @throws IllegalArgumentException
 *             thrown if the file and/or ID of the project are already in use
 * @throws RepositoryException
 *             thrown if one or more managed repository items cannot be accessed
 */
public Project loadProject(File projectFile, ValidationFindings findings)
        throws LibraryLoaderException, RepositoryException {
    ProjectType jaxbProject = ProjectFileUtils.loadJaxbProjectFile(projectFile, findings);
    Project project = null;

    if (jaxbProject != null) {
        ValidationFindings loaderFindings = new ValidationFindings();

        // Attempt to register any new repositories that are defined in this project file
        registerUnknownRepositories(jaxbProject, projectFile, loaderFindings);

        // Construct the new project instance and add it to the current list of projects
        project = new Project(this);
        project.setProjectId(jaxbProject.getProjectId());
        project.setProjectFile(projectFile);
        project.setName(jaxbProject.getName());
        project.setDescription(jaxbProject.getDescription());
        project.setDefaultContextId(jaxbProject.getDefaultContextId());

        validateProjectID(project.getProjectId(), null);
        validateProjectFile(projectFile, null);
        projects.add(project);

        // Load the contents of the model using the library reference from each of the project
        // items
        // defined in the file.
        List<RepositoryItem> managedItems = new ArrayList<RepositoryItem>();
        List<File> unmanagedItemFiles = new ArrayList<File>();
        RepositoryItem defaultItem = null;
        URL defaultItemUrl = null;

        for (JAXBElement<? extends ProjectItemType> jaxbItem : jaxbProject.getProjectItemBase()) {
            URL projectFolderUrl = URLUtils.toURL(projectFile.getParentFile());

            if (jaxbItem.getValue() instanceof UnmanagedProjectItemType) {
                UnmanagedProjectItemType projectItem = (UnmanagedProjectItemType) jaxbItem.getValue();
                try {
                    URL libraryUrl = URLUtils.getResolvedURL(projectItem.getFileLocation(), projectFolderUrl);
                    unmanagedItemFiles.add(URLUtils.toFile(libraryUrl));

                    if ((projectItem.isDefaultItem() != null) && projectItem.isDefaultItem()) {
                        defaultItemUrl = libraryUrl;
                    }

                } catch (MalformedURLException e) {
                    loaderFindings.addFinding(FindingType.ERROR, new FileValidationSource(projectFile),
                            LoaderValidationMessageKeys.ERROR_INVALID_PROJECT_ITEM_LOCATION,
                            projectItem.getFileLocation());
                }

            } else if (jaxbItem.getValue() instanceof ManagedProjectItemType) {
                ManagedProjectItemType projectItem = (ManagedProjectItemType) jaxbItem.getValue();
                try {
                    String repositoryId = projectItem.getRepository();
                    Repository repository;

                    if ((repositoryId != null) && (repositoryId.length() > 0)) {
                        repository = repositoryManager.getRepository(repositoryId);

                        if (repository == null) {
                            throw new RepositoryException("Unknown repository specified: " + repositoryId);
                        }
                    } else {
                        // If the item's repository ID was not explicitly specified, invoking
                        // the search on the
                        // repository manager will call will force a searchin all known
                        // repositories.
                        repository = repositoryManager;
                    }
                    RepositoryItem repositoryItem = repository.getRepositoryItem(projectItem.getBaseNamespace(),
                            projectItem.getFilename(), projectItem.getVersion());

                    if (repositoryItem.getRepository() == null) {
                        loaderFindings.addFinding(FindingType.ERROR, new FileValidationSource(projectFile),
                                LoaderValidationMessageKeys.ERROR_MISSING_REPOSITORY,
                                projectItem.getFilename());
                    }
                    if ((projectItem.isDefaultItem() != null) && projectItem.isDefaultItem()) {
                        defaultItem = repositoryItem;
                    }
                    managedItems.add(repositoryItem);

                } catch (RepositoryUnavailableException e) {
                    loaderFindings.addFinding(FindingType.ERROR, new FileValidationSource(projectFile),
                            LoaderValidationMessageKeys.ERROR_REPOSITORY_UNAVAILABLE, projectItem.getFilename(),
                            projectItem.getRepository());

                } catch (RepositoryException e) {
                    loaderFindings.addFinding(FindingType.ERROR, new FileValidationSource(projectFile),
                            LoaderValidationMessageKeys.ERROR_LOADING_FROM_REPOSITORY,
                            projectItem.getFilename(), e.getClass().getSimpleName(), e.getMessage());
                }
            }
        }

        // Attempt to load the project and its items into the current project manager session
        boolean success = false;
        try {
            loadAllProjectItems(unmanagedItemFiles, managedItems, project, loaderFindings);
            success = true;

        } finally {
            // If the load threw an exception, we need to discard the project and any items that
            // might have been loaded prior to the error
            if (!success) {
                projects.remove(project);
                purgeOrphanedProjectItems();
            }
        }

        // Assign the default project item
        if (defaultItemUrl != null) {
            AbstractLibrary defaultLib = model.getLibrary(defaultItemUrl);

            if (defaultLib != null) {
                project.setDefaultItem(getProjectItem(defaultLib));
            }

        } else if (defaultItem != null) {
            for (ProjectItem item : projectItems) {
                if ((item != null)
                        && ((item.getBaseNamespace() != null)
                                && item.getBaseNamespace().equals(defaultItem.getBaseNamespace()))
                        && ((item.getFilename() != null)
                                && item.getFilename().equals(defaultItem.getFilename()))
                        && ((item.getVersion() != null)
                                && item.getVersion().equals(defaultItem.getVersion()))) {
                    project.setDefaultItem(item);
                    break;
                }
            }
        }

        // Validate for errors/warnings if requested by the caller
        if (findings != null) {
            findings.addAll(TLModelValidator.validateModel(model, ValidatorFactory.COMPILE_RULE_SET_ID));
            findings.addAll(loaderFindings);
        }

        // Ensure that all of the project items were loaded, and place any that did
        // not in the 'failedProjectItems' list.
        for (JAXBElement<? extends ProjectItemType> jaxbItem : jaxbProject.getProjectItemBase()) {
            ProjectItemType item = jaxbItem.getValue();

            if (!isProjectItemLoaded(item, project)) {
                project.getFailedProjectItems().add(item);
            }
        }

    } else {
        throw new LibraryLoaderException("Unable to load project: " + projectFile.getName());
    }
    return project;
}