Example usage for java.lang String contentEquals

List of usage examples for java.lang String contentEquals

Introduction

In this page you can find the example usage for java.lang String contentEquals.

Prototype

public boolean contentEquals(CharSequence cs) 

Source Link

Document

Compares this string to the specified CharSequence .

Usage

From source file:com.android.mail.utils.NotificationUtils.java

private static void configureLatestEventInfoFromConversation(final Context context, final Account account,
        final FolderPreferences folderPreferences, final NotificationCompat.Builder notificationBuilder,
        final NotificationCompat.WearableExtender wearableExtender,
        final Map<Integer, NotificationBuilders> msgNotifications, final int summaryNotificationId,
        final Cursor conversationCursor, final PendingIntent clickIntent, final Intent notificationIntent,
        final int unreadCount, final int unseenCount, final Folder folder, final long when,
        final ContactFetcher contactFetcher) {
    final Resources res = context.getResources();
    final boolean multipleUnseen = unseenCount > 1;

    LogUtils.i(LOG_TAG, "Showing notification with unreadCount of %d and unseenCount of %d", unreadCount,
            unseenCount);/*from  ww w.  j  a  v a 2  s.c  o m*/

    String notificationTicker = null;

    // Boolean indicating that this notification is for a non-inbox label.
    final boolean isInbox = folder.folderUri.fullUri.equals(account.settings.defaultInbox);

    // Notification label name for user label notifications.
    final String notificationLabelName = isInbox ? null : folder.name;

    if (multipleUnseen) {
        // Build the string that describes the number of new messages
        final String newMessagesString = createTitle(context, unseenCount);

        // The ticker initially start as the new messages string.
        notificationTicker = newMessagesString;

        // The title of the notification is the new messages string
        notificationBuilder.setContentTitle(newMessagesString);

        // TODO(skennedy) Can we remove this check?
        if (com.android.mail.utils.Utils.isRunningJellybeanOrLater()) {
            // For a new-style notification
            final int maxNumDigestItems = context.getResources()
                    .getInteger(R.integer.max_num_notification_digest_items);

            // The body of the notification is the account name, or the label name.
            notificationBuilder.setSubText(isInbox ? account.getDisplayName() : notificationLabelName);

            final NotificationCompat.InboxStyle digest = new NotificationCompat.InboxStyle(notificationBuilder);

            // Group by account and folder
            final String notificationGroupKey = createGroupKey(account, folder);
            // Track all senders to later tag them along with the digest notification
            final HashSet<String> senderAddressesSet = new HashSet<String>();
            notificationBuilder.setGroup(notificationGroupKey).setGroupSummary(true);

            ConfigResult firstResult = null;
            int numDigestItems = 0;
            do {
                final Conversation conversation = new Conversation(conversationCursor);

                if (!conversation.read) {
                    boolean multipleUnreadThread = false;
                    // TODO(cwren) extract this pattern into a helper

                    Cursor cursor = null;
                    MessageCursor messageCursor = null;
                    try {
                        final Uri.Builder uriBuilder = conversation.messageListUri.buildUpon();
                        uriBuilder.appendQueryParameter(UIProvider.LABEL_QUERY_PARAMETER,
                                notificationLabelName);
                        cursor = context.getContentResolver().query(uriBuilder.build(),
                                UIProvider.MESSAGE_PROJECTION, null, null, null);
                        messageCursor = new MessageCursor(cursor);

                        String from = "";
                        String fromAddress = "";
                        if (messageCursor.moveToPosition(messageCursor.getCount() - 1)) {
                            final Message message = messageCursor.getMessage();
                            fromAddress = message.getFrom();
                            if (fromAddress == null) {
                                fromAddress = "";
                            }
                            from = getDisplayableSender(fromAddress);
                            addEmailAddressToSet(fromAddress, senderAddressesSet);
                        }
                        while (messageCursor.moveToPosition(messageCursor.getPosition() - 1)) {
                            final Message message = messageCursor.getMessage();
                            if (!message.read && !fromAddress.contentEquals(message.getFrom())) {
                                multipleUnreadThread = true;
                                addEmailAddressToSet(message.getFrom(), senderAddressesSet);
                            }
                        }
                        final SpannableStringBuilder sendersBuilder;
                        if (multipleUnreadThread) {
                            final int sendersLength = res.getInteger(R.integer.swipe_senders_length);

                            sendersBuilder = getStyledSenders(context, conversationCursor, sendersLength,
                                    account);
                        } else {
                            sendersBuilder = new SpannableStringBuilder(getWrappedFromString(from));
                        }
                        final CharSequence digestLine = getSingleMessageInboxLine(context,
                                sendersBuilder.toString(),
                                ConversationItemView.filterTag(context, conversation.subject),
                                conversation.getSnippet());
                        digest.addLine(digestLine);
                        numDigestItems++;

                        // Adding conversation notification for Wear.
                        NotificationCompat.Builder conversationNotif = new NotificationCompat.Builder(context);
                        conversationNotif.setCategory(NotificationCompat.CATEGORY_EMAIL);

                        conversationNotif.setSmallIcon(R.drawable.ic_notification_multiple_mail_24dp);

                        if (com.android.mail.utils.Utils.isRunningLOrLater()) {
                            conversationNotif
                                    .setColor(context.getResources().getColor(R.color.notification_icon_color));
                        }
                        conversationNotif.setContentText(digestLine);
                        Intent conversationNotificationIntent = createViewConversationIntent(context, account,
                                folder, conversationCursor);
                        PendingIntent conversationClickIntent = createClickPendingIntent(context,
                                conversationNotificationIntent);
                        conversationNotif.setContentIntent(conversationClickIntent);
                        conversationNotif.setAutoCancel(true);

                        // Conversations are sorted in descending order, but notification sort
                        // key is in ascending order.  Invert the order key to get the right
                        // order.  Left pad 19 zeros because it's a long.
                        String groupSortKey = String.format("%019d", (Long.MAX_VALUE - conversation.orderKey));
                        conversationNotif.setGroup(notificationGroupKey);
                        conversationNotif.setSortKey(groupSortKey);
                        conversationNotif.setWhen(conversation.dateMs);

                        int conversationNotificationId = getNotificationId(summaryNotificationId,
                                conversation.hashCode());

                        final NotificationCompat.WearableExtender conversationWearExtender = new NotificationCompat.WearableExtender();
                        final ConfigResult result = configureNotifForOneConversation(context, account,
                                folderPreferences, conversationNotif, conversationWearExtender,
                                conversationCursor, notificationIntent, folder, when, res, isInbox,
                                notificationLabelName, conversationNotificationId, contactFetcher);
                        msgNotifications.put(conversationNotificationId,
                                NotificationBuilders.of(conversationNotif, conversationWearExtender));

                        if (firstResult == null) {
                            firstResult = result;
                        }
                    } finally {
                        if (messageCursor != null) {
                            messageCursor.close();
                        }
                        if (cursor != null) {
                            cursor.close();
                        }
                    }
                }
            } while (numDigestItems <= maxNumDigestItems && conversationCursor.moveToNext());

            // Tag main digest notification with the senders
            tagNotificationsWithPeople(notificationBuilder, senderAddressesSet);

            if (firstResult != null && firstResult.contactIconInfo != null) {
                wearableExtender.setBackground(firstResult.contactIconInfo.wearableBg);
            } else {
                LogUtils.w(LOG_TAG, "First contact icon is null!");
                wearableExtender.setBackground(getDefaultWearableBg(context));
            }
        } else {
            // The body of the notification is the account name, or the label name.
            notificationBuilder.setContentText(isInbox ? account.getDisplayName() : notificationLabelName);
        }
    } else {
        // For notifications for a single new conversation, we want to get the information
        // from the conversation

        // Move the cursor to the most recent unread conversation
        seekToLatestUnreadConversation(conversationCursor);

        final ConfigResult result = configureNotifForOneConversation(context, account, folderPreferences,
                notificationBuilder, wearableExtender, conversationCursor, notificationIntent, folder, when,
                res, isInbox, notificationLabelName, summaryNotificationId, contactFetcher);
        notificationTicker = result.notificationTicker;

        if (result.contactIconInfo != null) {
            wearableExtender.setBackground(result.contactIconInfo.wearableBg);
        } else {
            wearableExtender.setBackground(getDefaultWearableBg(context));
        }
    }

    // Build the notification ticker
    if (notificationLabelName != null && notificationTicker != null) {
        // This is a per label notification, format the ticker with that information
        notificationTicker = res.getString(R.string.label_notification_ticker, notificationLabelName,
                notificationTicker);
    }

    if (notificationTicker != null) {
        // If we didn't generate a notification ticker, it will default to account name
        notificationBuilder.setTicker(notificationTicker);
    }

    // Set the number in the notification
    if (unreadCount > 1) {
        notificationBuilder.setNumber(unreadCount);
    }

    notificationBuilder.setContentIntent(clickIntent);
}

