Java Code Examples for java.io.IOException

The following are top voted examples for showing how to use java.io.IOException. 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: MFM   File: VideoUtils.java   View source code 9 votes vote down vote up
static ArrayList<BufferedImage> getFrames(File gif) throws IOException {
    ArrayList<BufferedImage> frames = new ArrayList<BufferedImage>();
    ImageReader ir = new GIFImageReader(new GIFImageReaderSpi());
    ir.setInput(ImageIO.createImageInputStream(gif));
    for (int i = 0; i < ir.getNumImages(true); i++) {
        frames.add(ir.read(i));
    }
    // Release resources for Garbage Collection
    ir.dispose();
    return frames;
}
 
Example 2
Project: mp4parser_android   File: QuicktimeTextTrackImpl.java   View source code 6 votes vote down vote up
public List<ByteBuffer> getSamples() {
    List<ByteBuffer> samples = new LinkedList<ByteBuffer>();
    long lastEnd = 0;
    for (Line sub : subs) {
        long silentTime = sub.from - lastEnd;
        if (silentTime > 0) {
            samples.add(ByteBuffer.wrap(new byte[]{0, 0}));
        } else if (silentTime < 0) {
            throw new Error("Subtitle display times may not intersect");
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);
        try {
            dos.writeShort(sub.text.getBytes("UTF-8").length);
            dos.write(sub.text.getBytes("UTF-8"));
            dos.close();
        } catch (IOException e) {
            throw new Error("VM is broken. Does not support UTF-8");
        }
        samples.add(ByteBuffer.wrap(baos.toByteArray()));
        lastEnd = sub.to;
    }
    return samples;
}
 
Example 3
Project: Nibo   File: LocationAddress.java   View source code 6 votes vote down vote up
public Observable<Address> getObservableAddressFromLocation(final double latitude, final double longitude,
                                                            final Context context) {
    return new Observable<Address>() {
        @Override
        protected void subscribeActual(Observer<? super Address> observer) {
            Geocoder geocoder = new Geocoder(context, Locale.getDefault());
            try {
                List<Address> addressList = geocoder.getFromLocation(
                        latitude, longitude, 1);
                if (addressList != null && addressList.size() > 0) {
                    address = addressList.get(0);
                    observer.onNext(address);
                }
            } catch (IOException e) {
                Log.e(TAG, "Unable connect to Geocoder", e);
            }

        }
    }.subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread());
}
 
Example 4
Project: chromium-net-for-android   File: CronetHttpURLConnectionTest.java   View source code 6 votes vote down vote up
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testServerNotAvailable() throws Exception {
    URL url = new URL(NativeTestServer.getFileURL("/success.txt"));
    HttpURLConnection urlConnection =
            (HttpURLConnection) url.openConnection();
    assertEquals("this is a text file\n", TestUtil.getResponseAsString(urlConnection));
    // After shutting down the server, the server should not be handling
    // new requests.
    NativeTestServer.shutdownNativeTestServer();
    HttpURLConnection secondConnection =
            (HttpURLConnection) url.openConnection();
    // Default implementation reports this type of error in connect().
    // However, since Cronet's wrapper only receives the error in its listener
    // callback when message loop is running, Cronet's wrapper only knows
    // about the error when it starts to read response.
    try {
        secondConnection.getResponseCode();
        fail();
    } catch (IOException e) {
        assertTrue(e instanceof java.net.ConnectException
                || e instanceof UrlRequestException);
        assertTrue((e.getMessage().contains("ECONNREFUSED")
                || (e.getMessage().contains("Connection refused"))
                || e.getMessage().contains("net::ERR_CONNECTION_REFUSED")));
    }
    checkExceptionsAreThrown(secondConnection);
    // Starts the server to avoid crashing on shutdown in tearDown().
    assertTrue(NativeTestServer.startNativeTestServer(getContext()));
}
 
Example 5
Project: ditb   File: FileLink.java   View source code 6 votes vote down vote up
/**
 * Try to open the file from one of the available locations.
 *
 * @return FSDataInputStream stream of the opened file link
 * @throws IOException on unexpected error, or file not found.
 */
