类java.io.IOException源码实例Demo

下面列出了怎么用java.io.IOException的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: nifi-registry   文件: JerseyExtensionRepoClient.java
@Override
public InputStream getVersionExtensionDocs(final String bucketName, final String groupId, final String artifactId,
                                     final String version, final String extensionName)
        throws IOException, NiFiRegistryException {

    validate(bucketName, groupId, artifactId, version);

    if (StringUtils.isBlank(extensionName)) {
        throw new IllegalArgumentException("Extension name is required");
    }

    return executeAction("Error retrieving versions for extension repo", () -> {
        final WebTarget target = extensionRepoTarget
                .path("{bucketName}/{groupId}/{artifactId}/{version}/extensions/{extensionName}/docs")
                .resolveTemplate("bucketName", bucketName)
                .resolveTemplate("groupId", groupId)
                .resolveTemplate("artifactId", artifactId)
                .resolveTemplate("version", version)
                .resolveTemplate("extensionName", extensionName);

        return getRequestBuilder(target)
                .accept(MediaType.TEXT_HTML)
                .get()
                .readEntity(InputStream.class);
    });
}
 
源代码2 项目: product-ei   文件: ESBTestCaseUtils.java
/**
 * This method can be used to check whether file specified by the location has contents
 *
 * @param fullPath path to file
 * @return true if file has no contents
 */
public boolean isFileEmpty(String fullPath) {
	try {
		BufferedReader br = new BufferedReader(new FileReader(fullPath));
		if (br.readLine() == null) {
			return true;
		}
	} catch (FileNotFoundException fileNotFoundException) {
		//synapse config is not found therefore it should copy original file to the location
		log.info("Synapse config file cannot be found in " + fullPath + " copying Backup Config to the location.");
		return true;
	} catch (IOException ioException) {
		//exception ignored
		log.info("Couldn't read the synapse config from the location " + fullPath);
	}
	return false;
}
 
源代码3 项目: Bytecoder   文件: Utility.java
@Override
public void write( final int b ) throws IOException {
    if (isJavaIdentifierPart((char) b) && (b != ESCAPE_CHAR)) {
        out.write(b);
    } else {
        out.write(ESCAPE_CHAR); // Escape character
        // Special escape
        if (b >= 0 && b < FREE_CHARS) {
            out.write(CHAR_MAP[b]);
        } else { // Normal escape
            final char[] tmp = Integer.toHexString(b).toCharArray();
            if (tmp.length == 1) {
                out.write('0');
                out.write(tmp[0]);
            } else {
                out.write(tmp[0]);
                out.write(tmp[1]);
            }
        }
    }
}
 
源代码4 项目: charliebot   文件: Log.java
public static void log(Throwable throwable, String s) {
    Toolkit.checkOrCreate(s, "log file");
    GENERAL_LOG.error(throwable.getMessage(), throwable);
    FileWriter filewriter;
    try {
        filewriter = new FileWriter(s, true);
    } catch (IOException ioexception) {
        throw new UserError("Could not create log file \"" + s + "\".");
    }
    String s1 = throwable.getMessage();
    if (s1 != null)
        MessagePrinter.println(s1, s, filewriter, 2);
    for (StringTokenizer stringtokenizer = StackParser.getStackTraceFor(throwable); stringtokenizer.hasMoreElements(); MessagePrinter.println(stringtokenizer.nextToken(), s, filewriter, 2))
        ;
    try {
        filewriter.close();
    } catch (IOException ioexception1) {
        throw new DeveloperError("Could not close FileWriter!");
    }
}
 
