Java Code Examples for java.io.IOException#getMessage()

The following examples show how to use java.io.IOException#getMessage() . 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: StyledDocumentReader.java    From editorconfig-netbeans with MIT License 6 votes vote down vote up
public static ArrayList<String> readFileObjectIntoLines(FileObject fo, Charset charset, String lineEnding)
        throws FileAccessException {
  ArrayList<String> lines = new ArrayList<>();
  String line;

  try (BufferedReader reader = new BufferedReader(new InputStreamReader(fo.getInputStream(), charset))) {
    while ((line = reader.readLine()) != null) {
      lines.add(line);
      lines.add(lineEnding);
    }

    // Remove last line-break
    lines.remove(lines.size() - 1);
  } catch (IOException ex) {
    throw new FileAccessException("Document could not be read: " + ex.getMessage());
  }

  return lines;
}
 
Example 2
Source File: XProtocol.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <QR extends QueryResult> QR readQueryResult() {
    try {
        StatementExecuteOkBuilder builder = new StatementExecuteOkBuilder();
        XMessageHeader header;
        if ((header = this.reader.readHeader()).getMessageType() == ServerMessages.Type.RESULTSET_FETCH_DONE_VALUE) {
            this.reader.readMessage(null, header);
        }
        while ((header = this.reader.readHeader()).getMessageType() == ServerMessages.Type.NOTICE_VALUE) {
            builder.addNotice(this.noticeFactory.createFromMessage(this.reader.readMessage(null, header)));
        }
        this.reader.readMessage(null, ServerMessages.Type.SQL_STMT_EXECUTE_OK_VALUE);
        return (QR) builder.build();
    } catch (IOException e) {
        throw new XProtocolError(e.getMessage(), e);
    }
}
 
Example 3
Source File: BirtWizardUtil.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Create zip entry from plugin directory
 * 
 * @param pluginRelativePath
 * @param symbolicName
 * @return
 * @throws CoreException
 */
private static ZipFile getZipFileFromPluginDir( String pluginRelativePath,
		String symbolicName ) throws CoreException
{
	try
	{
		Bundle bundle = Platform.getBundle( symbolicName );
		if ( bundle == null )
			return null;

		URL starterURL = new URL(
				bundle.getEntry( "/" ), pluginRelativePath ); //$NON-NLS-1$
		return new ZipFile( FileLocator.toFileURL( starterURL ).getFile( ) );
	}
	catch ( IOException e )
	{
		String message = pluginRelativePath + ": " + e.getMessage( ); //$NON-NLS-1$
		Logger.logException( e );
		throw BirtCoreException.getException( message, e );
	}
}
 
Example 4
Source File: OpenVidu.java    From openvidu with Apache License 2.0 6 votes vote down vote up
/**
 * Gets an existing recording
 *
 * @param recordingId The id property of the recording you want to retrieve
 * 
 * @throws OpenViduJavaClientException
 * @throws OpenViduHttpException       Value returned from
 *                                     {@link io.openvidu.java.client.OpenViduHttpException#getStatus()}
 *                                     <ul>
 *                                     <li><code>404</code>: no recording exists
 *                                     for the passed <i>recordingId</i></li>
 *                                     </ul>
 */
public Recording getRecording(String recordingId) throws OpenViduJavaClientException, OpenViduHttpException {
	HttpGet request = new HttpGet(this.hostname + API_RECORDINGS + "/" + recordingId);
	HttpResponse response;
	try {
		response = this.httpClient.execute(request);
	} catch (IOException e) {
		throw new OpenViduJavaClientException(e.getMessage(), e.getCause());
	}

	try {
		int statusCode = response.getStatusLine().getStatusCode();
		if ((statusCode == org.apache.http.HttpStatus.SC_OK)) {
			return new Recording(httpResponseToJson(response));
		} else {
			throw new OpenViduHttpException(statusCode);
		}
	} finally {
		EntityUtils.consumeQuietly(response.getEntity());
	}
}
 