private FSDataInputStream tryOpen() throws IOException {
  for (Path path: fileLink.getLocations()) {
    if (path.equals(currentPath)) continue;
    try {
      in = fs.open(path, bufferSize);
      if (pos != 0) in.seek(pos);
      assert(in.getPos() == pos) : "Link unable to seek to the right position=" + pos;
      if (LOG.isTraceEnabled()) {
        if (currentPath == null) {
          LOG.debug("link open path=" + path);
        } else {
          LOG.trace("link switch from path=" + currentPath + " to path=" + path);
        }
      }
      currentPath = path;
      return(in);
    } catch (FileNotFoundException e) {
      // Try another file location
    }
  }
  throw new FileNotFoundException("Unable to open link: " + fileLink);
}
 
Example 6
Project: phone-simulator   File: CurrentSecurityContextImpl.java   View source code 6 votes vote down vote up
private void _decode(AsnInputStream ais, int length) throws MAPParsingComponentException, IOException, AsnException {

        this.gsmSecurityContextData = null;
        this.umtsSecurityContextData = null;

        int tag = ais.getTag();

        if (ais.getTagClass() != Tag.CLASS_CONTEXT_SPECIFIC || ais.isTagPrimitive())
            throw new MAPParsingComponentException("Error while decoding " + _PrimitiveName
                    + ": Primitive has bad tag class or is primitive", MAPParsingComponentExceptionReason.MistypedParameter);

        switch (tag) {
            case _TAG_gsmSecurityContextData:
                this.gsmSecurityContextData = new GSMSecurityContextDataImpl();
                ((GSMSecurityContextDataImpl) this.gsmSecurityContextData).decodeData(ais, length);
                break;
            case _TAG_umtsSecurityContextData:
                this.umtsSecurityContextData = new UMTSSecurityContextDataImpl();
                ((UMTSSecurityContextDataImpl) this.umtsSecurityContextData).decodeData(ais, length);
                break;

            default:
                throw new MAPParsingComponentException("Error while decoding " + _PrimitiveName + ": bad choice tag",
                        MAPParsingComponentExceptionReason.MistypedParameter);
        }
    }
 
Example 7
Project: hadoop   File: SLSRunner.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void startAM() throws YarnException, IOException {
  // application/container configuration
  int heartbeatInterval = conf.getInt(
          SLSConfiguration.AM_HEARTBEAT_INTERVAL_MS,
          SLSConfiguration.AM_HEARTBEAT_INTERVAL_MS_DEFAULT);
  int containerMemoryMB = conf.getInt(SLSConfiguration.CONTAINER_MEMORY_MB,
          SLSConfiguration.CONTAINER_MEMORY_MB_DEFAULT);
  int containerVCores = conf.getInt(SLSConfiguration.CONTAINER_VCORES,
          SLSConfiguration.CONTAINER_VCORES_DEFAULT);
  Resource containerResource =
          BuilderUtils.newResource(containerMemoryMB, containerVCores);

  // application workload
  if (isSLS) {
    startAMFromSLSTraces(containerResource, heartbeatInterval);
  } else {
    startAMFromRumenTraces(containerResource, heartbeatInterval);
  }
  numAMs = amMap.size();
  remainingApps = numAMs;
}
 
Example 8
Project: XXXX   File: LoggerTest.java   View source code 6 votes vote down vote up
@Test
public void unknownHostEmits() throws IOException, InterruptedException {
  SendsStuff api = Feign.builder()
      .logger(logger)
      .logLevel(logLevel)
      .retryer(new Retryer() {
        @Override
        public void continueOrPropagate(RetryableException e) {
          throw e;
        }
        @Override public Retryer clone() {
            return this;
        }
      })
      .target(SendsStuff.class, "http://robofu.abc");

  thrown.expect(FeignException.class);

  api.login("netflix", "denominator", "password");
}
 