源代码5 项目: buck   文件: GwtBinaryIntegrationTest.java
@Test(timeout = (2 * 60 * 1000))
public void shouldBeAbleToBuildAGwtBinary() throws IOException {
  ProjectWorkspace workspace =
      TestDataHelper.createProjectWorkspaceForScenario(this, "gwt_binary", tmp);
  workspace.setUp();
  setWorkspaceCompilationMode(workspace);
  workspace.enableDirCache();

  workspace.runBuckBuild("//:binary").assertSuccess();
  workspace.deleteRecursivelyIfExists("buck-out/annotation");
  workspace.runBuckCommand("clean", "--keep-cache");
  workspace.copyFile(
      "com/example/gwt/emul/java/io/DataOutputStream.java.new",
      "com/example/gwt/emul/java/io/DataOutputStream.java");
  workspace.runBuckBuild("//:binary").assertSuccess();

  Path zip = workspace.buildAndReturnOutput("//:binary");
  ZipInspector inspector = new ZipInspector(zip);
  inspector.assertFileExists("a/a.devmode.js");
  inspector.assertFileExists("a/a.nocache.js");
  inspector.assertFileExists("a/clear.cache.gif");
  inspector.assertFileExists("a/compilation-mappings.txt");
}
 
源代码6 项目: tajo   文件: TestTajoClientV2.java
@Test
public void testExecuteQueryType3() throws TajoException, IOException, SQLException {
  ResultSet res = null;
  try {
    clientv2.executeUpdate("create database client_v2_type3");
    clientv2.selectDB("client_v2_type3");
    clientv2.executeUpdate("create table t1 (c1 int)");
    clientv2.executeUpdate("create table t2 (c2 int)");

    // why we shouldn't use join directly on virtual tables? Currently, join on virtual tables is not supported.
    res = clientv2.executeQuery("select db_id from information_schema.databases where db_name = 'client_v2_type3'");
    assertTrue(res.next());
    int dbId = res.getInt(1);
    res.close();

    res = clientv2.executeQuery(
        "select table_name from information_schema.tables where db_id = " + dbId + " order by table_name");
    assertResultSet(res);
  } finally {
    if (res != null) {
      res.close();
    }

    clientv2.executeUpdate("drop database IF EXISTS client_v2_types3");
  }
}
 
源代码7 项目: dragonwell8_jdk   文件: MidiSystem.java
/**
 * Obtains a MIDI sequence from the specified <code>File</code>.
 * The <code>File</code> must point to valid MIDI file data
 * for a file type recognized by the system.
 * <p>
 * This operation can only succeed for files of a type which can be parsed
 * by an installed file reader.  It may fail with an InvalidMidiDataException
 * even for valid files if no compatible file reader is installed.  It
 * will also fail with an InvalidMidiDataException if a compatible file reader
 * is installed, but encounters errors while constructing the <code>Sequence</code>
 * object from the file data.
 *
 * @param file the <code>File</code> from which the <code>Sequence</code>
 * should be constructed
 * @return a <code>Sequence</code> object based on the MIDI file data
 * pointed to by the File
 * @throws InvalidMidiDataException if the File does not point to valid MIDI
 * file data recognized by the system
 * @throws IOException if an I/O exception occurs
 */
public static Sequence getSequence(File file)
    throws InvalidMidiDataException, IOException {

    List providers = getMidiFileReaders();
    Sequence sequence = null;

    for(int i = 0; i < providers.size(); i++) {
        MidiFileReader reader = (MidiFileReader) providers.get(i);
        try {
            sequence = reader.getSequence( file ); // throws IOException
            break;
        } catch (InvalidMidiDataException e) {
            continue;
        }
    }

    if( sequence==null ) {
        throw new InvalidMidiDataException("could not get sequence from file");
    } else {
        return sequence;
    }
}
 
源代码8 项目: vividus   文件: BeanFactoryIntegrationTests.java
@ParameterizedTest
@CsvSource({
        "${profile-to-use}, basicenv,               integration",
        "basicprofile,      ${environments-to-use}, integration",
        "basicprofile,      basicenv,               ${suite-to-use}"
})
void shouldResolvePlaceholdersInConfigurationProperties(String profile, String environments, String suite)
        throws IOException
{
    System.setProperty(CONFIGURATION_PROFILE, profile);
    System.setProperty(CONFIGURATION_ENVIRONMENTS, environments);
    System.setProperty(CONFIGURATION_SUITE, suite);
    BeanFactory.open();
    assertProperties(null, null);
    assertIntegrationSuiteProperty();
}
 