Example 5
Source File: CompensablePrimaryFilter.java    From ByteTCC with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void beforeConsumerInvokeForSVC(Invocation invocation, TransactionRequestImpl request,
		TransactionResponseImpl response) {
	CompensableBeanRegistry beanRegistry = CompensableBeanRegistry.getInstance();
	CompensableBeanFactory beanFactory = beanRegistry.getBeanFactory();
	TransactionInterceptor transactionInterceptor = beanFactory.getTransactionInterceptor();
	RemoteCoordinator compensableCoordinator = (RemoteCoordinator) beanFactory.getCompensableNativeParticipant();

	Map<String, String> attachments = invocation.getAttachments();
	attachments.put(RemoteCoordinator.class.getName(), compensableCoordinator.getIdentifier());

	transactionInterceptor.beforeSendRequest(request);
	if (request.getTransactionContext() != null) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		HessianOutput output = new HessianOutput(baos);
		try {
			output.writeObject(request.getTransactionContext());
		} catch (IOException ex) {
			logger.error("Error occurred in remote call!", ex);
			throw new RemotingException(ex.getMessage());
		}

		String transactionContextContent = ByteUtils.byteArrayToString(baos.toByteArray());
		attachments.put(TransactionContext.class.getName(), transactionContextContent);
	}
}
 
Example 6
Source File: NetscapeCertRequest.java    From ripple-lib-java with ISC License 6 votes vote down vote up
private ASN1Primitive getKeySpec() throws NoSuchAlgorithmException,
        InvalidKeySpecException, NoSuchProviderException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    ASN1Primitive obj = null;
    try
    {

        baos.write(pubkey.getEncoded());
        baos.close();

        ASN1InputStream derin = new ASN1InputStream(
                new ByteArrayInputStream(baos.toByteArray()));

        obj = derin.readObject();
    }
    catch (IOException ioe)
    {
        throw new InvalidKeySpecException(ioe.getMessage());
    }
    return obj;
}
 
Example 7
Source File: AppDeploymentsClientResource.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
/**
 * POST /rest/activiti/apps: upload a app
 */
@RequestMapping(method=RequestMethod.POST)
public void handleFileUpload(HttpServletRequest request, HttpServletResponse httpResponse, @RequestParam("file") MultipartFile file){
    if (!file.isEmpty()) {
    	try {
    		ServerConfig serverConfig = retrieveServerConfig();
    		String fileName = file.getOriginalFilename();
    		if (fileName != null && fileName.endsWith(".zip")) {
    			clientService.uploadAppDefinition(httpResponse, serverConfig, fileName, file.getInputStream());
    		} else {
    			throw new BadRequestException("Invalid file name");
    		}
        } catch (IOException e) {
        	throw new InternalServerErrorException("Could not deploy file: " + e.getMessage());
        }
    } else {
        throw new BadRequestException("No file found in POST body");
    }
}
 
Example 8
Source File: PropertyManager.java    From mdw with Apache License 2.0 5 votes vote down vote up
private synchronized static PropertyManager initializePropertyManager()
        throws StartupException {

    String pm = System.getProperty(MDW_PROPERTY_MANAGER);
    if (pm != null) {
        System.out.println("Using Property Manager: " + pm);
        try {
            Class<?> cls = PropertyManager.class.getClassLoader().loadClass(pm);
            instance = (PropertyManager) cls.newInstance();
        }
        catch (Exception e) {
            String msg = "Cannot create property manager " + pm;
            System.out.println(msg);
            e.printStackTrace();
            throw new StartupException(msg);
        }
    }
    else {
        File yamlFile = FileHelper.getConfigurationFile("mdw.yaml");
        if (yamlFile.exists()) {
            try {
                instance = new YamlPropertyManager(yamlFile);
            }
            catch (IOException ex) {
                throw new StartupException(ex.getMessage(), ex);
            }
        }
        else {
            instance = new JavaPropertyManager();
        }
    }
    // override limberest json formatting
    JsonObject.configure(instance);

    return instance;
}
 