Example 9
Project: DStream   File: SynopsisHashMap.java   View source code 6 votes vote down vote up
private void writeObject(ObjectOutputStream s)
    throws IOException
{
    Iterator<Map.Entry<K,V>> i =
        (size > 0) ? entrySet0().iterator() : null;

    // Write out the threshold, loadfactor, and any hidden stuff
    s.defaultWriteObject();

    // Write out number of buckets
    s.writeInt(table.length);

    // Write out size (number of Mappings)
    s.writeInt(size);

    // Write out keys and values (alternating)
    if (i != null) {
        while (i.hasNext()) {
            Map.Entry<K,V> e = i.next();
            s.writeObject(e.getKey());
            s.writeObject(e.getValue());
        }
    }
}
 
Example 10
Project: social-signin   File: GooglePlusDisconnectServlet.java   View source code 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	LOGGER.debug("Finding token to revoke ...");
	String token = req.getParameter("token");
	if (!Preconditions.isEmptyString(token)) {
		try {
			this.service.revokeToken(token);
		} catch (UnrecoverableOAuthException e) {
			OAuthError err = e.getError();
			LOGGER.warn(String.format("Unable to revoke token %s because [%s]%s", token, err.getName(), err.getDescription()));
		}
	} else {
		LOGGER.debug("No token found in parameter, skipping ...");
	}
	this.postSignOut(req, resp);
}
 
Example 11
Project: jerrydog   File: DefaultServlet.java   View source code 6 votes vote down vote up
/**
 * Check if the if-modified-since condition is satisfied.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 * @param resourceInfo File object
 * @return boolean true if the resource meets the specified condition,
 * and false if the condition is not satisfied, in which case request 
 * processing is stopped
 */
private boolean checkIfModifiedSince(HttpServletRequest request,
                                     HttpServletResponse response,
                                     ResourceInfo resourceInfo)
    throws IOException {
    try {
        long headerValue = request.getDateHeader("If-Modified-Since");
        long lastModified = resourceInfo.date;
        if (headerValue != -1) {

            // If an If-None-Match header has been specified, if modified since
            // is ignored.
            if ((request.getHeader("If-None-Match") == null) 
                && (lastModified <= headerValue + 1000)) {
                // The entity has not been modified since the date
                // specified by the client. This is not an error case.
                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                return false;
            }
        }
    } catch(IllegalArgumentException illegalArgument) {
        return false;
    }
    return true;

}
 
Example 12
Project: xlight_android_native   File: ConnectDeviceToNetworkStep.java   View source code 6 votes vote down vote up
@Override
protected void onRunStep() throws SetupStepException {
    try {
        log.d("Ensuring connection to AP");
        workerThreadApConnector.ensureConnectionToSoftAp();

        log.d("Sending connect-ap command");
        ConnectAPCommand.Response response = commandClient.sendCommand(
                // FIXME: is hard-coding zero here correct?  If so, document why
                new ConnectAPCommand(0), ConnectAPCommand.Response.class);
        if (!response.isOK()) {
            throw new SetupStepException("ConnectAPCommand returned non-zero response code: " +
                    response.responseCode);
        }

        commandSent = true;

    } catch (IOException e) {
        throw new SetupStepException(e);
    }
}
 
Example 13
Project: web3j-maven-plugin   File: JavaClassGeneratorMojo.java   View source code 6 votes vote down vote up
private String parseSoliditySource(String includedFile) throws MojoExecutionException {
    try {
        byte[] contract = Files.readAllBytes(Paths.get(soliditySourceFiles.getDirectory(), includedFile));
        CompilerResult result = SolidityCompiler.getInstance(getLog()).compileSrc(
                contract,
                SolidityCompiler.Options.ABI,
                SolidityCompiler.Options.BIN,
                SolidityCompiler.Options.INTERFACE,
                SolidityCompiler.Options.METADATA
        );
        if (result.isFailed()) {
            throw new MojoExecutionException("Could not compile solidity files\n" + result.errors);
        }

        getLog().debug("\t\tResult:\t" + result.output);
        getLog().debug("\t\tError: \t" + result.errors);
        return result.output;
    } catch (IOException ioException) {
        throw new MojoExecutionException("Could not compile files", ioException);
    }
}
 
