Example usage for org.apache.commons.lang3 StringUtils leftPad

List of usage examples for org.apache.commons.lang3 StringUtils leftPad

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils leftPad.

Prototype

public static String leftPad(final String str, final int size, String padStr) 

Source Link

Document

Left pad a String with a specified String.

Pad to a size of size .

 StringUtils.leftPad(null, *, *)      = null StringUtils.leftPad("", 3, "z")      = "zzz" StringUtils.leftPad("bat", 3, "yz")  = "bat" StringUtils.leftPad("bat", 5, "yz")  = "yzbat" StringUtils.leftPad("bat", 8, "yz")  = "yzyzybat" StringUtils.leftPad("bat", 1, "yz")  = "bat" StringUtils.leftPad("bat", -1, "yz") = "bat" StringUtils.leftPad("bat", 5, null)  = "  bat" StringUtils.leftPad("bat", 5, "")    = "  bat" 

Usage

From source file:edu.kit.dama.dataworkflow.util.DataWorkflowTaskUtils.java

/**
 * Print the provided list of DataWorkflow tasks to StdOut, either in a basic
 * tabular view or in verbose mode, in a detailed representation.
 *
 * @param pTasks The list of tasks to print out.
 * @param pVerbose TRUE = print detailed view, FALSE = print basic tabular
 * view.//from  w w  w .  j a  v  a 2  s . c om
 */
public static void printTaskList(List<DataWorkflowTask> pTasks, boolean pVerbose) {
    if (!pVerbose) {
        //do table listing
        //Headers: ID | STATUS | LAST_MODIFIED
        //Lengths: 10 | 34 | 34
        StringBuilder listing = new StringBuilder();
        listing.append(StringUtils.center("Task ID", 10)).append("|").append(StringUtils.center("Status", 34))
                .append("|").append(StringUtils.center("Last Modified", 34)).append("\n");
        for (DataWorkflowTask task : pTasks) {
            listing.append(StringUtils.center(Long.toString(task.getId()), 10)).append("|")
                    .append(StringUtils.center(task.getStatus().toString(), 34)).append("|")
                    .append(StringUtils.center(new SimpleDateFormat().format(task.getLastUpdate()), 34))
                    .append("\n");
        }
        System.out.println(listing.toString());
    } else {
        //do detailed listing
        //ID: <ID>     Status: <STATUS>  Last Update: <LAST_UPDATE>
        //Config: <CONFIG_ID> Environment: <ID> Predecessor: <ID>
        //Group: <GID> Executor: <UID> Contact: <EMAIL>
        //Investigation: <ID>
        //InputDir: <URL>
        //OutputDir: <URL>              
        //WorkingDir: <URL>              
        //TempDir: <URL>
        //Input Objects         
        // Object | View 
        //  OID 1 | default
        //  OID 2 | default
        //Transfers          
        // Object | TransferId 
        //  OID 1 | 123
        //--------------------------------------------------------------
        StringBuilder builder = new StringBuilder();
        for (DataWorkflowTask task : pTasks) {
            builder.append(StringUtils.rightPad("Id: " + task.getId(), 40))
                    .append(StringUtils.rightPad(
                            "Predecessor: "
                                    + ((task.getPredecessor() != null) ? task.getPredecessor().getId() : "-"),
                            40))
                    .append("\n").append(StringUtils.rightPad("Status: " + task.getStatus(), 40))
                    .append(StringUtils.rightPad(
                            "Last Update: " + new SimpleDateFormat().format(task.getLastUpdate()), 40))
                    .append("\n")
                    .append(StringUtils.rightPad("Configuration: "
                            + ((task.getConfiguration() != null) ? task.getConfiguration().getId() : "-"), 40))
                    .append(StringUtils.rightPad("Environment: "
                            + ((task.getExecutionEnvironment() != null) ? task.getExecutionEnvironment().getId()
                                    : "-"),
                            40))
                    .append("\n").append(StringUtils.rightPad("Group: " + task.getExecutorGroupId(), 40))
                    .append(StringUtils.rightPad("User: " + task.getExecutorId(), 40)).append("\n")
                    .append(StringUtils.rightPad("Contact UserId: "
                            + ((task.getContactUserId() != null) ? task.getContactUserId() : "-"), 80))
                    .append("\n")
                    .append(StringUtils.rightPad("InvestigationId: " + task.getInvestigationId(), 80))
                    .append("\n").append(StringUtils.rightPad("Input Dir:", 15))
                    .append(StringUtils.abbreviateMiddle(task.getInputDirectoryUrl(), "...", 65)).append("\n")
                    .append(StringUtils.rightPad("Output Dir:", 15))
                    .append(StringUtils.abbreviateMiddle(task.getOutputDirectoryUrl(), "...", 65)).append("\n")
                    .append(StringUtils.rightPad("Working Dir:", 15))
                    .append(StringUtils.abbreviateMiddle(task.getWorkingDirectoryUrl(), "...", 65)).append("\n")
                    .append(StringUtils.rightPad("Temp Dir:", 15))
                    .append(StringUtils.abbreviateMiddle(task.getTempDirectoryUrl(), "...", 65)).append("\n")
                    .append(StringUtils.rightPad("Input Objects:", 80)).append("\n")
                    .append(StringUtils.center("ObjectId", 39)).append("|")
                    .append(StringUtils.center("View", 40)).append("\n");
            try {
                Properties objectViewMap = task.getObjectViewMapAsObject();
                Set<Entry<Object, Object>> entries = objectViewMap.entrySet();
                if (entries.isEmpty()) {
                    builder.append(StringUtils.center("---", 39)).append("|")
                            .append(StringUtils.center("---", 40)).append("\n");
                } else {
                    for (Entry<Object, Object> entry : entries) {
                        builder.append(StringUtils.center((String) entry.getKey(), 39)).append("|")
                                .append(StringUtils.center((String) entry.getValue(), 40)).append("\n");
                    }
                }
            } catch (IOException ex) {
                LOGGER.error("Failed to deserialize object-view map of DataWorkflow task " + task.getId(), ex);
                builder.append(StringUtils.center("---", 39)).append("|").append(StringUtils.center("---", 40))
                        .append("\n");
            }
            builder.append(StringUtils.rightPad("Transfers:", 80)).append("\n")
                    .append(StringUtils.center("ObjectId", 39)).append("|")
                    .append(StringUtils.center("TransferId", 40)).append("\n");
            try {
                Properties objectTransferMap = task.getObjectTransferMapAsObject();
                Set<Entry<Object, Object>> entries = objectTransferMap.entrySet();
                if (entries.isEmpty()) {
                    builder.append(StringUtils.center("---", 39)).append("|")
                            .append(StringUtils.center("---", 40)).append("\n");
                } else {
                    for (Entry<Object, Object> entry : entries) {
                        builder.append(StringUtils.center((String) entry.getKey(), 39)).append("|")
                                .append(StringUtils.center((String) entry.getValue(), 40)).append("\n");
                    }
                }
            } catch (IOException ex) {
                LOGGER.error("Failed to deserialize object-transfer map of DataWorkflow task " + task.getId(),
                        ex);
                builder.append(StringUtils.center("---", 39)).append("|").append(StringUtils.center("---", 40))
                        .append("\n");
            }
            //add closing line
            builder.append(StringUtils.leftPad("", 80, '-')).append("\n");
        }
        System.out.println(builder.toString());
    }
}

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  ww  w . j ava  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:com.google.uzaygezen.core.LongBitVector.java