Example 9
Source File: ReplayAllCommand.java    From Cardshifter with Apache License 2.0 5 votes vote down vote up
private boolean checkReplay(Server server, File file, String mod) {
	ReplayRecordSystem replay;
	try {
		replay = CardshifterIO.mapper().readValue(file, ReplayRecordSystem.class);
	} catch (IOException e1) {
		throw new RuntimeException("Error loading replay: " + e1.getMessage(), e1);
	}
	
	String actualMod = replay.getModName() != null ? replay.getModName() : mod;
	TCGGame game = (TCGGame) server.createGame(actualMod);
	ReplayPlaybackSystem playback = new ReplayPlaybackSystem(game.getGameModel(), replay);
	game.getGameModel().addSystem(playback);
	FakeClient fake1 = new FakeClient(server, e -> {});
	FakeClient fake2 = new FakeClient(server, e -> {});
	game.start(Arrays.asList(fake1, fake2));
	System.out.println("Game state is " + game.getState());
	if (game.getState() == ECSGameState.NOT_STARTED) {
		System.out.println("Loading configs from saved data");
		playback.setPlayerConfigs(game.getGameModel());
		game.checkStartGame();
	}

	while (!playback.isReplayFinished()) {
		playback.nextStep();
	}
	
	return game.isGameOver();
}
 
Example 10
Source File: ExcelUtils.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public static void closeIO(Closeable io){
	try {
		if(io!=null)
			io.close();
	} catch (IOException e) {
		throw new RuntimeException("close io error: " + e.getMessage(), e);
	}
}
 
Example 11
Source File: KairosDB.java    From iotdb-benchmark with Apache License 2.0 5 votes vote down vote up
@Override
public void close() throws TsdbException {
  try {
    client.close();
  } catch (IOException e) {
    throw new TsdbException("Close KairosDB client failed, because " + e.getMessage());
  }
}
 
Example 12
Source File: FileFixture.java    From hsac-fitnesse-fixtures with Apache License 2.0 5 votes vote down vote up
public String unzipAs(String zipname, String targetDir) {
    String zipfile = getFullName(zipname);

    try {
        String nonExistingTarget = findNameForFile(targetDir);
        getEnvironment().getZipHelper().unzip(zipfile, nonExistingTarget);
        return linkToFile(nonExistingTarget);
    } catch (IOException e) {
        throw new SlimFixtureException(true, "Unable to unzip. " + e.getMessage(), e);
    }

}
 
Example 13
Source File: Session.java    From openvidu with Apache License 2.0 5 votes vote down vote up
/**
 * Forces some user to unpublish a Stream. OpenVidu Browser will trigger the
 * proper events on the client-side (<code>streamDestroyed</code>) with reason
 * set to "forceUnpublishByServer". <br>
 * 
 * You can get <code>streamId</code> parameter with
 * {@link io.openvidu.java.client.Session#getActiveConnections()} and then for
 * each Connection you can call
 * {@link io.openvidu.java.client.Connection#getPublishers()}. Finally
 * {@link io.openvidu.java.client.Publisher#getStreamId()}) will give you the
 * <code>streamId</code>. Remember to call
 * {@link io.openvidu.java.client.Session#fetch()} before to fetch the current
 * actual properties of the Session from OpenVidu Server
 * 
 * @throws OpenViduJavaClientException
 * @throws OpenViduHttpException
 */