Example 14
Project: apache-tomcat-7.0.73-with-comment   File: SSIFlastmod.java   View source code 6 votes vote down vote up
/**
 * @see SSICommand
 */
@Override
public long process(SSIMediator ssiMediator, String commandName,
        String[] paramNames, String[] paramValues, PrintWriter writer) {
    long lastModified = 0;
    String configErrMsg = ssiMediator.getConfigErrMsg();
    for (int i = 0; i < paramNames.length; i++) {
        String paramName = paramNames[i];
        String paramValue = paramValues[i];
        String substitutedValue = ssiMediator
                .substituteVariables(paramValue);
        try {
            if (paramName.equalsIgnoreCase("file")
                    || paramName.equalsIgnoreCase("virtual")) {
                boolean virtual = paramName.equalsIgnoreCase("virtual");
                lastModified = ssiMediator.getFileLastModified(
                        substitutedValue, virtual);
                Date date = new Date(lastModified);
                String configTimeFmt = ssiMediator.getConfigTimeFmt();
                writer.write(formatDate(date, configTimeFmt));
            } else {
                ssiMediator.log("#flastmod--Invalid attribute: "
                        + paramName);
                writer.write(configErrMsg);
            }
        } catch (IOException e) {
            ssiMediator.log(
                    "#flastmod--Couldn't get last modified for file: "
                            + substitutedValue, e);
            writer.write(configErrMsg);
        }
    }
    return lastModified;
}
 
Example 15
Project: myfaces-trinidad   File: OutputDocumentRenderer.java   View source code 6 votes vote down vote up
/**
 * Renders the currently opened paragraph with the currently buffered content,
 * escaping it if necessary, then close it and flush the buffer.
 *
 * @param rw      the response writer used to put content in the underlying
 *                response.
 * @param bean    the property holder for the rendered document.
 * @param builder the content buffer
 *
 * @throws IOException if a problem occurs while writing the content to the
 *                     underlying response.
 */
private void _renderParagraph(
  FacesContext  context,
  StringBuilder builder
  ) throws IOException
{
  // Pre-conditions that would cause NullPointerException if not met
  assert builder != null;
  assert context != null;

  renderFormattedText(context, builder.toString());

  context.getResponseWriter().endElement(_PARAGRAPH_ELEMENT);

  // Clear buffer content
  builder.delete(0, builder.length());
}
 
Example 16
Project: quilt   File: DerOutputStream.java   View source code 6 votes vote down vote up
/**
 * Writes a DER encoded length indicator to the stream.
 * 
 * @param length The length value to writeFulfillment to the stream.
 */
public void writeLength(int length) throws IOException {
  if (length > 127) {
    int size = 1;
    int val = length;

    while ((val >>>= 8) != 0) {
      size++;
    }

    write((byte) (size | 0x80));

    for (int i = (size - 1) * 8; i >= 0; i -= 8) {
      write((byte) (length >> i));
    }
  } else {
    write((byte) length);
  }
}
 
Example 17
Project: alfresco-repository   File: ContentDiskDriver2.java   View source code 6 votes vote down vote up
public void deleteEmptyFile(NodeRef rootNode, String path)
{
    try
    {
        NodeRef target = getCifsHelper().getNodeRef(rootNode, path);
            if(target!=null)
        {
            if (nodeService.hasAspect(target, ContentModel.ASPECT_NO_CONTENT))
            {
                nodeService.deleteNode(target);
            }
        }
    }
    catch(IOException ne)
    {
        // Do nothing
        if ( logger.isDebugEnabled())
        {   
            logger.debug("Unable to delete empty file:" + path, ne);
        }
  
    }
}
 
Example 18
Project: OpenJSharp   File: AiffFileWriter.java   View source code 6 votes vote down vote up
public int write(AudioInputStream stream, AudioFileFormat.Type fileType, OutputStream out) throws IOException {

        //$$fb the following check must come first ! Otherwise
        // the next frame length check may throw an IOException and
        // interrupt iterating File Writers. (see bug 4351296)

        // throws IllegalArgumentException if not supported
        AiffFileFormat aiffFileFormat = (AiffFileFormat)getAudioFileFormat(fileType, stream);

        // we must know the total data length to calculate the file length
        if( stream.getFrameLength() == AudioSystem.NOT_SPECIFIED ) {
            throw new IOException("stream length not specified");
        }

        int bytesWritten = writeAiffFile(stream, aiffFileFormat, out);
        return bytesWritten;
    }
 
