Example usage for com.google.common.io Closeables closeQuietly

List of usage examples for com.google.common.io Closeables closeQuietly

Introduction

In this page you can find the example usage for com.google.common.io Closeables closeQuietly.

Prototype

public static void closeQuietly(@Nullable Reader reader) 

Source Link

Document

Closes the given Reader , logging any IOException that's thrown rather than propagating it.

Usage

From source file:co.cask.cdap.internal.app.runtime.spark.ClientSparkContext.java

@Override
public synchronized void close() {
    for (Dataset dataset : datasets) {
        Closeables.closeQuietly(dataset);
    }
}

From source file:com.google.dart.compiler.PrettyErrorFormatter.java

@Override
public void format(DartCompilationError event) {
    Source sourceFile = event.getSource();

    // if this is an unknown source type, default to the basic error formatter
    if (!(sourceFile instanceof DartSource) && !(sourceFile instanceof LibrarySource)) {
        super.format(event);
        return;/*from ww  w  .j  a  v  a 2s.  c o m*/
    }

    BufferedReader reader = null;
    try {
        Reader sourceReader = sourceFile.getSourceReader();
        if (sourceReader != null) {
            reader = new BufferedReader(sourceReader);
        }

        // get the error line and the line above it (note: line starts at 1)
        int line = event.getLineNumber();
        String lineBefore = null;
        String lineText = null;

        if (reader != null) {
            lineBefore = getLineAt(reader, line - 1);
            lineText = getLineAt(reader, 1);
        }

        // if there is no line to highlight, default to the basic error formatter
        if (lineText == null) {
            super.format(event);
            return;
        }

        // get column/length and ensure they are within the line limits.
        int col = event.getColumnNumber() - 1;
        // TODO(ngeoffray): if length is 0, we may want to expand it in order
        // to highlight something.
        int length = event.getLength();
        col = between(col, 0, lineText.length());
        length = between(length, 0, lineText.length() - col);

        // print the error message
        StringBuilder buf = new StringBuilder();
        buf.append(String.format("%s%s:%d: %s%s\n", useColor ? RED_BOLD_COLOR : "", sourceFile.getName(),
                event.getLineNumber(), event.getMessage(), useColor ? NO_COLOR : ""));

        // show the previous line for context
        if (lineBefore != null) {
            buf.append(String.format("%6d: %s\n", line - 1, lineBefore));
        }

        if (useColor) {
            // highlight error in red
            buf.append(String.format("%6d: %s%s%s%s%s\n", line, lineText.substring(0, col), RED_COLOR,
                    lineText.substring(col, col + length), NO_COLOR, lineText.substring(col + length)));
        } else {
            // print the error line without formatting
            buf.append(String.format("%6d: %s\n", line, lineText));

            // underline error portion
            buf.append("        ");
            for (int i = 0; i < col; ++i) {
                buf.append(' ');
            }
            buf.append('~');
            if (length > 1) {
                for (int i = 0; i < length - 2; ++i) {
                    buf.append('~');
                }
                buf.append('~');
            }
            buf.append('\n');
        }

        outputStream.println(buf.toString());
    } catch (IOException ex) {
        super.format(event);
    } finally {
        if (reader != null) {
            Closeables.closeQuietly(reader);
        }
    }
}

From source file:org.sonar.batch.scan.JsonReport.java

@VisibleForTesting
void writeJson(Writer writer) {
    JsonWriter json = null;//from  w w  w . ja  v a  2s. co m
    try {
        json = new JsonWriter(writer);
        json.setSerializeNulls(false);
        json.beginObject();
        json.name("version").value(server.getVersion());

        Set<RuleKey> ruleKeys = newHashSet();
        Set<String> componentKeys = newHashSet();
        writeJsonIssues(json, ruleKeys, componentKeys);
        writeJsonComponents(json, componentKeys);
        writeJsonRules(json, ruleKeys);
        json.endObject().flush();

    } catch (IOException e) {
        throw new SonarException("Unable to write JSON report", e);
    } finally {
        Closeables.closeQuietly(json);
    }
}

From source file:co.cask.cdap.app.runtime.spark.SparkProgramRuntimeProvider.java