public void forceUnpublish(String streamId) throws OpenViduJavaClientException, OpenViduHttpException {
	HttpDelete request = new HttpDelete(
			this.openVidu.hostname + OpenVidu.API_SESSIONS + "/" + this.sessionId + "/stream/" + streamId);
	request.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");

	HttpResponse response;
	try {
		response = this.openVidu.httpClient.execute(request);
	} catch (IOException e) {
		throw new OpenViduJavaClientException(e.getMessage(), e.getCause());
	}

	try {
		int statusCode = response.getStatusLine().getStatusCode();
		if ((statusCode == org.apache.http.HttpStatus.SC_NO_CONTENT)) {
			for (Connection connection : this.activeConnections.values()) {
				// Try to remove the Publisher from the Connection publishers collection
				if (connection.publishers.remove(streamId) != null) {
					continue;
				}
				// Try to remove the Publisher from the Connection subscribers collection
				connection.subscribers.remove(streamId);
			}
			log.info("Stream {} unpublished", streamId);
		} else {
			throw new OpenViduHttpException(statusCode);
		}
	} finally {
		EntityUtils.consumeQuietly(response.getEntity());
	}
}
 
Example 14
Source File: SubjectManageAction.java    From OnLineTest with Apache License 2.0 5 votes vote down vote up
public String addSubject(){
	Subject subject = new Subject();
	subject.setSubjectName(subjectName);
	Subject subject2 = subjectService.getSubjectByName(subject);
	int success = 0;
	if(subject2!=null){
		success = -1;//已经存在试卷
	}else{
		subject.setChoiceScore(choiceScore);
		subject.setJudgeScore(judgeScore);
		subject.setSubjectTime(subjectTime);
		Course course = new Course();
		course.setCourseId(courseId);
		subject.setCourse(course);
		boolean b = subjectService.addSubject(subject);
		if(b){
			success = 1;
		}else{
			success = 0;
		
		}
	}
	try {
		ServletActionContext.getResponse().getWriter().print(success);//向浏览器响应是否成功的状态码
	} catch (IOException e) {
		// TODO Auto-generated catch block
		throw new RuntimeException(e.getMessage());
	}
	return null;
}
 
Example 15
Source File: QueryAction.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
protected void updateRequestWithCollapse(Select select, SearchRequestBuilder request) throws SqlParseException {
    for (Hint hint : select.getHints()) {
        if (hint.getType() == HintType.COLLAPSE && hint.getParams() != null && 0 < hint.getParams().length) {
            try (XContentParser parser = JsonXContent.jsonXContent.createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, hint.getParams()[0].toString())) {
                request.setCollapse(CollapseBuilder.fromXContent(parser));
            } catch (IOException e) {
                throw new SqlParseException("could not parse collapse hint: " + e.getMessage());
            }
        }
    }
}
 
Example 16
Source File: ScanTask.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    output.getParentFile().mkdirs();
    try (final OutputStream stream = new FileOutputStream(output)) {
        final Properties properties = new Properties();
        properties.setProperty("classes.list", scanList().collect(joining(",")));
        properties.store(stream, "generated by " + getClass() + " at " + new Date());
    } catch (final IOException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}
 
