Example usage for java.lang IndexOutOfBoundsException getMessage

List of usage examples for java.lang IndexOutOfBoundsException getMessage

Introduction

In this page you can find the example usage for java.lang IndexOutOfBoundsException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:ch.cyberduck.core.sftp.SFTPPath.java

protected void readAttributes(SFTPv3FileAttributes attributes) {
    if (null != attributes.size) {
        if (this.attributes().isFile()) {
            this.attributes().setSize(attributes.size);
        }/*from   ww w. j av a  2  s  .  co m*/
    }
    String perm = attributes.getOctalPermissions();
    if (null != perm) {
        try {
            String octal = Integer.toOctalString(attributes.permissions);
            this.attributes()
                    .setPermission(new Permission(Integer.parseInt(octal.substring(octal.length() - 4))));
        } catch (IndexOutOfBoundsException e) {
            log.warn(String.format("Failure parsing mode:%s", e.getMessage()));
        } catch (NumberFormatException e) {
            log.warn(String.format("Failure parsing mode:%s", e.getMessage()));
        }
    }
    if (null != attributes.uid) {
        this.attributes().setOwner(attributes.uid.toString());
    }
    if (null != attributes.gid) {
        this.attributes().setGroup(attributes.gid.toString());
    }
    if (null != attributes.mtime) {
        this.attributes().setModificationDate(Long.parseLong(attributes.mtime.toString()) * 1000L);
    }
    if (null != attributes.atime) {
        this.attributes().setAccessedDate(Long.parseLong(attributes.atime.toString()) * 1000L);
    }
    if (attributes.isSymlink()) {
        try {
            String target = this.getSession().sftp().readLink(this.getAbsolute());
            if (!target.startsWith(String.valueOf(Path.DELIMITER))) {
                target = Path
                        .normalize(this.getParent().getAbsolute() + String.valueOf(Path.DELIMITER) + target);
            }
            this.setSymlinkTarget(target);
            SFTPv3FileAttributes targetAttributes = this.getSession().sftp().stat(target);
            if (targetAttributes.isDirectory()) {
                this.attributes().setType(SYMBOLIC_LINK_TYPE | DIRECTORY_TYPE);
            } else if (targetAttributes.isRegularFile()) {
                this.attributes().setType(SYMBOLIC_LINK_TYPE | FILE_TYPE);
            }
        } catch (IOException e) {
            log.warn(String.format("Cannot read symbolic link target of %s:%s", this.getAbsolute(),
                    e.getMessage()));
            this.attributes().setType(FILE_TYPE);
        }
    }
}

From source file:eu.operando.proxy.service.ProxyService.java