Example 19
Project: EasyLogin   File: JoinEvent.java   View source code 6 votes vote down vote up
@SubscribeEvent
public void keyListener(KeyInputEvent event) throws IOException {
	if (EasyLogin.logingui.isPressed()) {
		Minecraft mc = Minecraft.getMinecraft();
		mc.displayGuiScreen(new MainGui(mc.currentScreen));
		// 密码读取
		InputStream in = new BufferedInputStream(new FileInputStream("config/easylogin.properties"));
		prop.load(in);
		// 解密密码
		byte[] passwordByte = prop.getProperty("PassWord").getBytes();
		byte key = 124;
		for (int i = 0; i < passwordByte.length; i++) {
			passwordByte[i] ^= key;
		}
		MainGui.settext(new String(passwordByte));
		System.out.println(new String(passwordByte));
	}
}
 
Example 20
Project: Reactive4JavaFlow   File: ParallelFromPublisherTest.java   View source code 6 votes vote down vote up
@Test
public void asyncFusedMapCrash() {
    SolocastProcessor<Integer> up = new SolocastProcessor<>();

    up.onNext(1);

    up
            .map(v -> {
                throw new IOException();
            })
            .compose(new StripBoundary<>(null))
            .parallel()
            .sequential()
            .test()
            .assertFailure(IOException.class);

    assertFalse(up.hasSubscribers());
}
 
Example 21
Project: parabuild-ci   File: SourceLineAnnotation.java   View source code 6 votes vote down vote up
public void writeXML(XMLOutput xmlOutput) throws IOException {
	XMLAttributeList attributeList = new XMLAttributeList()
		.addAttribute("classname", getClassName())
		.addAttribute("start", String.valueOf(getStartLine()))
		.addAttribute("end", String.valueOf(getEndLine()))
		.addAttribute("startBytecode", String.valueOf(getStartBytecode()))
		.addAttribute("endBytecode", String.valueOf(getEndBytecode()));

	if (isSourceFileKnown())
		attributeList.addAttribute("sourcefile", sourceFile);

	String role = getDescription();
	if (!role.equals(DEFAULT_ROLE))
		attributeList.addAttribute("role", getDescription());

	xmlOutput.openCloseTag(ELEMENT_NAME, attributeList);
}
 
Example 22
Project: Elasticsearch   File: QueryBuilder.java   View source code 5 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    builder.startObject();
    doXContent(builder, params);
    builder.endObject();
    return builder;
}
 
Example 23
Project: googles-monorepo-demo   File: FilesTest.java   View source code 5 votes vote down vote up
public void testHash() throws IOException {
  File asciiFile = getTestFile("ascii.txt");
  File i18nFile = getTestFile("i18n.txt");

  String init = "d41d8cd98f00b204e9800998ecf8427e";
  assertEquals(init, Hashing.md5().newHasher().hash().toString());

  String asciiHash = "e5df5a39f2b8cb71b24e1d8038f93131";
  assertEquals(asciiHash, Files.hash(asciiFile, Hashing.md5()).toString());

  String i18nHash = "7fa826962ce2079c8334cd4ebf33aea4";
  assertEquals(i18nHash, Files.hash(i18nFile, Hashing.md5()).toString());
}
 
Example 24
Project: the-one-mdonnyk   File: Settings.java   View source code 5 votes vote down vote up
/**
 * Reads another settings file and adds the key-value pairs to the current
 * settings overriding any values that already existed with the same keys.
 * @param propFile Path to the property file
 * @throws SettingsError If loading the settings file didn't succeed
 * @see #init(String)
 */
public static void addSettings(String propFile) throws SettingsError {
	try {
		props.load(new FileInputStream(propFile));
	} catch (IOException e) {
		throw new SettingsError(e);
	}
}
 