源代码9 项目: logging-log4j-audit   文件: ClassGenerator.java
private OutputStream openOutputStream(File file) throws IOException {
    if (file.exists()) {
        if (file.isDirectory()) {
            throw new IOException("File '" + file + "' exists but is a directory");
        }
        if (!file.canWrite()) {
            throw new IOException("File '" + file + "' cannot be written to");
        }
    } else {
        final File parent = file.getParentFile();
        if (parent != null) {
            if (!parent.mkdirs() && !parent.isDirectory()) {
                throw new IOException("Directory '" + parent + "' could not be created");
            }
        }
    }
    return new FileOutputStream(file, false);
}
 
源代码10 项目: Elasticsearch   文件: RepositoriesService.java
/**
 * Creates a new repository and adds it to the list of registered repositories.
 * <p>
 * If a repository with the same name but different types or settings already exists, it will be closed and
 * replaced with the new repository. If a repository with the same name exists but it has the same type and settings
 * the new repository is ignored.
 *
 * @param repositoryMetaData new repository metadata
 * @return {@code true} if new repository was added or {@code false} if it was ignored
 */
private boolean registerRepository(RepositoryMetaData repositoryMetaData) throws IOException {
    RepositoryHolder previous = repositories.get(repositoryMetaData.name());
    if (previous != null) {
        if (!previous.type.equals(repositoryMetaData.type()) && previous.settings.equals(repositoryMetaData.settings())) {
            // Previous version is the same as this one - ignore it
            return false;
        }
    }
    RepositoryHolder holder = createRepositoryHolder(repositoryMetaData);
    if (previous != null) {
        // Closing previous version
        closeRepository(repositoryMetaData.name(), previous);
    }
    Map<String, RepositoryHolder> newRepositories = newHashMap(repositories);
    newRepositories.put(repositoryMetaData.name(), holder);
    repositories = ImmutableMap.copyOf(newRepositories);
    return true;
}
 
源代码11 项目: jrobin   文件: RrdSafeFileBackend.java
private void lockFile(final long lockWaitTime, final long lockRetryPeriod) throws IOException {
    final long entryTime = System.currentTimeMillis();
    final FileChannel channel = file.getChannel();
	m_lock = channel.tryLock(0, Long.MAX_VALUE, false);
	if (m_lock != null) {
		counters.registerQuickLock();
		return;
	}
	do {
		try {
			Thread.sleep(lockRetryPeriod);
		}
		catch (final InterruptedException e) {
		    Thread.currentThread().interrupt();
		}
		m_lock = channel.tryLock(0, Long.MAX_VALUE, false);
		if (m_lock != null) {
			counters.registerDelayedLock();
			return;
		}
	} while (System.currentTimeMillis() - entryTime <= lockWaitTime);
	counters.registerError();
	throw new IOException("Could not obtain exclusive m_lock on file: " + getPath() + "] after " + lockWaitTime + " milliseconds");
}
 
源代码12 项目: pmq   文件: MqResourceTest.java
@Test
public void heartbeatSucTest() throws IOException, BrokerException {
	IHttpClient httpClient = mock(IHttpClient.class);
	MqResource mqResource = new MqResource(httpClient, "http://localhost");
	HeartbeatResponse response = new HeartbeatResponse();
	response.setSuc(false);
	when(httpClient.post(anyString(), anyObject(), eq(HeartbeatResponse.class))).thenReturn(response);
	mqResource.heartbeat(new HeartbeatRequest());
}
 
源代码13 项目: GVGAI_GYM   文件: JsonWriter.java
/**
 * Encodes {@code null}.
 *
 * @return this writer.
 */
public JsonWriter nullValue() throws IOException {
  if (deferredName != null) {
    if (serializeNulls) {
      writeDeferredName();
    } else {
      deferredName = null;
      return this; // skip the name and the value
    }
  }
  beforeValue();
  out.write("null");
  return this;
}
 