/**
 * Creates a {@link ProgramRunner} that execute Spark program from the given {@link Injector}.
 *//*from  w  ww. j  a va  2s.  c  o  m*/
private ProgramRunner createSparkProgramRunner(Injector injector, String programRunnerClassName,
        boolean rewriteYarnClient, boolean rewriteDStreamGraph) {
    try {
        SparkRunnerClassLoader classLoader = createClassLoader(rewriteYarnClient, rewriteDStreamGraph);
        try {
            ClassLoader oldClassLoader = ClassLoaders.setContextClassLoader(classLoader);
            try {
                // Closing of the SparkRunnerClassLoader is done by the SparkProgramRunner when the program execution finished
                // The current CDAP call run right after it get a ProgramRunner and never reuse a ProgramRunner.
                // TODO: CDAP-5506 to refactor the program runtime architecture to remove the need of this assumption
                return createInstance(injector, classLoader.loadClass(programRunnerClassName), classLoader);
            } finally {
                ClassLoaders.setContextClassLoader(oldClassLoader);
            }
        } catch (Throwable t) {
            // If there is any exception, close the SparkRunnerClassLoader
            Closeables.closeQuietly(classLoader);
            throw t;
        }
    } catch (Throwable t) {
        throw Throwables.propagate(t);
    }
}

From source file:net.sourceforge.vaticanfetcher.model.Daemon.java

public void writeIndexesToFile() {
    FileWriter writer = null;/*  ww  w . j  a v  a  2 s . c  o m*/
    try {
        writer = new FileWriter(indexesFile);
        for (LuceneIndex index : indexRegistry.getIndexes()) {
            writer.write(index.getCanonicalRootFile().getPath());
            writer.write(Util.LS);
        }
    } catch (IOException e) {
        Util.printErr(e);
    } finally {
        Closeables.closeQuietly(writer);
    }
}

From source file:com.griddynamics.jagger.util.SerializationUtils.java

public static Object deserialize(byte[] data) {
    ObjectInputStream ois = null;
    try {/*  w  ww.  j a  v a  2s  .  c o  m*/
        try {
            //TODO fixes for support old reports
            ois = new JBossObjectInputStream(new ByteArrayInputStream(data));
        } catch (IOException e) {
            //data stored not with JBoss
            ois = new ObjectInputStream(new ByteArrayInputStream(data));
        }
        Object payload = ois.readObject();

        return payload;
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        Closeables.closeQuietly(ois);
    }
}

From source file:com.zimbra.cs.dav.resource.ScheduleOutbox.java