Example 25
Project: incubator-netbeans   File: InstalledFileLocatorImplDirTest.java   View source code 5 votes vote down vote up
private static void touch(File f) throws IOException {
    File p = f.getParentFile();
    if (!p.exists()) {
        if (!p.mkdirs()) {
            throw new IOException(p.getAbsolutePath());
        }
    }
    OutputStream os = new FileOutputStream(f);
    os.close();
}
 
Example 26
Project: GameProject-V1.0Beta   File: AdminFilter.java   View source code 5 votes vote down vote up
/**
 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
		throws IOException, ServletException {
	// TODO Auto-generated method stub
	// place your code here

	// pass the request along the filter chain
	HttpServletRequest hsRequest = (HttpServletRequest) request;
	HttpServletResponse hsResponse=(HttpServletResponse)response;
	
	//用于获取当前页面的路径
	String servletPath = hsRequest.getServletPath();
	//获取session储存的admin信息
	Admin admin = (Admin)hsRequest.getSession().getAttribute("loginedAdmin");
	List<GameCompleteServer> list = new GameServerListDao().findGameServers();
	
	if("/adminjsp/server.jsp".equals(servletPath)) {
		if(null != admin) {
			if(null != list && list.size() > 0 
					&& null == hsRequest.getSession().getAttribute("gameServerList"))
				hsRequest.getSession().setAttribute("gameServerList", list);
			System.out.println(list.size());
		}
	} else if("/userjsp/login.jsp".equals(servletPath)) {
		if(null != list && list.size() > 0 
				&& null == hsRequest.getSession().getAttribute("gameServerList")) {
			hsRequest.getSession().setAttribute("gameServerList", list);
			System.out.println(list.size());
		}
	}
	
	chain.doFilter(request, response);
}
 
Example 27
Project: hadoop   File: ThreadedMapBenchmark.java   View source code 5 votes vote down vote up
public void map(WritableComparable key, 
                Writable value,
                OutputCollector<BytesWritable, BytesWritable> output, 
                Reporter reporter) throws IOException {
  int itemCount = 0;
  while (numBytesToWrite > 0) {
    int keyLength = minKeySize 
                    + (keySizeRange != 0 
                       ? random.nextInt(keySizeRange) 
                       : 0);
    randomKey.setSize(keyLength);
    randomizeBytes(randomKey.getBytes(), 0, randomKey.getLength());
    int valueLength = minValueSize 
                      + (valueSizeRange != 0 
                         ? random.nextInt(valueSizeRange) 
                         : 0);
    randomValue.setSize(valueLength);
    randomizeBytes(randomValue.getBytes(), 0, randomValue.getLength());
    output.collect(randomKey, randomValue);
    numBytesToWrite -= keyLength + valueLength;
    reporter.incrCounter(Counters.BYTES_WRITTEN, 1);
    reporter.incrCounter(Counters.RECORDS_WRITTEN, 1);
    if (++itemCount % 200 == 0) {
      reporter.setStatus("wrote record " + itemCount + ". " 
                         + numBytesToWrite + " bytes left.");
    }
  }
  reporter.setStatus("done with " + itemCount + " records.");
}
 
Example 28
Project: UpdogFarmer   File: SteamWebHandler.java   View source code 5 votes vote down vote up
public boolean autoVote() {
    final String url = STEAM_STORE + "SteamAwards/?l=english";
    try {
        final Document doc = Jsoup.connect(url)
                .referrer(url)
                .followRedirects(true)
                .cookies(generateWebCookies())
                .get();
        final Element container = doc.select("div.vote_nominations").first();
        if (container == null) {
            return false;
        }
        final String voteId = container.attr("data-voteid");
        final Elements voteNominations = container.select("div.vote_nomination");
        if (voteNominations == null) {
            return false;
        }
        final Element choice = voteNominations.get(new Random().nextInt(voteNominations.size()));
        final String appId = choice.attr("data-vote-appid");
        final Document doc2 = Jsoup.connect(STEAM_STORE + "salevote")
                .referrer(STEAM_STORE)
                .cookies(generateWebCookies())
                .data("sessionid", sessionId)
                .data("voteid", voteId)
                .data("appid", appId)
                .post();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}
 
Example 29
Project: OpenJSharp   File: SSLServerCertStoreHelper.java   View source code 5 votes vote down vote up
@Override
public X509CertSelector wrap(X509CertSelector selector,
                             X500Principal certSubject,
                             String ldapDN)
    throws IOException
{
    throw new UnsupportedOperationException();
}
 
Example 30
Project: flow-platform   File: GitWebhookTest.java   View source code 5 votes vote down vote up
private MockHttpServletRequestBuilder createGitHubPushRequest(String flowName, String pathOfPayload) throws IOException {
    return post("/hooks/git/" + flowName)
        .contentType(MediaType.APPLICATION_JSON)
        .content(getResourceContent(pathOfPayload))
        .header("x-github-event", "push")
        .header("x-github-delivery", "29087180-8177-11e7-83a4-3b68852f0c9e");
}
 
Example 31
Project: sstore-soft   File: ClosableCharArrayWriter.java   View source code 5 votes vote down vote up
/**
 * @throws java.io.IOException if this writer is freed.
 */
