java.net.URISyntaxException Java Examples

The following examples show how to use java.net.URISyntaxException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MapReduceServiceImpl.java    From pentaho-hadoop-shims with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings( "squid:S2095" )
private Class<?> loadClassByName( final String className, final URL jarUrl, final ClassLoader parentClassLoader, boolean addConfigFiles )
  throws ClassNotFoundException, MalformedURLException, URISyntaxException {
  if ( className != null ) {
    // ignoring this warning; paths are to the local file system so no host name lookup should happen
    @SuppressWarnings( "squid:S2112" )
    Set<URL> urlSet = new HashSet<>();
    if ( addConfigFiles ) {
      List<URL> urlList = new ArrayList<>();
      ShimConfigsLoader.addConfigsAsResources( namedCluster.getName(), urlList::add );
      for ( URL url : urlList ) {
        // get the parent dir of each config file
        urlSet.add( Paths.get( url.toURI() ).getParent().toUri().toURL() );
      }
    }
    urlSet.add( jarUrl );
    URLClassLoader cl = new URLClassLoader( urlSet.toArray( new URL[0] ), parentClassLoader );
    return cl.loadClass( className.replace( "/", "." ) );
  } else {
    return null;
  }
}
 
Example #2
Source File: AtomEntryEntityProducer.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
private void appendAtomNavigationLink(final XMLStreamWriter writer, final String target,
    final String navigationPropertyName, final boolean isFeed, final EntityInfoAggregator eia,
    final Map<String, Object> data) throws EntityProviderException, EdmException, URISyntaxException {
  try {
    writer.writeStartElement(FormatXml.ATOM_LINK);
    writer.writeAttribute(FormatXml.ATOM_HREF, target);
    writer.writeAttribute(FormatXml.ATOM_REL, Edm.NAMESPACE_REL_2007_08 + navigationPropertyName);
    writer.writeAttribute(FormatXml.ATOM_TITLE, navigationPropertyName);
    if (isFeed) {
      writer.writeAttribute(FormatXml.ATOM_TYPE, ContentType.APPLICATION_ATOM_XML_FEED.toString());
      appendInlineFeed(writer, navigationPropertyName, eia, data, target);
    } else {
      writer.writeAttribute(FormatXml.ATOM_TYPE, ContentType.APPLICATION_ATOM_XML_ENTRY.toString());
      appendInlineEntry(writer, navigationPropertyName, eia, data);
    }
    writer.writeEndElement();
  } catch (XMLStreamException e) {
    throw new EntityProviderProducerException(EntityProviderException.COMMON, e);
  }
}
 
Example #3
Source File: PandorabotsAPI.java    From pb-java with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * composing URI for handling file.
 * <p>
 * URI form varies as follows depending on extension.<br>
 * <ul>
 * <li>/bot/{appId}/{botName}/{fileKind} for pdefaults, properties.
 * <li>/bot/{appId}/{botName}/{fileKind}/baseName for map, set,
 * substitution.
 * <li>/bot/{appId}/{botName}/file/baseName.extName for aiml.
 * </ul>
 * <p>
 * 
 * @param botName
 * @param pathName
 * @return URI for request
 * @throws URISyntaxException
 * @since 0.0.9
 */
private URI fileUri(String botName, String pathName)
		throws URISyntaxException {
	String baseName = FilenameUtils.getBaseName(pathName);
	String extName = FilenameUtils.getExtension(pathName);
	String fileKind = extName;
	String fileName = null;
	if (extName.equals("pdefaults") || extName.equals("properties")) {
		;
	} else if (extName.equals("map") || extName.equals("set")
			|| extName.equals("substitution")) {
		fileName = baseName;
	} else if (extName.equals("aiml")) {
		fileKind = "file";
		fileName = baseName + "." + extName;
	}
	return new URI(composeUri("bot", botName, fileKind, fileName)
			+ composeParams(null));
}
 