From source file:com.openatk.planting.MainActivity.java

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    String todo = intent.getStringExtra("todo");
    if (todo != null) {
        if (todo.contentEquals("sync")) {
            trelloController.sync();/*from w  w  w.jav  a 2  s.  c om*/
        }
    }
}

From source file:cl.ipp.katbag.fragment.Develop.java

public boolean canIndent(String statement, String value, int position) {
    dialogList.clear();/*from   ww w.j a  v  a  2s .  c  o  m*/
    if (statement.contentEquals("motion")) {

    } else if (statement.contentEquals("look")) {

    } else if (statement.contentEquals("sound")) {

    } else if (statement.contentEquals("control")) {
        dialogList = new ArrayList<String>(
                Arrays.asList(getResources().getStringArray(R.array.control_indent)));

    } else if (statement.contentEquals("sensing")) {
        dialogList = new ArrayList<String>(
                Arrays.asList(getResources().getStringArray(R.array.sensing_indent)));
    }

    boolean indent = false;
    if (dialogList.size() > 0) {
        for (int i = 0; i < dialogList.size(); i++) {
            if (value.contentEquals(dialogList.get(i))) {
                indent = true;
                break;
            }
        }
    }

    return indent;
}

From source file:com.openatk.planting.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    dbHelper = new DatabaseHelper(this);

    FragmentManager fm = getSupportFragmentManager();
    fragMap = (SupportMapFragment) fm.findFragmentById(R.id.map);

    fragmentEditField = (FragmentEditJobPopup) fm.findFragmentByTag("edit_job");

    if (savedInstanceState == null) {
        // First incarnation of this activity.
        fragMap.setRetainInstance(true);
    } else {/*  w w w.  j ava  2  s .c  o  m*/
        // Reincarnated activity. The obtained map is the same map instance
        // in the previous
        // activity life cycle. There is no need to reinitialize it.
        map = fragMap.getMap();
    }
    checkGPS();

    actionBar = getActionBar();
    // Specify that a dropdown list should be displayed in the action bar.
    // actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

    // Hide the title
    actionBar.setDisplayShowTitleEnabled(false);
    actionBar.setDisplayUseLogoEnabled(false);

    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM, ActionBar.DISPLAY_SHOW_CUSTOM);
    View view;
    LayoutInflater inflater = (LayoutInflater) this.getApplicationContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    view = inflater.inflate(R.layout.action_bar, null);
    RelativeLayout item = (RelativeLayout) view.findViewById(R.id.action_bar_layout);
    spinnerMenu = (Spinner) view.findViewById(R.id.action_bar_operation_spinner);
    actionBarSearch = (EditText) view.findViewById(R.id.action_bar_search_box);
    actionBar.setCustomView(item, new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT,
            ActionBar.LayoutParams.WRAP_CONTENT, Gravity.CENTER_VERTICAL | Gravity.LEFT));

    actionBarSearch.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus == false) {
                InputMethodManager imm = (InputMethodManager) v.getContext()
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        }
    });
    actionBarSearch.addTextChangedListener(new TextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {
            if (fragmentListView != null)
                fragmentListView.search(s.toString());
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }
    });

    Fragment fragment = fm.findFragmentById(R.id.list_view);
    FragmentTransaction ft = fm.beginTransaction();
    ft.hide(fragment);
    ft.commit();

    //Trello
    trelloController = new TrelloController(getApplicationContext());
    syncController = new SyncController(getApplicationContext(), trelloController, this);
    trelloController.setSyncController(syncController);

    // Get last selected operation
    if (savedInstanceState != null) {
        // Find current field
        currentField = FindFieldById(savedInstanceState.getInt("currentField"));

        // Find current job
        currentJob = FindJobById(savedInstanceState.getInt("currentJob"));

        // Find current operation
        currentOperationId = savedInstanceState.getInt("currentOperationId");

        editIsShowing = savedInstanceState.getInt("editIsShowing");
        addIsShowing = savedInstanceState.getInt("addIsShowing");

        this.addingBoundary = savedInstanceState.getString("drawingBoundary", "");

        // Switch to correct state
        setState(savedInstanceState.getInt("mCurrentState"), false);
    }

    // Load operations from database
    loadOperations();

    // Specify a SpinnerAdapter to populate the dropdown list.
    spinnerMenuAdapter = new ArrayAdapter<Operation>(this, R.layout.operation_list_item, operationsList);
    spinnerMenu.setAdapter(spinnerMenuAdapter);
    // Load current from preferences
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    currentOperationId = prefs.getInt("currentOperationId", 0);
    this.showingHazards = prefs.getBoolean("showingHazards", false);
    selectCurrentOperationInSpinner();
    spinnerMenu.setOnItemSelectedListener(this);

    setUpMapIfNeeded();

    Intent intent = this.getIntent();
    String todo = intent.getStringExtra("todo");
    if (todo != null) {
        if (todo.contentEquals("sync")) {
            trelloController.sync();
        }
    }
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}

From source file:com.tct.mail.utils.NotificationUtils.java