protected synchronized void checkFreed() throws IOException {

    if (freed) {
        throw new IOException("write buffer is freed.");    // NOI18N
    }
}
 
Example 32
Project: SimpleController   File: TotalController.java   View source code 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ControllerContext controllerContext=new ControllerContext();
    controllerContext.setRequest(request);
    controllerContext.setResponse(response);
    try {
        requestDispatcher.dispatch(controllerContext);
        resultDispatcher.dispatch(controllerContext);
    } catch (NoResourceException e) {
        e.printStackTrace();
        controllerContext.setResultDescriptor("error");
        response.sendRedirect(request.getContextPath()+ controllerContext.getResultDescriptor().getValue());
    }
}
 
Example 33
Project: incubator-netbeans   File: Starvation37045SecondTest.java   View source code 5 votes vote down vote up
public java.io.OutputStream outputStream() throws java.io.IOException {
    class ContentStream extends java.io.ByteArrayOutputStream {
        public void close () throws java.io.IOException {
            super.close ();
            content = new String (toByteArray ());
        }
    }
    
    return new ContentStream ();
}
 
Example 34
Project: jdk8u-jdk   File: IncorrectDestinationOffset.java   View source code 5 votes vote down vote up
private static void validate(BufferedImage bi, int point2draw,
                             int size2draw)
        throws IOException {
    for (int x = 0; x < SIZE; ++x) {
        for (int y = 0; y < SIZE; ++y) {
            if (isInsideGreenArea(point2draw, size2draw, x, y)) {
                if (bi.getRGB(x, y) != Color.green.getRGB()) {
                    ImageIO.write(bi, "png", new File("image.png"));
                    throw new RuntimeException("Test failed.");
                }
            } else {
                if (isRedArea(x, y)) {
                    if (bi.getRGB(x, y) != Color.red.getRGB()) {
                        ImageIO.write(bi, "png", new File("image.png"));
                        throw new RuntimeException("Test failed.");
                    }
                }
                if (isBlueArea(x, y)) {
                    if (bi.getRGB(x, y) != Color.blue.getRGB()) {
                        ImageIO.write(bi, "png", new File("image.png"));
                        throw new RuntimeException("Test failed.");
                    }
                }
                if (isOrangeArea(x, y)) {
                    if (bi.getRGB(x, y) != Color.orange.getRGB()) {
                        ImageIO.write(bi, "png", new File("image.png"));
                        throw new RuntimeException("Test failed.");
                    }
                }
                if (isMagentaArea(x, y)) {
                    if (bi.getRGB(x, y) != Color.magenta.getRGB()) {
                        ImageIO.write(bi, "png", new File("image.png"));
                        throw new RuntimeException("Test failed.");
                    }
                }
            }
        }
    }
}
 
