Java Code Examples for java.net.URISyntaxException

The following are top voted examples for showing how to use java.net.URISyntaxException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: FirefoxData-android   File: BaseResource.java   View source code 6 votes vote down vote up
public BaseResource(URI uri, boolean rewrite) {
  if (uri == null) {
    throw new IllegalArgumentException("uri must not be null");
  }
  if (rewrite && "localhost".equals(uri.getHost())) {
    // Rewrite localhost URIs to refer to the special Android emulator loopback passthrough interface.
    Logger.debug(LOG_TAG, "Rewriting " + uri + " to point to " + ANDROID_LOOPBACK_IP + ".");
    try {
      this.uri = new URI(uri.getScheme(), uri.getUserInfo(), ANDROID_LOOPBACK_IP, uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());
    } catch (URISyntaxException e) {
      Logger.error(LOG_TAG, "Got error rewriting URI for Android emulator.", e);
      throw new IllegalArgumentException("Invalid URI", e);
    }
  } else {
    this.uri = uri;
  }
}
 
Example 2
Project: kheera   File: TestExecutionController.java   View source code 6 votes vote down vote up
public AbstractPage addPageObject(AbstractPage p) {
	String url = p.forUrl();
	if(!mapper.containsKey(url)){
		mapper.put(url, p);
		String currentUrl = null;
		try{
			String currUrl = driver.getCurrentUrl();
			URI url2 = new URI(currUrl);
			String path = url2.getPath();
			currentUrl = currUrl.substring(0, currUrl.indexOf(path));
		}catch (URISyntaxException e) {
			e.printStackTrace();
		} catch(NullPointerException npe){
			currentUrl = baseUrl;
		}
		p.setBaseUrl(baseUrl.equals(currentUrl) ? baseUrl: currentUrl);
		PageFactory.initElements(driver, p);
	}
	return mapper.get(url);
}
 
Example 3
Project: gate-core   File: MainFrame.java   View source code 6 votes vote down vote up
private String getPluginName(URL url) {

      // url.getPath() works for jar URLs; url.toURI().getPath() doesn't
      // because jars aren't considered "hierarchical"
      String name = url.getPath();
      
      //remove the '/creole.xml' from the end
      name = name.substring(0, name.length() - 11);
      
      //get everything after the last /
      int lastSlash = name.lastIndexOf("/");
      if(lastSlash != -1) {
        name = name.substring(lastSlash + 1);
      }
      
      try {
        // convert to (relative) URI and extract path. This will
        // decode any %20 escapes in the name.
        name = new URI(name).getPath();
      } catch(URISyntaxException ex) {
        // ignore, this should have been checked when adding the URL!
      }
      
      return name;
    }
 
Example 4
Project: MaximoForgeViewerPlugin   File: ForgeRS.java   View source code 6 votes vote down vote up
@POST
   @Produces(MediaType.APPLICATION_JSON)
   @Path("bucket/{bucketKey}")
   public Response bucketCreate(
    	@Context HttpServletRequest request,
	@PathParam("bucketKey") String bucketKey,
	@QueryParam("policy") String policy,
	@QueryParam("region") String region
) 
	throws IOException, 
	       URISyntaxException 
   {
   	APIImpl impl = getAPIImpl( request );
   	if( impl == null )
   	{
           return Response.status( Response.Status.UNAUTHORIZED ).build();     
   	}
   	Result result = impl.bucketCreate( bucketKey, policy, region );
   	return formatReturn( result );
   }
 