private static void configureLatestEventInfoFromConversation(final Context context, final Account account,
        final FolderPreferences folderPreferences, final NotificationCompat.Builder notification,
        final NotificationCompat.WearableExtender wearableExtender,
        final Map<Integer, NotificationBuilders> msgNotifications, final int summaryNotificationId,
        final Cursor conversationCursor, final PendingIntent clickIntent, final Intent notificationIntent,
        final int unreadCount, final int unseenCount, final Folder folder, final long when,
        final ContactPhotoFetcher photoFetcher) {
    final Resources res = context.getResources();
    final String notificationAccountDisplayName = account.getDisplayName();
    final String notificationAccountEmail = account.getEmailAddress();
    final boolean multipleUnseen = unseenCount > 1;

    LogUtils.i(LOG_TAG, "Showing notification with unreadCount of %d and unseenCount of %d", unreadCount,
            unseenCount);//from   www  .j a  v  a  2s . c  om

    String notificationTicker = null;

    // Boolean indicating that this notification is for a non-inbox label.
    final boolean isInbox = folder.folderUri.fullUri.equals(account.settings.defaultInbox);

    // Notification label name for user label notifications.
    final String notificationLabelName = isInbox ? null : folder.name;

    if (multipleUnseen) {
        // Build the string that describes the number of new messages
        final String newMessagesString = createTitle(context, unseenCount);

        // Use the default notification icon
        notification
                .setLargeIcon(getDefaultNotificationIcon(context, folder, true /* multiple new messages */));

        // The ticker initially start as the new messages string.
        notificationTicker = newMessagesString;

        // The title of the notification is the new messages string
        notification.setContentTitle(newMessagesString);

        // TODO(skennedy) Can we remove this check?
        if (com.tct.mail.utils.Utils.isRunningJellybeanOrLater()) {
            // For a new-style notification
            final int maxNumDigestItems = context.getResources()
                    .getInteger(R.integer.max_num_notification_digest_items);

            // The body of the notification is the account name, or the label name.
            notification.setSubText(isInbox ? notificationAccountDisplayName : notificationLabelName);

            final NotificationCompat.InboxStyle digest = new NotificationCompat.InboxStyle(notification);

            // Group by account and folder
            final String notificationGroupKey = createGroupKey(account, folder);
            notification.setGroup(notificationGroupKey).setGroupSummary(true);

            ConfigResult firstResult = null;
            int numDigestItems = 0;
            do {
                final Conversation conversation = new Conversation(conversationCursor);

                if (!conversation.read) {
                    boolean multipleUnreadThread = false;
                    // TODO(cwren) extract this pattern into a helper

                    Cursor cursor = null;
                    MessageCursor messageCursor = null;
                    try {
                        final Uri.Builder uriBuilder = conversation.messageListUri.buildUpon();
                        uriBuilder.appendQueryParameter(UIProvider.LABEL_QUERY_PARAMETER,
                                notificationLabelName);
                        cursor = context.getContentResolver().query(uriBuilder.build(),
                                UIProvider.MESSAGE_PROJECTION, null, null, null);
                        messageCursor = new MessageCursor(cursor);

                        String from = "";
                        String fromAddress = "";
                        if (messageCursor.moveToPosition(messageCursor.getCount() - 1)) {
                            final Message message = messageCursor.getMessage();
                            fromAddress = message.getFrom();
                            if (fromAddress == null) {
                                fromAddress = "";
                            }
                            from = getDisplayableSender(fromAddress);
                        }
                        while (messageCursor.moveToPosition(messageCursor.getPosition() - 1)) {
                            final Message message = messageCursor.getMessage();
                            if (!message.read && !fromAddress.contentEquals(message.getFrom())) {
                                multipleUnreadThread = true;
                                break;
                            }
                        }
                        final SpannableStringBuilder sendersBuilder;
                        if (multipleUnreadThread) {
                            final int sendersLength = res.getInteger(R.integer.swipe_senders_length);

                            sendersBuilder = getStyledSenders(context, conversationCursor, sendersLength,
                                    notificationAccountEmail);
                        } else {
                            sendersBuilder = new SpannableStringBuilder(getWrappedFromString(from));
                        }
                        //TS: zheng.zou 2015-03-20 EMAIL BUGFIX_-954980 MOD_S
                        CharSequence digestLine = getSingleMessageInboxLine(context, sendersBuilder.toString(),
                                ConversationItemView.filterTag(context, conversation.subject),
                                conversation.getSnippet());
                        if (digestLine == null) {
                            digestLine = "";
                        }
                        //TS: zheng.zou 2015-03-20 EMAIL BUGFIX_-954980 MOD_E
                        digest.addLine(digestLine);
                        numDigestItems++;

                        // Adding conversation notification for Wear.
                        NotificationCompat.Builder conversationNotif = new NotificationCompat.Builder(context);

                        // TODO(shahrk) - fix for multiple mail
                        // Check that the group's folder is assigned an icon res (one of the
                        // 4 sections). If it is, we can add the gmail badge. If not, it is
                        // accompanied by the multiple_mail_24dp icon and we don't want a badge
                        // if (folder.notificationIconResId != 0) {
                        conversationNotif.setSmallIcon(R.drawable.ic_notification_mail_24dp);

                        if (com.tct.mail.utils.Utils.isRunningLOrLater()) {
                            conversationNotif.setColor(
                                    context.getResources().getColor(R.color.notification_icon_mail_orange));
                        }
                        conversationNotif.setContentText(digestLine);
                        Intent conversationNotificationIntent = createViewConversationIntent(context, account,
                                folder, conversationCursor);
                        PendingIntent conversationClickIntent = createClickPendingIntent(context,
                                conversationNotificationIntent);
                        conversationNotif.setContentIntent(conversationClickIntent);
                        conversationNotif.setAutoCancel(true);

                        // Conversations are sorted in descending order, but notification sort
                        // key is in ascending order.  Invert the order key to get the right
                        // order.  Left pad 19 zeros because it's a long.
                        String groupSortKey = String.format("%019d", (Long.MAX_VALUE - conversation.orderKey));
                        conversationNotif.setGroup(notificationGroupKey);
                        conversationNotif.setSortKey(groupSortKey);

                        int conversationNotificationId = getNotificationId(summaryNotificationId,
                                conversation.hashCode());

                        final NotificationCompat.WearableExtender conversationWearExtender = new NotificationCompat.WearableExtender();
                        final ConfigResult result = configureNotifForOneConversation(context, account,
                                folderPreferences, conversationNotif, conversationWearExtender,
                                conversationCursor, notificationIntent, folder, when, res,
                                notificationAccountDisplayName, notificationAccountEmail, isInbox,
                                notificationLabelName, conversationNotificationId, photoFetcher);
                        // TS: chenyanhua 2015-02-11 EMAIL BUGFIX-926747 ADD_S
                        result.contactIconInfo = getContactIcon(context, folder, photoFetcher);
                        notification.setLargeIcon(result.contactIconInfo.icon);
                        // TS: chenyanhua 2015-02-11 EMAIL BUGFIX-926747 ADD_E
                        msgNotifications.put(conversationNotificationId,
                                NotificationBuilders.of(conversationNotif, conversationWearExtender));

                        if (firstResult == null) {
                            firstResult = result;
                        }
                    } finally {
                        if (messageCursor != null) {
                            messageCursor.close();
                        }
                        if (cursor != null) {
                            cursor.close();
                        }
                    }
                }
            } while (numDigestItems <= maxNumDigestItems && conversationCursor.moveToNext());

            if (firstResult != null && firstResult.contactIconInfo != null) {
                wearableExtender.setBackground(firstResult.contactIconInfo.wearableBg);
            } else {
                LogUtils.w(LOG_TAG, "First contact icon is null!");
                wearableExtender.setBackground(getDefaultWearableBg(context));
            }
        } else {
            // The body of the notification is the account name, or the label name.
            notification.setContentText(isInbox ? notificationAccountDisplayName : notificationLabelName);
        }
    } else {
        // For notifications for a single new conversation, we want to get the information
        // from the conversation

        // Move the cursor to the most recent unread conversation
        seekToLatestUnreadConversation(conversationCursor);

        final ConfigResult result = configureNotifForOneConversation(context, account, folderPreferences,
                notification, wearableExtender, conversationCursor, notificationIntent, folder, when, res,
                notificationAccountDisplayName, notificationAccountEmail, isInbox, notificationLabelName,
                summaryNotificationId, photoFetcher);
        notificationTicker = result.notificationTicker;

        if (result.contactIconInfo != null) {
            wearableExtender.setBackground(result.contactIconInfo.wearableBg);
        } else {
            wearableExtender.setBackground(getDefaultWearableBg(context));
        }
    }

    // Build the notification ticker
    if (notificationLabelName != null && notificationTicker != null) {
        // This is a per label notification, format the ticker with that information
        notificationTicker = res.getString(R.string.label_notification_ticker, notificationLabelName,
                notificationTicker);
    }

    if (notificationTicker != null) {
        // If we didn't generate a notification ticker, it will default to account name
        notification.setTicker(notificationTicker);
    }

    // Set the number in the notification
    if (unreadCount > 1) {
        notification.setNumber(unreadCount);
    }

    notification.setContentIntent(clickIntent);
}