Example #4
Source File: AsciidocConverterTest.java    From swagger2markup with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithInlineSchemaAndFlatBody() throws URISyntaxException {
    //Given
    Path file = Paths.get(AsciidocConverterTest.class.getResource("/yaml/swagger_inlineSchema.yaml").toURI());
    Path outputDirectory = Paths.get("build/test/asciidoc/inline_schema_flat_body");
    FileUtils.deleteQuietly(outputDirectory.toFile());

    //When
    Swagger2MarkupConfig config =  new Swagger2MarkupConfigBuilder()
            .withFlatBody()
            .build();
    Swagger2MarkupConverter.from(file)
            .withConfig(config)
            .build()
            .toFolder(outputDirectory);

    //Then
    String[] files = outputDirectory.toFile().list();
    assertThat(files).hasSize(4).containsAll(expectedFiles);
    Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/asciidoc/inline_schema_flat_body").toURI());
    DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testWithInlineSchemaAndFlatBody.html");
}
 
Example #5
Source File: CreateManifest.java    From fxlauncher with Apache License 2.0 6 votes vote down vote up
public static FXManifest create(URI baseURI, String launchClass, Path appPath) throws IOException, URISyntaxException {
    FXManifest manifest = new FXManifest();
    manifest.ts = System.currentTimeMillis();
    manifest.uri = baseURI;
    manifest.launchClass = launchClass;

    if (!manifest.uri.getPath().endsWith("/")) {
        manifest.uri = new URI(String.format("%s/", baseURI.toString()));
    }
    Files.walkFileTree(appPath, new SimpleFileVisitor<Path>() {
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (!Files.isDirectory(file) && shouldIncludeInManifest(file) && !file.getFileName().toString().startsWith("fxlauncher"))
                manifest.files.add(new LibraryFile(appPath, file));
            return FileVisitResult.CONTINUE;
        }
    });

    return manifest;
}
 
Example #6
Source File: AbstractWrapperWSDLLocator.java    From cxf with Apache License 2.0 6 votes vote down vote up
public InputSource getImportInputSource(String parentLocation, String importLocation) {
    // Do a check on the scheme to see if it's anything that could be a security risk
    try {
        URI url = new URI(importLocation);
        if (!(url.getScheme() == null || ALLOWED_SCHEMES.contains(url.getScheme()))) {
            throw new IllegalArgumentException("The " + url.getScheme() + " URI scheme is not allowed");
        }
    } catch (URISyntaxException e) {
        // Just continue here as we might still be able to load it from the filesystem
    }

    InputSource src = parent.getImportInputSource(parentLocation, importLocation);
    lastImport = null;
    if (src == null || (src.getByteStream() == null && src.getCharacterStream() == null)) {
        src = getInputSource(parentLocation, importLocation);
        if (src != null) {
            lastImport = src.getSystemId();
        }
    }
    return src;
}
 
Example #7
Source File: CharsetConverterTest.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
@Test(expected=FileDecoderException.class)
public void testCharsetConverterCharsetCharsetInvalid() throws IOException, UnsupportedCharsetException, ConnectionException, RequestException, AccessException, NoSuchObjectException, ConfigException, ResourceException, URISyntaxException, FileDecoderException, FileEncoderException {
	File testResourceFile = loadFileFromClassPath(CLASS_PATH_PREFIX + "/euc-jp.txt");
	
	CharsetConverter convert = new CharsetConverter(PerforceCharsets.getP4Charset("shiftjis"), CharsetDefs.UTF8);
	
	InputStream inStream = new FileInputStream(testResourceFile);

	byte[] bytes = new byte[2048];
	int read = inStream.read(bytes);
	inStream.close();
	
	byte[] trueIn = new byte[read];
	System.arraycopy(bytes, 0, trueIn, 0, read);
	
	ByteBuffer bufIn  = ByteBuffer.wrap(bytes, 0, read);
	convert.convert(bufIn);
}
 
Example #8
Source File: Oauth2JwtClientTest.java    From components with Apache License 2.0 6 votes vote down vote up
@Test
public void testOK() throws UnsupportedEncodingException, IOException, InterruptedException, URISyntaxException {
    // start server
    JwtTestServer server = new JwtTestServer(UseCase.OK);
    Thread serverThread = new Thread(server);
    serverThread.start();

    Map<String, String> params = new HashMap<>();
    params.put("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer");

    // Get Access Token
    JsonNode accessToken = Oauth2JwtClient.builder()//
            .withJwsHeaders(jwsHeaders())//
            .withJwtClaims(claims())//
            .signWithX509Key(x509Key(), org.talend.components.common.oauth.X509Key.Algorithm.SHA256withRSA)//
            .fromTokenEndpoint("http://" + endpoint + ":" + server.getLocalPort())//
            .withPlayloadParams(params)//
            .build()//
            .getAccessToken();

    serverThread.join(30000);

    assertNotNull(accessToken);
    assertNotNull(accessToken.get("access_token"));
}
 