Example 5
Project: Sem-Update   File: VentanaPrincipal.java   View source code 6 votes vote down vote up
private void jButtonIniciarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonIniciarActionPerformed
    try {      
        // Consumiendo web service
        String json = iniciarServidor();
        user = new Gson().fromJson(json, Pc.class);
        System.out.println("Recibido: " + user);
        
        jLabel1.setForeground(Color.green);
        Desktop.getDesktop().browse(new URI("http://" + ip + ":" + user.getPuertoPHP() + "/phpmyadmin"));
        url.setText("http://" + ip + ":" + user.getPuertoPHP() + "/phpmyadmin");
        jlabelSQL.setText("PuertoSQL: " + user.getPuertoSQL());
        this.setTitle("App [ID:" + user.getId() + "]");

    } catch (IOException | URISyntaxException ex) {
        Logger.getLogger(VentanaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example 6
Project: hadoop   File: TestJobEndNotifier.java   View source code 6 votes vote down vote up
@Override
public void doGet(HttpServletRequest request, 
                  HttpServletResponse response
                  ) throws ServletException, IOException {
  InputStreamReader in = new InputStreamReader(request.getInputStream());
  PrintStream out = new PrintStream(response.getOutputStream());

  calledTimes++;
  try {
    requestUri = new URI(null, null,
        request.getRequestURI(), request.getQueryString(), null);
  } catch (URISyntaxException e) {
  }

  in.close();
  out.close();
}
 
Example 7
Project: CustomWorldGen   File: ModClassLoader.java   View source code 6 votes vote down vote up
public File[] getParentSources() {
    try
    {
        List<File> files=new ArrayList<File>();
        for(URL url : mainClassLoader.getSources())
        {
            URI uri = url.toURI();
            if(uri.getScheme().equals("file"))
            {
                files.add(new File(uri));
            }
        }
        return files.toArray(new File[]{});
    }
    catch (URISyntaxException e)
    {
        FMLLog.log(Level.ERROR, e, "Unable to process our input to locate the minecraft code");
        throw new LoaderException(e);
    }
}
 
Example 8
Project: minikube-build-tools-for-java   File: CachedLayerTest.java   View source code 6 votes vote down vote up
@Test
public void testGetBlob() throws URISyntaxException, IOException {
  Path fileA = Paths.get(Resources.getResource("fileA").toURI());
  String expectedFileAString = new String(Files.readAllBytes(fileA), StandardCharsets.UTF_8);

  CachedLayer cachedLayer = new CachedLayer(fileA, mockBlobDescriptor, mockDiffId);

  ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  Blob fileBlob = cachedLayer.getBlob();
  fileBlob.writeTo(outputStream);

  Assert.assertEquals(
      expectedFileAString, new String(outputStream.toByteArray(), StandardCharsets.UTF_8));
  Assert.assertEquals(mockBlobDescriptor, cachedLayer.getBlobDescriptor());
  Assert.assertEquals(mockDiffId, cachedLayer.getDiffId());
}
 
Example 9
Project: Reer   File: GradleRuntimeShadedJarDetector.java   View source code 6 votes vote down vote up
public static boolean isLoadedFrom(Class<?> clazz) {
    if (clazz == null) {
        throw new IllegalArgumentException("Need to provide valid class reference");
    }

    CodeSource codeSource = clazz.getProtectionDomain().getCodeSource();

    if (codeSource != null) {
        URL location = codeSource.getLocation();

        if (isJarUrl(location)) {
            try {
                return findMarkerFileInJar(new File(location.toURI()));
            } catch (URISyntaxException e) {
                throw UncheckedException.throwAsUncheckedException(e);
            }
        }
    }

    return false;
}
 
Example 10
Project: incubator-netbeans   File: RepositoryPreferences.java   View source code 6 votes vote down vote up
/**
 * if the repository has a mirror, then create a repositoryinfo object for it..
 */

private RepositoryInfo getMirrorInfo(RepositoryInfo info, MirrorSelector selector, Settings settings) {
    RemoteRepository original = new RemoteRepository.Builder(info.getId(), /* XXX do we even support any other layout?*/"default", info.getRepositoryUrl()).build();
    RemoteRepository mirror = selector.getMirror(original);
    if (mirror != null) {
        try {
            String name = mirror.getId();
            //#213078 need to lookup name for mirror
            for (Mirror m : settings.getMirrors()) {
                if (m.getId() != null && m.getId().equals(mirror.getId())) {
                    name = m.getName();
                    break;
                }
            }
            RepositoryInfo toret = new RepositoryInfo(mirror.getId(), name, null, mirror.getUrl());
            toret.setMirrorStrategy(RepositoryInfo.MirrorStrategy.NONE);
            return toret;
        } catch (URISyntaxException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
    return null;
}
 
Example 11
Project: incubator-netbeans   File: AutoUpdateCatalogParser.java   View source code 6 votes vote down vote up
private static URL getDistribution (String distribution, URI base) {
    URL retval = null;
    if (distribution != null && distribution.length () > 0) {
        try {
            URI distributionURI = new URI (distribution);
            if (! distributionURI.isAbsolute ()) {
                if (base != null) {
                    distributionURI = base.resolve (distributionURI);
                }
            }
            retval = distributionURI.toURL ();
        } catch (MalformedURLException | URISyntaxException ex) {
            ERR.log (Level.INFO, null, ex);
        }
    }
    return retval;
}
 
Example 12
Project: groupsio-api-java   File: MemberResource.java   View source code 6 votes vote down vote up
/**
 * Send a bounce probe to a user if they are bouncing
 * 
 * @param groupId
 *            of the group they belong to
 * @param subscriptionId
 *            of the subscription they have
 * @return the user's {@link Subscription}
 * @throws URISyntaxException
 * @throws IOException
 * @throws GroupsIOApiException
 */
public Subscription sendBounceProbe(final Integer groupId, final Integer subscriptionId)
        throws URISyntaxException, IOException, GroupsIOApiException
{
    if (apiClient.group().getPermissions(groupId).getManageMemberSubscriptionOptions()
            && getMemberInGroup(groupId, subscriptionId).getUserStatus().canSendBounceProbe())
    {
        final URIBuilder uri = new URIBuilder().setPath(baseUrl + "sendbounceprobe");
        uri.setParameter("group_id", groupId.toString());
        uri.setParameter("sub_id", subscriptionId.toString());
        final HttpRequestBase request = new HttpGet();
        request.setURI(uri.build());
        
        return callApi(request, Subscription.class);
    }
    else
    {
        final Error error = new Error();
        error.setType(GroupsIOApiExceptionType.INADEQUATE_PERMISSIONS);
        throw new GroupsIOApiException(error);
    }
}
 
Example 13
Project: OpenJSharp   File: JCmd.java   View source code 6 votes vote down vote up
private static String getMainClass(VirtualMachineDescriptor vmd)
        throws URISyntaxException, MonitorException {
    try {
        String mainClass = null;
        VmIdentifier vmId = new VmIdentifier(vmd.id());
        MonitoredHost monitoredHost = MonitoredHost.getMonitoredHost(vmId);
        MonitoredVm monitoredVm = monitoredHost.getMonitoredVm(vmId, -1);
        mainClass = MonitoredVmUtil.mainClass(monitoredVm, true);
        monitoredHost.detach(monitoredVm);
        return mainClass;
    } catch(NullPointerException e) {
        // There is a potential race, where a running java app is being
        // queried, unfortunately the java app has shutdown after this
        // method is started but before getMonitoredVM is called.
        // If this is the case, then the /tmp/hsperfdata_xxx/pid file
        // will have disappeared and we will get a NullPointerException.
        // Handle this gracefully....
        return null;
    }
}
 
Example 14
Project: q-mail   File: AccountSetupAccountType.java   View source code 6 votes vote down vote up
private void setupEWS() throws URISyntaxException {
    URI uriForDecode = new URI(mAccount.getStoreUri());

    //TODO: Different EWS auth types?
    /*
     * The user info we have been given from
     * AccountSetupBasics.onManualSetup() is encoded as an IMAP store
     * URI: AuthType:UserName:Password (no fields should be empty).
     * However, AuthType is not applicable to EWS nor to its store
     * URI. Re-encode without it, using just the UserName and Password.
     */
    String userPass = "";
    String[] userInfo = uriForDecode.getUserInfo().split(":");
    if (userInfo.length > 1) {
        userPass = userInfo[1];
    }
    if (userInfo.length > 2) {
        userPass = userPass + ":" + userInfo[2];
    }

    String domainPart = EmailHelper.getDomainFromEmailAddress(mAccount.getEmail());
    String suggestedServerName = serverNameSuggester.suggestServerName(EWS, domainPart);
    URI uri = new URI("ews+ssl+", userPass, suggestedServerName, uriForDecode.getPort(),
            "/"+ ExchangeVersion.Exchange2010_SP2.name()+"/EWS/Exchange.asmx", null, null);
    mAccount.setStoreUri(uri.toString());
}
 
Example 15
Project: weixin_api   File: OpenApi.java   View source code 6 votes vote down vote up
/**
 * 获取公众号基本信息。
 * 
 * @param mpAppid
 * @return
 * @throws ClientProtocolException
 * @throws URISyntaxException
 * @throws IOException
 * @throws AccessTokenFailException
 */
public GetAuthorizerInfo apiGetAuthorizerInfo(String mpAppid)
		throws ClientProtocolException, URISyntaxException, IOException, AccessTokenFailException {

	// 检查MpAccessToken是否存在
	AuthorizerAccessToken mpToken = runtime.getMpAuthorizerToken(mpAppid);
	if (mpToken == null) {
		throw new IllegalStateException("无法获取公众号基本信息,因为MpAccessToken不存在");
	}

	ComponentAccessToken caToken = apiComponentToken();
	// 构建请求参数进行获取
	TreeMap<String, String> reqMsg = new TreeMap<String, String>();
	reqMsg.put("component_appid", config.getComponentAppid());
	reqMsg.put("authorizer_appid", mpAppid);
	String path = String.format("/component/api_get_authorizer_info?component_access_token=%s",
			caToken.getComponentAccessToken());

	String respText = HttpUtil.post(config.getApiHttps(), path, reqMsg);
	GetAuthorizerInfo resp = new Gson().fromJson(respText, GetAuthorizerInfo.class);
	if (log.isInfoEnabled()) {
		log.info(String.format("apiGetAuthorizerInfo %s", resp));
	}

	return resp;
}
 
Example 16
Project: spring-hateoas-examples   File: HomeController.java   View source code 6 votes vote down vote up
/**
 * Instead of putting the creation link from the remote service in the template (a security concern),
 * have a local route for {@literal POST} requests. Gather up the information, and form a remote call,
 * using {@link Traverson} to fetch the {@literal employees} {@link Link}.
 *
 * Once a new employee is created, redirect back to the root URL.
 *
 * @param employee
 * @return
 * @throws URISyntaxException
 */
@PostMapping("/employees")
public String newEmployee(@ModelAttribute Employee employee) throws URISyntaxException {

	Traverson client = new Traverson(new URI(REMOTE_SERVICE_ROOT_URI), MediaTypes.HAL_JSON);
	Link employeesLink = client
		.follow("employees")
		.asLink();

	this.rest.postForEntity(employeesLink.expand().getHref(), employee, Employee.class);

	return "redirect:/";
}
 
Example 17
Project: GitHub   File: HpackJsonUtil.java   View source code 6 votes vote down vote up
/** Iterate through the hpack-test-case resources, only picking stories for the current draft. */
public static String[] storiesForCurrentDraft() throws URISyntaxException {
  File testCaseDirectory = new File(HpackJsonUtil.class.getResource("/hpack-test-case").toURI());
  List<String> storyNames = new ArrayList<>();
  for (File path : testCaseDirectory.listFiles()) {
    if (path.isDirectory() && Arrays.asList(path.list()).contains("story_00.json")) {
      try {
        Story firstStory = readStory(new File(path, "story_00.json"));
        if (firstStory.getDraft() >= BASE_DRAFT) {
          storyNames.add(path.getName());
        }
      } catch (IOException ignored) {
        // Skip this path.
      }
    }
  }
  return storyNames.toArray(new String[storyNames.size()]);
}
 
Example 18
Project: buenojo   File: SatelliteImageResource.java   View source code 6 votes vote down vote up
@RequestMapping(value= "/satelliteImages/upload",
		method = RequestMethod.POST,
		produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<SatelliteImage> uploadSatelliteImage(@RequestParam("imageFile")MultipartFile imageFile, @RequestParam("metadata") MultipartFile csvMetadataFile) throws URISyntaxException, InvalidSatelliteImageType, IOException, BuenOjoFileException, BuenOjoInconsistencyException{
	if (imageFile == null)
		return ResponseEntity.badRequest().headers(HeaderUtil.createBadRequestHeaderAlert("Image file parameter missing")).body(null);
	if (csvMetadataFile == null)
		return ResponseEntity.badRequest().headers(HeaderUtil.createBadRequestHeaderAlert("CSV file parameter missing")).body(null);



	SatelliteImage satelliteImage;

	try {
		satelliteImage = satelliteImageFactory.imageFromFile(imageFile, csvMetadataFile);
	} catch (BuenOjoCSVParserException b){
		return ResponseEntity.badRequest().headers(HeaderUtil.createBadRequestHeaderAlert("CSV file format incorrect")).body(null);
	}
	return createSatelliteImage(satelliteImage);
}
 
Example 19
Project: minikube-build-tools-for-java   File: V22ManifestTemplateTest.java   View source code 6 votes vote down vote up
@Test
public void testToJson() throws DigestException, IOException, URISyntaxException {
  // Loads the expected JSON string.
  Path jsonFile = Paths.get(Resources.getResource("json/v22manifest.json").toURI());
  String expectedJson = new String(Files.readAllBytes(jsonFile), StandardCharsets.UTF_8);

  // Creates the JSON object to serialize.
  V22ManifestTemplate manifestJson = new V22ManifestTemplate();

  manifestJson.setContainerConfiguration(
      1000,
      DescriptorDigest.fromDigest(
          "sha256:8c662931926fa990b41da3c9f42663a537ccd498130030f9149173a0493832ad"));

  manifestJson.addLayer(
      1000_000,
      DescriptorDigest.fromHash(
          "4945ba5011739b0b98c4a41afe224e417f47c7c99b2ce76830999c9a0861b236"));

  // Serializes the JSON object.
  ByteArrayOutputStream jsonStream = new ByteArrayOutputStream();
  JsonTemplateMapper.writeJson(jsonStream, manifestJson);

  Assert.assertEquals(expectedJson, jsonStream.toString());
}
 
Example 20
Project: MaximoForgeViewerPlugin   File: ViewableDownloadBubble.java   View source code 6 votes vote down vote up
/**
 * @param args
 * @throws URISyntaxException 
 * @throws IOException 
 */
public static void main(
    String[] arg
   )
	throws IOException, 
	   URISyntaxException 
{
	if( arg.length != 2 )
	{
		System.out.println( "Usage: viewableDownloadBubble urn derivitive fileName" );
		return;
	}
	ViewableDownloadBubble download = new ViewableDownloadBubble();
	
	Result result = download.viewableDownload( arg[0], arg[1] );
	if( result.isError() )
	{
		System.out.println( result.toString() );
		return;
	}
}
 
Example 21
Project: MaximoForgeViewerPlugin   File: DataRESTAPI.java   View source code 6 votes vote down vote up
public Result viewableDeregister(
		String viewableURN
	) 
	    throws IOException, 
	           URISyntaxException
	{
		String scope[] = { SCOPE_DATA_READ, SCOPE_DATA_WRITE };
		ResultAuthentication authResult = authenticate( scope );
		if( authResult.isError() )
		{
			return authResult;
		}

		viewableURN = new String( Base64.encodeBase64( viewableURN.getBytes() ) );
		String params[] = { viewableURN };
		String frag = makeURN( API_VIEWING, PATT_VIEW_DEREGISTER, params );
		
		URI uri = new URI( _protocol, null, lookupHostname(), _port, frag, null, null );

		URL url = new URL( uri.toASCIIString() );
		HttpURLConnection connection = (HttpURLConnection)url.openConnection();

		connection.setRequestMethod( "DELETE" );
		authResult.setAuthHeader( connection );
//        connection.setRequestProperty( "Accept", "Application/json" );
		
		return new Result( connection );
	}
 
Example 22
Project: incubator-netbeans   File: J2SEModularProjectProperties.java   View source code 6 votes vote down vote up
private void validateURL(final URL url, final File file) {
    try {
        final URI uri = url.toURI();
        if (!uri.isAbsolute()) {
            throw new IllegalArgumentException("URI is not absolute: " + uri.toString() + " File: " + file.getAbsolutePath());   //NOI18N
        }
        if (uri.isOpaque()) {
            throw new IllegalArgumentException("URI is not hierarchical: " + uri.toString() + " File: " + file.getAbsolutePath());   //NOI18N
        }
        if (!"file".equals(uri.getScheme())) {
            throw new IllegalArgumentException("URI scheme is not \"file\": " + uri.toString() + " File: " + file.getAbsolutePath());   //NOI18N
        }
    } catch (URISyntaxException use) {
        throw new IllegalArgumentException(use);
    }
}
 
Example 23
Project: rapidminer   File: ExcelResultSetAdapterTest.java   View source code 6 votes vote down vote up
@Test(expected = IndexOutOfBoundsException.class)
public void testAccessOutOfColumnBoundsImport()
		throws DataSetException, OperatorException, URISyntaxException, ParseException {
	try (ExcelResultSetConfiguration configuration = new ExcelResultSetConfiguration()) {
		// configure data import
		configuration.setWorkbookFile(testFile);
		configuration.setSheet(1);

		try (ExcelResultSetAdapter excelResultSet = makeResultSet(configuration, 0, 100)) {
			assertTrue(excelResultSet.hasNext());

			while (excelResultSet.hasNext()) {
				excelResultSet.nextRow().getString(5);
			}
		}
	}
}
 
Example 24
Project: devops-cstack   File: SimpleDockerDriver.java   View source code 6 votes vote down vote up
@Override
public DockerResponse removeNetwork(Network network) throws FatalDockerJSONException {
    URI uri = null;
    String body = new String();
    DockerResponse dockerResponse = null;
    try {
        uri = new URIBuilder().setScheme(NamingUtils.getProtocolSocket(isUnixSocket, mode)).setHost(host).setPath("/networks/" + network.getId()).build();
        dockerResponse = client.sendDelete(uri, false);
    } catch (URISyntaxException | JSONClientException e) {
        StringBuilder contextError = new StringBuilder(256);
        contextError.append("uri : " + uri + " - ");
        contextError.append("request body : " + body + " - ");
        contextError.append("server response : " + dockerResponse);
        logger.error(contextError.toString());
        throw new FatalDockerJSONException("An error has occurred for removeImage request due to " + e.getMessage(),
                e);
    }
    return dockerResponse;
}
 
Example 25
Project: weixin_api   File: MpUserApi.java   View source code 5 votes vote down vote up
/**
 * 获取用户列表
 * 
 * @param nextOpenid
 * @return
 * @throws ClientProtocolException
 * @throws URISyntaxException
 * @throws IOException
 * @throws AccessTokenFailException
 */
public UserGetResp apiUserGet(String nextOpenid)
		throws ClientProtocolException, URISyntaxException, IOException, AccessTokenFailException {
	MpAccessToken token = mpApi.apiToken();
	String path = String.format("/user/get?access_token=%s&next_openid=%s", token, nextOpenid);

	String respText = HttpUtil.get(mpApi.config.getApiHttps(), path);
	UserGetResp resp = new Gson().fromJson(respText, UserGetResp.class);
	if (mpApi.log.isInfoEnabled()) {
		mpApi.log.info(String.format("apiUserGet %s", new Gson().toJson(resp)));
	}
	return resp;
}
 
Example 26
Project: joal   File: TrackerClientTest.java   View source code 5 votes vote down vote up
@Test
public void shouldThrowAnnounceExceptionWhenMessageIsAnErrorMessageOnHandleTrackerResponse() throws URISyntaxException, IOException, TrackerMessage.MessageValidationException {
    final TorrentWithStats torrent = Mockito.mock(TorrentWithStats.class);
    final ConnectionHandler connectionHandler = Mockito.mock(ConnectionHandler.class);
    final URI uri = new URI("http://example.tracker.com/announce");

    final DefaultTrackerClient trackerClient = new DefaultTrackerClient(torrent, connectionHandler, uri);

    final TrackerMessage.ErrorMessage message = HTTPTrackerErrorMessage.craft(TrackerMessage.ErrorMessage.FailureReason.UNKNOWN_TORRENT.getMessage());

    assertThatThrownBy(() -> trackerClient.handleTrackerAnnounceResponse((TrackerMessage) message))
            .isInstanceOf(AnnounceException.class)
            .hasMessage(TrackerMessage.ErrorMessage.FailureReason.UNKNOWN_TORRENT.getMessage());
}
 
Example 27
Project: jhipster-microservices-example   File: ProductResource.java   View source code 5 votes vote down vote up
/**
 * POST  /products : Create a new product.
 *
 * @param product the product to create
 * @return the ResponseEntity with status 201 (Created) and with body the new product, or with status 400 (Bad Request) if the product has already an ID
 * @throws URISyntaxException if the Location URI syntax is incorrect
 */
@PostMapping("/products")
@Timed
public ResponseEntity<Product> createProduct(@Valid @RequestBody Product product) throws URISyntaxException {
    log.debug("REST request to save Product : {}", product);
    if (product.getId() != null) {
        return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new product cannot already have an ID")).body(null);
    }
    Product result = productRepository.save(product);
    return ResponseEntity.created(new URI("/api/products/" + result.getId()))
        .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
        .body(result);
}
 
Example 28
Project: buenojo   File: TagPairResource.java   View source code 5 votes vote down vote up
/**
 * PUT  /tagPairs -> Updates an existing tagPair.
 */
@RequestMapping(value = "/tagPairs",
    method = RequestMethod.PUT,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<TagPair> updateTagPair(@Valid @RequestBody TagPair tagPair) throws URISyntaxException {
    log.debug("REST request to update TagPair : {}", tagPair);
    if (tagPair.getId() == null) {
        return createTagPair(tagPair);
    }
    TagPair result = tagPairRepository.save(tagPair);
    return ResponseEntity.ok()
        .headers(HeaderUtil.createEntityUpdateAlert("tagPair", tagPair.getId().toString()))
        .body(result);
}
 
Example 29
Project: Armory   File: ProgramResource.java   View source code 5 votes vote down vote up
/**
 * PUT  /programs : Updates an existing program.
 *
 * @param programDTO the programDTO to update
 * @return the ResponseEntity with status 200 (OK) and with body the updated programDTO,
 * or with status 400 (Bad Request) if the programDTO is not valid,
 * or with status 500 (Internal Server Error) if the programDTO couldnt be updated
 * @throws URISyntaxException if the Location URI syntax is incorrect
 */
@PutMapping("/programs")
@Timed
public ResponseEntity<ProgramDTO> updateProgram(@Valid @RequestBody ProgramDTO programDTO) throws URISyntaxException {
    log.debug("REST request to update Program : {}", programDTO);
    if (programDTO.getId() == null) {
        return createProgram(programDTO);
    }
    ProgramDTO result = programService.save(programDTO);
    return ResponseEntity.ok()
        .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, programDTO.getId().toString()))
        .body(result);
}
 
Example 30
Project: weixin_api   File: MpMsgApi.java   View source code 5 votes vote down vote up
/**
 * 查询群发消息发送状态【订阅号与服务号认证后均可用】
 * 
 * @param massMsgId
 * @return
 * @throws ClientProtocolException
 * @throws URISyntaxException
 * @throws IOException
 * @throws AccessTokenFailException
 */
public BaseResp apiMessageMassGet(String massMsgId)
		throws ClientProtocolException, URISyntaxException, IOException, AccessTokenFailException {
	MpAccessToken token = mpApi.apiToken();
	String path = String.format("/message/mass/get?access_token=%s", token.getAccessToken());

	TreeMap<String, String> reqMap = new TreeMap<String, String>();
	reqMap.put("msg_id", massMsgId);
	String respText = HttpUtil.post(mpApi.config.getApiHttps(), path, reqMap);
	MessageMassGetResp resp = new Gson().fromJson(respText, MessageMassGetResp.class);
	if (mpApi.log.isInfoEnabled()) {
		mpApi.log.info(String.format("apiMessageMassGet %s", new Gson().toJson(resp)));
	}
	return resp;
}
 
Example 31
Project: IPPR2016   File: OwlImportGatewayCallerImpl.java   View source code 5 votes vote down vote up
@Async
public Future<ResponseEntity<OWLProcessModelDTO>> getOWLProcessModel(final String owlContent,
    final HttpHeaderUser headerUser) throws URISyntaxException {
  final URIBuilder uri =
      new URIBuilder(gatewayConfig.getProcessModelStorageAddress()).setPath("/owlprocessmodel");

  return createRequest(uri, HttpMethod.POST, owlContent, OWLProcessModelDTO.class,
      headerUser.getHttpHeaders());
}
 
Example 32
Project: circus-train   File: GCPCredentialCopier.java   View source code 5 votes vote down vote up
private void copyCredentialIntoDistributedCache() throws URISyntaxException {
  LOG.debug("{} added to distributed cache with symlink {}", HDFS_GS_CREDENTIAL_DIRECTORY,
      "." + CACHED_CREDENTIAL_NAME);
  DistributedCache.addCacheFile(new URI(HDFS_GS_CREDENTIAL_ABSOLUTE_PATH), conf);
  //The "." must be prepended for the symlink to be created correctly for reference in Map Reduce job
  conf.set(GCP_KEYFILE_CACHED_LOCATION, "." + CACHED_CREDENTIAL_NAME);
}
 
Example 33
Project: elasticsearch_my   File: Security.java   View source code 5 votes vote down vote up
/** Adds access to classpath jars/classes for jar hell scan, etc */
@SuppressForbidden(reason = "accesses fully qualified URLs to configure security")
static void addClasspathPermissions(Permissions policy) throws IOException {
    // add permissions to everything in classpath
    // really it should be covered by lib/, but there could be e.g. agents or similar configured)
    for (URL url : JarHell.parseClassPath()) {
        Path path;
        try {
            path = PathUtils.get(url.toURI());
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
        // resource itself
        policy.add(new FilePermission(path.toString(), "read,readlink"));
        // classes underneath
        if (Files.isDirectory(path)) {
            policy.add(new FilePermission(path.toString() + path.getFileSystem().getSeparator() + "-", "read,readlink"));
        }
    }
}
 
Example 34
Project: buenojo   File: ImageCompletionExerciseResource.java   View source code 5 votes vote down vote up
/**
 * PUT  /imageCompletionExercises -> Updates an existing imageCompletionExercise.
 */
@RequestMapping(value = "/imageCompletionExercises",
    method = RequestMethod.PUT,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<ImageCompletionExercise> updateImageCompletionExercise(@RequestBody ImageCompletionExercise imageCompletionExercise) throws URISyntaxException {
    log.debug("REST request to update ImageCompletionExercise : {}", imageCompletionExercise);
    if (imageCompletionExercise.getId() == null) {
        return createImageCompletionExercise(imageCompletionExercise);
    }
    ImageCompletionExercise result = imageCompletionExerciseRepository.save(imageCompletionExercise);
    return ResponseEntity.ok()
        .headers(HeaderUtil.createEntityUpdateAlert("imageCompletionExercise", imageCompletionExercise.getId().toString()))
        .body(result);
}
 
Example 35
Project: scott-eu   File: Variable.java   View source code 5 votes vote down vote up
public Variable(final URI about)
       throws URISyntaxException
{
    super(about);

    // Start of user code constructor2
    // End of user code
}
 
Example 36
Project: cookietray   File: OriginUriTest.java   View source code 5 votes vote down vote up
@Test
public void shouldOriginUriReturnUriFromHttpCookie() throws URISyntaxException {
    URI associated = new URI("http", "google.com", "/", "");
    HttpCookie cookie = new HttpCookie("name", "value");
    cookie.setDomain("abc.xyz");
    OriginUri uri = new OriginUri(cookie, associated);
    assertNotEquals(associated, uri.uri());
}
 
Example 37
Project: hadoop   File: AbstractFSContract.java   View source code 5 votes vote down vote up
/**
 * Create a URI off the scheme
 * @param path path of URI
 * @return a URI
 * @throws IOException if the URI could not be created
 */
protected URI toURI(String path) throws IOException {
  try {
    return new URI(getScheme(),path, null);
  } catch (URISyntaxException e) {
    throw new IOException(e.toString() + " with " + path, e);
  }
}
 
Example 38
Project: BUbiNG   File: HttpResponseWarcRecordTest.java   View source code 5 votes vote down vote up
public static void main(String[] arg) throws JSAPException, URISyntaxException, NoSuchAlgorithmException, ClientProtocolException, IOException, InterruptedException, ConfigurationException, IllegalArgumentException, ClassNotFoundException {

		SimpleJSAP jsap = new SimpleJSAP(HttpResponseWarcRecordTest.class.getName(), "Outputs an URL (given as argument) as the UncompressedWarcWriter would do",
			new Parameter[] {
				new UnflaggedOption("url", JSAP.STRING_PARSER, JSAP.REQUIRED, "The url of the page."),
			});

		JSAPResult jsapResult = jsap.parse(arg);
		if (jsap.messagePrinted()) System.exit(1);

		final String url = jsapResult.getString("url");

		final URI uri = new URI(url);
		final WarcWriter writer = new UncompressedWarcWriter(System.out);

		// Setup FetchData
		final RuntimeConfiguration testConfiguration = Helpers.getTestConfiguration(null);
		final HttpClient httpClient = FetchDataTest.getHttpClient(null, false);
		final FetchData fetchData = new FetchData(testConfiguration);

		fetchData.fetch(uri, httpClient, null, null, false);
		final HttpResponseWarcRecord record = new HttpResponseWarcRecord(uri, fetchData.response());
		writer.write(record);
		fetchData.close();
		System.out.println(record);

		writer.close();
	}
 
Example 39
Project: SWET   File: Utils.java   View source code 5 votes vote down vote up
public String getResourceURI(String resourceFileName) {
	try {
		URI uri = this.getClass().getClassLoader().getResource(resourceFileName)
				.toURI();
		// System.err.println("Resource URI: " + uri.toString());
		return uri.toString();
	} catch (URISyntaxException e) {
		throw new RuntimeException(e);
	}
}
 
Example 40
Project: spring-cloud-release-tools   File: PomReaderTests.java   View source code 5 votes vote down vote up
@Before
public void setup() throws URISyntaxException {
	URI scRelease = GitRepoTests.class.getResource("/projects/spring-cloud-release").toURI();
	this.springCloudReleaseProject = new File(scRelease);
	this.springCloudReleaseProjectPom = new File(scRelease.getPath(), "pom.xml");
	this.licenseFile = new File(scRelease.getPath(), "LICENSE.txt");
}