From source file:skoa.helpers.Graficos.java

private void compararFicheros(String freferencia, String fcomparar) {
    System.out.println("min=" + rangoMinutos + ".");
    File fr = new File(ruta + freferencia); //El primer fichero es el de referencia, y del que se sacan los incrementos.
    File fc = new File(ruta + fcomparar);
    FileReader fr1 = null, fr2 = null;
    BufferedReader linea1 = null, linea2 = null;
    String L1 = null, L2 = null;//  ww w  .  java  2s .com
    SimpleDateFormat formatoDelTexto = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    //Vamos a abrir los dos ficheros a la vez, leyendo lnea por lnea y comparando.
    try {
        File temp = new File(ruta + "temp.txt");
        if (!temp.exists())
            temp.createNewFile(); //Crea el fichero
        //LEEMOS EL PRIMER FICHERO
        fr1 = new FileReader(fr);
        linea1 = new BufferedReader(fr1);
        Vector<String> fechas = new Vector<String>(); //vector donde irn todas las fechas
        Date d1 = null, dini = null, dfin = null;
        boolean primeravez = true, nuevo = true;
        float media1 = 0;
        int nelem1 = 0, segd1 = 0;
        String fecha = "", aux = "", lant = "";
        while ((L1 = linea1.readLine()) != null) {
            aux = L1.substring(0, L1.indexOf("\t")); //Fecha de la lnea.
            d1 = formatoDelTexto.parse(aux);
            String Ssegd1 = aux.substring(aux.indexOf(" ") + 7, aux.indexOf(" ") + 9);
            segd1 = Integer.parseInt(Ssegd1);
            d1.setSeconds(segd1);
            if (nuevo) { //Si terminamos el intervalo, pasamos al siguiente.
                Calendar c = Calendar.getInstance();
                if (!primeravez) {//Si no es la primera iteracion, se guarda antes de inicializar.
                    //System.out.println(media1+"  "+nelem1);
                    media1 = media1 / nelem1;
                    BufferedWriter bw = new BufferedWriter(new FileWriter(ruta + "temp.txt", true)); //Para escribir.
                    String x1 = "" + media1;
                    if (!x1.contentEquals("NaN"))
                        bw.write("" + fecha + "\t" + media1 + " " + unidad + "\n");
                    bw.close();
                    media1 = nelem1 = 0;
                    String v = lant.substring(lant.indexOf("\t") + 1);
                    v = v.substring(0, v.indexOf(" "));
                    media1 = Float.parseFloat(v);//Se inicializan con los valores de la anterior linea.
                    nelem1 = 1;
                } else {
                    String u = L1.substring(L1.indexOf("\t") + 1);
                    unidad = u.substring(u.indexOf(" ") + 1);
                    lant = L1;
                    //Si es la 1 vez, tambin se inicializa la fecha inicial.
                }
                primeravez = false;
                fecha = lant.substring(0, lant.indexOf("\t"));
                fechas.add(fecha);
                //Inserta la fecha en el vector de fechas, para luego usarlo en el 2 fichero.
                Date diniaux = formatoDelTexto.parse(fecha);
                String Ssegd2 = fecha.substring(fecha.indexOf(" ") + 7, fecha.indexOf(" ") + 9);
                int segd2 = Integer.parseInt(Ssegd2);
                c.setTime(diniaux);
                dini = c.getTime();
                dini.setSeconds(segd2);
                //System.out.println("Ini="+dini);
                c.add(Calendar.MINUTE, Integer.parseInt(rangoMinutos));
                dfin = c.getTime();
                dfin.setSeconds(segd2);
                //System.out.println("Fin="+dfin);
                nuevo = false;//Esta variable se usa para definir otra vez un nuevo intervalo
            }
            if (d1.compareTo(dini) == 0) { //Fechas Iguales
                aux = L1.substring(L1.indexOf("\t") + 1);
                aux = aux.substring(0, aux.indexOf(" "));
                media1 = media1 + Float.parseFloat(aux);
                nelem1++;
            } else if (d1.compareTo(dini) > 0 && d1.compareTo(dfin) < 0) { //Est dentro del intervalo
                aux = L1.substring(L1.indexOf("\t") + 1);
                aux = aux.substring(0, aux.indexOf(" "));
                media1 = media1 + Float.parseFloat(aux);
                nelem1++;
            } else {//Si la fecha es menor que la fecha inicial o mayor que la final, se cambia de intervalo.
                nuevo = true;
            }
            lant = L1;
        }
        //guardo lo ultimo y penultimo si lo hay
        media1 = media1 / nelem1;
        BufferedWriter bw = new BufferedWriter(new FileWriter(ruta + "temp.txt", true)); //Para escribir.
        String x1 = "" + media1;
        String auxi = dini.toGMTString(); //d mon yyyy hh:mm:ss
        String d = auxi.substring(0, auxi.indexOf(" "));
        if (Integer.parseInt(d) < 10)
            d = "0" + d;
        auxi = auxi.substring(auxi.indexOf(" ") + 1);
        String m = auxi.substring(0, auxi.indexOf(" "));
        if (m.contentEquals("Jan"))
            m = "01";
        if (m.contentEquals("Feb"))
            m = "02";
        if (m.contentEquals("Mar"))
            m = "03";
        if (m.contentEquals("Apr"))
            m = "04";
        if (m.contentEquals("May"))
            m = "05";
        if (m.contentEquals("Jun"))
            m = "06";
        if (m.contentEquals("Jul"))
            m = "07";
        if (m.contentEquals("Aug"))
            m = "08";
        if (m.contentEquals("Sep"))
            m = "09";
        if (m.contentEquals("Oct"))
            m = "10";
        if (m.contentEquals("Nov"))
            m = "11";
        if (m.contentEquals("Dec"))
            m = "12";
        auxi = auxi.substring(auxi.indexOf(" ") + 1);
        String y = auxi.substring(0, auxi.indexOf(" "));
        auxi = auxi.substring(auxi.indexOf(" ") + 1);
        String h = auxi.substring(0, auxi.indexOf(" "));
        //System.out.println(y+"-"+m+"-"+d+" "+h);
        if (!x1.contentEquals("NaN"))
            bw.write("" + y + "-" + m + "-" + d + " " + h + "\t" + media1 + " " + unidad + "\n");
        bw.close();
        fechas.add(y + "-" + m + "-" + d + " " + h);
        fecha = lant.substring(0, lant.indexOf("\t"));
        if (!fecha.isEmpty()) {
            String auxr = lant.substring(lant.indexOf("\t") + 1);
            auxr = auxr.substring(0, auxr.indexOf(" "));
            media1 = Float.parseFloat(auxr);
            bw = new BufferedWriter(new FileWriter(ruta + "temp.txt", true)); //Para escribir.
            x1 = "" + media1;
            if (!x1.contentEquals("NaN"))
                bw.write("" + fecha + "\t" + media1 + " " + unidad + "\n");
            bw.close();
            fechas.add(fecha);
        }
        fr1.close();
        //for (int i=0;i<fechas.size();i++) System.out.println("*"+fechas.elementAt(i));

        //Leido el primer fichero, leo el segundo.
        File temp2 = new File(ruta + "temp2.txt");
        if (!temp2.exists())
            temp2.createNewFile(); //Crea el fichero
        fr2 = new FileReader(fc);
        linea2 = new BufferedReader(fr2);
        int pos = 0;
        String fechaf = "";
        media1 = nelem1 = 0;
        nuevo = true;
        primeravez = true;
        while ((L2 = linea2.readLine()) != null) {
            aux = L2.substring(0, L2.indexOf("\t")); //Fecha de la lnea.
            d1 = formatoDelTexto.parse(aux);
            String Ssegd1 = aux.substring(aux.indexOf(" ") + 7, aux.indexOf(" ") + 9);
            segd1 = Integer.parseInt(Ssegd1);
            d1.setSeconds(segd1);
            if (nuevo) { //Si terminamos el intervalo, pasamos al siguiente.            
                Calendar c = Calendar.getInstance();
                if (!primeravez) {//Si no es la primera iteracion, se guarda antes de inicializar.
                    media1 = media1 / nelem1;
                    BufferedWriter bw1 = new BufferedWriter(new FileWriter(ruta + "temp2.txt", true)); //Para escribir.
                    x1 = "" + media1;
                    if (!x1.contentEquals("NaN"))
                        bw1.write("" + /*fechas.elementAt(pos)+"\t"+*/media1 + " " + unidad + "\n");
                    bw1.close();
                    pos++;
                    //media1=nelem1=0;
                    String v = lant.substring(lant.indexOf("\t") + 1);
                    v = v.substring(0, v.indexOf(" "));
                    media1 = Float.parseFloat(v);//Se inicializan con los valores de la anterior linea.
                    nelem1 = 1;
                } else {
                    String u = L2.substring(L2.indexOf("\t") + 1);
                    unidad = u.substring(u.indexOf(" ") + 1);
                    lant = L1;
                    pos = 0;
                    //Si es la 1 vez, tambin se inicializa la fecha inicial.
                }
                //System.out.println(fechas.elementAt(pos));
                primeravez = false;
                fecha = fechas.elementAt(pos);
                Date diniaux = formatoDelTexto.parse(fecha);
                String Ssegd2 = fecha.substring(fecha.indexOf(" ") + 7, fecha.indexOf(" ") + 9);
                int segd2 = Integer.parseInt(Ssegd2);
                c.setTime(diniaux);
                dini = c.getTime(); //FECHA INICIAL.                    
                dini.setSeconds(segd2);

                if (pos + 1 >= fechas.size())
                    break;
                fechaf = fechas.elementAt(pos + 1);
                Date dfinaux = formatoDelTexto.parse(fechaf);
                Ssegd2 = fecha.substring(fechaf.indexOf(" ") + 7, fechaf.indexOf(" ") + 9);
                segd2 = Integer.parseInt(Ssegd2);
                c.setTime(dfinaux);
                dfin = c.getTime(); //FECHA FINAL
                dfin.setSeconds(segd2);
                //System.out.println("INI="+dini);
                //System.out.println("FIN="+dfin);
                nuevo = false;//Esta variable se usa para definir otra vez un nuevo intervalo
            }
            if (d1.compareTo(dini) == 0) { //Fechas Iguales
                aux = L2.substring(L2.indexOf("\t") + 1);
                aux = aux.substring(0, aux.indexOf(" "));
                media1 = media1 + Float.parseFloat(aux);
                nelem1++;
            } else if (d1.compareTo(dini) > 0 && d1.compareTo(dfin) < 0) { //Est dentro del intervalo
                aux = L2.substring(L2.indexOf("\t") + 1);
                aux = aux.substring(0, aux.indexOf(" "));
                media1 = media1 + Float.parseFloat(aux);
                nelem1++;
            } else {//Si la fecha es menor que la fecha inicial o mayor que la final, se cambia de intervalo.
                nuevo = true;
            }
            lant = L2;
        }
        //guardo lo ultimo si lo hay
        fecha = lant.substring(0, lant.indexOf("\t"));
        if (!fecha.isEmpty()) {
            String auxr = lant.substring(lant.indexOf("\t") + 1);
            auxr = auxr.substring(0, auxr.indexOf(" "));
            media1 = Float.parseFloat(auxr);
            BufferedWriter bw2 = new BufferedWriter(new FileWriter(ruta + "temp2.txt", true)); //Para escribir.
            x1 = "" + media1;
            if (!x1.contentEquals("NaN"))
                bw2.write("" + /*fechas.elementAt(pos+1)+"\t"+*/media1 + " " + unidad + "\n");
            bw2.close();
        }
        fr2.close();
        //CREAMOS EL UNIFICADO
        File unificado = new File(ruta + "unificado.txt");
        if (!unificado.exists())
            unificado.createNewFile(); //Crea el fichero
        fr1 = new FileReader(temp);
        linea1 = new BufferedReader(fr1);
        fr2 = new FileReader(temp2);
        linea2 = new BufferedReader(fr2);
        L1 = L2 = "";
        BufferedWriter bwf = new BufferedWriter(new FileWriter(ruta + "unificado.txt", true)); //Para escribir.
        while ((L1 = linea1.readLine()) != null && (L2 = linea2.readLine()) != null) {
            bwf.write(L1 + "\t" + L2 + "\n");
        }
        bwf.close();
        fechas.removeAllElements();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (null != fr1)
                fr1.close(); //cierra el 1 fichero.
            if (null != fr2)
                fr2.close(); //cierra el 2 fichero.
        } catch (Exception e2) { //Sino salta una excepcion.
            e2.printStackTrace();
        }
    }
    File temp1 = new File(ruta + "temp.txt");
    File temp2 = new File(ruta + "temp2.txt");
    temp1.delete();
    temp2.delete();
}