Example #9
Source File: UriResolver.java    From tomee with Apache License 2.0 6 votes vote down vote up
private void tryClasspath(String uriStr) throws IOException {
    if (uriStr.startsWith("classpath:")) {
        uriStr = uriStr.substring(10);
    }
    url = getResource(uriStr, calling);
    if (url == null) {
        tryRemote(uriStr);
    } else {
        try {
            uri = url.toURI();
        } catch (final URISyntaxException e) {
            // processing the jar:file:/ type value
            final String urlStr = url.toString();
            if (urlStr.startsWith("jar:")) {
                final int pos = urlStr.indexOf('!');
                if (pos != -1) {
                    uri = URLs.uri("classpath:" + urlStr.substring(pos + 1));
                }
            }

        }
        is = IO.read(url);
    }
}
 
Example #10
Source File: BotsHttpClient.java    From geoportal-server-harvester with Apache License 2.0 6 votes vote down vote up
private URI applyPHP(URI uri) throws ClientProtocolException  {
  if (bots!=null) {
    try {
      String orgUri = uri.toString();
      PHP php = parsePHP(bots.getHost());
      if (php!=null) {
        uri = updateURI(uri,php);
      }
      if (!uri.toString().equals(orgUri)) {
        LOG.debug(String.format("Uri updated from %s to %s", orgUri, uri));
      }
    } catch (URISyntaxException ex) {
      throw new ClientProtocolException("Unable to apply host robots.txt host directive.", ex);
    }
  }
  return uri;
}
 
Example #11
Source File: GameStateRunner.java    From magarena with GNU General Public License v3.0 6 votes vote down vote up
private JPanel getMainPanel() {

        try {
            testClasses = new JList<>(getListOfTestClasses());
        } catch (IOException | URISyntaxException ex) {
            System.err.println(ex);
        }

        testClasses.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        testClasses.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) {
                    loadTestClassAndRun(testClasses.getSelectedValue());
                }
            }
        });

        final JScrollPane listScroller = new JScrollPane(testClasses);
        listScroller.setPreferredSize(new Dimension(getWidth(), getHeight()));

        final JPanel panel = new JPanel(new MigLayout("insets 0, gap 0"));
        panel.add(listScroller, "w 100%, h 100%");
        return panel;
    }
 
Example #12
Source File: MockGitHubService.java    From apicurio-studio with Apache License 2.0 6 votes vote down vote up
/**
 * @see io.apicurio.hub.api.github.IGitHubSourceConnector#validateResourceExists(java.lang.String)
 */
@Override
public ApiDesignResourceInfo validateResourceExists(String repositoryUrl) throws NotFoundException {
    getAudit().add("validateResourceExists::" + repositoryUrl);
    if (repositoryUrl.endsWith("new-api.json")) {
        throw new NotFoundException();
    }
    try {
        URI uri = new URI(repositoryUrl);
        String name = new File(uri.getPath()).getName();
        ApiDesignResourceInfo info = new ApiDesignResourceInfo();
        info.setName(name);
        info.setDescription(repositoryUrl);
        info.setTags(new HashSet<String>(Arrays.asList("tag1", "tag2")));
        info.setType(ApiDesignType.OpenAPI20);
        return info;
    } catch (URISyntaxException e) {
        throw new NotFoundException();
    }
}
 
