java.io.IOException Java Examples
The following examples show how to use
java.io.IOException.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RrdSafeFileBackend.java From jrobin with GNU Lesser General Public License v2.1 | 8 votes |
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"); }
Example #2
Source File: JerseyExtensionRepoClient.java From nifi-registry with Apache License 2.0 | 7 votes |
@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); }); }
Example #3
Source File: Log.java From charliebot with GNU General Public License v2.0 | 7 votes |
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!"); } }
Example #4
Source File: Utility.java From Bytecoder with Apache License 2.0 | 7 votes |
@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]); } } } }
Example #5
Source File: FactTypeEntityTest.java From act-platform with ISC License | 7 votes |
@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); }
Example #6
Source File: GwtBinaryIntegrationTest.java From buck with Apache License 2.0 | 7 votes |
@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"); }
Example #7
Source File: ESBTestCaseUtils.java From product-ei with Apache License 2.0 | 7 votes |
/** * 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; }
Example #8
Source File: TestTajoClientV2.java From tajo with Apache License 2.0 | 7 votes |
@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"); } }
Example #9
Source File: RepositoriesService.java From Elasticsearch with Apache License 2.0 | 6 votes |
/** * 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; }
Example #10
Source File: MidiSystem.java From dragonwell8_jdk with GNU General Public License v2.0 | 6 votes |
/** * 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; } }
Example #11
Source File: BeanFactoryIntegrationTests.java From vividus with Apache License 2.0 | 6 votes |
@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(); }
Example #12
Source File: RetriableFileCopyCommand.java From hadoop with Apache License 2.0 | 5 votes |
private void compareFileLengths(FileStatus sourceFileStatus, Path target, Configuration configuration, long targetLen) throws IOException { final Path sourcePath = sourceFileStatus.getPath(); FileSystem fs = sourcePath.getFileSystem(configuration); if (fs.getFileStatus(sourcePath).getLen() != targetLen) throw new IOException("Mismatch in length of source:" + sourcePath + " and target:" + target); }
Example #13
Source File: SetOfLong.java From tlaplus with MIT License | 5 votes |
public final void recover(DataInputStream dis) throws IOException { this.count = dis.readInt(); this.length = dis.readInt(); this.thresh = dis.readInt(); this.hasZero = dis.readBoolean(); this.table = new long[this.length]; int num = this.hasZero ? this.count-1 : this.count; for (int i = 0; i < num; i++) { this.put(dis.readLong()); } }
Example #14
Source File: DefaultZipkinRestTemplateCustomizer.java From spring-cloud-sleuth with Apache License 2.0 | 5 votes |
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { request.getHeaders().add("Content-Encoding", "gzip"); ByteArrayOutputStream gzipped = new ByteArrayOutputStream(); try (GZIPOutputStream compressor = new GZIPOutputStream(gzipped)) { compressor.write(body); } return execution.execute(request, gzipped.toByteArray()); }
Example #15
Source File: TLChannelParticipantModerator.java From kotlogram with MIT License | 5 votes |
@Override @SuppressWarnings({"unchecked", "SimplifiableConditionalExpression"}) public void deserializeBody(InputStream stream, TLContext context) throws IOException { userId = readInt(stream); inviterId = readInt(stream); date = readInt(stream); }
Example #16
Source File: LogUpdateProcessorFactory.java From lucene-solr with Apache License 2.0 | 5 votes |
@Override public void processMergeIndexes(MergeIndexesCommand cmd) throws IOException { if (logDebug) { log.debug("PRE_UPDATE {} {}", cmd, req); } if (next != null) next.processMergeIndexes(cmd); toLog.add("mergeIndexes", cmd.toString()); }
Example #17
Source File: MiniDFS.java From vxquery with Apache License 2.0 | 5 votes |
public void startHDFS(String folder) throws IOException { JobConf conf = new JobConf(); conf.addResource(new Path(PATH_TO_HADOOP_CONF + "/core-site.xml")); conf.addResource(new Path(PATH_TO_HADOOP_CONF + "/mapred-site.xml")); conf.addResource(new Path(PATH_TO_HADOOP_CONF + "/hdfs-site.xml")); int numDataNodes = 1; int nameNodePort = 40000; System.setProperty("hadoop.log.dir", "logs"); System.setProperty("test.build.data", folder.concat("/")); MiniDFSCluster.Builder build = new MiniDFSCluster.Builder(conf); build.nameNodePort(nameNodePort); build.nameNodeHttpPort(nameNodePort + 34); build.numDataNodes(numDataNodes); build.checkExitOnShutdown(true); build.startupOption(StartupOption.REGULAR); build.format(true); build.waitSafeMode(true); dfsCluster = build.build(); FileSystem dfs = FileSystem.get(conf); Path src = new Path(DATA_PATH); dfs.mkdirs(new Path("/tmp")); Path dest = new Path("/tmp/vxquery-hdfs-test"); dfs.copyFromLocalFile(src, dest); if (dfs.exists(dest)) { System.err.println("Test files copied to HDFS successfully"); } dfs.close(); }
Example #18
Source File: DWARFProgram.java From ghidra with Apache License 2.0 | 5 votes |
/** * 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(); } } }
Example #19
Source File: Annotation.java From HotswapAgent with GNU General Public License v2.0 | 5 votes |
/** * Writes this annotation. * * @param writer the output. * @throws IOException for an error during the write */ public void write(AnnotationsWriter writer) throws IOException { String typeName = pool.getUtf8Info(typeIndex); if (members == null) { writer.annotation(typeName, 0); return; } writer.annotation(typeName, members.size()); for (Pair pair:members.values()) { writer.memberValuePair(pair.name); pair.value.write(writer); } }
Example #20
Source File: Fragments.java From container with Apache License 2.0 | 5 votes |
/** * 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; }
Example #21
Source File: JobPrefixFile.java From helios with Apache License 2.0 | 5 votes |
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(); }
Example #22
Source File: IdpFaviconServlet.java From oxTrust with MIT License | 5 votes |
private boolean readDefaultFavicon(HttpServletResponse response) { String defaultFaviconFileName = "/WEB-INF/static/images/favicon_icosahedron.ico"; try (InputStream in = getServletContext().getResourceAsStream(defaultFaviconFileName); OutputStream out = response.getOutputStream()) { IOUtils.copy(in, out); return true; } catch (IOException e) { log.debug("Error loading default favicon: " + e.getMessage()); return false; } }
Example #23
Source File: FaceLandmarks.java From ssj with GNU General Public License v3.0 | 5 votes |
@Override public void init(double frame, double delta) throws SSJException { if (!new File(MODEL_PATH).exists()) { try { Pipeline.getInstance().download(MODEL_NAME, FileCons.REMOTE_MODEL_PATH, FileCons.MODELS_DIR, true); } catch (IOException e) { throw new SSJException("Error while downloading landmark model!", e); } } }
Example #24
Source File: SqoopReducer.java From aliyun-maxcompute-data-collectors with Apache License 2.0 | 5 votes |
@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(); } }
Example #25
Source File: DOMSignatureMethod.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
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); }
Example #26
Source File: Socks4Message.java From T0rlib4j with Apache License 2.0 | 5 votes |
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); } }
Example #27
Source File: DispatcherServletTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@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); }
Example #28
Source File: GreetingServiceTest.java From tomee with Apache License 2.0 | 5 votes |
@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); }
Example #29
Source File: SessionClusterEvent.java From keycloak with Apache License 2.0 | 5 votes |
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); }
Example #30
Source File: MqResourceTest.java From pmq with Apache License 2.0 | 5 votes |
@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()); }