List of usage examples for java.io Writer append
public Writer append(char c) throws IOException
From source file:org.sonar.plugins.csharp.gendarme.profiles.GendarmeProfileExporter.java
private void marshall(Writer writer, List<ActiveRule> rules, RulePriority priority) throws IOException { Map<String, List<ActiveRule>> assemblyRulesMap = new HashMap<String, List<ActiveRule>>(); boolean assemblyRulesMapEmpty = true; for (ActiveRule activeRule : rules) { if (priority != null && priority != activeRule.getSeverity()) { continue; }// w w w. j av a 2 s . c om String key = activeRule.getConfigKey(); String assembly = StringUtils.substringAfter(key, "@"); List<ActiveRule> assemblyRules = assemblyRulesMap.get(assembly); if (assemblyRules == null) { assemblyRules = new ArrayList<ActiveRule>(); assemblyRulesMap.put(assembly, assemblyRules); assemblyRulesMapEmpty = false; } assemblyRules.add(activeRule); } if (!assemblyRulesMapEmpty) { if (priority == null) { writer.append(" <ruleset name=\"default\">\n"); } else { writer.append(" <ruleset name=\"" + priority.name().toLowerCase() + "\">\n"); } for (Map.Entry<String, List<ActiveRule>> entry : assemblyRulesMap.entrySet()) { writer.append(" <rules include=\""); appendRuleList(writer, entry.getValue()); writer.append("\" from=\""); writer.append(entry.getKey()); writer.append("\">\n"); appendRuleParams(writer, entry.getValue()); writer.append(" </rules>\n"); } writer.append(" </ruleset>\n"); } }
From source file:org.exoplatform.social.notification.plugin.RequestJoinSpacePlugin.java
@Override public boolean makeDigest(NotificationContext ctx, Writer writer) { List<NotificationInfo> notifications = ctx.getNotificationInfos(); NotificationInfo first = notifications.get(0); String language = getLanguage(first); TemplateContext templateContext = new TemplateContext(first.getKey().getId(), language); Map<String, List<String>> map = new LinkedHashMap<String, List<String>>(); try {/*from w w w . j av a 2 s .c o m*/ for (NotificationInfo message : notifications) { String spaceId = message.getValueOwnerParameter(SocialNotificationUtils.SPACE_ID.getKey()); String fromUser = message.getValueOwnerParameter("request_from"); Space space = Utils.getSpaceService().getSpaceById(spaceId); if (ArrayUtils.contains(space.getPendingUsers(), fromUser) == false) { continue; } // SocialNotificationUtils.processInforSendTo(map, spaceId, fromUser); } writer.append(SocialNotificationUtils.getMessageByIds(map, templateContext)); } catch (IOException e) { ctx.setException(e); return false; } return true; }
From source file:pltag.parser.Lexicon.java
public void postProcessLexicon(boolean writeToDisk) { // lexiconReduce(); if (writeToDisk) { try {/*from w ww . j ava2 s .c o m*/ Writer lexWriter = IOUtils.openOutEasy("normal_lexicon.txt"); for (String key : lexEntriesTree.keySet()) { lexWriter.append(key).append("-> ["); for (Object val : lexEntriesTree.getCollection(key)) { lexWriter.append(val.toString()).append(","); } lexWriter.append("]\n"); } lexWriter.close(); } catch (IOException e) { LogInfo.error(e); } try { Writer familywriter = IOUtils.openOutEasy("family_lexicon.txt"); for (String key : trees.keySet()) { familywriter.append(key).append("-> ["); for (String val : trees.getCollection(key)) { familywriter.append(val).append(","); } familywriter.append("]\n"); } familywriter.close(); } catch (IOException e) { LogInfo.error(e); } } // if extractFamilyLexicon(writeToDisk); removeHelps(); }
From source file:org.wso2.carbon.registry.ws.client.registry.WSRegistryServiceClient.java
public void restore(String path, Reader reader) throws RegistryException { try {// w ww . j av a 2s.c o m BufferedReader bufferedReader = new BufferedReader(reader); File tempFile = new File("tempFile"); tempFile.deleteOnExit(); FileOutputStream fileOutputStream = new FileOutputStream(tempFile); Writer writer = new OutputStreamWriter(fileOutputStream); String inputLine; while ((inputLine = bufferedReader.readLine()) != null) { writer.append(inputLine); } writer.flush(); fileOutputStream.close(); writer.close(); bufferedReader.close(); DataHandler handler = new DataHandler(new FileDataSource(tempFile)); stub.wsRestore(path, handler); @SuppressWarnings("unused") boolean ignored = tempFile.delete(); } catch (Exception e) { String msg = "Failed to perform restore operation."; log.error(msg, e); throw new RegistryException(msg, e); } }
From source file:pltag.parser.semantics.SemanticLexicon.java
@Override protected void extractFamilyLexicon(boolean writeToDisk) { try {//from w w w.j av a 2s.c o m Writer unlexSizeWriter = writeToDisk ? IOUtils.openOutEasy("family_size_lexicon.txt") : null; Collection<String> keyset = new ArrayList<String>(noOfTrees.keySet()); for (String key : keyset) { if (!key.contains("LEXEME")) { noOfTrees.remove(key); continue; } Integer frequency = noOfTrees.get(key); String val = frequency.toString(); if (unlexSizeWriter != null) unlexSizeWriter.append(val).append("\t").append(key).append("\n"); if (frequency < 5) { noOfTrees.remove(key); } else if (frequency >= 100) { String[] posUnlexTree = key.split("\t"); MultiValueMap temp = new MultiValueMap(); for (Object obj : lexEntriesTree.values()) { LexiconEntryWithRoles entry = (LexiconEntryWithRoles) obj; if (entry.getUnlexEntry().equals(posUnlexTree[1])) { updateEntryWithRolesMap(temp, posUnlexTree[0], entry); } } lexEntriesTree.putAll(temp); } } if (unlexSizeWriter != null) unlexSizeWriter.close(); } catch (IOException e) { LogInfo.error(e); } }
From source file:com.dm.material.dashboard.candybar.fragments.RequestFragment.java
private void sendRequest(BillingProcessor billingProcessor) { new AsyncTask<Void, Void, Boolean>() { MaterialDialog dialog;//from w w w .j a v a 2s . co m StringBuilder sb; String zipFile; String productId = ""; String orderId = ""; @Override protected void onPreExecute() { super.onPreExecute(); sb = new StringBuilder(); MaterialDialog.Builder builder = new MaterialDialog.Builder(getActivity()); builder.content(R.string.request_building); builder.cancelable(false); builder.canceledOnTouchOutside(false); builder.progress(true, 0); builder.progressIndeterminateStyle(true); dialog = builder.build(); dialog.show(); } @Override protected Boolean doInBackground(Void... voids) { while (!isCancelled()) { try { Thread.sleep(1); Database database = new Database(getActivity()); File directory = getActivity().getCacheDir(); sb.append(DeviceHelper.getDeviceInfo(getActivity())); if (Preferences.getPreferences(getActivity()).isPremiumRequest()) { if (billingProcessor == null) return false; TransactionDetails details = billingProcessor.getPurchaseTransactionDetails( Preferences.getPreferences(getActivity()).getPremiumRequestProductId()); if (details != null) { orderId = details.purchaseInfo.purchaseData.orderId; productId = details.purchaseInfo.purchaseData.productId; sb.append("Order Id : ").append(orderId).append("\nProduct Id : ").append(productId) .append("\n"); } } List<Integer> selectedItems = mAdapter.getSelectedItems(); List<String> files = new ArrayList<>(); File appFilter = new File(directory.toString() + "/" + "appfilter.xml"); Writer out = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(appFilter), "UTF8")); for (int i = 0; i < selectedItems.size(); i++) { Request item = mAdapter.getRequest(selectedItems.get(i)); database.addRequest(item.getName(), item.getActivity(), null); mAdapter.setRequested(selectedItems.get(i), true); String string = RequestHelper.writeRequest(item); sb.append(string); String string1 = RequestHelper.writeAppFilter(item); out.append(string1); Bitmap bitmap = DrawableHelper.getHighQualityIcon(getActivity(), item.getPackageName()); String icon = FileHelper.saveIcon(directory, bitmap, item.getName()); if (icon != null) files.add(icon); if (Preferences.getPreferences(getActivity()).isPremiumRequest()) { database.addPremiumRequest(null, orderId, productId, item.getName(), item.getActivity(), null); } } out.flush(); out.close(); files.add(appFilter.toString()); zipFile = directory.toString() + "/" + "icon_request.zip"; FileHelper.createZip(files, zipFile); return true; } catch (Exception e) { LogUtil.e(Log.getStackTraceString(e)); return false; } } return false; } @Override protected void onPostExecute(Boolean aBoolean) { super.onPostExecute(aBoolean); dialog.dismiss(); if (aBoolean) { String subject = Preferences.getPreferences(getActivity()).isPremiumRequest() ? "Premium Icon Request " : "Icon Request "; subject = subject + getActivity().getResources().getString(R.string.app_name); Request request = new Request(subject, sb.toString(), zipFile, mAdapter.getSelectedItemsSize()); try { RequestListener listener = (RequestListener) getActivity(); listener.onRequestBuilt(request); } catch (Exception ignored) { } mAdapter.resetSelectedItems(); } else { Toast.makeText(getActivity(), R.string.request_build_failed, Toast.LENGTH_LONG).show(); } dialog = null; sb.setLength(0); sb.trimToSize(); } }.execute(); }
From source file:org.callimachusproject.auth.DetachedRealm.java
public void transformErrorPage(String xhtml, Writer writer, String target, String query) throws IOException { if (error != null && inError.get() == null && activeErrors.get() < MAX_PRETTY_CONCURRENT_ERRORS) { String id = error.getSystemId(); if (id == null || !id.equals(target)) { try { inError.set(true);//from ww w. ja v a 2s . co m activeErrors.incrementAndGet(); Pipe pb = error.pipeReader(new StringReader(xhtml), target); try { pb.passOption("target", target); pb.passOption("query", query); String body = pb.asString(); writer.append(body); return; } finally { pb.close(); } } catch (Throwable exc) { logger.error(exc.toString(), exc); } finally { inError.remove(); activeErrors.decrementAndGet(); } } } writer.write(xhtml); }
From source file:org.apache.hadoop.hbase.regionserver.TestFailedAppendAndSync.java
/** * Reproduce locking up that happens when we get an exceptions appending and syncing. * See HBASE-14317./*from www. j a va 2 s . c o m*/ * First I need to set up some mocks for Server and RegionServerServices. I also need to * set up a dodgy WAL that will throw an exception when we go to append to it. */ @Test(timeout = 300000) public void testLockupAroundBadAssignSync() throws IOException { final AtomicLong rolls = new AtomicLong(0); // Dodgy WAL. Will throw exceptions when flags set. class DodgyFSLog extends FSHLog { volatile boolean throwSyncException = false; volatile boolean throwAppendException = false; public DodgyFSLog(FileSystem fs, Path root, String logDir, Configuration conf) throws IOException { super(fs, root, logDir, conf); } @Override public byte[][] rollWriter(boolean force) throws FailedLogCloseException, IOException { byte[][] regions = super.rollWriter(force); rolls.getAndIncrement(); return regions; } @Override protected Writer createWriterInstance(Path path) throws IOException { final Writer w = super.createWriterInstance(path); return new Writer() { @Override public void close() throws IOException { w.close(); } @Override public void sync() throws IOException { if (throwSyncException) { throw new IOException("FAKE! Failed to replace a bad datanode..."); } w.sync(); } @Override public void append(Entry entry) throws IOException { if (throwAppendException) { throw new IOException("FAKE! Failed to replace a bad datanode..."); } w.append(entry); } @Override public long getLength() throws IOException { return w.getLength(); } }; } } // Make up mocked server and services. Server server = mock(Server.class); when(server.getConfiguration()).thenReturn(CONF); when(server.isStopped()).thenReturn(false); when(server.isAborted()).thenReturn(false); RegionServerServices services = mock(RegionServerServices.class); // OK. Now I have my mocked up Server and RegionServerServices and my dodgy WAL, go ahead with // the test. FileSystem fs = FileSystem.get(CONF); Path rootDir = new Path(dir + getName()); DodgyFSLog dodgyWAL = new DodgyFSLog(fs, rootDir, getName(), CONF); LogRoller logRoller = new LogRoller(server, services); logRoller.addWAL(dodgyWAL); logRoller.start(); boolean threwOnSync = false; boolean threwOnAppend = false; boolean threwOnBoth = false; HRegion region = initHRegion(tableName, null, null, dodgyWAL); try { // Get some random bytes. byte[] value = Bytes.toBytes(getName()); try { // First get something into memstore Put put = new Put(value); put.addColumn(COLUMN_FAMILY_BYTES, Bytes.toBytes("1"), value); region.put(put); } catch (IOException ioe) { fail(); } long rollsCount = rolls.get(); try { dodgyWAL.throwAppendException = true; dodgyWAL.throwSyncException = false; Put put = new Put(value); put.addColumn(COLUMN_FAMILY_BYTES, Bytes.toBytes("3"), value); region.put(put); } catch (IOException ioe) { threwOnAppend = true; } while (rollsCount == rolls.get()) Threads.sleep(100); rollsCount = rolls.get(); // When we get to here.. we should be ok. A new WAL has been put in place. There were no // appends to sync. We should be able to continue. try { dodgyWAL.throwAppendException = true; dodgyWAL.throwSyncException = true; Put put = new Put(value); put.addColumn(COLUMN_FAMILY_BYTES, Bytes.toBytes("4"), value); region.put(put); } catch (IOException ioe) { threwOnBoth = true; } while (rollsCount == rolls.get()) Threads.sleep(100); // Again, all should be good. New WAL and no outstanding unsync'd edits so we should be able // to just continue. // So, should be no abort at this stage. Verify. Mockito.verify(server, Mockito.atLeast(0)).abort(Mockito.anyString(), (Throwable) Mockito.anyObject()); try { dodgyWAL.throwAppendException = false; dodgyWAL.throwSyncException = true; Put put = new Put(value); put.addColumn(COLUMN_FAMILY_BYTES, Bytes.toBytes("2"), value); region.put(put); } catch (IOException ioe) { threwOnSync = true; } // An append in the WAL but the sync failed is a server abort condition. That is our // current semantic. Verify. It takes a while for abort to be called. Just hang here till it // happens. If it don't we'll timeout the whole test. That is fine. while (true) { try { Mockito.verify(server, Mockito.atLeast(1)).abort(Mockito.anyString(), (Throwable) Mockito.anyObject()); break; } catch (WantedButNotInvoked t) { Threads.sleep(1); } } } finally { // To stop logRoller, its server has to say it is stopped. Mockito.when(server.isStopped()).thenReturn(true); if (logRoller != null) logRoller.interrupt(); if (region != null) { try { region.close(true); } catch (DroppedSnapshotException e) { LOG.info("On way out; expected!", e); } } if (dodgyWAL != null) dodgyWAL.close(); assertTrue("The regionserver should have thrown an exception", threwOnBoth); assertTrue("The regionserver should have thrown an exception", threwOnAppend); assertTrue("The regionserver should have thrown an exception", threwOnSync); } }
From source file:ca.uhn.hl7v2.testpanel.controller.Prefs.java
public void setOpenProfiles(List<ProfileGroup> theProfiles, TableFileList theTableFileList) { int index = 0; List<File> files = new ArrayList<File>(); try {/*from www . j a v a 2 s. co m*/ for (ProfileGroup profileGroup : theProfiles) { index++; String seq = StringUtils.leftPad(Integer.toString(index), 10, '0'); File fileName = createProfileGroupFileName(seq, profileGroup); files.add(fileName); FileOutputStream fos = new FileOutputStream(fileName); Writer nextWriter = new OutputStreamWriter(fos, Charset.forName("UTF-8")); if (isNotBlank(profileGroup.getSourceUrl())) { ExportedProfileGroupFile exported = new ExportedProfileGroupFile(profileGroup, theTableFileList); nextWriter.append(exported.exportConfigToXm()); } else { nextWriter.append(profileGroup.exportConfigToXml()); } nextWriter.close(); } IOUtils.deleteAllFromDirectoryExcept(getProfileGroupFileDirectory(), files); } catch (IOException e) { ourLog.error("Failed to flush profile group file", e); } }
From source file:org.apache.hadoop.hbase.regionserver.TestWALLockup.java
/** * Reproduce locking up that happens when we get an inopportune sync during setup for * zigzaglatch wait. See HBASE-14317. If below is broken, we will see this test timeout because * it is locked up.//from w w w . j ava 2 s . com * <p>First I need to set up some mocks for Server and RegionServerServices. I also need to * set up a dodgy WAL that will throw an exception when we go to append to it. */ @Test(timeout = 30000) public void testLockupWhenSyncInMiddleOfZigZagSetup() throws IOException { // A WAL that we can have throw exceptions when a flag is set. class DodgyFSLog extends FSHLog { // Set this when want the WAL to start throwing exceptions. volatile boolean throwException = false; // Latch to hold up processing until after another operation has had time to run. CountDownLatch latch = new CountDownLatch(1); public DodgyFSLog(FileSystem fs, Path root, String logDir, Configuration conf) throws IOException { super(fs, root, logDir, conf); } @Override protected void afterCreatingZigZagLatch() { // If throwException set, then append will throw an exception causing the WAL to be // rolled. We'll come in here. Hold up processing until a sync can get in before // the zigzag has time to complete its setup and get its own sync in. This is what causes // the lock up we've seen in production. if (throwException) { try { LOG.info("LATCHED"); this.latch.await(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } @Override protected void beforeWaitOnSafePoint() { if (throwException) { LOG.info("COUNTDOWN"); // Don't countdown latch until someone waiting on it otherwise, the above // afterCreatingZigZagLatch will get to the latch and no one will ever free it and we'll // be stuck; test won't go down while (this.latch.getCount() <= 0) Threads.sleep(1); this.latch.countDown(); } } @Override protected Writer createWriterInstance(Path path) throws IOException { final Writer w = super.createWriterInstance(path); return new Writer() { @Override public void close() throws IOException { w.close(); } @Override public void sync() throws IOException { if (throwException) { throw new IOException("FAKE! Failed to replace a bad datanode...SYNC"); } w.sync(); } @Override public void append(Entry entry) throws IOException { if (throwException) { throw new IOException("FAKE! Failed to replace a bad datanode...APPEND"); } w.append(entry); } @Override public long getLength() throws IOException { return w.getLength(); } }; } } // Mocked up server and regionserver services. Needed below. Server server = Mockito.mock(Server.class); Mockito.when(server.getConfiguration()).thenReturn(CONF); Mockito.when(server.isStopped()).thenReturn(false); Mockito.when(server.isAborted()).thenReturn(false); RegionServerServices services = Mockito.mock(RegionServerServices.class); // OK. Now I have my mocked up Server & RegionServerServices and dodgy WAL, go ahead with test. FileSystem fs = FileSystem.get(CONF); Path rootDir = new Path(dir + getName()); DodgyFSLog dodgyWAL = new DodgyFSLog(fs, rootDir, getName(), CONF); Path originalWAL = dodgyWAL.getCurrentFileName(); // I need a log roller running. LogRoller logRoller = new LogRoller(server, services); logRoller.addWAL(dodgyWAL); // There is no 'stop' once a logRoller is running.. it just dies. logRoller.start(); // Now get a region and start adding in edits. HTableDescriptor htd = new HTableDescriptor(TableName.META_TABLE_NAME); final HRegion region = initHRegion(tableName, null, null, dodgyWAL); byte[] bytes = Bytes.toBytes(getName()); try { // First get something into memstore. Make a Put and then pull the Cell out of it. Will // manage append and sync carefully in below to manufacture hang. We keep adding same // edit. WAL subsystem doesn't care. Put put = new Put(bytes); put.addColumn(COLUMN_FAMILY_BYTES, Bytes.toBytes("1"), bytes); WALKey key = new WALKey(region.getRegionInfo().getEncodedNameAsBytes(), htd.getTableName()); WALEdit edit = new WALEdit(); List<Cell> cells = new ArrayList<Cell>(); for (CellScanner cs = put.cellScanner(); cs.advance();) { edit.add(cs.current()); cells.add(cs.current()); } // Put something in memstore and out in the WAL. Do a big number of appends so we push // out other side of the ringbuffer. If small numbers, stuff doesn't make it to WAL for (int i = 0; i < 1000; i++) { dodgyWAL.append(htd, region.getRegionInfo(), key, edit, region.getSequenceId(), true, cells); } // Set it so we start throwing exceptions. dodgyWAL.throwException = true; // This append provokes a WAL roll. dodgyWAL.append(htd, region.getRegionInfo(), key, edit, region.getSequenceId(), true, cells); boolean exception = false; try { dodgyWAL.sync(); } catch (Exception e) { exception = true; } assertTrue("Did not get sync exception", exception); // Get a memstore flush going too so we have same hung profile as up in the issue over // in HBASE-14317. Flush hangs trying to get sequenceid because the ringbuffer is held up // by the zigzaglatch waiting on syncs to come home. Thread t = new Thread("flusher") { public void run() { try { region.flush(false); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }; }; t.setDaemon(true); t.start(); // Wait till it gets into flushing. It will get stuck on getSequenceId. Then proceed. while (!region.writestate.flushing) Threads.sleep(1); // Now assert I got a new WAL file put in place even though loads of errors above. assertTrue(originalWAL != dodgyWAL.getCurrentFileName()); // Can I append to it? dodgyWAL.throwException = false; region.put(put); } finally { // To stop logRoller, its server has to say it is stopped. Mockito.when(server.isStopped()).thenReturn(true); if (logRoller != null) logRoller.interrupt(); if (region != null) region.close(); if (dodgyWAL != null) dodgyWAL.close(); } }