Example 35
Project: ipack   File: X509CRLObject.java   View source code 5 votes vote down vote up
public X500Principal getIssuerX500Principal()
{
    try
    {
        return new X500Principal(c.getIssuer().getEncoded());
    }
    catch (IOException e)
    {
        throw new IllegalStateException("can't encode issuer DN");
    }
}
 
Example 36
Project: JInsight   File: Agent.java   View source code 5 votes vote down vote up
private static void main0(String agentArgs, Instrumentation instrumentation,
    BiConsumer<String, Instrumentation> delegate) {
  if (ClassLoader.getSystemResource(BTM_SCRIPTS_RESOURCE_PATH) == null) {
    System.err.println("Could not load " + BTM_SCRIPTS_RESOURCE_PATH + "."
        + "Agent will not be started.");
    return;
  }

  try {
    ConfigService.initialize();
  } catch (ConfigurationException | IOException | RuntimeException e) {
    System.err.println(e.getMessage());
    System.err.println("Agent will not be started.");
    return;
  }

  if (agentArgs != null && agentArgs.trim().length() > 0) {
    agentArgs += "," + AGENT_PARAMS;
  } else {
    agentArgs = AGENT_PARAMS;
  }

  JarFile bytemanJar = createBytemanJar();
  if (bytemanJar == null) {
    System.err.println("Could not locate: " + BYTEMAN_JAR_RESOURCE_NAME);
    System.err.println("Agent will not be started.");
    return;
  }

  instrumentation.appendToBootstrapClassLoaderSearch(bytemanJar);
  delegate.accept(agentArgs, instrumentation);
}
 
Example 37
Project: newrelic-alerts-configurator   File: NewRelicApiIntegrationTest.java   View source code 5 votes vote down vote up
@Before
public void setUp() throws IOException {
    WIRE_MOCK.resetMappings();
    testee = new NewRelicApi("http://localhost:6766", "secret");
    applications = IOUtils.toString(NewRelicApiIntegrationTest.class.getResource("/applications.json"), UTF_8);
    channels1 = IOUtils.toString(NewRelicApiIntegrationTest.class.getResource("/channels1.json"), UTF_8);
    channels2 = IOUtils.toString(NewRelicApiIntegrationTest.class.getResource("/channels2.json"), UTF_8);
}
 
Example 38
Project: ChemistryAdministrativePortal   File: LoginFilter.java   View source code 5 votes vote down vote up
/**
 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
	// TODO Auto-generated method stub
	// place your code here
	HttpServletRequest loginRequest = (HttpServletRequest) request;
	if((User)loginRequest.getSession().getAttribute("user") != null) {
		chain.doFilter(request, response);
	}
	
	else {
		loginRequest.getRequestDispatcher("/index.jsp").forward(request, response);
	}
}
 
Example 39
Project: incubator-netbeans   File: CategoryTest.java   View source code 5 votes vote down vote up
private Transferable createTransferable( final Item item ) {
    return new ExTransferable.Single( PaletteController.ITEM_DATA_FLAVOR ) {
        protected Object getData() throws IOException, UnsupportedFlavorException {
            return item.getLookup();
        }
    };
}
 
Example 40
Project: incubator-netbeans   File: FileObjectCrawlerTest.java   View source code 5 votes vote down vote up
public void testDuplicateResults2() throws IOException {
    FileObject root = FileUtil.createFolder(new File(getWorkDir(), "src"));
    String [] paths = new String [] {
            "org/pckg1/file1.txt",
            "org/pckg1/pckg2/file1.txt",
            "org/pckg1/pckg2/file2.txt",
    };

    populateFolderStructure(root, paths);

    FileObjectCrawler crawler = new FileObjectCrawler(root, new FileObject[] {root.getFileObject("org/pckg1/pckg2/file1.txt"), root.getFileObject("org/pckg1/pckg2/file2.txt")}, EnumSet.<Crawler.TimeStampAction>of(Crawler.TimeStampAction.UPDATE), null, CR, SuspendSupport.NOP);
    assertCollectedFiles("Wrong files collected", crawler.getResources(), new String[] {"org/pckg1/pckg2/file1.txt", "org/pckg1/pckg2/file2.txt"});
}