Example 17
Source File: KeyProtector.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
public Key recover(EncryptedPrivateKeyInfo encrInfo)
    throws UnrecoverableKeyException
{
    int i;
    byte[] digest;
    int numRounds;
    int xorOffset; // offset in xorKey where next digest will be stored
    int encrKeyLen; // the length of the encrpyted key

    // do we support the algorithm?
    AlgorithmId encrAlg = encrInfo.getAlgorithm();
    if (!(encrAlg.getOID().toString().equals(KEY_PROTECTOR_OID))) {
        throw new UnrecoverableKeyException("Unsupported key protection "
                                            + "algorithm");
    }

    byte[] protectedKey = encrInfo.getEncryptedData();

    /*
     * Get the salt associated with this key (the first SALT_LEN bytes of
     * <code>protectedKey</code>)
     */
    byte[] salt = new byte[SALT_LEN];
    System.arraycopy(protectedKey, 0, salt, 0, SALT_LEN);

    // Determine the number of digest rounds
    encrKeyLen = protectedKey.length - SALT_LEN - DIGEST_LEN;
    numRounds = encrKeyLen / DIGEST_LEN;
    if ((encrKeyLen % DIGEST_LEN) != 0) numRounds++;

    // Get the encrypted key portion and store it in "encrKey"
    byte[] encrKey = new byte[encrKeyLen];
    System.arraycopy(protectedKey, SALT_LEN, encrKey, 0, encrKeyLen);

    // Set up the byte array which will be XORed with "encrKey"
    byte[] xorKey = new byte[encrKey.length];

    // Compute the digests, and store them in "xorKey"
    for (i = 0, xorOffset = 0, digest = salt;
         i < numRounds;
         i++, xorOffset += DIGEST_LEN) {
        md.update(passwdBytes);
        md.update(digest);
        digest = md.digest();
        md.reset();
        // Copy the digest into "xorKey"
        if (i < numRounds - 1) {
            System.arraycopy(digest, 0, xorKey, xorOffset,
                             digest.length);
        } else {
            System.arraycopy(digest, 0, xorKey, xorOffset,
                             xorKey.length - xorOffset);
        }
    }

    // XOR "encrKey" with "xorKey", and store the result in "plainKey"
    byte[] plainKey = new byte[encrKey.length];
    for (i = 0; i < plainKey.length; i++) {
        plainKey[i] = (byte)(encrKey[i] ^ xorKey[i]);
    }

    /*
     * Check the integrity of the recovered key by concatenating it with
     * the password, digesting the concatenation, and comparing the
     * result of the digest operation with the digest provided at the end
     * of <code>protectedKey</code>. If the two digest values are
     * different, throw an exception.
     */
    md.update(passwdBytes);
    Arrays.fill(passwdBytes, (byte)0x00);
    passwdBytes = null;
    md.update(plainKey);
    digest = md.digest();
    md.reset();
    for (i = 0; i < digest.length; i++) {
        if (digest[i] != protectedKey[SALT_LEN + encrKeyLen + i]) {
            throw new UnrecoverableKeyException("Cannot recover key");
        }
    }

    // The parseKey() method of PKCS8Key parses the key
    // algorithm and instantiates the appropriate key factory,
    // which in turn parses the key material.
    try {
        return PKCS8Key.parseKey(new DerValue(plainKey));
    } catch (IOException ioe) {
        throw new UnrecoverableKeyException(ioe.getMessage());
    }
}
 
Example 18
Source File: TestIndexWriterMaxDocs.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
/** 
 * LUCENE-6299: Test if addindexes(Dir[]) prevents exceeding max docs.
 */
// TODO: can we use the setter to lower the amount of docs to be written here?
@Nightly
public void testAddTooManyIndexesDir() throws Exception {
  // we cheat and add the same one over again... IW wants a write lock on each
  Directory dir = newDirectory(random(), NoLockFactory.INSTANCE);
  Document doc = new Document();
  IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(null));
  for (int i = 0; i < 100000; i++) {
    w.addDocument(doc);
  }
  w.forceMerge(1);
  w.commit();
  w.close();
  
  // wrap this with disk full, so test fails faster and doesn't fill up real disks.
  MockDirectoryWrapper dir2 = newMockDirectory();
  w = new IndexWriter(dir2, new IndexWriterConfig(null));
  w.commit(); // don't confuse checkindex
  dir2.setMaxSizeInBytes(dir2.sizeInBytes() + 65536); // 64KB
  Directory dirs[] = new Directory[1 + (IndexWriter.MAX_DOCS / 100000)];
  for (int i = 0; i < dirs.length; i++) {
    // bypass iw check for duplicate dirs
    dirs[i] = new FilterDirectory(dir) {};
  }

  try {
    w.addIndexes(dirs);
    fail("didn't get expected exception");
  } catch (IllegalArgumentException expected) {
    // pass
  } catch (IOException fakeDiskFull) {
    final Exception e;
    if (fakeDiskFull.getMessage() != null && fakeDiskFull.getMessage().startsWith("fake disk full")) {
      e = new RuntimeException("test failed: IW checks aren't working and we are executing addIndexes");
      e.addSuppressed(fakeDiskFull);
    } else {
      e = fakeDiskFull;
    }
    throw e;
  }
  
  w.close();
  dir.close();
  dir2.close();
}
 