@Override
public void handlePost(DavContext ctxt) throws DavException, IOException, ServiceException {
    DelegationInfo delegationInfo = new DelegationInfo(
            ctxt.getRequest().getHeader(DavProtocol.HEADER_ORIGINATOR));
    Enumeration<String> recipients = ctxt.getRequest().getHeaders(DavProtocol.HEADER_RECIPIENT);

    InputStream in = ctxt.getUpload().getInputStream();

    ZCalendar.ZVCalendar vcalendar = ZCalendar.ZCalendarBuilder.build(in, MimeConstants.P_CHARSET_UTF8);
    Closeables.closeQuietly(in);
    Iterator<ZComponent> iter = vcalendar.getComponentIterator();
    ZComponent req = null;//from   w w  w.j a  va 2s  .c o m
    while (iter.hasNext()) {
        req = iter.next();
        if (req.getTok() != ICalTok.VTIMEZONE)
            break;
        req = null;
    }
    if (req == null) {
        throw new DavException("empty request", HttpServletResponse.SC_BAD_REQUEST);
    }
    ZimbraLog.dav.debug("originator: %s", delegationInfo.getOriginator());

    boolean isVEventOrVTodo = ICalTok.VEVENT.equals(req.getTok()) || ICalTok.VTODO.equals(req.getTok());
    boolean isOrganizerMethod = false, isCancel = false;
    if (isVEventOrVTodo) {
        String method = vcalendar.getPropVal(ICalTok.METHOD, null);
        if (method != null) {
            isOrganizerMethod = Invite.isOrganizerMethod(method);
            isCancel = ICalTok.CANCEL.toString().equalsIgnoreCase(method);
            ;
        }

        CalDavUtils.removeAttendeeForOrganizer(req); // Apple iCal fixup
    }

    // Get organizer and list of attendees. (mailto:email values)
    ArrayList<String> attendees = new ArrayList<String>();
    String organizer = null;
    for (Iterator<ZProperty> propsIter = req.getPropertyIterator(); propsIter.hasNext();) {
        ZProperty prop = propsIter.next();
        ICalTok token = prop.getToken();
        if (ICalTok.ATTENDEE.equals(token)) {
            String val = prop.getValue();
            if (val != null) {
                attendees.add(val.trim());
            }
        } else if (ICalTok.ORGANIZER.equals(token)) {
            String val = prop.getValue();
            if (val != null) {
                organizer = val.trim();
                String addr = CalDavUtils.stripMailto(organizer);
                // Rewrite the alias to primary address
                Account acct = Provisioning.getInstance().get(AccountBy.name, addr);
                if (acct != null) {
                    String newAddr = acct.getName();
                    if (!addr.equals(newAddr)) {
                        organizer = "mailto:" + newAddr;
                        prop.setValue(organizer);
                    }
                }
            }
        }
    }

    // Keep originator address consistent with the address used in ORGANIZER/ATTENDEE.
    // Apple iCal is very inconsistent about the user's identity when the account has aliases.
    if (isVEventOrVTodo && delegationInfo.getOriginator() != null && ctxt.getAuthAccount() != null) {
        AccountAddressMatcher acctMatcher = new AccountAddressMatcher(ctxt.getAuthAccount());
        if (acctMatcher.matches(delegationInfo.getOriginatorEmail())) {
            if (isOrganizerMethod) {
                if (organizer != null) {
                    String organizerEmail = CalDavUtils.stripMailto(organizer);
                    if (!organizerEmail.equalsIgnoreCase(delegationInfo.getOriginatorEmail())
                            && acctMatcher.matches(organizerEmail)) {
                        delegationInfo.setOriginator(organizer);
                        ZimbraLog.dav.debug(
                                "changing originator to %s to match address/alias used in ORGANIZER",
                                delegationInfo.getOriginator());
                    }
                }
            } else {
                for (String at : attendees) {
                    String atEmail = CalDavUtils.stripMailto(at);
                    if (delegationInfo.getOriginatorEmail().equalsIgnoreCase(atEmail)) {
                        break;
                    } else if (acctMatcher.matches(atEmail)) {
                        delegationInfo.setOriginator(at);
                        ZimbraLog.dav.debug("changing originator to %s to match address/alias used in ATTENDEE",
                                delegationInfo.getOriginator());
                        break;
                    }
                }
            }
        }
    }

    // Get the recipients.
    ArrayList<String> rcptArray = new ArrayList<String>();
    while (recipients.hasMoreElements()) {
        String rcptHdr = recipients.nextElement();
        String[] rcpts = null;
        if (rcptHdr.indexOf(',') > 0) {
            rcpts = rcptHdr.split(",");
        } else {
            rcpts = new String[] { rcptHdr };
        }
        for (String rcpt : rcpts) {
            if (rcpt != null) {
                rcpt = rcpt.trim();
                if (rcpt.length() != 0) {
                    // Workaround for Apple iCal: Ignore attendees with address "invalid:nomail".
                    if (rcpt.equalsIgnoreCase("invalid:nomail")) {
                        continue;
                    }
                    if (isVEventOrVTodo) {
                        // Workaround for Apple iCal: Never send REQUEST/CANCEL notification to organizer.
                        // iCal can sometimes do that when organizer account has aliases.
                        if (isOrganizerMethod && rcpt.equalsIgnoreCase(organizer)) {
                            continue;
                        }
                        // bug 49987: Workaround for Apple iCal
                        // iCal sends cancel notice to all original attendees when some attendees are removed from the
                        // appointment.  As a result the appointment is cancelled from the calendars of all original
                        // attendees.  Counter this bad behavior by filtering out any recipients who aren't listed
                        // as ATTENDEE in the CANCEL component being sent.  (iCal does that part correctly, at least.)
                        if (isCancel) {
                            boolean isAttendee = false;
                            // Rcpt must be an attendee of the cancel component.
                            for (String at : attendees) {
                                if (rcpt.equalsIgnoreCase(at)) {
                                    isAttendee = true;
                                    break;
                                }
                            }
                            if (!isAttendee) {
                                ZimbraLog.dav.info(
                                        "Ignoring non-attendee recipient '%s' of CANCEL request; likely a client bug",
                                        rcpt);
                                continue;
                            }
                        }
                    }
                    // All checks passed.
                    rcptArray.add(rcpt);
                }
            }
        }
    }

    Element scheduleResponse = ctxt.getDavResponse().getTop(DavElements.E_SCHEDULE_RESPONSE);
    for (String rcpt : rcptArray) {
        ZimbraLog.dav.debug("recipient email: " + rcpt);
        Element resp = scheduleResponse.addElement(DavElements.E_CALDAV_RESPONSE);
        switch (req.getTok()) {
        case VFREEBUSY:
            handleFreebusyRequest(ctxt, req, delegationInfo.getOriginator(), rcpt, resp);
            break;
        case VEVENT:
            // adjustOrganizer works around issues where we don't have delegation enabled but clients write
            // to the shared calendar as if it was the delegate's calendar instead of the owner.
            // Note assumption that clients won't generate replies on behalf of owner as they won't be aware
            // that they should be working on behalf of the owner and will only look for their own attendee
            // records.
            if (isOrganizerMethod) {
                adjustOrganizer(ctxt, vcalendar, req, delegationInfo);
            }
            validateRequest(isOrganizerMethod, delegationInfo, organizer, ctxt, req);
            handleEventRequest(ctxt, vcalendar, req, delegationInfo, rcpt, resp);
            break;
        default:
            throw new DavException("unrecognized request: " + req.getTok(), HttpServletResponse.SC_BAD_REQUEST);
        }
    }
}