@Override
public String toString() {
    return StringUtils.leftPad(Long.toBinaryString(data), size, '0');
}

From source file:com.mgmtp.jfunk.core.JFunk.java

private ExecutorService createExecutorService() {
    return new FixedSizeThreadExecutor(min(threadCount, scripts.size()), new ThreadFactory() {
        private final AtomicInteger threadNumber = new AtomicInteger(1);

        @Override/*from   ww w.  j a  v a  2s.  c o m*/
        public Thread newThread(final Runnable r) {
            int id = threadNumber.getAndIncrement();
            String threadName = StringUtils.leftPad(String.valueOf(id), 2, "0");
            Thread th = new Thread(r);
            th.setName(threadName);
            return th;
        }
    });
}

From source file:com.netsteadfast.greenstep.util.SimpleUtils.java

public static final String getStrYMD(String splitStr) {
    StringBuilder sb = new StringBuilder();
    Calendar calendar = Calendar.getInstance();
    sb.append(calendar.get(Calendar.YEAR)).append(splitStr);
    sb.append(StringUtils.leftPad((calendar.get(Calendar.MONTH) + 1) + "", 2, "0")).append(splitStr);
    sb.append(StringUtils.leftPad(calendar.get(Calendar.DAY_OF_MONTH) + "", 2, "0"));
    return sb.toString();
}

From source file:com.norconex.commons.lang.time.YearMonthDay.java

/**
 * Converts the YearMonthDay to a string of this format: 
 * <code>yyyy-MM-dd</code>./*from  w w  w.  ja  va2 s. c  o  m*/
 */