源代码14 项目: incubator-batchee   文件: DocumentationMojoTest.java
@Test
public void documentAdoc() throws MojoFailureException, MojoExecutionException, IOException {
    final File out = new File("target/DocumentationMojoTest/output.adoc");
    new DocumentationMojo() {{
        classes = new File("target/test-classes/org/apache/batchee/tools/maven/");
        output = out;
    }}.execute();
    final FileInputStream fis = new FileInputStream(out);
    assertEquals(
        "= myChildComponent\n" +
        "\n" +
        "a child comp\n" +
        "\n" +
        "|===\n" +
        "|Name|Description\n" +
        "|config2|2\n" +
        "|configByDefault|this is an important config\n" +
        "|expl|this one is less important\n" +
        "|===\n" +
        "\n" +
        "= myComponent\n" +
        "\n" +
        "|===\n" +
        "|Name|Description\n" +
        "|configByDefault|this is an important config\n" +
        "|expl|this one is less important\n" +
        "|===\n" +
        "\n" +
        "= org.apache.batchee.tools.maven.batchlet.SimpleBatchlet\n" +
        "\n" +
        "|===\n" +
        "|Name|Description\n" +
        "|fail|-\n" +
        "|sleep|-\n" +
        "|===\n" +
        "\n", IOUtil.toString(fis));
    fis.close();
}
 
源代码15 项目: Bytecoder   文件: Formatter.java
private void printFloat(Object arg, Locale l) throws IOException {
    if (arg == null)
        print("null", l);
    else if (arg instanceof Float)
        print(((Float)arg).floatValue(), l);
    else if (arg instanceof Double)
        print(((Double)arg).doubleValue(), l);
    else if (arg instanceof BigDecimal)
        print(((BigDecimal)arg), l);
    else
        failConversion(c, arg);
}
 
源代码16 项目: timbuctoo   文件: HuygensAuthenticationHandler.java
@Override
public SecurityInformation getSecurityInformation(String sessionToken) throws UnauthorizedException, IOException {
    HuygensSession session = doSessionDetailsRequest(sessionToken);
    doSessionRefresh(sessionToken);

    return new HuygensSecurityInformation(session.getOwner());
}
 
源代码17 项目: mr4c   文件: MR4CReducerTest.java
public void collect(Text key, Text value) throws IOException {
	//key --> name
	String name = key.toString();
	if ( m_outputs.containsKey(name) ) {
		throw new IllegalStateException(String.format("Already added dataset [%s]", name));
	}
	Reader reader = new StringReader(value.toString());
	Dataset dataset = m_serializer.deserializeDataset(reader);
	m_outputs.put(name,dataset);
}
 
源代码18 项目: hadoop-ozone   文件: OzoneFileSystem.java
@Override
protected OzoneClientAdapter createAdapter(ConfigurationSource conf,
    String bucketStr, String volumeStr, String omHost, int omPort)
    throws IOException {
  return new OzoneClientAdapterImpl(omHost, omPort, conf, volumeStr,
      bucketStr,
      storageStatistics);
}
 
源代码19 项目: hbase   文件: MasterCoprocessorHost.java
public void postRemoveServers(final Set<Address> servers)
    throws IOException {
  execOperation(coprocEnvironments.isEmpty() ? null : new MasterObserverOperation() {
    @Override
    public void call(MasterObserver observer) throws IOException {
      observer.postRemoveServers(this, servers);
    }
  });
}
 