Example #13
Source File: SqlServerJdbcUrlCreator.java    From java-cfenv with Apache License 2.0 6 votes vote down vote up
@Override
public String buildJdbcUrlFromUriField(CfCredentials cfCredentials) {
	UriInfo uriInfo = cfCredentials.getUriInfo(SQLSERVER_SCHEME);
	Map<String, String> uriParameters = parseSqlServerUriParameters(uriInfo.getUriString());
	String databaseName = getDatabaseName(uriParameters);
	try {
		URI uri = new URI(uriInfo.getUriString().substring(0, uriInfo.getUriString().indexOf(";")));
		return String.format("jdbc:%s://%s:%d%s%s%s%s",
				SQLSERVER_SCHEME,
				uri.getHost(),
				uri.getPort(),
				uri.getPath() != null && !uri.getPath().isEmpty() ? "/" + uri.getPath() : "",
				databaseName != null ? ";database=" + UriInfo.urlEncode(databaseName) : "",
				uriParameters.containsKey("user") ? ";user=" +  UriInfo.urlEncode(uriParameters.get("user")) : "",
				uriParameters.containsKey("password") ? ";password=" +  UriInfo.urlEncode(uriParameters.get("password")) : ""
		);
	}
	catch (URISyntaxException e) {
		throw new RuntimeException(e);
	}
}
 
Example #14
Source File: TemplateManagerImpl.java    From cosmic with Apache License 2.0 6 votes vote down vote up
@Override
@ActionEvent(eventType = EventTypes.EVENT_TEMPLATE_CREATE, eventDescription = "creating template")
public VirtualMachineTemplate registerTemplate(final RegisterTemplateCmd cmd) throws URISyntaxException, ResourceAllocationException {
    final Account account = CallContext.current().getCallingAccount();
    if (cmd.getTemplateTag() != null) {
        if (!this._accountService.isRootAdmin(account.getId())) {
            throw new PermissionDeniedException("Parameter templatetag can only be specified by a Root Admin, permission denied");
        }
    }
    if (cmd.isRoutingType() != null) {
        if (!this._accountService.isRootAdmin(account.getId())) {
            throw new PermissionDeniedException("Parameter isrouting can only be specified by a Root Admin, permission denied");
        }
    }

    final TemplateAdapter adapter = getAdapter(HypervisorType.getType(cmd.getHypervisor()));
    final TemplateProfile profile = adapter.prepare(cmd);
    final VMTemplateVO template = adapter.create(profile);

    if (template != null) {
        return template;
    } else {
        throw new CloudRuntimeException("Failed to create a template");
    }
}
 
Example #15
Source File: ContainerCredentialsProvider.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Override
public URI getCredentialsEndpoint() throws URISyntaxException {
    String fullUri = System.getenv(CONTAINER_CREDENTIALS_FULL_URI);
    if (fullUri == null || fullUri.length() == 0) {
        throw new SdkClientException("The environment variable " + CONTAINER_CREDENTIALS_FULL_URI + " is empty");
    }

    URI uri = new URI(fullUri);

    if (!ALLOWED_FULL_URI_HOSTS.contains(uri.getHost())) {
        throw new SdkClientException("The full URI (" + uri + ") contained withing environment variable " +
            CONTAINER_CREDENTIALS_FULL_URI + " has an invalid host. Host can only be one of [" +
            CollectionUtils.join(ALLOWED_FULL_URI_HOSTS, ", ") + "]");
    }

    return uri;
}
 
Example #16
Source File: HttpEngine.java    From phonegapbootcampsite with MIT License 6 votes vote down vote up
/**
 * @param requestHeaders the client's supplied request headers. This class
 *     creates a private copy that it can mutate.
 * @param connection the connection used for an intermediate response
 *     immediately prior to this request/response pair, such as a same-host
 *     redirect. This engine assumes ownership of the connection and must
 *     release it when it is unneeded.
 */
public HttpEngine(OkHttpClient client, Policy policy, String method, RawHeaders requestHeaders,
    Connection connection, RetryableOutputStream requestBodyOut) throws IOException {
  this.client = client;
  this.policy = policy;
  this.method = method;
  this.connection = connection;
  this.requestBodyOut = requestBodyOut;

  try {
    uri = Platform.get().toUriLenient(policy.getURL());
  } catch (URISyntaxException e) {
    throw new IOException(e.getMessage());
  }

  this.requestHeaders = new RequestHeaders(uri, new RawHeaders(requestHeaders));
}
 