From source file:com.netflix.exhibitor.core.config.s3.S3ConfigProvider.java

@Override
public LoadedInstanceConfig loadConfig() throws Exception {
    Date lastModified;/*from w  w w.ja va2  s. c om*/
    Properties properties = new Properties();
    S3Object object = getConfigObject();
    if (object != null) {
        try {
            lastModified = object.getObjectMetadata().getLastModified();
            properties.load(object.getObjectContent());
        } finally {
            Closeables.closeQuietly(object.getObjectContent());
        }
    } else {
        lastModified = new Date(0L);
    }

    PropertyBasedInstanceConfig config = new PropertyBasedInstanceConfig(properties, defaults);
    return new LoadedInstanceConfig(config, lastModified.getTime());
}

From source file:org.sonar.plugins.activedirectoy.server.ApacheDS.java

/**
 * Stream will be closed automatically./*from  w  w w  .j  ava 2  s . co  m*/
 */
public void importLdif(@WillClose InputStream is) throws Exception {
    Preconditions.checkState(directoryService.isStarted(), "Directory service not started");
    try {
        LdifReader entries = new LdifReader(is);
        CoreSession rootDSE = directoryService.getAdminSession();
        for (LdifEntry ldifEntry : entries) {
            rootDSE.add(new DefaultServerEntry(rootDSE.getDirectoryService().getRegistries(),
                    ldifEntry.getEntry()));
        }
    } finally {
        Closeables.closeQuietly(is);
    }
}

From source file:org.solenopsis.checkstyle.PropertyCacheFile.java

/**
 * Load cached values from file./*ww w  .  j  ava2 s . c  o m*/
 * @throws IOException when there is a problems with file read
 */
public void load() throws IOException {
    // get the current config so if the file isn't found
    // the first time the hash will be added to output file
    final String currentConfigHash = getConfigHashCode(config);
    if (new File(fileName).exists()) {
        FileInputStream inStream = null;
        try {
            inStream = new FileInputStream(fileName);
            details.load(inStream);
            final String cachedConfigHash = details.getProperty(CONFIG_HASH_KEY);
            if (!currentConfigHash.equals(cachedConfigHash)) {
                // Detected configuration change - clear cache
                details.clear();
                details.setProperty(CONFIG_HASH_KEY, currentConfigHash);
            }
        } finally {
            Closeables.closeQuietly(inStream);
        }
    } else {
        // put the hash in the file if the file is going to be created
        details.setProperty(CONFIG_HASH_KEY, currentConfigHash);
    }
}