From source file:org.gvnix.service.roo.addon.addon.ws.WSConfigServiceImpl.java

/**
 * Updates web services configuration file.
 * //from w  ww.  j a  va 2  s . c om
 * @param className to export.
 * @param annotationMetadata values from web service class to set in
 *        configuration file.
 * @return true if annotation from className has to be updated because of
 *         changes in package or class name.
 */
private boolean updateConfiguration(JavaType className, AnnotationMetadata annotationMetadata) {

    StringAttributeValue serviceName = (StringAttributeValue) annotationMetadata
            .getAttribute(new JavaSymbolName("serviceName"));

    Validate.isTrue(serviceName != null && StringUtils.isNotBlank(serviceName.getValue()),
            "Annotation attribute 'serviceName' in " + className.getFullyQualifiedTypeName() + MUST_BE_DEFINED);

    StringAttributeValue address = (StringAttributeValue) annotationMetadata
            .getAttribute(new JavaSymbolName(ADDRESS2));

    Validate.isTrue(address != null && StringUtils.isNotBlank(address.getValue()),
            "Annotation attribute 'address' in " + className.getFullyQualifiedTypeName() + MUST_BE_DEFINED);

    StringAttributeValue fullyQualifiedTypeName = (StringAttributeValue) annotationMetadata
            .getAttribute(new JavaSymbolName("fullyQualifiedTypeName"));

    Validate.notNull(fullyQualifiedTypeName, "Annotation attribute 'fullyQualifiedTypeName' in "
            + className.getFullyQualifiedTypeName() + MUST_BE_DEFINED);
    Validate.isTrue(fullyQualifiedTypeName != null && StringUtils.isNotBlank(fullyQualifiedTypeName.getValue()),
            "Annotation attribute 'fullyQualifiedTypeName' in " + className.getFullyQualifiedTypeName()
                    + MUST_BE_DEFINED);

    BooleanAttributeValue exported = (BooleanAttributeValue) annotationMetadata
            .getAttribute(new JavaSymbolName("exported"));

    Validate.isTrue(exported != null,
            "Annotation attribute 'exported' in " + className.getFullyQualifiedTypeName() + MUST_BE_DEFINED);

    String cxfXmlPath = getCxfConfigAbsoluteFilePath();

    boolean updateFullyQualifiedTypeName = false;
    // Check if class name and annotation class name are different.
    if (fullyQualifiedTypeName != null
            && !className.getFullyQualifiedTypeName().contentEquals(fullyQualifiedTypeName.getValue())) {
        updateFullyQualifiedTypeName = true;
    }

    if (getFileManager().exists(cxfXmlPath)) {

        MutableFile cxfXmlMutableFile = getFileManager().updateFile(cxfXmlPath);
        Document cxfXml = getInputDocument(cxfXmlMutableFile.getInputStream());

        Element root = cxfXml.getDocumentElement();

        // Check if service exists in configuration file.
        boolean updateService = true;

        // 1) Check if class and id exists in bean.
        Element classAndIdService = XmlUtils
                .findFirstElement("/beans/bean[@id='" + serviceName.getValue().concat(IMPL) + "' and @class='"
                        + className.getFullyQualifiedTypeName() + "']", root);

        // Service is already published.
        if (classAndIdService != null) {
            logger.log(Level.FINE,
                    THE_SERVICE + serviceName.getValue() + "' is already set in cxf config file.");
            updateService = false;
        }

        if (updateService) {

            // 2) Check if class exists or it hasn't changed.
            Element classService = null;

            if (updateFullyQualifiedTypeName) {

                // Check if exists with class name.
                classService = XmlUtils.findFirstElement(
                        "/beans/bean[@class='" + className.getFullyQualifiedTypeName() + "']", root);

                if (classService != null) {

                    // Update bean with new Id attribute.
                    Element updateClassService = classService;
                    String idValue = classService.getAttribute("id");

                    if (!StringUtils.isNotBlank(idValue)
                            || !idValue.contentEquals(serviceName.getValue().concat(IMPL))) {
                        updateClassService.setAttribute("id", serviceName.getValue().concat(IMPL));

                        classService.getParentNode().replaceChild(updateClassService, classService);
                        logger.log(Level.INFO, THE_SERVICE + serviceName.getValue() + HAS_UPDATED);
                    }

                } else {

                    // Check if exists with fullyQualifiedTypeName.
                    classService = XmlUtils.findFirstElement(
                            "/beans/bean[@class='" + fullyQualifiedTypeName.getValue() + "']", root);

                    if (classService != null) {

                        Element updateClassService = classService;
                        String idValue = classService.getAttribute("id");

                        updateClassService.setAttribute(CLASS, className.getFullyQualifiedTypeName());

                        if (!StringUtils.isNotBlank(idValue)
                                || !idValue.contentEquals(serviceName.getValue().concat(IMPL))) {
                            updateClassService.setAttribute("id", serviceName.getValue().concat(IMPL));

                            logger.log(Level.INFO, THE_SERVICE + serviceName.getValue() + HAS_UPDATED);
                        }

                        classService.getParentNode().replaceChild(updateClassService, classService);
                        logger.log(Level.INFO, THE_SERVICE + serviceName.getValue()
                                + "' has updated 'class' attribute in cxf config file.");
                    }

                }
            } else {

                // Check if exists with class name.
                classService = XmlUtils.findFirstElement(
                        "/beans/bean[@class='" + className.getFullyQualifiedTypeName() + "']", root);

                if (classService != null) {

                    // Update bean with new Id attribute.
                    Element updateClassService = classService;
                    String idValue = classService.getAttribute("id");

                    if (!StringUtils.isNotBlank(idValue)
                            || !idValue.contentEquals(serviceName.getValue().concat(IMPL))) {
                        updateClassService.setAttribute("id", serviceName.getValue().concat(IMPL));

                        classService.getParentNode().replaceChild(updateClassService, classService);
                        logger.log(Level.INFO, THE_SERVICE + serviceName.getValue() + HAS_UPDATED);
                    }
                }
            }

            // 3) Check if id exists.
            Element idService = XmlUtils
                    .findFirstElement("/beans/bean[@id='" + serviceName.getValue().concat(IMPL) + "']", root);

            if (idService != null) {

                // Update bean with new class attribute.
                Element updateIdService = idService;
                String classNameAttribute = idService.getAttribute(CLASS);

                if (!StringUtils.isNotBlank(classNameAttribute)
                        || !classNameAttribute.contentEquals(className.getFullyQualifiedTypeName())) {
                    updateIdService.setAttribute(CLASS, className.getFullyQualifiedTypeName());
                    idService.getParentNode().replaceChild(updateIdService, idService);
                    logger.log(Level.INFO, THE_SERVICE + serviceName.getValue()
                            + "' has updated 'class' attribute in cxf config file.");
                }

            }

            Element bean;
            // Check id and class values to create a new bean.
            if (classService == null && idService == null) {

                bean = cxfXml.createElement("bean");
                bean.setAttribute("id", serviceName.getValue().concat(IMPL));
                bean.setAttribute(CLASS, className.getFullyQualifiedTypeName());

                root.appendChild(bean);
            }
        }

        boolean updateEndpoint = true;

        // Check if endpoint exists in the configuration file.
        Element jaxwsBean = XmlUtils.findFirstElement("/beans/endpoint[@address='/" + address.getValue()
                + "' and @id='" + serviceName.getValue() + "']", root);

        // 1) Check if exists with id and address.
        if (jaxwsBean != null) {

            logger.log(Level.FINE,
                    "The endpoint '" + serviceName.getValue() + "' is already set in cxf config file.");
            updateEndpoint = false;
        }

        if (updateEndpoint) {

            // 2) Check if exists a bean with annotation address value and
            // updates id attribute with annotation serviceName value.
            Element addressEndpoint = XmlUtils
                    .findFirstElement("/beans/endpoint[@address='/" + address.getValue() + "']", root);

            if (addressEndpoint != null) {

                // Update bean with new Id attribute.
                Element updateAddressEndpoint = addressEndpoint;
                String idAttribute = addressEndpoint.getAttribute("id");

                if (!StringUtils.isNotBlank(idAttribute)
                        || !idAttribute.contentEquals(serviceName.getValue())) {

                    updateAddressEndpoint.setAttribute("id", serviceName.getValue());
                    updateAddressEndpoint.setAttribute("implementor",
                            "#".concat(serviceName.getValue()).concat(IMPL));

                    addressEndpoint.getParentNode().replaceChild(updateAddressEndpoint, addressEndpoint);
                    logger.log(Level.INFO, "The endpoint bean '" + serviceName.getValue() + HAS_UPDATED);

                }

            }

            Element idEndpoint = XmlUtils
                    .findFirstElement("/beans/endpoint[@id='" + serviceName.getValue() + "']", root);

            // 3) Check if exists a bean with annotation address value in id
            // attribute and updates address attribute with annotation
            // address
            // value.
            if (idEndpoint != null) {

                // Update bean with new Id attribute.
                Element updateIdEndpoint = idEndpoint;

                String addressAttribute = idEndpoint.getAttribute(ADDRESS2);

                if (!StringUtils.isNotBlank(addressAttribute)
                        || !addressAttribute.contentEquals("/".concat(address.getValue()))) {

                    updateIdEndpoint.setAttribute(ADDRESS2, "/".concat(address.getValue()));

                    idEndpoint.getParentNode().replaceChild(updateIdEndpoint, idEndpoint);
                    logger.log(Level.INFO, "The endpoint bean '" + serviceName.getValue()
                            + "' has updated 'address' attribute in cxf config file.");

                }

            }

            Element endpoint;
            // Check values to create new endpoint bean.
            if (addressEndpoint == null && idEndpoint == null) {

                endpoint = cxfXml.createElement("jaxws:endpoint");
                endpoint.setAttribute("id", serviceName.getValue());
                endpoint.setAttribute("implementor", "#".concat(serviceName.getValue()).concat(IMPL));
                endpoint.setAttribute(ADDRESS2, "/".concat(address.getValue()));
                root.appendChild(endpoint);
            }

        }

        // Update configuration file.
        if (updateService || updateEndpoint) {
            XmlUtils.writeXml(cxfXmlMutableFile.getOutputStream(), cxfXml);
        }

    }

    return updateFullyQualifiedTypeName;
}