private HttpFiltersSource getFiltersSource() {

    return new HttpFiltersSourceAdapter() {

        //                @Override
        //                public int getMaximumRequestBufferSizeInBytes() {
        //                    // TODO Auto-generated method stub
        //                    return 10 * 1024 * 1024;
        ////from w w w .ja v a  2 s  .c  o  m
        //                }
        //
        //                @Override
        //                public int getMaximumResponseBufferSizeInBytes() {
        //                    // TODO Auto-generated method stub
        //                    return 10 * 1024 * 1024;
        //                }

        @Override
        public HttpFilters filterRequest(HttpRequest originalRequest) {

            return new HttpFiltersAdapter(originalRequest) {

                @Override
                public HttpObject serverToProxyResponse(HttpObject httpObject) {

                    if (MainUtil.isProxyPaused(mainContext))
                        return httpObject;

                    if (httpObject instanceof HttpMessage) {
                        HttpMessage response = (HttpMessage) httpObject;
                        response.headers().set(HttpHeaderNames.CACHE_CONTROL,
                                "no-cache, no-store, must-revalidate");
                        response.headers().set(HttpHeaderNames.PRAGMA, "no-cache");
                        response.headers().set(HttpHeaderNames.EXPIRES, "0");
                    }
                    try {
                        Method content = httpObject.getClass().getMethod("content");
                        if (content != null) {
                            ByteBuf buf = (ByteBuf) content.invoke(httpObject);
                            boolean flag = false;
                            List<ResponseFilter> responseFilters = db.getAllResponseFilters();
                            if (responseFilters.size() > 0) {

                                String contentStr = buf.toString(Charset.forName("UTF-8")); //Charset.forName(Charset.forName("UTF-8")
                                for (ResponseFilter responseFilter : responseFilters) {

                                    String toReplace = responseFilter.getContent();

                                    if (StringUtils.containsIgnoreCase(contentStr, toReplace)) {
                                        contentStr = contentStr.replaceAll("(?i)" + toReplace,
                                                StringUtils.leftPad("", toReplace.length(), '#'));
                                        flag = true;
                                    }

                                }
                                if (flag) {
                                    buf.clear().writeBytes(contentStr.getBytes(Charset.forName("UTF-8")));
                                }
                            }

                        }
                    } catch (IndexOutOfBoundsException ex) {
                        ex.printStackTrace();
                        Log.e("Exception", ex.getMessage());
                    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
                        //ignore
                    }
                    return httpObject;
                }

                @Override
                public HttpResponse clientToProxyRequest(HttpObject httpObject) {

                    if (MainUtil.isProxyPaused(mainContext))
                        return null;

                    String requestURI;
                    Set<RequestFilterUtil.FilterType> exfiltrated = new HashSet<>();
                    String[] locationInfo = requestFilterUtil.getLocationInfo();
                    String[] contactsInfo = requestFilterUtil.getContactsInfo();
                    String[] phoneInfo = requestFilterUtil.getPhoneInfo();

                    if (httpObject instanceof HttpMessage) {
                        HttpMessage request = (HttpMessage) httpObject;
                        if (request.headers().contains(CustomHeaderField)) {
                            applicationInfoStr = request.headers().get(CustomHeaderField);
                            request.headers().remove(CustomHeaderField);
                        }

                        if (request.headers().contains(HttpHeaderNames.ACCEPT_ENCODING)) {
                            request.headers().remove(HttpHeaderNames.ACCEPT_ENCODING);
                        }

                        /*
                        Sanitize Hosts
                        */
                        if (!ProxyUtils.isCONNECT(request)
                                && request.headers().contains(HttpHeaderNames.HOST)) {
                            String hostName = request.headers().get(HttpHeaderNames.HOST).toLowerCase();
                            if (db.isDomainBlocked(hostName))
                                return getBlockedHostResponse(hostName);
                        }

                    }

                    if (httpObject instanceof HttpRequest) {

                        HttpRequest request = (HttpRequest) httpObject;
                        requestURI = request.uri();

                        try {
                            requestURI = URLDecoder.decode(requestURI, "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }

                        /*
                        Request URI checks
                         */
                        if (StringUtils.containsAny(requestURI, locationInfo)) {
                            exfiltrated.add(RequestFilterUtil.FilterType.LOCATION);
                        }

                        if (StringUtils.containsAny(requestURI, contactsInfo)) {
                            exfiltrated.add(RequestFilterUtil.FilterType.CONTACTS);
                        }

                        if (StringUtils.containsAny(requestURI, phoneInfo)) {
                            exfiltrated.add(RequestFilterUtil.FilterType.PHONEINFO);
                        }

                        if (!exfiltrated.isEmpty()) {
                            mainContext.getNotificationUtil().displayExfiltratedNotification(applicationInfoStr,
                                    exfiltrated);
                            return getForbiddenRequestResponse(applicationInfoStr, exfiltrated);
                        }

                    }

                    try {
                        Method content = httpObject.getClass().getMethod("content");
                        if (content != null) {
                            ByteBuf buf = (ByteBuf) content.invoke(httpObject);

                            String contentStr = buf.toString(Charset.forName("UTF-8"));

                            if (StringUtils.containsAny(contentStr, locationInfo)) {
                                exfiltrated.add(RequestFilterUtil.FilterType.LOCATION);
                            }

                            if (StringUtils.containsAny(contentStr, contactsInfo)) {
                                exfiltrated.add(RequestFilterUtil.FilterType.CONTACTS);
                            }

                            if (StringUtils.containsAny(contentStr, phoneInfo)) {
                                exfiltrated.add(RequestFilterUtil.FilterType.PHONEINFO);
                            }

                            if (!exfiltrated.isEmpty()) {
                                mainContext.getNotificationUtil()
                                        .displayExfiltratedNotification(applicationInfoStr, exfiltrated);
                                return getForbiddenRequestResponse(applicationInfoStr, exfiltrated);
                            }

                        }
                    } catch (IndexOutOfBoundsException ex) {
                        ex.printStackTrace();
                        Log.e("Exception", ex.getMessage());
                    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
                        //ignore
                    }

                    return null;
                }

            };
        }
    };
}

From source file:eu.operando.operandoapp.service.ProxyService.java

private HttpFiltersSource getFiltersSource() {
    return new HttpFiltersSourceAdapter() {
        @Override//from w  w w  . j  ava2 s .  c  o m
        public HttpFilters filterRequest(HttpRequest originalRequest) {
            return new HttpFiltersAdapter(originalRequest) {
                @Override
                public HttpObject serverToProxyResponse(HttpObject httpObject) {
                    //check for proxy running
                    if (MainUtil.isProxyPaused(mainContext))
                        return httpObject;

                    if (httpObject instanceof HttpMessage) {
                        HttpMessage response = (HttpMessage) httpObject;
                        response.headers().set(HttpHeaderNames.CACHE_CONTROL,
                                "no-cache, no-store, must-revalidate");
                        response.headers().set(HttpHeaderNames.PRAGMA, "no-cache");
                        response.headers().set(HttpHeaderNames.EXPIRES, "0");
                    }
                    try {
                        Method content = httpObject.getClass().getMethod("content");
                        if (content != null) {
                            ByteBuf buf = (ByteBuf) content.invoke(httpObject);
                            boolean flag = false;
                            List<ResponseFilter> responseFilters = db.getAllResponseFilters();
                            if (responseFilters.size() > 0) {
                                String contentStr = buf.toString(Charset.forName("UTF-8")); //Charset.forName(Charset.forName("UTF-8")
                                for (ResponseFilter responseFilter : responseFilters) {
                                    String toReplace = responseFilter.getContent();
                                    if (StringUtils.containsIgnoreCase(contentStr, toReplace)) {
                                        contentStr = contentStr.replaceAll("(?i)" + toReplace,
                                                StringUtils.leftPad("", toReplace.length(), '#'));
                                        flag = true;
                                    }
                                }
                                if (flag) {
                                    buf.clear().writeBytes(contentStr.getBytes(Charset.forName("UTF-8")));
                                }
                            }
                        }
                    } catch (IndexOutOfBoundsException ex) {
                        ex.printStackTrace();
                        Log.e("Exception", ex.getMessage());
                    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
                        //ignore
                    }
                    return httpObject;
                }

                @Override
                public HttpResponse clientToProxyRequest(HttpObject httpObject) {
                    //check for proxy running
                    if (MainUtil.isProxyPaused(mainContext)) {
                        return null;
                    }

                    //check for trusted access point
                    String ssid = ((WifiManager) getSystemService(Context.WIFI_SERVICE)).getConnectionInfo()
                            .getSSID();
                    String bssid = ((WifiManager) getSystemService(Context.WIFI_SERVICE)).getConnectionInfo()
                            .getBSSID();
                    boolean trusted = false;
                    TrustedAccessPoint curr_tap = new TrustedAccessPoint(ssid, bssid);
                    for (TrustedAccessPoint tap : db.getAllTrustedAccessPoints()) {
                        if (curr_tap.isEqual(tap)) {
                            trusted = true;
                        }
                    }
                    if (!trusted) {
                        return getUntrustedGatewayResponse();
                    }

                    //check for blocked url

                    //check for exfiltration
                    requestFilterUtil = new RequestFilterUtil(getApplicationContext());
                    locationInfo = requestFilterUtil.getLocationInfo();
                    contactsInfo = requestFilterUtil.getContactsInfo();
                    IMEI = requestFilterUtil.getIMEI();
                    phoneNumber = requestFilterUtil.getPhoneNumber();
                    subscriberID = requestFilterUtil.getSubscriberID();
                    carrierName = requestFilterUtil.getCarrierName();
                    androidID = requestFilterUtil.getAndroidID();
                    macAdresses = requestFilterUtil.getMacAddresses();

                    if (httpObject instanceof HttpMessage) {
                        HttpMessage request = (HttpMessage) httpObject;
                        if (request.headers().contains(CustomHeaderField)) {
                            applicationInfo = request.headers().get(CustomHeaderField);
                            request.headers().remove(CustomHeaderField);
                        }
                        if (request.headers().contains(HttpHeaderNames.ACCEPT_ENCODING)) {
                            request.headers().remove(HttpHeaderNames.ACCEPT_ENCODING);
                        }
                        if (!ProxyUtils.isCONNECT(request)
                                && request.headers().contains(HttpHeaderNames.HOST)) {
                            String hostName = ((HttpRequest) request).uri(); //request.headers().get(HttpHeaderNames.HOST).toLowerCase();
                            if (db.isDomainBlocked(hostName))
                                return getBlockedHostResponse(hostName);
                        }
                    }

                    String requestURI;
                    Set<RequestFilterUtil.FilterType> exfiltrated = new HashSet<>();

                    if (httpObject instanceof HttpRequest) {
                        HttpRequest request = (HttpRequest) httpObject;
                        requestURI = request.uri();
                        try {
                            requestURI = URLDecoder.decode(requestURI, "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        if (locationInfo.length > 0) {
                            //tolerate location miscalculation
                            float latitude = Float.parseFloat(locationInfo[0]);
                            float longitude = Float.parseFloat(locationInfo[1]);
                            Matcher m = Pattern.compile("\\d+\\.\\d+").matcher(requestURI);
                            List<String> floats_in_uri = new ArrayList();
                            while (m.find()) {
                                floats_in_uri.add(m.group());
                            }
                            for (String s : floats_in_uri) {
                                if (Math.abs(Float.parseFloat(s) - latitude) < 0.5
                                        || Math.abs(Float.parseFloat(s) - longitude) < 0.1) {
                                    exfiltrated.add(RequestFilterUtil.FilterType.LOCATION);
                                }
                            }
                        }
                        if (StringUtils.containsAny(requestURI, contactsInfo)) {
                            exfiltrated.add(RequestFilterUtil.FilterType.CONTACTS);
                        }
                        if (StringUtils.containsAny(requestURI, macAdresses)) {
                            exfiltrated.add(RequestFilterUtil.FilterType.MACADRESSES);
                        }
                        if (requestURI.contains(IMEI) && !IMEI.equals("")) {
                            exfiltrated.add(RequestFilterUtil.FilterType.IMEI);
                        }
                        if (requestURI.contains(phoneNumber) && !phoneNumber.equals("")) {
                            exfiltrated.add(RequestFilterUtil.FilterType.PHONENUMBER);
                        }
                        if (requestURI.contains(subscriberID) && !subscriberID.equals("")) {
                            exfiltrated.add(RequestFilterUtil.FilterType.IMSI);
                        }
                        if (requestURI.contains(carrierName) && !carrierName.equals("")) {
                            exfiltrated.add(RequestFilterUtil.FilterType.CARRIERNAME);
                        }
                        if (requestURI.contains(androidID) && !androidID.equals("")) {
                            exfiltrated.add(RequestFilterUtil.FilterType.ANDROIDID);
                        }
                    }
                    try {
                        Method content = httpObject.getClass().getMethod("content");
                        if (content != null) {
                            ByteBuf buf = (ByteBuf) content.invoke(httpObject);
                            String contentStr = buf.toString(Charset.forName("UTF-8"));
                            if (locationInfo.length > 0) {
                                //tolerate location miscalculation
                                float latitude = Float.parseFloat(locationInfo[0]);
                                float longitude = Float.parseFloat(locationInfo[1]);
                                Matcher m = Pattern.compile("\\d+\\.\\d+").matcher(contentStr);
                                List<String> floats_in_uri = new ArrayList();
                                while (m.find()) {
                                    floats_in_uri.add(m.group());
                                }
                                for (String s : floats_in_uri) {
                                    if (Math.abs(Float.parseFloat(s) - latitude) < 0.5
                                            || Math.abs(Float.parseFloat(s) - longitude) < 0.1) {
                                        exfiltrated.add(RequestFilterUtil.FilterType.LOCATION);
                                    }
                                }
                            }
                            if (StringUtils.containsAny(contentStr, contactsInfo)) {
                                exfiltrated.add(RequestFilterUtil.FilterType.CONTACTS);
                            }
                            if (StringUtils.containsAny(contentStr, macAdresses)) {
                                exfiltrated.add(RequestFilterUtil.FilterType.MACADRESSES);
                            }
                            if (contentStr.contains(IMEI) && !IMEI.equals("")) {
                                exfiltrated.add(RequestFilterUtil.FilterType.IMEI);
                            }
                            if (contentStr.contains(phoneNumber) && !phoneNumber.equals("")) {
                                exfiltrated.add(RequestFilterUtil.FilterType.PHONENUMBER);
                            }
                            if (contentStr.contains(subscriberID) && !subscriberID.equals("")) {
                                exfiltrated.add(RequestFilterUtil.FilterType.IMSI);
                            }
                            if (contentStr.contains(carrierName) && !carrierName.equals("")) {
                                exfiltrated.add(RequestFilterUtil.FilterType.CARRIERNAME);
                            }
                            if (contentStr.contains(androidID) && !androidID.equals("")) {
                                exfiltrated.add(RequestFilterUtil.FilterType.ANDROIDID);
                            }
                        }
                    } catch (IndexOutOfBoundsException ex) {
                        ex.printStackTrace();
                        Log.e("Exception", ex.getMessage());
                    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
                        //ignore
                    }

                    //check exfiltrated list
                    if (!exfiltrated.isEmpty()) {
                        //retrieve all blocked and allowed domains
                        List<BlockedDomain> blocked = db.getAllBlockedDomains();
                        List<AllowedDomain> allowed = db.getAllAllowedDomains();
                        //get application name from app info
                        String appName = applicationInfo.replaceAll("\\(.+?\\)", "");
                        //check blocked domains
                        //if domain is stored as blocked, return a forbidden response
                        for (BlockedDomain b_dmn : blocked) {
                            if (b_dmn.info.equals(appName)) {
                                return getForbiddenRequestResponse(applicationInfo, exfiltrated);
                            }
                        }
                        //if domain is stored as allowed, return null for actual response
                        for (AllowedDomain a_dmn : allowed) {
                            if (a_dmn.info.equals(appName)) {
                                return null;
                            }
                        }
                        //get exfiltrated info to string array
                        String[] exfiltrated_array = new String[exfiltrated.size()];
                        int i = 0;
                        for (RequestFilterUtil.FilterType filter_type : exfiltrated) {
                            exfiltrated_array[i] = filter_type.name();
                            i++;
                        }
                        //retrieve all pending notifications
                        List<PendingNotification> pending = db.getAllPendingNotifications();
                        for (PendingNotification pending_notification : pending) {
                            //if pending notification includes specific app name and app permissions return response that a pending notification exists
                            if (pending_notification.app_info.equals(applicationInfo)) {
                                return getPendingResponse();
                            }
                        }
                        //if none pending notification exists, display a new notification
                        int notificationId = mainContext.getNotificationId();
                        mainContext.getNotificationUtil().displayExfiltratedNotification(getBaseContext(),
                                applicationInfo, exfiltrated, notificationId);
                        mainContext.setNotificationId(notificationId + 3);
                        //and update statistics
                        db.updateStatistics(exfiltrated);
                        return getAwaitingResponse();
                    }
                    return null;
                }
            };
        }
    };
}

From source file:org.apache.pig.backend.hadoop.executionengine.physicalLayer.expressionOperators.POUserFunc.java

private Result getNext() throws ExecException {
    Result result = processInput();
    long startNanos = 0;
    boolean timeThis = doTiming && (numInvocations++ % timingFrequency == 0);
    if (timeThis) {
        startNanos = System.nanoTime();
        PigStatusReporter.getInstance().incrCounter(counterGroup, TIME_UDFS_INVOCATION_COUNTER,
                timingFrequency);//from  www.  j a  va 2s  .  com
    }
    try {
        if (result.returnStatus == POStatus.STATUS_OK) {
            if (isAccumulative()) {
                if (isAccumStarted()) {
                    if (!haveCheckedIfTerminatingAccumulator) {
                        haveCheckedIfTerminatingAccumulator = true;
                        if (func instanceof TerminatingAccumulator<?>)
                            setIsEarlyTerminating();
                    }

                    if (!hasBeenTerminated() && isEarlyTerminating()
                            && ((TerminatingAccumulator<?>) func).isFinished()) {
                        earlyTerminate();
                    }

                    if (hasBeenTerminated()) {
                        result.returnStatus = POStatus.STATUS_EARLY_TERMINATION;
                        result.result = null;
                        isAccumulationDone = false;
                    } else {
                        ((Accumulator) func).accumulate((Tuple) result.result);
                        result.returnStatus = POStatus.STATUS_BATCH_OK;
                        result.result = null;
                        isAccumulationDone = false;
                    }
                } else {
                    if (isAccumulationDone) {
                        //PORelationToExprProject does not return STATUS_EOP
                        // so that udf gets called both when isAccumStarted
                        // is first true and then set to false, even
                        //when the input relation is empty.
                        // so the STATUS_EOP has to be sent from POUserFunc,
                        // after the results have been sent.
                        result.result = null;
                        result.returnStatus = POStatus.STATUS_EOP;
                    } else {
                        result.result = ((Accumulator) func).getValue();
                        result.returnStatus = POStatus.STATUS_OK;
                        ((Accumulator) func).cleanup();
                        isAccumulationDone = true;
                    }
                }
            } else {
                if (parentPlan != null && parentPlan.endOfAllInput && needEndOfAllInputProcessing()) {
                    func.setEndOfAllInput(true);
                }
                if (executor != null) {
                    result.result = executor.monitorExec((Tuple) result.result);
                } else {
                    result.result = func.exec((Tuple) result.result);
                }
            }
        }
        if (timeThis) {
            PigStatusReporter.getInstance().incrCounter(counterGroup, TIME_UDFS_ELAPSED_TIME_COUNTER,
                    Math.round((System.nanoTime() - startNanos) / 1000) * timingFrequency);
        }
        return result;
    } catch (ExecException ee) {
        throw ee;
    } catch (IOException ioe) {
        int errCode = 2078;
        String msg = "Caught error from UDF: " + funcSpec.getClassName();
        String footer = " [" + ioe.getMessage() + "]";

        if (ioe instanceof PigException) {
            int udfErrorCode = ((PigException) ioe).getErrorCode();
            if (udfErrorCode != 0) {
                errCode = udfErrorCode;
                msg = ((PigException) ioe).getMessage();
            } else {
                msg += " [" + ((PigException) ioe).getMessage() + " ]";
            }
        } else {
            msg += footer;
        }

        throw new ExecException(msg, errCode, PigException.BUG, ioe);
    } catch (IndexOutOfBoundsException ie) {
        int errCode = 2078;
        String msg = "Caught error from UDF: " + funcSpec.getClassName() + ", Out of bounds access ["
                + ie.getMessage() + "]";
        throw new ExecException(msg, errCode, PigException.BUG, ie);
    }
}

From source file:org.potpie.cordova.plugins.chromecast.ChromecastPlugin.java

public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (action.equals("startReceiverListener")) {
        receiverCallback = callbackContext;
        PluginResult result = new PluginResult(PluginResult.Status.OK, new JSONObject());
        result.setKeepCallback(true);/*from  w w  w. java 2 s  . co  m*/
        receiverCallback.sendPluginResult(result);
        return true;
    } else if (action.equals("setReceiver")) {
        int index = args.getInt(0);
        try {
            RouteInfo route = routes.get(index);
            System.out.println("route :" + index + " " + route.getId() + " selected");
            mediaRouter.selectRoute(route);
            callbackContext.success();
            return true;
        } catch (IndexOutOfBoundsException e) {
            callbackContext.error("Receiver not found");
            return false;
        }
    } else if (action.equals("cast")) {
        String mediaurl = args.getString(0);
        try {
            System.out.println("cast :" + mediaurl);
            startCast(mediaurl);
            callbackContext.success();
            return true;
        } catch (IOException e) {
            callbackContext.error("cast failed :" + e.getMessage());
            return false;
        }
    } else if (action.equals("pause")) {
        try {
            System.out.println("pause");
            pause();
            callbackContext.success();
            return true;
        } catch (IOException e) {
            callbackContext.error("pause failed :" + e.getMessage());
            return false;
        }
    } else if (action.equals("play")) {
        try {
            int position = args.getInt(0);
            System.out.println("play :" + position);
            play(position);
            callbackContext.success();
            return true;
        } catch (IOException e) {
            callbackContext.error("play failed :" + e.getMessage());
            return false;
        }
    } else if (action.equals("stopCast")) {
        try {
            System.out.println("stopCast");
            stopCast();
            callbackContext.success();
            return true;
        } catch (IOException e) {
            callbackContext.error("stop cast failed :" + e.getMessage());
            return false;
        }
    } else if (action.equals("startStatusListener")) {
        statusCallback = callbackContext;
        callbackContext.sendPluginResult(getStatus(null));
        return true;
    } else {
        callbackContext.error("Invalid action");
        return false;
    }
}

From source file:edu.harvard.mcz.imagecapture.ImageDisplayFrame.java

public void setActiveTab(int tab) {
    try {/*from  www .  ja  v  a  2  s.  c o m*/
        jTabbedPane.setSelectedIndex(tab);
    } catch (IndexOutOfBoundsException e) {
        System.out.println("Failed to activate tab. " + e.getMessage());
    }
}

From source file:org.jnode.net.SocketBuffer.java

/**
 * Gets a byte-array in the buffer/*from   w  ww  .  j av a  2s  .co m*/
 * 
 * @param index
 */
public void get(byte[] dst, int dstOffset, int index, int length) {
    try {
        if (index >= size) {
            // Index is beyond my data
            if (next != null) {
                next.get(dst, dstOffset, index - size, length);
            } else {
                throw new IndexOutOfBoundsException("at index " + index);
            }
        } else if (index + length <= size) {
            // All bytes are within my data
            System.arraycopy(data, start + index, dst, dstOffset, length);
        } else {
            // First byte is within my data, last is not
            if (next != null) {
                final int myLength = size - index;
                System.arraycopy(data, start + index, dst, dstOffset, myLength);
                next.get(dst, dstOffset + myLength, Math.max(0, index - myLength), length - myLength);
            } else {
                throw new IndexOutOfBoundsException("at index " + index);
            }
        }
    } catch (IndexOutOfBoundsException ex) {
        log.debug(
                "get(dst, " + dstOffset + ", " + index + ", " + length + ") start=" + start + ", size=" + size);
        throw new IndexOutOfBoundsException(ex.getMessage());
    }
}

From source file:org.entrystore.repository.impl.ListImpl.java

public void loadChildren() {
    try {/*  w  ww .j a  va 2s . c  o  m*/
        synchronized (this.entry.repository) {
            if (children != null) {
                return;
            }
            children = new Vector<URI>();

            RepositoryConnection rc = entry.repository.getConnection();
            try {
                RepositoryResult<Statement> statements = rc.getStatements(null, null, null, false,
                        this.resourceURI);
                while (statements.hasNext()) {
                    Statement statement = statements.next();
                    org.openrdf.model.URI predicate = statement.getPredicate();
                    if (!predicate.toString().startsWith(RDF.NAMESPACE.toString() + "_")) {
                        continue;
                    }

                    try {
                        //                     children.add(URI.create(statement.getObject().stringValue())); 
                        String value = predicate.toString().substring(RDF.NAMESPACE.length());
                        int index = Integer.parseInt(value.substring(value.lastIndexOf("_") + 1));
                        //                     children.ensureCapacity(index);

                        if (index > children.size()) {
                            children.setSize(index);
                        }

                        children.set(index - 1, URI.create(statement.getObject().stringValue()));
                    } catch (IndexOutOfBoundsException iobe) {
                        log.error(
                                "loadChildren() " + iobe.getClass().getSimpleName() + ": " + iobe.getMessage());
                    } catch (NumberFormatException nfe) {
                        log.error("loadChildren() " + nfe.getClass().getSimpleName() + ": " + nfe.getMessage());
                        log.error("Causing statement: " + statement);
                    }
                }
                children.trimToSize();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                rc.close();
            }
        }
    } catch (RepositoryException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.pig.backend.hadoop.executionengine.physicalLayer.expressionOperators.POUserFuncRollupSample.java

private Result getNext() throws ExecException {
    Result result = processInput();
    long startNanos = 0;
    boolean timeThis = doTiming && (numInvocations++ % TIMING_FREQ == 0);
    if (timeThis) {
        startNanos = System.nanoTime();
        PigStatusReporter.getInstance().getCounter(counterGroup, INVOCATION_COUNTER).increment(TIMING_FREQ);

    }//from  w  w w  .  ja va2 s .  c  o m
    try {
        if (result.returnStatus == POStatus.STATUS_OK) {
            Tuple t = (Tuple) result.result;

            // For backward compatibility, we short-circuit tuples whose
            // fields are all null. (See PIG-3679)
            boolean allNulls = true;
            for (int i = 0; i < t.size(); i++) {
                if (!t.isNull(i)) {
                    allNulls = false;
                    break;
                }
            }
            if (allNulls) {
                pigLogger.warn(this, "All the input values are null, skipping the invocation of UDF",
                        PigWarning.SKIP_UDF_CALL_FOR_NULL);
                Schema outputSchema = func.outputSchema(func.getInputSchema());
                // If the output schema is tuple (i.e. multiple fields are
                // to be returned), we return a tuple where every field is
                // null.
                if (outputSchema != null && outputSchema.getField(0).type == DataType.TUPLE) {
                    result.result = tf.newTuple(outputSchema.getField(0).schema.size());
                    // Otherwise, we simply return null since it can be cast
                    // to
                    // any data type.
                } else {
                    result.result = null;
                }
                return result;
            }

            if (isAccumulative()) {
                if (isAccumStarted()) {
                    if (!haveCheckedIfTerminatingAccumulator) {
                        haveCheckedIfTerminatingAccumulator = true;
                        if (func instanceof TerminatingAccumulator<?>)
                            setIsEarlyTerminating();
                    }

                    if (!hasBeenTerminated() && isEarlyTerminating()
                            && ((TerminatingAccumulator<?>) func).isFinished()) {
                        earlyTerminate();
                    }

                    if (hasBeenTerminated()) {
                        result.returnStatus = POStatus.STATUS_EARLY_TERMINATION;
                        result.result = null;
                        isAccumulationDone = false;
                    } else {
                        ((Accumulator) func).accumulate((Tuple) result.result);
                        result.returnStatus = POStatus.STATUS_BATCH_OK;
                        result.result = null;
                        isAccumulationDone = false;
                    }
                } else {
                    if (isAccumulationDone) {
                        // PORelationToExprProject does not return
                        // STATUS_EOP
                        // so that udf gets called both when isAccumStarted
                        // is first true and then set to false, even
                        // when the input relation is empty.
                        // so the STATUS_EOP has to be sent from POUserFunc,
                        // after the results have been sent.
                        result.result = null;
                        result.returnStatus = POStatus.STATUS_EOP;
                    } else {
                        result.result = ((Accumulator) func).getValue();
                        result.returnStatus = POStatus.STATUS_OK;
                        ((Accumulator) func).cleanup();
                        isAccumulationDone = true;
                    }
                }
            } else {
                if (executor != null) {
                    result.result = executor.monitorExec((Tuple) result.result);
                } else {
                    if (funcSpec.getClassName().equals(ROLLUP_UDF) && this.rollupH2IRGoptimizable != false) {
                        ((RollupDimensions) func).setPivot(this.pivot);
                        ((RollupDimensions) func).setRollupH2IRGOptimizable(this.rollupH2IRGoptimizable);
                        ((RollupDimensions) func).setIsSampler(this.isSampler);
                    }
                    result.result = func.exec((Tuple) result.result);
                }
            }
        }
        if (timeThis) {
            PigStatusReporter.getInstance().getCounter(counterGroup, TIMING_COUNTER)
                    .increment((Math.round((System.nanoTime() - startNanos) / 1000)) * TIMING_FREQ);
        }
        return result;
    } catch (ExecException ee) {
        throw ee;
    } catch (IOException ioe) {
        int errCode = 2078;
        String msg = "Caught error from UDF: " + funcSpec.getClassName();
        String footer = " [" + ioe.getMessage() + "]";

        if (ioe instanceof PigException) {
            int udfErrorCode = ((PigException) ioe).getErrorCode();
            if (udfErrorCode != 0) {
                errCode = udfErrorCode;
                msg = ((PigException) ioe).getMessage();
            } else {
                msg += " [" + ((PigException) ioe).getMessage() + " ]";
            }
        } else {
            msg += footer;
        }

        throw new ExecException(msg, errCode, PigException.BUG, ioe);
    } catch (IndexOutOfBoundsException ie) {
        int errCode = 2078;
        String msg = "Caught error from UDF: " + funcSpec.getClassName() + ", Out of bounds access ["
                + ie.getMessage() + "]";
        throw new ExecException(msg, errCode, PigException.BUG, ie);
    }
}

From source file:org.hdiv.filter.ValidatorHelperRequest.java

/**
 * Checks if the suffix added in the memory version to all requests in the HDIV parameter is the same as the one
 * stored in session, which is the original suffix. So any request using the memory version should keep the suffix
 * unchanged./*from  ww w  .  j  av a 2s  .  c  o  m*/
 * 
 * @param value
 *            value received in the HDIV parameter
 * @return True if the received value of the suffix is valid. False otherwise.
 */
public boolean validateHDIVSuffix(String value) {

    int firstSeparator = value.indexOf("-");
    int lastSeparator = value.lastIndexOf("-");

    if (firstSeparator == -1) {

        return false;
    }

    if (firstSeparator >= lastSeparator) {

        return false;
    }

    try {
        // read hdiv's suffix from request
        String requestSuffix = value.substring(lastSeparator + 1);

        // read suffix from page stored in session
        String pageId = value.substring(0, firstSeparator);
        IPage currentPage = this.session.getPage(pageId);

        if (currentPage == null) {
            if (log.isErrorEnabled()) {
                log.error("Page with id [" + pageId + "] not found in session.");
            }
            throw new HDIVException(HDIVErrorCodes.PAGE_ID_INCORRECT);
        }

        return currentPage.getRandomToken().equals(requestSuffix);

    } catch (IndexOutOfBoundsException e) {
        String errorMessage = HDIVUtil.getMessage("validation.error", e.getMessage());
        if (log.isErrorEnabled()) {
            log.error(errorMessage);
        }
        throw new HDIVException(errorMessage, e);
    }
}