@Override
public String toString() {
    return new StringBuilder().append(year).append('-')
            .append(StringUtils.leftPad(Integer.toString(month), 2, '0')).append('-')
            .append(StringUtils.leftPad(Integer.toString(day), 2, '0')).toString();
}

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

private HttpFiltersSource getFiltersSource() {
    return new HttpFiltersSourceAdapter() {
        @Override//  w  ww . j av  a  2  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:com.netsteadfast.greenstep.publish.impl.SystemMessagePublishServiceImpl.java

private boolean isPublishDateTimeRange(TbSysMsgNotice sysMsgNotice, Date sysDate) throws Exception {
    String timeStr = sysMsgNotice.getTime();
    String dateStr = sysMsgNotice.getDate();
    String systemDateStr = SimpleUtils.getStrYMD(sysDate, "");
    boolean f = false;
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(sysDate);/*from   ww w . j  ava2  s .  c  o m*/
    int nowTimeNum = Integer
            .parseInt(StringUtils.leftPad(String.valueOf(calendar.get(Calendar.HOUR_OF_DAY)), 2, "0")
                    + StringUtils.leftPad(String.valueOf(calendar.get(Calendar.MINUTE)), 2, "0"));
    int nowDateNum = Integer.parseInt(systemDateStr);
    String dateTmp[] = dateStr.split(Constants.DATETIME_DELIMITER);
    String timeTmp[] = timeStr.split(Constants.DATETIME_DELIMITER);
    int begDateNum = Integer.parseInt(dateTmp[0]);
    int endDateNum = Integer.parseInt(dateTmp[1]);
    int begTimeNum = Integer.parseInt(timeTmp[0]);
    int endTimeNum = Integer.parseInt(timeTmp[1]);
    if ((nowDateNum >= begDateNum && nowDateNum <= endDateNum) || dateStr.equals("00000000-00000000")) { // ?  
        if ("0000-0000".equals(timeStr)) { // 
            f = true;
        }
        if (nowTimeNum >= begTimeNum && nowTimeNum <= endTimeNum) { // ?
            f = true;
        }
    }
    return f;
}

From source file:com.shadows.hkprogrammer.core.MessageHandler.java

private ParameterMessage CreateParameterMessageFromBytes(ByteArray msgBytes) {
    ByteArray Payload = msgBytes.Read(2, msgBytes.length - 4);
    ParameterMessage message = new ParameterMessage();
    String BaseTypesValue = Integer.toBinaryString(Payload.Read(0, 1).ToByte());
    String BaseTypes = StringUtils.leftPad(BaseTypesValue, 8, '0');
    message.setTXModelType(TXModel.fromInteger(Integer.parseInt(BaseTypes.substring(0, 4), 2)));
    String CraftTypeString = BaseTypes.substring(4, 8);
    message.setCraftTypeNum(CraftType.fromInteger(Integer.parseInt(CraftTypeString, 2)));
    for (int i = 0; i < 3; i++) {
        int onValue = Payload.Read(2 + (i) * 2, 1).ToByte(), offValue = Payload.Read(3 + (i) * 2, 1).ToByte();
        message.setDRValueForChannel(DRChannel.fromInteger(i), onValue, offValue);
        int swash = Payload.Read(8 + i, 1).ToByte();
        message.setSwashValueForChannel(SwashChannel.fromInteger(i), swash);
        String mixCommunicationValue = Integer.toBinaryString(Payload.Read(49 + i * 4, 1).ToByte());
        String mixCommunication = StringUtils.leftPad(mixCommunicationValue, 8, '0');

        int mixUprate = Payload.Read(50 + i * 4, 1).ToByte(),
                mixDownrate = Payload.Read(51 + i * 4, 1).ToByte(),
                mixSwitch = Payload.Read(52 + i * 4, 1).ToByte();
        message.setMixSettingsValue(i + 1,
                MixDestination.fromInteger(Integer.parseInt(mixCommunication.substring(4, 8), 2)),
                MixSource.fromInteger(Integer.parseInt(mixCommunication.substring(0, 4), 2)),
                MixSwitch.fromInteger(mixSwitch), mixDownrate, mixUprate);
    }/*from   ww w .  j a  v a2s .c om*/
    String ReverseBytes = Integer.toBinaryString(Payload.Read(1, 1).ToByte());
    ReverseBytes = StringUtils.leftPad(ReverseBytes, 8, '0');
    for (int i = 0; i < 6; i++) {
        int endPointLeft = Payload.Read(11 + (i) * 2, 1).ToByte(),
                endPointRight = Payload.Read(12 + (i) * 2, 1).ToByte();
        message.setEndPointValueForChannel(ControlChannel.fromInteger(i), endPointLeft, endPointRight);
        message.setReverseBitmaskForChannel(ControlChannel.fromInteger(i),
                Integer.parseInt(ReverseBytes.substring(7 - i, 8 - i), 2) == 1);
        int subtrim = Payload.Read(43 + i, 1).ToByte();
        message.setSubtrimValueForChannel(ControlChannel.fromInteger(i), subtrim);
    }
    for (int i = 0; i < 5; i++) {
        byte throttleNormal = Payload.Read(23 + (i) * 2, 1).ToByte(),
                throttleId = Payload.Read(24 + (i) * 2, 1).ToByte(),
                pitchNormal = Payload.Read(33 + (i) * 2, 1).ToByte(),
                pitchId = Payload.Read(34 + (i) * 2, 1).ToByte();
        message.setThrottleCurveValueForChannel(HeliEndPoint.fromInteger(i), throttleNormal, throttleId);
        message.setPitchCurveValueForChannel(HeliEndPoint.fromInteger(i), pitchNormal, pitchId);
    }
    for (int i = 0; i < 2; i++) {
        int SwitchFunctionVal = Payload.Read(61 + i, 1).ToByte(),
                VRFunctionVal = Payload.Read(63 + i, 1).ToByte();
        message.setSwitchFunction(SwitchType.fromInteger(i), SwitchFunction.fromInteger(SwitchFunctionVal));
        message.setVRFunction(VRType.fromInteger(i), VRFunction.fromInteger(VRFunctionVal));
    }
    return message;
}

From source file:fr.outadev.android.timeo.TimeoRequestHandler.java

/**
 * Fetch the bus lines from the API.//from w w  w.j a  v  a 2s . c o  m
 *
 * @param networkCode the code for the city's bus network
 * @return a list of lines
 * @throws HttpRequestException   if an HTTP error occurred
 * @throws XmlPullParserException if a parsing exception occurred
 * @throws IOException            if an I/O exception occurred whilst parsing the XML
 * @throws TimeoException         if the API returned an error
 */
@NonNull
public static List<TimeoLine> getLines(int networkCode)
        throws HttpRequestException, XmlPullParserException, IOException, TimeoException {
    String params = "xml=1";
    String result = requestWebPage(API_BASE_URL + getPageNameForNetworkCode(networkCode), params, true);

    XmlPullParser parser = getParserForXMLString(result);
    int eventType = parser.getEventType();

    TimeoLine tmpLine = null;
    TimeoIDNameObject tmpDirection;

    ArrayList<TimeoLine> lines = new ArrayList<>();

    String errorCode = null;
    String text = null;

    boolean isInLineTag = false;

    while (eventType != XmlPullParser.END_DOCUMENT) {
        String tagname = parser.getName();

        switch (eventType) {
        case XmlPullParser.START_TAG:

            if (tagname.equals("ligne")) {
                isInLineTag = true;
                tmpDirection = new TimeoIDNameObject();
                tmpLine = new TimeoLine(new TimeoIDNameObject(), tmpDirection, networkCode);

            } else if (tagname.equals("arret")) {
                isInLineTag = false;

            } else if (tagname.equals("erreur")) {
                errorCode = parser.getAttributeValue(null, "code");
            }

            break;

        case XmlPullParser.TEXT:
            text = parser.getText();
            break;

        case XmlPullParser.END_TAG:
            if (tagname.equals("ligne")) {
                lines.add(tmpLine);

            } else if (tmpLine != null && tagname.equals("code") && isInLineTag) {
                tmpLine.getDetails().setId(text);

            } else if (tmpLine != null && tagname.equals("nom") && isInLineTag) {
                tmpLine.getDetails().setName(smartCapitalize(text));

            } else if (tmpLine != null && tagname.equals("sens") && isInLineTag) {
                tmpLine.getDirection().setId(text);

            } else if (tmpLine != null && tagname.equals("vers") && isInLineTag) {
                tmpLine.getDirection().setName(smartCapitalize(text));

            } else if (tmpLine != null && tagname.equals("couleur") && isInLineTag) {
                tmpLine.setColor("#" + StringUtils.leftPad(Integer.toHexString(Integer.valueOf(text)), 6, '0'));

            } else if (tagname.equals("erreur")) {
                if ((errorCode != null && !errorCode.equals("000"))
                        || (text != null && !text.trim().isEmpty())) {
                    throw new TimeoException(errorCode + " - " + text);
                }
            }

            break;

        default:
            break;
        }

        eventType = parser.next();
    }

    return lines;
}