下面列出了怎么用java.io.IOException的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
});
}
/**
* 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;
}
@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]);
}
}
}
}
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!");
}
}
@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");
}
@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");
}
}
/**
* 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;
}
}
@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();
}
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);
}
/**
* 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;
}
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");
}
@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());
}
/**
* 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;
}
@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();
}
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);
}
@Override
public SecurityInformation getSecurityInformation(String sessionToken) throws UnauthorizedException, IOException {
HuygensSession session = doSessionDetailsRequest(sessionToken);
doSessionRefresh(sessionToken);
return new HuygensSecurityInformation(session.getOwner());
}
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);
}
@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);
}
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);
}
});
}
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);
}
}
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();
}
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);
}
@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);
}
@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);
}
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);
}
}
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();
}
}
/**
* 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;
}
/**
* 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();
}
}
}