From source file:com.mobshep.mobileshepherd.CSInjection1.java

public void onClick(View arg0) {
    switch (arg0.getId()) {

    case (R.id.bLogin):

        String unsanitizeName = username.getText().toString();
        String unsanitizePass = password.getText().toString();

        String sanitizeName = unsanitizeName.replace("OR", " ");
        sanitizeName = sanitizeName.replace("or", " ");
        sanitizeName = sanitizeName.replace("SELECT", " ");
        sanitizeName = sanitizeName.replace("AND", " ");
        sanitizeName = sanitizeName.replace("UPDATE", " ");
        sanitizeName = sanitizeName.replace("DROP", " ");
        sanitizeName = sanitizeName.replace("1=1", " ");
        sanitizeName = sanitizeName.replace("1 = 1", " ");

        String sanitizePass = unsanitizePass.replace("OR", "  ");
        sanitizePass = sanitizePass.replace("or", "  ");
        sanitizePass = sanitizePass.replace("SELECT", "  ");
        sanitizePass = sanitizePass.replace("AND", "  ");
        sanitizePass = sanitizePass.replace("UPDATE", "  ");
        sanitizePass = sanitizePass.replace("DROP", "  ");
        sanitizePass = sanitizePass.replace("1=1", "  ");
        sanitizePass = sanitizePass.replace("1 = 1", "  ");

        try {/*from   w w  w.j  a v  a 2  s  .  com*/
            if (login(sanitizeName, sanitizePass) == true) {
                outputKey(this, dbPassword);
                Toast loggedin = Toast.makeText(CSInjection1.this, "Logged in!", Toast.LENGTH_LONG);
                loggedin.show();

            }
        } catch (IOException e1) {
            Toast error = Toast.makeText(CSInjection1.this, "An error occurred!", Toast.LENGTH_LONG);
            error.show();
        }

        try {
            if (login(sanitizeName, sanitizePass) == false) {
                Toast invalid = Toast.makeText(CSInjection1.this, "Invalid Credentials, " + sanitizeName,
                        Toast.LENGTH_LONG);
                invalid.show();

            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if (sanitizeName.contentEquals("") || sanitizePass.contentEquals("")) {
            Toast blank = Toast.makeText(CSInjection1.this, "Empty Fields Detected.", Toast.LENGTH_SHORT);
            blank.show();

        }

    }

}

From source file:org.bonitasoft.engine.activity.CallActivityIT.java

private void executeCallAtivityUntilEndOfProcess(final boolean addInputOperations,
        final boolean addOutputOperations, final String strTargetVersion, final boolean terminateEnd)
        throws Exception {
    final ProcessDefinition targetProcessDef1 = getSimpleProcess(ACTOR_NAME, "targetProcess", PROCESS_VERSION,
            terminateEnd);/*from   w  w  w . j av  a 2  s. c o  m*/
    final ProcessDefinition targetProcessDef3 = getSimpleProcess(ACTOR_NAME, "targetProcess", "3.0",
            terminateEnd);
    final ProcessDefinition targetProcessDef2 = getSimpleProcess(ACTOR_NAME, "targetProcess", "2.0",
            terminateEnd);

    final ProcessDefinition callingProcessDef = buildProcessWithCallActivity(addInputOperations,
            addOutputOperations, "callingProcess", "targetProcess", 0, strTargetVersion);

    assertThat(getProcessAPI().getNumberOfProcessInstances()).isEqualTo(0L);

    final List<Operation> operations = getStartOperations();
    final ProcessInstance callingProcessInstance = getProcessAPI().startProcess(callingProcessDef.getId(),
            operations, null);

    if (strTargetVersion != null && strTargetVersion.contentEquals("4.0")) {
        checkNbOfProcessInstances(2, ProcessInstanceCriterion.NAME_DESC);
        final List<ProcessInstance> processInstances = getProcessAPI().getProcessInstances(0, 10,
                ProcessInstanceCriterion.NAME_DESC);
        assertThat(processInstances).hasSize(1);

        waitForFlowNodeInFailedState(callingProcessInstance, "callActivity");
        return;
    }

    checkNbOfProcessInstances(2, ProcessInstanceCriterion.NAME_DESC);
    final List<ProcessInstance> processInstances = getProcessAPI().getProcessInstances(0, 10,
            ProcessInstanceCriterion.NAME_DESC);
    assertThat(processInstances).hasSize(2); // two instances are expected calling and target processes
    final ProcessInstance targetPI = processInstances.get(0);

    // System.out.println("Version of the definition of targetProcess : "
    // + getProcessAPI().getProcessDefinition(targetPI.getProcessDefinitionId()).getVersion());

    if (strTargetVersion == null || strTargetVersion.contentEquals("2.0")) {
        assertThat(targetPI.getProcessDefinitionId()).isEqualTo(targetProcessDef2.getId());
    } else if (strTargetVersion.contentEquals(PROCESS_VERSION)) {
        assertThat(targetPI.getProcessDefinitionId()).isEqualTo(targetProcessDef1.getId());
    }

    final FlowNodeInstance callActivityInstance = waitForFlowNodeInExecutingState(callingProcessInstance,
            "callActivity", true);
    assertThat(targetPI.getRootProcessInstanceId()).isEqualTo(callingProcessInstance.getId());
    assertThat(targetPI.getCallerId()).isEqualTo(callActivityInstance.getId());

    ActivityInstance activityInstance = waitForUserTaskAndGetIt(callingProcessInstance, "tStep1");
    assertThat(activityInstance.getParentProcessInstanceId()).isEqualTo(targetPI.getId());
    assertThat(activityInstance.getRootContainerId()).isEqualTo(callingProcessInstance.getId());
    checkDataInputOperations(addInputOperations, targetPI);

    // execute step in the target process
    assignAndExecuteStep(activityInstance, cebolinha.getId());

    activityInstance = waitForUserTaskAndGetIt(callingProcessInstance, "step1");
    checkOutputOperations(addOutputOperations, callingProcessInstance);
    waitForProcessToFinish(targetPI);
    assertThat(activityInstance.getParentProcessInstanceId()).isEqualTo(callingProcessInstance.getId());

    assignAndExecuteStep(activityInstance, cascao.getId());

    waitForProcessToFinish(callingProcessInstance);

    disableAndDeleteProcess(callingProcessDef, targetProcessDef1, targetProcessDef2, targetProcessDef3);
}

From source file:org.openmrs.module.sdmxhddataexport.web.controller.report.ReportDataElementController.java

@RequestMapping(value = "/module/sdmxhddataexport/downloadExecutedReport.form", method = RequestMethod.GET)
public String downloadExecutedReport(@RequestParam(value = "reportId", required = false) Integer reportId,
        @RequestParam(value = "startDate", required = false) String startDate,
        @RequestParam(value = "endDate", required = false) String endDate,
        @RequestParam(value = "outputType", required = false) String outputType, HttpServletRequest request,
        HttpServletResponse response, Model model) throws ParseException, IOException {
    String u = request.getParameter("url");
    System.out.print("i think it is a url - " + u);
    //String s=(u.split("/")[2]).split(":")[0];
    String urlToRead = "http://" + u + request.getContextPath()
            + "/module/sdmxhddataexport/resultExecuteReport.form?reportId=" + reportId + "&startDate="
            + startDate + "&endDate=" + endDate;
    //       String urlToRead = "http://" + "127.0.0.1" + ":"
    //        + request.getLocalPort() + request.getContextPath()
    //        + "/module/sdmxhddataexport/resultExecuteReport.form?reportId="
    //        + reportId + "&startDate=" + startDate + "&endDate=" + endDate;
    URL url;/*from w w w. j  a  v a  2  s  . c  o m*/

    System.out.println("http servlet request" + u + request.getLocalAddr() + "," + request.getLocalName());
    HttpURLConnection conn;
    InputStream rd = null;
    String contents = "";
    try {
        url = new URL(urlToRead);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        rd = conn.getInputStream();
        byte[] bytes = new byte[1024];
        int bytesRead;
        boolean firstRead = true;

        while ((bytesRead = rd.read(bytes)) != -1) {
            String str = new String(bytes);
            str = str.substring(0, bytesRead);
            //if(firstRead){
            firstRead = false;
            str = str.replaceAll("^\\s+", "");
            System.out.print(str);
            //}
            contents = contents.concat(str);

        }
        //rd.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (outputType.contentEquals("download")) {
        //           File fil1=new File("/sdmx-temp-sdmx.xml");
        //           FileOutputStream fos = new FileOutputStream("sdmx-temp-sdmx.xml");
        File file = File.createTempFile("sdmx", "report");
        Writer output = new BufferedWriter(new FileWriter(file));
        output.write(contents);
        output.flush();
        //           output = new BufferedWriter(new FileWriter(fil1));
        //           output.write(contents);
        //           output.flush();

        output.close();
        System.out.println("these are contents ------------------------");
        System.out.println(contents);
        System.out.println("these wre contents ------------------------");
        response.setContentType("application/download");
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
        response.setHeader("Content-Disposition",
                "attachment; filename=\"" + "sdmxhd-" + formatter.format(new Date()) + ".xml" + "\"");
        FileCopyUtils.copy(new FileInputStream(file), response.getOutputStream());
        file.delete();

    }

    if (outputType.equals("view")) {
        try {
            contents = transform(contents);
        } catch (Exception e) {
            System.out.println("some error" + contents);
            e.printStackTrace();
        }
        model.addAttribute("contents", contents);
        System.out.println("Now contents---------------------------" + contents + ":");
        return "/module/sdmxhddataexport/report/resultView";
    } else if (outputType.equals("send")) {
        HttpSession httpSession = request.getSession();

        String urlStr = Context.getAdministrationService().getGlobalProperty("sdmxhddataexport.reportUrl");
        String[] paramName = { "report1" };
        String[] paramVal = new String[10];
        paramVal[0] = contents;
        try {
            String Response = HttpRestUtil.httpRestPost(urlStr, paramName, paramVal);
            System.out.println("Response:" + Response);
            String temp = "Report Sent Successfully";
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                    StringUtils.isBlank(temp) ? "sdmxhddataexport.dataElement.deleted" : temp);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return "/module/sdmxhddataexport/report/list";
}