Example #17
Source File: AsciidocConverterTest.java    From swagger2markup with Apache License 2.0 6 votes vote down vote up
@Test
public void testInterDocumentCrossReferences() throws URISyntaxException {
    //Given
    Path file = Paths.get(AsciidocConverterTest.class.getResource("/yaml/swagger_petstore.yaml").toURI());
    Path outputDirectory = Paths.get("build/test/asciidoc/idxref");
    FileUtils.deleteQuietly(outputDirectory.toFile());

    //When
    Swagger2MarkupConfig config =  new Swagger2MarkupConfigBuilder()
            .withInterDocumentCrossReferences()
            .build();

    Swagger2MarkupConverter.from(file).withConfig(config).build()
            .toFolder(outputDirectory);

    //Then
    String[] files = outputDirectory.toFile().list();
    assertThat(files).hasSize(4).containsAll(expectedFiles);

    Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/asciidoc/idxref").toURI());
    DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testInterDocumentCrossReferences.html");
}
 
Example #18
Source File: AbstractYarnClusterDescriptor.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Uploads and registers a single resource and adds it to <tt>localResources</tt>.
 *
 * @param key
 * 		the key to add the resource under
 * @param fs
 * 		the remote file system to upload to
 * @param appId
 * 		application ID
 * @param localSrcPath
 * 		local path to the file
 * @param localResources
 * 		map of resources
 *
 * @return the remote path to the uploaded resource
 */
private static Path setupSingleLocalResource(
		String key,
		FileSystem fs,
		ApplicationId appId,
		Path localSrcPath,
		Map<String, LocalResource> localResources,
		Path targetHomeDir,
		String relativeTargetPath) throws IOException, URISyntaxException {

	Tuple2<Path, LocalResource> resource = Utils.setupLocalResource(
		fs,
		appId.toString(),
		localSrcPath,
		targetHomeDir,
		relativeTargetPath);

	localResources.put(key, resource.f1);

	return resource.f0;
}
 
Example #19
Source File: Test_ConfigurationRepository.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUpTest_ConfigurationRepository() throws URISyntaxException {

    URL configFile1URL = Test_ConfigurationRepository.class.getResource(configFile1Name);
    configFile1 = new File(configFile1URL.toURI());

    URL configFile2URL = Test_ConfigurationRepository.class.getResource(configFile2Name);
    configFile2 = new File(configFile2URL.toURI());
}
 
Example #20
Source File: BWAMemInstance.java    From halvade with GNU General Public License v3.0 5 votes vote down vote up
static public BWAMemInstance getBWAInstance(Mapper.Context context, String bin) throws IOException, InterruptedException, URISyntaxException {
    if(instance == null) {
        instance = new BWAMemInstance(context, bin);
        instance.startAligner(context);
    }
    BWAMemInstance.context = context;
    return instance;
}
 
Example #21
Source File: ZipExtractorProviderTest.java    From appengine-plugins-core with Apache License 2.0 5 votes vote down vote up
@Test
public void testZipSlipVulnerability_windows() throws URISyntaxException {
  Assume.assumeTrue(System.getProperty("os.name").startsWith("Windows"));

  Path extractionRoot = tmp.getRoot().toPath();
  Path testArchive = getResource("zipSlipSamples/zip-slip-win.zip");
  try {
    zipExtractorProvider.extract(testArchive, extractionRoot, mockProgressListener);
    Assert.fail("IOException expected");
  } catch (IOException expected) {
    MatcherAssert.assertThat(
        expected.getMessage(),
        CoreMatchers.startsWith("Blocked unzipping files outside destination: "));
  }
}
 