源代码20 项目: dubbo-2.6.5   文件: MulticastGroup.java
private void send(String msg) throws RemotingException {
    DatagramPacket hi = new DatagramPacket(msg.getBytes(), msg.length(), mutilcastAddress, mutilcastSocket.getLocalPort());
    try {
        mutilcastSocket.send(hi);
    } catch (IOException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}
 
源代码21 项目: helios   文件: JobPrefixFile.java
private JobPrefixFile(final Path file, final FileChannel channel, final FileLock lock)
    throws IOException, IllegalStateException {
  this.file = Preconditions.checkNotNull(file, "file");
  this.channel = Preconditions.checkNotNull(channel, "channel");
  this.lock = Preconditions.checkNotNull(lock, "lock");
  this.prefix = file.getFileName().toString();
}
 
源代码22 项目: keycloak   文件: SessionClusterEvent.java
protected void marshallTo(ObjectOutput output) throws IOException {
    output.writeByte(VERSION_1);

    MarshallUtil.marshallString(realmId, output);
    MarshallUtil.marshallString(eventKey, output);
    output.writeBoolean(resendingEvent);
    MarshallUtil.marshallString(siteId, output);
    MarshallUtil.marshallString(nodeId, output);
}
 
源代码23 项目: act-platform   文件: FactTypeEntityTest.java
@Test
public void setRelevantObjectBindingsFromString() throws IOException {
  String bindings = "[{\"sourceObjectTypeID\":\"ad35e1ec-e42f-4509-bbc8-6516a90b66e8\",\"destinationObjectTypeID\":\"95959968-f2fb-4913-9c0b-fc1b9144b60f\",\"bidirectionalBinding\":false}," +
          "{\"sourceObjectTypeID\":\"95959968-f2fb-4913-9c0b-fc1b9144b60f\",\"destinationObjectTypeID\":\"ad35e1ec-e42f-4509-bbc8-6516a90b66e8\",\"bidirectionalBinding\":true}]";
  FactTypeEntity entity = new FactTypeEntity().setRelevantObjectBindingsStored(bindings);

  assertFactObjectBindingDefinitions(entity.getRelevantObjectBindings(), bindings);
}
 
源代码24 项目: tomee   文件: GreetingServiceTest.java
@Test
public void getJson() throws IOException {
    final String message = WebClient.create("http://localhost:4204")
            .path("/test/greeting/")
            .accept(MediaType.APPLICATION_JSON_TYPE)
            .get(String.class);
    assertEquals("{\"value\":\"Hi REST!\"}", message);
}
 
@Test
public void detectHandlerMappingFromParent() throws ServletException, IOException {
	// create a parent context that includes a mapping
	StaticWebApplicationContext parent = new StaticWebApplicationContext();
	parent.setServletContext(getServletContext());
	parent.registerSingleton("parentHandler", ControllerFromParent.class, new MutablePropertyValues());

	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.addPropertyValue(new PropertyValue("mappings", URL_KNOWN_ONLY_PARENT + "=parentHandler"));

	parent.registerSingleton("parentMapping", SimpleUrlHandlerMapping.class, pvs);
	parent.refresh();

	DispatcherServlet complexDispatcherServlet = new DispatcherServlet();
	// will have parent
	complexDispatcherServlet.setContextClass(ComplexWebApplicationContext.class);
	complexDispatcherServlet.setNamespace("test");

	ServletConfig config = new MockServletConfig(getServletContext(), "complex");
	config.getServletContext().setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, parent);
	complexDispatcherServlet.init(config);

	MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", URL_KNOWN_ONLY_PARENT);
	MockHttpServletResponse response = new MockHttpServletResponse();
	complexDispatcherServlet.service(request, response);

	assertFalse("Matched through parent controller/handler pair: not response=" + response.getStatus(),
			response.getStatus() == HttpServletResponse.SC_NOT_FOUND);
}
 
源代码26 项目: T0rlib4j   文件: Socks4Message.java
public void read(final InputStream in, final boolean clientMode)
		throws IOException {
	final DataInputStream d_in = new DataInputStream(in);
	version = d_in.readUnsignedByte();
	command = d_in.readUnsignedByte();
	if (clientMode && (command != REPLY_OK)) {
		String errMsg;
		// FIXME: Range should be replaced with cases.
		if ((command > REPLY_OK) && (command < REPLY_BAD_IDENTD)) {
			errMsg = replyMessage[command - REPLY_OK];
		} else {
			errMsg = "Unknown Reply Code";
		}
		throw new SocksException(command, errMsg);
	}
	port = d_in.readUnsignedShort();
	final byte[] addr = new byte[4];
	d_in.readFully(addr);
	ip = bytes2IP(addr);
	host = ip.getHostName();
	if (!clientMode) {
		int b = in.read();
		// FIXME: Hope there are no idiots with user name bigger than this
		final byte[] userBytes = new byte[256];
		int i = 0;
		for (i = 0; (i < userBytes.length) && (b > 0); ++i) {
			userBytes[i] = (byte) b;
			b = in.read();
		}
		user = new String(userBytes, 0, i);
	}
}
 