Example 19
Source File: DocPretty.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
UncheckedIOException(IOException e) {
    super(e.getMessage(), e);
}
 
Example 20
Source File: BulkIngestMapFileLoaderTest.java    From datawave with Apache License 2.0 2 votes vote down vote up
@Test
public void testCleanUpJobDirectoryWithFailedJobAndFailedRenames() throws Exception {
    
    BulkIngestMapFileLoaderTest.logger.info("testCleanUpJobDirectoryWithFailedJobAndFailedRenames called...");
    
    try {
        
        URL url = BulkIngestMapFileLoaderTest.class.getResource("/datawave/ingest/mapreduce/job/");
        
        String workDir = ".";
        String jobDirPattern = "jobs/";
        String instanceName = "localhost";
        String zooKeepers = "localhost";
        Credentials credentials = new Credentials("user", new PasswordToken("pass"));
        URI seqFileHdfs = url.toURI();
        URI srcHdfs = url.toURI();
        URI destHdfs = url.toURI();
        String jobtracker = "localhost";
        Map<String,Integer> tablePriorities = new HashMap<>();
        Configuration conf = new Configuration();
        
        BulkIngestMapFileLoader uut = new BulkIngestMapFileLoader(workDir, jobDirPattern, instanceName, zooKeepers, credentials, seqFileHdfs, srcHdfs,
                        destHdfs, jobtracker, tablePriorities, conf, 0);
        
        Assert.assertNotNull("BulkIngestMapFileLoader constructor failed to create an instance.", uut);
        
        BulkIngestMapFileLoaderTest.WrappedLocalFileSystem fs = new BulkIngestMapFileLoaderTest.WrappedLocalFileSystem(createMockInputStream(),
                        new FileStatus[] {createMockFileStatus()}, false, false, false, true, null, false, false);
        
        Whitebox.invokeMethod(FileSystem.class, "addFileSystemForTesting", BulkIngestMapFileLoaderTest.FILE_SYSTEM_URI, conf, fs);
        
        Path mapFilesDir = new Path(url.toString());
        
        uut.cleanUpJobDirectory(mapFilesDir);
        
        List<String> uutLogEntries = retrieveUUTLogs();
        
        Assert.assertTrue("BulkIngestMapFileLoader#cleanUpJobDirectory failed to call FileSystem#mkdirs",
                        processOutputContains(uutLogEntries, "There were failures bringing map files online."));
        Assert.assertTrue("BulkIngestMapFileLoader#cleanUpJobDirectory failed to call FileSystem#rename",
                        processOutputContains(uutLogEntries, "Unable to rename map files directory "));
    } catch (URISyntaxException e) {
        
        Assert.fail("Class#getResource failed to return a valid URI");
        
    } catch (IOException ioe) {
        
        String msg = ioe.getMessage();
        
        Assert.assertTrue("BulkIngestMapFileLoader#markSourceFilesLoaded failed to throw the excepted IOException.",
                        msg.startsWith("Unable to create parent dir "));
        
    } catch (Throwable t) {
        
        Assert.fail(String.format("BulkIngestMapFileLoader unexpectedly threw an exception: %s with message of '%s'", t.getClass().getName(),
                        t.getMessage()));
        
    } finally {
        
        Whitebox.invokeMethod(FileSystem.class, "addFileSystemForTesting", BulkIngestMapFileLoaderTest.FILE_SYSTEM_URI, null, null);
        
        BulkIngestMapFileLoaderTest.logger.info("testCleanUpJobDirectoryWithFailedJobAndFailedRenames completed.");
    }
    
}