Example #22
Source File: TestFile.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static URI toUri(URL url) {
    try {
        return url.toURI();
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
}
 
Example #23
Source File: SitestreamControllerTest.java    From hbc with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddUsers() throws IOException, ControlStreamException, URISyntaxException {
  SitestreamController controlstreams = setupSimplControlStreamRequest(200, "{}");
  controlstreams.addUsers("mock_stream_id", Longs.asList(1111, 2222, 3333, 4444));
  Mockito.verify(client).execute(argThat(new ArgumentValidator<HttpPost>() {
    public void validate(HttpPost post) throws Exception {
      assertEquals("application/x-www-form-urlencoded", post.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());
      assertEquals("https://host.com/1.1/site/c/mock_stream_id/add_user.json", post.getURI().toString());
      assertEquals("user_id=1111%2C2222%2C3333%2C4444", consumeUtf8String(post.getEntity().getContent()));
    }
  }));
}
 
Example #24
Source File: MinimizedFrame.java    From Repeat with Apache License 2.0 5 votes vote down vote up
private void show() {
	if (!Desktop.isDesktopSupported()) {
		LOGGER.warning("Cannot open browser to UI since Desktop module is not supported.");
		return;
	}

	IIPCService server = IPCServiceManager.getIPCService(IPCServiceName.WEB_UI_SERVER);
	try {
		Desktop.getDesktop().browse(new URI("http://localhost:" + server.getPort()));
	} catch (IOException | URISyntaxException ex) {
		LOGGER.log(Level.WARNING, "Failed to show UI in browser.", ex);
	}
}
 
Example #25
Source File: FileStream.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
private String getFilePath( String path ) {
  try {
    final FileObject fileObject = KettleVFS.getFileObject( environmentSubstitute( path ) );
    if ( !fileObject.exists() ) {
      throw new FileNotFoundException( path );
    }
    return Paths.get( fileObject.getURL().toURI() ).normalize().toString();
  } catch ( URISyntaxException | FileNotFoundException | FileSystemException | KettleFileException e ) {
    propagate( e );
  }
  return null;
}
 
Example #26
Source File: UDDIKeyConvention.java    From juddi with Apache License 2.0 5 votes vote down vote up
public static String getBindingKey(Properties properties, QName serviceName, String portName, URL bindingUrl) {
	
	String bindingKey = null;
	try {
		URI bindingURI = bindingUrl.toURI();
		bindingKey =  getBindingKey(properties, serviceName, portName, bindingURI);
	} catch (URISyntaxException e) {
		
	}
	return bindingKey;
	
}
 
Example #27
Source File: Test.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
static void eq0(URI u, URI v) throws URISyntaxException {
    testCount++;
    if (!u.equals(v))
        throw new RuntimeException("Not equal: " + u + " " + v);
    int uh = u.hashCode();
    int vh = v.hashCode();
    if (uh != vh)
        throw new RuntimeException("Hash codes not equal: "
                                   + u + " " + Integer.toHexString(uh) + " "
                                   + v + " " + Integer.toHexString(vh));
    out.println();
    out.println(u + " == " + v
                + "  [" + Integer.toHexString(uh) + "]");
}
 
Example #28
Source File: CloudFileTests.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testCloudFileDownloadRangeToByteArrayNegativeTest() throws URISyntaxException, StorageException,
        IOException {
    CloudFile file = this.share.getRootDirectoryReference().getFileReference(
            FileTestHelper.generateRandomFileName());
    FileTestHelper.doDownloadRangeToByteArrayNegativeTests(file);
}
 
Example #29
Source File: RegisteredURIResolutionTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void httpURL() throws URISyntaxException {
    SchemaClient mock = mock(SchemaClient.class);
    SchemaLoader loader = SchemaLoader.builder()
            .schemaClient(mock)
            .schemaJson(LOADER.readObj("ref-example-org.json"))
            .registerSchemaByURI(new URI("http://example.org"), LOADER.readObj("schema-by-urn.json"))
            .build();

    ReferenceSchema actual = (ReferenceSchema) loader.load().build();

    assertEquals("schema-by-urn", actual.getReferredSchema().getTitle());
    verifyNoMoreInteractions(mock);
}
 
Example #30
Source File: UncFile.java    From geoportal-server-harvester with Apache License 2.0 5 votes vote down vote up
/**
 * Reads content.
 * @return content reference
 * @throws IOException if reading content fails
 * @throws URISyntaxException if file url is an invalid URI
 */
public SimpleDataReference readContent() throws IOException, URISyntaxException {
  Date lastModifiedDate = readLastModifiedDate();
  MimeType contentType = readContentType();
  try (InputStream input = Files.newInputStream(file)) {
    SimpleDataReference ref = new SimpleDataReference(broker.getBrokerUri(), broker.getEntityDefinition().getLabel(), file.toAbsolutePath().toString(), lastModifiedDate, file.toUri(), broker.td.getSource().getRef(), broker.td.getRef());
    ref.addContext(contentType, IOUtils.toByteArray(input));
    return ref;
  }
}