源代码27 项目: openjdk-jdk9   文件: DOMSignatureMethod.java
boolean verify(Key key, SignedInfo si, byte[] sig,
               XMLValidateContext context)
    throws InvalidKeyException, SignatureException, XMLSignatureException
{
    if (key == null || si == null || sig == null) {
        throw new NullPointerException();
    }

    if (!(key instanceof PublicKey)) {
        throw new InvalidKeyException("key must be PublicKey");
    }
    checkKeySize(context, key);
    if (signature == null) {
        Provider p = (Provider)context.getProperty(
                "org.jcp.xml.dsig.internal.dom.SignatureProvider");
        try {
            signature = getSignature(p);
        } catch (NoSuchAlgorithmException nsae) {
            throw new XMLSignatureException(nsae);
        }
    }
    signature.initVerify((PublicKey)key);
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE,
                "Signature provider:" + signature.getProvider());
        log.log(java.util.logging.Level.FINE, "verifying with key: " + key);
    }
    ((DOMSignedInfo)si).canonicalize(context,
                                     new SignerOutputStream(signature));
    byte[] s;
    try {
        // Do any necessary format conversions
        s = preVerifyFormat(key, sig);
    } catch (IOException ioe) {
        throw new XMLSignatureException(ioe);
    }
    return signature.verify(s);
}
 
@Override
protected void setup(Context context)
  throws IOException, InterruptedException {
  super.setup(context);

  Configuration configuration = context.getConfiguration();

  // Propagate verbose flag if needed
  if (configuration.getBoolean(JobBase.PROPERTY_VERBOSE, false)) {
    LoggingUtils.setDebugLevel();
  }
}
 
源代码29 项目: container   文件: Fragments.java
/**
 * Creates a BPEL4RESTLight DELETE Activity with the given BPELVar as Url to request on.
 *
 * @param bpelVarName the variable containing an URL
 * @param responseVarName the variable to hold the response
 * @return a String containing a BPEL4RESTLight Activity
 * @throws IOException is thrown when reading internal files fails
 */
public String createRESTDeleteOnURLBPELVarAsString(final String bpelVarName,
                                                   final String responseVarName) throws IOException {
    String template = readFileAsString("BPEL4RESTLightDELETE.xml");
    // <!-- $urlVarName, $ResponseVarName -->
    template = template.replace("$urlVarName", bpelVarName);
    template = template.replace("$ResponseVarName", responseVarName);

    return template;
}
 
源代码30 项目: ghidra   文件: DWARFProgram.java
/**
 * Sets the currently active compilation unit.  Used when 'paging' through the DIE records
 * in a compilation-unit-at-a-time manner, vs the {@link DWARFImportOptions#isPreloadAllDIEs()}
 * where all DIE/DIEA records are loaded at once.
 *
 * @param cu {@link DWARFCompilationUnit} to set as the active element and load it's DIE records.
 * @param monitor {@link TaskMonitor} to update with status and check for cancelation.
 * @throws CancelledException if user cancels
 * @throws IOException if error reading data
 * @throws DWARFException if error in DWARF record structure
 */
public void setCurrentCompilationUnit(DWARFCompilationUnit cu, TaskMonitor monitor)
		throws CancelledException, IOException, DWARFException {
	if (cu != currentCompUnit) {
		currentCompUnit = cu;
		if (cu != null && !importOptions.isPreloadAllDIEs()) {
			clearDIEIndexes();
			cu.readDIEs(currentDIEs, monitor);
			rebuildDIEIndexes();
		}
	}
}
 
 类所在包
 同包方法