text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package userInterface;

import java.awt.Color;
import java.awt.Image;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

import applicationLogic.Address;
import applicationLogic.ContactPerson;
import applicationLogic.ContactPersonHistory;
import applicationLogic.DonationBox;
import applicationLogic.DonationCollection;
import applicationLogic.FixedDonationCollection;
import applicationLogic.OrgaCollectionHistory;
import applicationLogic.OrganisationPerson;
import applicationLogic.PersonHistory;
import applicationLogic.StreetDonationCollection;
import applicationLogicAccess.Access;
import applicationLogicAccess.CollectionAccess;
import applicationLogicAccess.InvalidArgumentsException;
import applicationLogicAccess.PersonHistoryAccess;

/**
 *
 * @author Marcel
 */
public class EditCollection extends javax.swing.JDialog {
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	StringBuilder errorMessage = new StringBuilder();
	ArrayList<DonationBox> selectBoxes = new ArrayList();
	DefaultTableModel boxModel;
        int collId;

        /**
         * Initializes the Window
         *
         * @param parent the parent
         * @param modal determines if the window should be modal or not
         * @param collId the ID of the collection we want to edit
         */
	public EditCollection(java.awt.Frame parent, boolean modal, int collId) {
            super(parent, modal);
            this.collId = collId;
            initComponents();
            jTable1.getTableHeader().setReorderingAllowed(false);

        // Define icons
        ImageIcon imgLupe = new ImageIcon("images/imgLupe.png");
        ImageIcon imgAuge = new ImageIcon("images/imgAuge.png");
        ImageIcon imgPerson = new ImageIcon("images/imgPerson.png");
        ImageIcon imgPlus = new ImageIcon("images/imgPlus.png");
        ImageIcon imgBearbeiten = new ImageIcon("images/imgBearbeiten.png");
        ImageIcon imgPfeil = new ImageIcon("images/imgPfeil.png");
        ImageIcon imgKreuz = new ImageIcon("images/imgKreuz.png");
        ImageIcon imgDocument = new ImageIcon("images/imgDocument.png");
        ImageIcon imgGeld = new ImageIcon("images/imgGeld.png");
        ImageIcon imgMinus = new ImageIcon("images/imgMinus.png");
        //added by sz
      	Image imgIcon = new ImageIcon("images/icon.png").getImage();
      	setIconImage(imgIcon);
      	//
		btnSammlungErstellen.setIcon(imgPlus);
		btnAddBoxToList.setIcon(imgPlus);
		jButton5.setIcon(imgKreuz);
		jButton1.setIcon(imgPerson);
		jButton6.setIcon(imgPerson);
		jButton3.setIcon(imgMinus);

		this.setLocationRelativeTo(null);
		rdbStrassensammlung.setEnabled(false);
		rdbFesteSammlung.setEnabled(false);

		jTable1.setModel(new javax.swing.table.DefaultTableModel(
				new Object[][] {}, new String[] { "ID", "Kommentar" }));

		DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
		ArrayList<DonationBox> dbx = CollectionAccess
				.searchDonationCollectionById(collId)
				.getDonationboxes();
		ArrayList<DonationBox> currentBoxesArray = new ArrayList<DonationBox>();

		for (int i = 0; dbx.size() > i; i++) {
			int idtoAdd = (dbx.get(i).getBoxId());
			model.addRow(new Object[] { idtoAdd, dbx.get(i).getComment() });

			currentBoxesArray.add(dbx.get(i));
		}

		jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(
				new String[] { "0 Bitte auswählen" }));

		DonationCollection myCol = CollectionAccess
				.searchDonationCollectionById(collId);

			// Set input forms enabled/disabled for each instance of
		if (myCol instanceof StreetDonationCollection) {
			boolean state = false;
			jTextField5.setEnabled(state);
			jTextField4.setEnabled(state);
			jTextField3.setEnabled(state);
			jTextField2.setEnabled(state);
			jLabel11.setEnabled(state);
			jLabel12.setEnabled(state);
			jLabel13.setEnabled(state);
			jLabel14.setEnabled(state);
			jLabel9.setEnabled(state);
			jComboBox1.setEnabled(state);
			jButton1.setEnabled(state);
			jLabel1.setEnabled(state);
			jLabel6.setEnabled(state);
			jComboBox1.setEnabled(state);
			jButton1.setEnabled(state);
			jLabel1.setEnabled(state);
		}

		if (myCol instanceof FixedDonationCollection) {
			rdbFesteSammlung.setSelected(true);
			jTextField1.setText(((FixedDonationCollection) myCol).getComment());
			jTextField2.setText(((FixedDonationCollection) myCol)
					.getFixedAddress().getStreetName());
			jTextField3.setText(String
					.valueOf(((FixedDonationCollection) myCol)
							.getFixedAddress().getHauseNumber()));

			jTextField4.setText(String
					.valueOf(((FixedDonationCollection) myCol)
							.getFixedAddress().getZip()));
			jTextField5.setText(((FixedDonationCollection) myCol)
					.getFixedAddress().getLocationName());

		}
		if (myCol instanceof StreetDonationCollection) {
			rdbStrassensammlung.setSelected(true);
			jTextField1.setText(((StreetDonationCollection) myCol).getComment());
		}

		jXDatePicker1.setDate(myCol.getBeginPeriode().getTime());

		try {
			jXDatePicker2.setDate(myCol.getEndPeriode().getTime());
		} catch (NullPointerException e) {

		}
		ArrayList<DonationBox> donbox = Access.getAvailableDonationBoxes();
		// Filter donbox deleted, inbox

		for (int i = 0; i < donbox.size(); i++) {

			cbSelectBoxes.addItem(donbox.get(i).getBoxId() + " "
					+ donbox.get(i).getComment().toString());

		}

		String[] conPersArray = new String[Access.getAllOrganisationPersons()
				.size()];
		int s = 0;

		for (OrganisationPerson currPers : Access.getAllOrganisationPersons()) {
			if(Access.getPersonById(currPers.getPersonId()).getIsActiveMember()){
			String currString2 = "" + currPers.getPersonId() + " "
					+ currPers.getLastName() + ", " + currPers.getForename();
			jComboBox2.addItem(currString2);

			conPersArray[s] = currString2;
			s++;}
		}

		String[] orgPersArray = new String[Access.getAllContactPersons().size()];
		int i = 0;
		for (ContactPerson currPers : Access.getAllContactPersons()) {
			String currString = "" + currPers.getPersonId() + " "
					+ currPers.getLastName() + ", " + currPers.getForename();
			jComboBox1.addItem(currString);

			i++;
		}

		int persId = 0;
		int persIdb = 0;

		// TODO: check if fixed ans dets rdb
		if (myCol instanceof FixedDonationCollection) {
			persId = (((FixedDonationCollection) myCol).getOrganizationPerson()
					.getPersonId()); // get pers ID to compare

			persIdb = (((FixedDonationCollection) myCol).getContactPerson()
					.getPersonId()); // get pers ID to compare
		} else {

			persId = (((StreetDonationCollection) myCol)
					.getOrganizationPerson().getPersonId()); // get pers ID to
																// compare

			persIdb = 0;
		}

		String[] persId1 = new String[jComboBox1.getItemCount()]; // create
																	// array
		int thepos = 0;
		for (int ii = 0; ii < jComboBox1.getItemCount(); ii++) {
			String[] split = jComboBox1.getItemAt(ii).toString().split(" "); // get
																				// ID
																				// from
																				// selected
																				// each

			persId1[ii] = split[0]; // insert id from selected

			if (persIdb == Integer.parseInt(persId1[ii])) {

				thepos = ii;
			}
		}
		jComboBox1.setSelectedIndex(thepos);

		String[] persId2 = new String[jComboBox2.getItemCount()]; // create
																	// array
		int thepos1 = 0;
		for (int ii = 0; ii < jComboBox2.getItemCount(); ii++) {
			String[] split = jComboBox2.getItemAt(ii).toString().split(" "); // get
																				// ID
																				// from
																				// selected
																				// each

			persId2[ii] = split[0]; // insert id from selected

			if (persId == Integer.parseInt(persId2[ii])) {

				thepos1 = ii;
			}
		}
		jComboBox2.setSelectedIndex(thepos1);

	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings({ "unchecked", "static-access", "null" })
	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	// desc="Generated Code">//GEN-BEGIN:initComponents
	private void initComponents() {
		btnAddBoxToList = new javax.swing.JButton();
		CollectionTypeRadioGrp = new javax.swing.ButtonGroup();
		jLabel10 = new javax.swing.JLabel();
		jLabel1 = new javax.swing.JLabel();
		jComboBox1 = new javax.swing.JComboBox();
		jButton1 = new javax.swing.JButton();
		jXDatePicker1 = new org.jdesktop.swingx.JXDatePicker();
		jXDatePicker2 = new org.jdesktop.swingx.JXDatePicker();
		jLabel2 = new javax.swing.JLabel();
		jLabel3 = new javax.swing.JLabel();
		jLabel4 = new javax.swing.JLabel();
		jTextField1 = new javax.swing.JTextField();
		jLabel5 = new javax.swing.JLabel();
		jLabel6 = new javax.swing.JLabel();
		rdbStrassensammlung = new javax.swing.JRadioButton();
		rdbFesteSammlung = new javax.swing.JRadioButton();
		jScrollPane1 = new javax.swing.JScrollPane();
		jTable1 = new javax.swing.JTable();
		jLabel7 = new javax.swing.JLabel();
		jButton3 = new javax.swing.JButton();
		btnSammlungErstellen = new javax.swing.JButton();
		jButton5 = new javax.swing.JButton();
		jComboBox2 = new javax.swing.JComboBox();
		jLabel8 = new javax.swing.JLabel();
		jButton6 = new javax.swing.JButton();
		jLabel9 = new javax.swing.JLabel();
		jLabel11 = new javax.swing.JLabel();
		jTextField2 = new javax.swing.JTextField();
		jLabel12 = new javax.swing.JLabel();
		jTextField3 = new javax.swing.JTextField();
		jLabel13 = new javax.swing.JLabel();
		jTextField4 = new javax.swing.JTextField();
		jLabel14 = new javax.swing.JLabel();
		jTextField5 = new javax.swing.JTextField();
		cbSelectBoxes = new javax.swing.JComboBox();

		setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
		setTitle("Sammlung ändern");
		setResizable(false);

		jLabel10.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
		jLabel10.setText("Sammlung ändern");

		jLabel1.setText("Kontaktperson auswählen");

		jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(
				new String[] { "0 Bitte auswählen" }));

		jButton1.setText("Neue Person hinzufügen");
		jButton1.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton1ActionPerformed(evt);
			}
		});

		jXDatePicker1.setName(""); // NOI18N

		jLabel2.setText("Beginn der Sammlung *");

		jLabel3.setText("Ende der Sammlung (optional)");

		jLabel4.setText("Kommentar (optional)");

		jLabel5.setText("Zugehörige Dosen auswählen");

		jLabel6.setText("Art der Sammlung auswählen *");

		CollectionTypeRadioGrp.add(rdbStrassensammlung);
		rdbStrassensammlung.setText("Straßensammlung");
		rdbStrassensammlung
				.addActionListener(new java.awt.event.ActionListener() {
					public void actionPerformed(java.awt.event.ActionEvent evt) {
						rdbStrassensammlungActionPerformed(evt);
					}
				});

		CollectionTypeRadioGrp.add(rdbFesteSammlung);
		rdbFesteSammlung.setText("Festinstallierte Sammlung");
		rdbFesteSammlung.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				rdbFesteSammlungActionPerformed(evt);
			}
		});

		jScrollPane1.setViewportView(jTable1);

		jLabel7.setText("Bisher ausgewählte Dosen");

		jButton3.setText("Markierte Dose aus der Auswahl entfernen");
		jButton3.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				try {
					jButton3ActionPerformed(evt);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

		btnSammlungErstellen.setText("Sammlung ändern");
		btnSammlungErstellen
				.addActionListener(new java.awt.event.ActionListener() {
					public void actionPerformed(java.awt.event.ActionEvent evt) {
						try {
							btnSammlungErstellenActionPerformed(evt);
						} catch (InvalidArgumentsException e) {

							JOptionPane.showMessageDialog(null, e.getMessage(), "Fehler!",
									JOptionPane.ERROR_MESSAGE);
						} catch (ParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (SQLException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});

		jButton5.setText("Abbrechen");
		jButton5.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton5ActionPerformed(evt);
			}
		});

		jLabel8.setText("Verantwortliche Person auswählen *");

		jButton6.setText("Neue Person hinzufügen");
		jButton6.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton6ActionPerformed(evt);
			}
		});

		jLabel9.setText("Adresse der Straßensammlung *");

		jLabel11.setText("Straße");

		jTextField2.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jTextField2ActionPerformed(evt);
			}
		});

		jLabel12.setText("Nr");

		jLabel13.setText("Plz");

		jLabel14.setText("Ort");

		cbSelectBoxes.setModel(new javax.swing.DefaultComboBoxModel(
				new String[] { "---" }));

		btnAddBoxToList.setText("Hinzufügen");
		btnAddBoxToList.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				btnAddBoxToListActionPerformed(evt);
			}
		});

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
				getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addGap(58, 58, 58)
								.addComponent(btnSammlungErstellen)
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.RELATED,
										javax.swing.GroupLayout.DEFAULT_SIZE,
										Short.MAX_VALUE)
								.addComponent(jButton5,
										javax.swing.GroupLayout.PREFERRED_SIZE,
										123,
										javax.swing.GroupLayout.PREFERRED_SIZE)
								.addGap(63, 63, 63))
				.addGroup(
						layout.createSequentialGroup()
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.LEADING)
												.addGroup(
														layout.createSequentialGroup()
																.addGap(212,
																		212,
																		212)
																.addComponent(
																		jLabel10,
																		javax.swing.GroupLayout.PREFERRED_SIZE,
																		144,
																		javax.swing.GroupLayout.PREFERRED_SIZE))
												.addGroup(
														layout.createSequentialGroup()
																.addGap(39, 39,
																		39)
																.addGroup(
																		layout.createParallelGroup(
																				javax.swing.GroupLayout.Alignment.LEADING)
																				.addGroup(
																						layout.createSequentialGroup()
																								.addComponent(
																										jLabel6)
																								.addGap(60,
																										60,
																										60)
																								.addComponent(
																										rdbStrassensammlung)
																								.addGap(18,
																										18,
																										18)
																								.addComponent(
																										rdbFesteSammlung))
																				.addGroup(
																						layout.createParallelGroup(
																								javax.swing.GroupLayout.Alignment.LEADING,
																								false)
																								.addGroup(
																										javax.swing.GroupLayout.Alignment.TRAILING,
																										layout.createSequentialGroup()
																												.addComponent(
																														jLabel1)
																												.addPreferredGap(
																														javax.swing.LayoutStyle.ComponentPlacement.RELATED,
																														javax.swing.GroupLayout.DEFAULT_SIZE,
																														Short.MAX_VALUE)
																												.addComponent(
																														jComboBox1,
																														javax.swing.GroupLayout.PREFERRED_SIZE,
																														132,
																														javax.swing.GroupLayout.PREFERRED_SIZE)
																												.addGap(18,
																														18,
																														18)
																												.addComponent(
																														jButton1))
																								.addGroup(
																										layout.createSequentialGroup()
																												.addComponent(
																														jLabel8)
																												.addGap(31,
																														31,
																														31)
																												.addComponent(
																														jComboBox2,
																														javax.swing.GroupLayout.PREFERRED_SIZE,
																														132,
																														javax.swing.GroupLayout.PREFERRED_SIZE)
																												.addGap(18,
																														18,
																														18)
																												.addComponent(
																														jButton6))
																								.addGroup(
																										layout.createSequentialGroup()
																												.addGroup(
																														layout.createParallelGroup(
																																javax.swing.GroupLayout.Alignment.TRAILING)
																																.addComponent(
																																		jLabel11)
																																.addComponent(
																																		jLabel2)
																																.addComponent(
																																		jLabel13))
																												.addGap(28,
																														28,
																														28)
																												.addGroup(
																														layout.createParallelGroup(
																																javax.swing.GroupLayout.Alignment.LEADING)
																																.addGroup(
																																		layout.createSequentialGroup()
																																				.addComponent(
																																						jTextField2,
																																						javax.swing.GroupLayout.PREFERRED_SIZE,
																																						186,
																																						javax.swing.GroupLayout.PREFERRED_SIZE)
																																				.addGap(18,
																																						18,
																																						18)
																																				.addComponent(
																																						jLabel12))
																																.addGroup(
																																		layout.createSequentialGroup()
																																				.addComponent(
																																						jTextField4,
																																						javax.swing.GroupLayout.PREFERRED_SIZE,
																																						109,
																																						javax.swing.GroupLayout.PREFERRED_SIZE)
																																				.addGap(28,
																																						28,
																																						28)
																																				.addComponent(
																																						jLabel14)
																																				.addGap(18,
																																						18,
																																						18)
																																				.addComponent(
																																						jTextField5,
																																						javax.swing.GroupLayout.PREFERRED_SIZE,
																																						190,
																																						javax.swing.GroupLayout.PREFERRED_SIZE))))
																								.addGroup(
																										layout.createSequentialGroup()
																												.addGroup(
																														layout.createParallelGroup(
																																javax.swing.GroupLayout.Alignment.LEADING)
																																.addComponent(
																																		jLabel3)
																																.addComponent(
																																		jLabel4)
																																.addComponent(
																																		jLabel5)
																																.addComponent(
																																		jLabel7))
																												.addGroup(
																														layout.createParallelGroup(
																																javax.swing.GroupLayout.Alignment.TRAILING)
																																.addGroup(
																																		layout.createSequentialGroup()
																																				.addPreferredGap(
																																						javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																																				.addGroup(
																																						layout.createParallelGroup(
																																								javax.swing.GroupLayout.Alignment.LEADING)
																																								.addGroup(
																																										layout.createSequentialGroup()
																																												.addGroup(
																																														layout.createParallelGroup(
																																																javax.swing.GroupLayout.Alignment.TRAILING,
																																																false)
																																																.addComponent(
																																																		jXDatePicker1,
																																																		javax.swing.GroupLayout.Alignment.LEADING,
																																																		javax.swing.GroupLayout.DEFAULT_SIZE,
																																																		javax.swing.GroupLayout.DEFAULT_SIZE,
																																																		Short.MAX_VALUE)
																																																.addComponent(
																																																		jXDatePicker2,
																																																		javax.swing.GroupLayout.PREFERRED_SIZE,
																																																		132,
																																																		javax.swing.GroupLayout.PREFERRED_SIZE))
																																												.addPreferredGap(
																																														javax.swing.LayoutStyle.ComponentPlacement.RELATED,
																																														javax.swing.GroupLayout.DEFAULT_SIZE,
																																														Short.MAX_VALUE)
																																												.addComponent(
																																														jTextField3,
																																														javax.swing.GroupLayout.PREFERRED_SIZE,
																																														140,
																																														javax.swing.GroupLayout.PREFERRED_SIZE))
																																								.addGroup(
																																										javax.swing.GroupLayout.Alignment.TRAILING,
																																										layout.createSequentialGroup()
																																												.addGap(0,
																																														0,
																																														Short.MAX_VALUE)
																																												.addComponent(
																																														jTextField1,
																																														javax.swing.GroupLayout.PREFERRED_SIZE,
																																														299,
																																														javax.swing.GroupLayout.PREFERRED_SIZE))))
																																.addGroup(
																																		javax.swing.GroupLayout.Alignment.LEADING,
																																		layout.createSequentialGroup()
																																				.addGap(36,
																																						36,
																																						36)
																																				.addComponent(
																																						cbSelectBoxes,
																																						javax.swing.GroupLayout.PREFERRED_SIZE,
																																						225,
																																						javax.swing.GroupLayout.PREFERRED_SIZE)
																																				.addPreferredGap(
																																						javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																																				.addComponent(
																																						btnAddBoxToList)
																																				.addGap(0,
																																						0,
																																						Short.MAX_VALUE)))))
																				.addComponent(
																						jLabel9)))
												.addGroup(
														layout.createSequentialGroup()
																.addGap(177,
																		177,
																		177)
																.addComponent(
																		jButton3))
												.addGroup(
														layout.createSequentialGroup()
																.addGap(49, 49,
																		49)
																.addComponent(
																		jScrollPane1,
																		javax.swing.GroupLayout.PREFERRED_SIZE,
																		501,
																		javax.swing.GroupLayout.PREFERRED_SIZE)))
								.addContainerGap(54, Short.MAX_VALUE)));
		layout.setVerticalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addGap(25, 25, 25)
								.addComponent(jLabel10)
								.addGap(18, 18, 18)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.BASELINE)
												.addComponent(jLabel6)
												.addComponent(
														rdbStrassensammlung)
												.addComponent(rdbFesteSammlung))
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.BASELINE)
												.addComponent(jLabel8)
												.addComponent(
														jComboBox2,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.PREFERRED_SIZE)
												.addComponent(jButton6))
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.BASELINE)
												.addComponent(jLabel1)
												.addComponent(
														jComboBox1,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.PREFERRED_SIZE)
												.addComponent(jButton1))
								.addGap(18, 18, 18)
								.addComponent(jLabel9)
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.BASELINE)
												.addComponent(jLabel11)
												.addComponent(
														jTextField2,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.PREFERRED_SIZE)
												.addComponent(jLabel12)
												.addComponent(
														jTextField3,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.PREFERRED_SIZE))
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.RELATED)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.LEADING)
												.addComponent(jLabel13)
												.addGroup(
														layout.createParallelGroup(
																javax.swing.GroupLayout.Alignment.BASELINE)
																.addComponent(
																		jTextField4,
																		javax.swing.GroupLayout.PREFERRED_SIZE,
																		javax.swing.GroupLayout.DEFAULT_SIZE,
																		javax.swing.GroupLayout.PREFERRED_SIZE)
																.addComponent(
																		jLabel14)
																.addComponent(
																		jTextField5,
																		javax.swing.GroupLayout.PREFERRED_SIZE,
																		javax.swing.GroupLayout.DEFAULT_SIZE,
																		javax.swing.GroupLayout.PREFERRED_SIZE)))
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.RELATED,
										23, Short.MAX_VALUE)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.BASELINE)
												.addComponent(jLabel2)
												.addComponent(
														jXDatePicker1,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.PREFERRED_SIZE))
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.BASELINE)
												.addComponent(jLabel3)
												.addComponent(
														jXDatePicker2,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.PREFERRED_SIZE))
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.BASELINE)
												.addComponent(jLabel4)
												.addComponent(
														jTextField1,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.PREFERRED_SIZE))
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.BASELINE)
												.addComponent(jLabel5)
												.addComponent(
														cbSelectBoxes,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.PREFERRED_SIZE)
												.addComponent(btnAddBoxToList))
								.addGap(18, 18, 18)
								.addComponent(jLabel7)
								.addGap(18, 18, 18)
								.addComponent(jScrollPane1,
										javax.swing.GroupLayout.PREFERRED_SIZE,
										127,
										javax.swing.GroupLayout.PREFERRED_SIZE)
								.addGap(18, 18, 18)
								.addComponent(jButton3)
								.addGap(31, 31, 31)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.BASELINE)
												.addComponent(
														btnSammlungErstellen)
												.addComponent(jButton5))
								.addGap(25, 25, 25)));

		pack();
	}//</editor-fold>//GEN-END:initComponents

	/**
	 *
	 * @author Marcel
	 */

	private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
		// TODO add your handling code here:
		AddContactPerson MainFrame = new AddContactPerson(null,
				true);
		MainFrame.setVisible(true);

		for (ContactPerson currPers : Access.getAllContactPersons()) {
			String currString = "" + currPers.getPersonId() + " "
					+ currPers.getLastName() + ", " + currPers.getForename();
			jComboBox1.addItem(currString);

		}
	}

	@SuppressWarnings("unchecked")
	private void jButton3ActionPerformed(java.awt.event.ActionEvent evt)
			throws SQLException, ParseException {//GEN-FIRST:event_jButton1ActionPerformed
		// TODO add your handling code here:
		int selectedRowIndex = jTable1.getSelectedRow();

		int idToDel = Integer.parseInt(jTable1.getValueAt(selectedRowIndex, 0)
				.toString());
		CollectionAccess.deleteBoxFromDonationCollection(idToDel);

		DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
		model.removeRow(selectedRowIndex);
		ArrayList<DonationBox> donbox = Access.getAvailableDonationBoxes();
		// Filter donbox deleted, inbox
		cbSelectBoxes.removeAllItems();

		for (int i = 0; i < donbox.size(); i++) {

			cbSelectBoxes.addItem(donbox.get(i).getBoxId() + " "
					+ donbox.get(i).getComment().toString());
			selectBoxes
					.add(Access.getDonationBoxById(donbox.get(i).getBoxId()));
		}

	}//GEN-LAST:event_jButton1ActionPerformed

	private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
		// TODO add your handling code here:
		dispose();
	}//GEN-LAST:event_jButton1ActionPerformed

	private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
		// TODO add your handling code here:
		AddOrganisationPerson MainFrame = new AddOrganisationPerson(null,
				true);
		MainFrame.setVisible(true);
		for (OrganisationPerson currPers : Access.getAllOrganisationPersons()) {
			String currString2 = "" + currPers.getPersonId() + " "
					+ currPers.getLastName() + ", " + currPers.getForename();
			jComboBox2.addItem(currString2);

		}
	}//GEN-LAST:event_jButton6ActionPerformed

	private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField2ActionPerformed
		// TODO add your handling code here:
	}//GEN-LAST:event_jTextField2ActionPerformed

	private void rdbFesteSammlungActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdbFesteSammlungActionPerformed
		// TODO add your handling code here:
		boolean state = true;
		jTextField5.setEnabled(state);
		jTextField4.setEnabled(state);
		jTextField3.setEnabled(state);
		jTextField2.setEnabled(state);
		jLabel11.setEnabled(state);
		jLabel12.setEnabled(state);
		jLabel13.setEnabled(state);
		jLabel14.setEnabled(state);
		jLabel9.setEnabled(state);
		jComboBox1.setEnabled(state);
		jButton1.setEnabled(state);
		jLabel1.setEnabled(state);
	}//GEN-LAST:event_rdbFesteSammlungActionPerformed

	private void rdbStrassensammlungActionPerformed(
			java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdbStrassensammlungActionPerformed
		// TODO add your handling code here:
		boolean state = false;
		jTextField5.setEnabled(state);
		jTextField4.setEnabled(state);
		jTextField3.setEnabled(state);
		jTextField2.setEnabled(state);
		jLabel11.setEnabled(state);
		jLabel12.setEnabled(state);
		jLabel13.setEnabled(state);
		jLabel14.setEnabled(state);
		jLabel9.setEnabled(state);
		jComboBox1.setEnabled(state);
		jButton1.setEnabled(state);
		jLabel1.setEnabled(state);

	}//GEN-LAST:event_rdbStrassensammlungActionPerformed

	private void btnAddBoxToListActionPerformed(java.awt.event.ActionEvent evt) {
		// TODO add your handling code here:

		DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
		ArrayList<DonationBox> donbox = Access.getAvailableDonationBoxes();
		String[] idOfBox = cbSelectBoxes.getSelectedItem().toString()
				.split(" ");
		String[] split1 = cbSelectBoxes.getSelectedItem().toString().split(" "); // liste
		boolean duplicate = false;
		if(split1[0].equals("---")) {

			JOptionPane.showMessageDialog(null,
					"Bitte treffen Sie eine Auswahl");
			duplicate = true;
		}
		else {
		for (int i = 0; model.getRowCount() >= i + 1; i++) {

			if (Integer.parseInt(model.getValueAt(i, 0).toString()) == Integer
					.parseInt(split1[0])) {
				JOptionPane.showMessageDialog(null,
						"Die Box ist bereits in der Liste");
				duplicate = true;

			}
		}}

		if (duplicate == false) {

			model.addRow(new Object[] { split1[0], split1[1] });

			cbSelectBoxes.removeAllItems();

			for (int n = 0; n < donbox.size(); n++) {
				cbSelectBoxes.addItem(donbox.get(n).getBoxId() + " "
						+ donbox.get(n).getComment().toString());

			}

		}

	}

	private void btnSammlungErstellenActionPerformed(
			java.awt.event.ActionEvent evt) throws InvalidArgumentsException,
			ParseException, SQLException {

		if (jComboBox2.getSelectedItem().toString().equals("0 Bitte auswählen")) {
			errorMessage
					.append("Bitte eine verantwortliche Kontaktperson auswählen.\n");
			jComboBox2.setBackground(Color.red);
		}

		if (jTextField2.getText().matches("([a-zA-Z]*[^a-zA-Z][a-zA-Z]*)+")) {
			errorMessage.append("Fehlerhafte Eingabe der Straße.\n");
			jTextField2.setBackground(Color.red);
		} else {
			jTextField2.setBackground(Color.white);
		}

		if (!jTextField3.getText().matches("([0-9]*)+")
				|| jTextField3.getText().length() > 5) {
			errorMessage
					.append("Bitte geben Sie eine gültige Hausnummer in Form 123 ein.\n");
			jTextField3.setBackground(Color.red);
		} else
			jTextField3.setBackground(Color.white);

		if (!jTextField4.getText().matches("([0-9]*)+")
				|| jTextField4.getText().length() > 5) {
			errorMessage.append("Die PLZ muss aus 5 Zahlen bestehen.\n");
			jTextField4.setBackground(Color.red);
		} else
			jTextField4.setBackground(Color.white);

		if (jTextField5.getText().matches("([a-zA-Z]*[^a-zA-Z][a-zA-Z]*)+")) {
			errorMessage.append("Ein Ort besteht nur aus Buchstaben.\n");
			jTextField5.setBackground(Color.red);
		} else
			jTextField5.setBackground(Color.white);

		if (jTextField1.getText().length() > 100) {
			errorMessage.append("Ein Ort besteht nur aus Buchstaben.\n");
			jTextField1.setBackground(Color.red);
		} else
			jTextField1.setBackground(Color.white);

		try {
			if(jXDatePicker1.getDate().getTime()>jXDatePicker2.getDate().getTime()) {
				errorMessage.append("Das Enddatum kann nicht vor Anfang liegen\n");
			}

		} catch (Exception x) {

		}

		String rdbSelected = "none";
		if (rdbFesteSammlung.isSelected()) {
			rdbSelected = "FesteSammlung";
		}
		if (rdbStrassensammlung.isSelected()) {
			rdbSelected = "StrassenSammlung";
		}

		if (errorMessage.length() < 1 && rdbStrassensammlung.isSelected()) {
			// organisationpers combo 2 // contactpers combo 1

			String[] cbox2sel = jComboBox2.getSelectedItem().toString()
					.split(" ");

			DefaultTableModel model = (DefaultTableModel) jTable1.getModel();

			ArrayList<DonationBox> boxesInList = new ArrayList<>();

			for (int i = 0; model.getRowCount() - 1 >= i; i++) {

				boxesInList.add(Access.getDonationBoxById(Integer
						.parseInt(model.getValueAt(i, 0).toString())));

			}

			CollectionAccess.editStreetDonationCollection(collId, boxesInList, jTextField1.getText(), (OrganisationPerson) Access.getPersonById(Integer.parseInt(cbox2sel[0])), jXDatePicker1.getDate(), jXDatePicker2.getDate());

			dispose();

		} else if (errorMessage.length() < 1 && rdbFesteSammlung.isSelected()) {

			DefaultTableModel model = (DefaultTableModel) jTable1.getModel();

			ArrayList<DonationBox> boxesInList = new ArrayList();

			for (int i = 0; model.getRowCount() - 1 >= i; i++) {

				boxesInList.add(Access.getDonationBoxById(Integer
						.parseInt(model.getValueAt(i, 0).toString())));

			}

			String[] cbox2sel = jComboBox2.getSelectedItem().toString()
					.split(" ");
			String[] cbox1sel = jComboBox1.getSelectedItem().toString()
					.split(" ");

			int cboxid1 = Integer.parseInt(cbox1sel[0]);
			int cboxid2 = Integer.parseInt(cbox2sel[0]);

			CollectionAccess.editFixedDonationCollection(collId, boxesInList, jTextField1.getText(), (OrganisationPerson) Access.getPersonById(Integer.parseInt(cbox2sel[0])), jXDatePicker1.getDate(), jXDatePicker2.getDate(), new Address(jTextField2.getText(), jTextField3.getText(), Integer.parseInt(jTextField4.getText()), jTextField5.getText()), (ContactPerson) Access.getPersonById(Integer.parseInt(cbox1sel[0])));

			dispose();

			// Access.
		} else {
			JOptionPane.showMessageDialog(null, errorMessage);
			errorMessage.setLength(0);
		}

	}

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		/* Set the Nimbus look and feel */
		// <editor-fold defaultstate="collapsed" desc="Generated Code">
		// desc=" Look and feel setting code (optional) ">
		/*
		 * If Nimbus (introduced in Java SE 6) is not available, stay with the
		 * default look and feel. For details see
		 * http://download.oracle.com/javase
		 * /tutorial/uiswing/lookandfeel/plaf.html
		 */
		if(Access.getAccessLevelOfProgramm()==1) {

		}
		try {
			for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager
					.getInstalledLookAndFeels()) {
				if ("Nimbus".equals(info.getName())) {
					javax.swing.UIManager.setLookAndFeel(info.getClassName());
					break;
				}
			}
		} catch (ClassNotFoundException ex) {
			java.util.logging.Logger.getLogger(EditCollection.class.getName())
					.log(java.util.logging.Level.SEVERE, null, ex);
		} catch (InstantiationException ex) {
			java.util.logging.Logger.getLogger(EditCollection.class.getName())
					.log(java.util.logging.Level.SEVERE, null, ex);
		} catch (IllegalAccessException ex) {
			java.util.logging.Logger.getLogger(EditCollection.class.getName())
					.log(java.util.logging.Level.SEVERE, null, ex);
		} catch (javax.swing.UnsupportedLookAndFeelException ex) {
			java.util.logging.Logger.getLogger(EditCollection.class.getName())
					.log(java.util.logging.Level.SEVERE, null, ex);
		}
		//</editor-fold>
	}

	// Variables declaration - do not modify//GEN-BEGIN:variables
	private javax.swing.ButtonGroup CollectionTypeRadioGrp;
	private javax.swing.JButton btnSammlungErstellen;
	private javax.swing.JComboBox cbSelectBoxes;
	private javax.swing.JButton jButton1;
	private javax.swing.JButton jButton3;
	private javax.swing.JButton jButton5;
	private javax.swing.JButton jButton6;
	private javax.swing.JComboBox jComboBox1;
	private javax.swing.JComboBox jComboBox2;
	private javax.swing.JLabel jLabel1;
	private javax.swing.JLabel jLabel10;
	private javax.swing.JLabel jLabel11;
	private javax.swing.JLabel jLabel12;
	private javax.swing.JLabel jLabel13;
	private javax.swing.JLabel jLabel14;
	private javax.swing.JLabel jLabel2;
	private javax.swing.JLabel jLabel3;
	private javax.swing.JLabel jLabel4;
	private javax.swing.JLabel jLabel5;
	private javax.swing.JLabel jLabel6;
	private javax.swing.JLabel jLabel7;
	private javax.swing.JLabel jLabel8;
	private javax.swing.JLabel jLabel9;
	private javax.swing.JScrollPane jScrollPane1;
	private javax.swing.JTable jTable1;
	private javax.swing.JTextField jTextField1;
	private javax.swing.JTextField jTextField2;
	private javax.swing.JTextField jTextField3;
	private javax.swing.JTextField jTextField4;
	private javax.swing.JTextField jTextField5;
	private javax.swing.JButton btnAddBoxToList;
	private org.jdesktop.swingx.JXDatePicker jXDatePicker1;
	private org.jdesktop.swingx.JXDatePicker jXDatePicker2;
	private javax.swing.JRadioButton rdbFesteSammlung;
	private javax.swing.JRadioButton rdbStrassensammlung;
	// End of variables declaration//GEN-END:variables
}


text:
/* eslint-env mocha */

import React from 'react'
import ReactDOM from 'react-dom'
import TestUtils from 'react-addons-test-utils'
import assert from 'assert'
import { state, signal, props } from 'cerebral/tags'
import { Controller, compute } from 'cerebral'
import { Container, StateContainer, connect, decorator } from './'

describe('React', () => {
  describe('state container', () => {
    it('should be able to wrap app with container', () => {
      class TestComponent extends React.Component {
        render() {
          return

        }
      }
      const tree = TestUtils.renderIntoDocument(
        <StateContainer>
          <TestComponent />
        </StateContainer>
      )

      assert.ok(TestUtils.findRenderedComponentWithType(tree, TestComponent))
    })
    it('should be able to expose state', () => {
      const model = {
        foo: 'bar',
      }
      const TestComponent = connect(
        {
          foo: state`foo`,
        },
        props => {
          return
{props.foo}

        }
      )
      const tree = TestUtils.renderIntoDocument(
        <StateContainer state={model}>
          <TestComponent />
        </StateContainer>
      )

      assert.equal(
        TestUtils.findRenderedDOMComponentWithTag(tree, 'div').innerHTML,
        'bar'
      )
    })
    it('should be able to expose signals', () => {
      const model = {
        foo: 'bar',
      }
      const signals = {
        test2: [() => {}],
      }
      const TestComponent = connect(
        {
          foo: state`foo`,
          test: signal`test`,
          test2: signal`test2`,
        },
        props => {
          assert.equal(typeof props.test === 'function', true)
          assert.equal(typeof props.test2 === 'object', true)
          return
{props.foo}

        }
      )
      const tree = TestUtils.renderIntoDocument(
        <StateContainer state={model} signals={signals}>
          <TestComponent />
        </StateContainer>
      )

      assert.equal(
        TestUtils.findRenderedDOMComponentWithTag(tree, 'div').innerHTML,
        'bar'
      )
    })
    it('should be able to expose state with connectDecorator', () => {
      const model = {
        foo: 'bar',
      }
      const TestComponent = decorator({
        foo: state`foo`,
      })(props => {
        return
{props.foo}

      })
      const tree = TestUtils.renderIntoDocument(
        <StateContainer state={model}>
          <TestComponent />
        </StateContainer>
      )

      assert.equal(
        TestUtils.findRenderedDOMComponentWithTag(tree, 'div').innerHTML,
        'bar'
      )
    })
  })
  describe('container', () => {
    it('should be able to expose controller', () => {
      const controller = Controller({
        state: {
          foo: 'bar',
        },
      })
      const TestComponent = connect(
        {
          foo: state`foo`,
        },
        props => {
          return
{props.foo}

        }
      )
      const tree = TestUtils.renderIntoDocument(
        <Container controller={controller}>
          <TestComponent />
        </Container>
      )

      assert.equal(
        TestUtils.findRenderedDOMComponentWithTag(tree, 'div').innerHTML,
        'bar'
      )
    })
    it('should throw when no controller provided', () => {
      const TestComponent = connect(
        {
          foo: state`foo`,
        },
        props => {
          return
{props.foo}

        }
      )
      assert.throws(
        () => {
          TestUtils.renderIntoDocument(
            <Container>
              <TestComponent />
            </Container>
          )
        },
        err => {
          if (err instanceof Error) {
            return (
              err.message ===
              'Cerebral - You are not passing controller to Container'
            )
          }
        }
      )
    })
    it('should throw when container component is not provided', () => {
      const TestComponent = connect(
        {
          foo: state`foo`,
        },
        props => {
          return
{props.foo}

        }
      )
      assert.throws(
        () => {
          TestUtils.renderIntoDocument(<TestComponent />)
        },
        err => {
          if (err instanceof Error) {
            return (
              err.message ===
              'Cerebral - Can not find controller, did you remember to use the Container component? Read more at: http://cerebraljs.com/docs/api/components.html#react'
            )
          }
        }
      )
    })
    it('should be able to unregister component from container after unmounting component', () => {
      const controller = Controller({
        devtools: { init() {}, send() {}, updateComponentsMap() {} },
        state: {
          foo: 'bar',
        },
      })
      const TestComponent = connect(
        {
          foo: state`foo`,
        },
        props => {
          return
{props.foo}

        }
      )
      const tree = TestUtils.renderIntoDocument(
        <Container controller={controller}>
          <TestComponent />
        </Container>
      )
      const TestComponentRef = TestUtils.findRenderedComponentWithType(
        tree,
        TestComponent
      )
      assert.equal(TestComponentRef._isUnmounting, undefined)
      assert.equal(
        TestUtils.findRenderedDOMComponentWithTag(tree, 'div').innerHTML,
        'bar'
      )
      ReactDOM.unmountComponentAtNode(
        TestUtils.findRenderedDOMComponentWithTag(tree, 'div').parentNode
      )
      assert.equal(TestComponentRef.view.isUnmounted, true)
      assert.deepEqual(
        controller.componentDependencyStore.getAllUniqueEntities(),
        []
      )
    })
  })
  describe('connect', () => {
    it('should convert component to json', () => {
      const controller = Controller({
        state: {
          foo: 'bar',
        },
      })
      const MyComponent = props => {
        return
{props.foo}

      }
      MyComponent.displayName = 'Test'
      const TestComponent = connect(
        {
          foo: state`foo`,
        },
        MyComponent
      )
      const tree = TestUtils.renderIntoDocument(
        <Container controller={controller}>
          <TestComponent />
        </Container>
      )
      assert.equal(
        TestUtils.findRenderedComponentWithType(tree, TestComponent).toJSON(),
        'Test'
      )
    })
    it('should render only ones where multiple state matches', () => {
      const controller = Controller({
        state: {
          foo: 'bar',
          bar: 'foo',
        },
        signals: {
          test: [
            ({ state }) => {
              state.set('foo', 'bar2')
              state.set('bar', 'foo2')
            },
          ],
        },
      })
      let renderCount = 0
      const TestComponent = connect(
        {
          foo: state`foo`,
          bar: state`bar`,
        },
        props => {
          renderCount++
          return
{props.foo}

        }
      )
      const tree = TestUtils.renderIntoDocument(
        <Container controller={controller}>
          <TestComponent />
        </Container>
      )

      assert.equal(
        TestUtils.findRenderedDOMComponentWithTag(tree, 'div').innerHTML,
        'bar'
      )
      assert.equal(renderCount, 1)
      controller.getSignal('test')()
      assert.equal(renderCount, 2)
    })
    it('should only rerender affected components', () => {
      let renderCount = 0
      const controller = Controller({
        state: {
          foo: 'bar',
        },
        signals: {
          methodCalled: [({ state }) => state.set('foo', 'bar2')],
        },
      })
      class TestComponentClass2 extends React.Component {
        render() {
          renderCount++
          return

        }
      }
      const TestComponent2 = connect({}, TestComponentClass2)
      class TestComponentClass extends React.Component {
        callSignal() {
          this.props.methodCalled()
        }
        render() {
          renderCount++
          return
<TestComponent2 />

        }
      }
      const TestComponent = connect(
        {
          foo: state`foo`,
          methodCalled: signal`methodCalled`,
        },
        TestComponentClass
      )
      const tree = TestUtils.renderIntoDocument(
        <Container controller={controller}>
          <TestComponent />
        </Container>
      )
      const component = TestUtils.findRenderedComponentWithType(
        tree,
        TestComponentClass
      )
      component.callSignal()
      assert.equal(renderCount, 3)
    })
    it('should allow props tag and computed', () => {
      const controller = Controller({
        state: {
          foo: {
            baz: 'mip',
          },
        },
      })
      const TestComponent = connect(
        {
          a: compute(props`foo`),
          b: props`bar.id`,
          c: state`foo.${props`propKey`}`,
        },
        ({ a, b, c }) => {
          return
{a + b + c}

        }
      )
      const tree = TestUtils.renderIntoDocument(
        <Container controller={controller}>
          <TestComponent foo="bar" bar={{ id: '1' }} propKey="baz" />
        </Container>
      )
      assert.equal(
        TestUtils.findRenderedDOMComponentWithTag(tree, 'div').innerHTML,
        'bar1mip'
      )
    })
    it('should update on props change', () => {
      const controller = Controller({})
      class TestComponentClass2 extends React.Component {
        render() {
          return
{this.props.foo}

        }
      }
      const TestComponent2 = connect({}, TestComponentClass2)
      class TestComponentClass extends React.Component {
        constructor(props) {
          super(props)
          this.state = { foo: 'bar' }
        }
        changePath() {
          this.setState({
            foo: 'bar2',
          })
        }
        render() {
          return <TestComponent2 foo={this.state.foo} />
        }
      }
      const TestComponent = connect({}, TestComponentClass)
      const tree = TestUtils.renderIntoDocument(
        <Container controller={controller}>
          <TestComponent />
        </Container>
      )
      assert.equal(
        TestUtils.findRenderedDOMComponentWithTag(tree, 'div').innerHTML,
        'bar'
      )
      const component = TestUtils.findRenderedComponentWithType(
        tree,
        TestComponentClass
      )
      component.changePath()
      assert.equal(
        TestUtils.findRenderedDOMComponentWithTag(tree, 'div').innerHTML,
        'bar2'
      )
    })
  })
})

redpajama_set_name: RedPajamaGithub


text: ./scripts/test.sh --runGlob **/*.integrationTest.js -g integration "$@"


text:
package gov.nih.nci.evs.restapi.util;

import gov.nih.nci.evs.restapi.bean.*;
import java.io.*;
import java.util.*;
import org.json.*;

/**
 * @author EVS Team
 * @version 1.0
 *
 * Modification history:
 *     Initial implementation kim.ong@ngc.com
 *
 */

public class JSONUtils {
	public JSONUtils() {

	}

    public static Vector<String> parseData(String line) {
		if (line == null) return null;
        String tab = "|";
        return parseData(line, tab);
    }

    public static Vector<String> parseData(String line, String tab) {
		if (line == null) return null;
        Vector data_vec = new Vector();
        StringTokenizer st = new StringTokenizer(line, tab);
        while (st.hasMoreTokens()) {
            String value = st.nextToken();
            if (value.compareTo("null") == 0)
                value = "";
            data_vec.add(value);
        }
        return data_vec;
    }

	public Vector findVars(String json) {
		String vars = null;
		Vector v = null;
		Vector u = new Vector();
		try {
			JSONObject obj = new JSONObject(json);
			vars = obj.getJSONObject("head").getString("vars");
			if (vars.startsWith("[")) {
				vars = vars.substring(1, vars.length()-1);
			}
			v = parseData(vars, ",");
			for (int i=0; i<v.size(); i++) {
				String s = (String) v.elementAt(i);
				if (s.startsWith("\"")) {
					s = s.substring(1, s.length()-1);
				}
				u.add(s);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return u;

	}

	public Vector parseJSON(String json) {
		if (json == null) {
			return null;
		}
		Vector u = new Vector();
        Vector vars = findVars(json);
		try {
			JSONObject obj = new JSONObject(json);
			obj = obj.getJSONObject("results");
			JSONArray arr = obj.getJSONArray("bindings");
			for (int i = 0; i < arr.length(); i++) {
				JSONObject o = arr.getJSONObject(i);
				StringBuffer buf = new StringBuffer();
				for (int j=0; j<vars.size(); j++) {
					String s = (String) vars.elementAt(j);
					buf.append(s).append("|");
					try {
						String type = o.getJSONObject(s).getString("type");
						String value = o.getJSONObject(s).getString("value");
						buf.append(type + "|" + value + "$");
						String t = buf.toString();
						t = t.substring(0, t.length()-1);
						u.add(t);
						buf = new StringBuffer();
					} catch (Exception ex) {
                        //ex.printStackTrace();
                        //System.out.println("parseJSON throws exception -- variable:" + s);
					}
			    }
			}
		} catch (Exception ex) {
			//ex.printStackTrace();
			System.out.println("parseJSON throws exception???");
		}
		return u;
	}

	public HashMap line2HashMap(String line) {
		HashMap hmap = new HashMap();
		Vector u = parseData(line, "$");
        for (int i=0; i<u.size(); i++) {
			String t = (String) u.elementAt(i);
			Vector w = JSONUtils.parseData(t, "|");
			String key = (String) w.elementAt(0);
			String type = (String) w.elementAt(1);
			String value = (String) w.elementAt(2);
			TypeAndValue typeAndValue = new TypeAndValue(type, value);
			hmap.put(key, typeAndValue);
		}
		return hmap;
	}

	public void dumpJsonHashMap(HashMap jsonHashMap) {
		Iterator it = jsonHashMap.keySet().iterator();
		while (it.hasNext()) {
			String line = (String) it.next();
			System.out.println(line);
			HashMap hmap = (HashMap) jsonHashMap.get(line);
			Iterator it2 = hmap.keySet().iterator();
			while (it2.hasNext()) {
				String key = (String) it2.next();
				TypeAndValue tv = (TypeAndValue) hmap.get(key);
				System.out.println("\t" + key);
				System.out.println("\t\t" + tv.getType());
				System.out.println("\t\t" + tv.getValue());
			}
		}
	}

	public HashMap json2HashMap(String json) {
		HashMap jsonHashMap = new HashMap();
		Vector v = parseJSON(json);
		for (int k=0; k<v.size(); k++) {
			String line = (String) v.elementAt(k);
			HashMap hmap = new HashMap();
			Vector u = parseData(line, "$");
			for (int i=0; i<u.size(); i++) {
				String t = (String) u.elementAt(i);
				Vector w = JSONUtils.parseData(t, "|");
				String key = (String) w.elementAt(0);
				String type = (String) w.elementAt(1);
				String value = (String) w.elementAt(2);
				TypeAndValue typeAndValue = new TypeAndValue(type, value);
				hmap.put(key, typeAndValue);
			}
			jsonHashMap.put(line, hmap);
		}
		return jsonHashMap;
	}

    public Vector extractValuesFromJSON(String json) {
		Vector vars = findVars(json);
		Vector w = new Vector();
		HashMap jsonHashMap = json2HashMap(json);
		Iterator it = jsonHashMap.keySet().iterator();
		while (it.hasNext()) {
			String line = (String) it.next();
			HashMap hmap = (HashMap) jsonHashMap.get(line);
			Iterator it2 = hmap.keySet().iterator();
			String[] values = new String[vars.size()];
			for (int i=0; i<vars.size(); i++) {
				values[i] = null;
			}
			while (it2.hasNext()) {
				String key = (String) it2.next();
				for (int i=0; i<vars.size(); i++) {
					String var = (String) vars.elementAt(i);
					if (key.compareTo(var) == 0) {
						TypeAndValue tv = (TypeAndValue) hmap.get(key);
						String value = tv.getValue();
						values[i] = value;
						break;
					}
				}
			}
			boolean valid = true;
			StringBuffer buf = new StringBuffer();
			for (int i=0; i<values.length; i++) {
				String value = values[i];
			    if (value == null) {
					valid = false;
					break;
				} else {
					buf.append(value);
					if (i < values.length-1) {
						buf.append("|");
					}
				}
			}
			if (valid) {
				w.add(buf.toString());
			}
		}
		return w;
	}

    public static String beautify(String input) {
        int tabCount = 0;

        StringBuilder inputBuilder = new StringBuilder();
        char[] inputChar = input.toCharArray();

        for (int i = 0; i < inputChar.length; i++) {
            String charI = String.valueOf(inputChar[i]);
            if (charI.equals("}") || charI.equals("]")) {
                tabCount--;
                if (!String.valueOf(inputChar[i - 1]).equals("[") && !String.valueOf(inputChar[i - 1]).equals("{"))
                    inputBuilder.append(newLine(tabCount));
            }
            inputBuilder.append(charI);
            if (charI.equals("{") || charI.equals("[")) {
                tabCount++;
                if (String.valueOf(inputChar[i + 1]).equals("]") || String.valueOf(inputChar[i + 1]).equals("}"))
                    continue;

                inputBuilder.append(newLine(tabCount));
            }

            if (charI.equals(",")) {
                inputBuilder.append(newLine(tabCount));
            }
        }

        return inputBuilder.toString();
    }

    private static String newLine(int tabCount) {
        StringBuilder builder = new StringBuilder();

        builder.append("\n");
        for (int j = 0; j < tabCount; j++)
            builder.append("  ");

        return builder.toString();
    }
}


text:
@interface PodsDummy_Pods_SZNZoteroTestsOSX_SZNZotero : NSObject
@end
@implementation PodsDummy_Pods_SZNZoteroTestsOSX_SZNZotero
@end


text:
<!DOCTYPE html>

	<meta http-equiv="content-type" content="text/html; charset=utf-8" />
	<meta http-equiv="content-language" content="en-US" />
	<meta http-equiv="default-style" content="text/css" />

	<meta name="MSSmartTagsPreventParsing" content="true" />
	<meta name="description" content="" />
	<meta name="keywords" content="" />
	<meta name="author" content="Scott McKee (closer9@gmail.com)" />

	<link rel="shortcut icon" type="image/x-icon" href="<?php echo $root?>images/favicon.ico" />

	<?php
	if (config ('web.css'))
		{
		foreach (config ('web.css') as $script)
			echo "\n\t<link rel=\"stylesheet\" type=\"text/css\" href=\"" . $script . "\">";
		}

	if (config ('web.javascript'))
		{
		foreach (config ('web.javascript') as $script)
			echo "\n\t";
		}
	?>

	<title><?php echo $title?></title>

LIMBO

		<?php
		if (! is_writable (config ('path.storage')))
			{
			echo '
The storage directory is not writable.
';
			}
		?>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mets_ln"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.sdwfqin.sample.view.motionslop.MeTsActivity">

    <com.sdwfqin.sample.view.motionslop.MeTsView
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>


text:
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.

#include <gtk/gtk.h>
#include <stdlib.h>
#include <unistd.h>
#include <string>
#include "cefclient/cefclient.h"
#include "include/cef_app.h"
#include "include/cef_browser.h"
#include "include/cef_frame.h"
#include "include/cef_runnable.h"
#include "cefclient/binding_test.h"
#include "cefclient/client_handler.h"
#include "cefclient/extension_test.h"
#include "cefclient/performance_test.h"
#include "cefclient/scheme_test.h"
#include "cefclient/string_util.h"

char szWorkingDir[512];  // The current working directory

// The global ClientHandler reference.
extern CefRefPtr<ClientHandler> g_handler;

void destroy(void) {
  CefQuitMessageLoop();
}

void TerminationSignalHandler(int signatl) {
  destroy();
}

// Callback for Debug > Get Source... menu item.
gboolean GetSourceActivated(GtkWidget* widget) {
  if (g_handler.get() && g_handler->GetBrowserHwnd())
    RunGetSourceTest(g_handler->GetBrowser());

  return FALSE;  // Don't stop this message.
}

// Callback for Debug > Get Source... menu item.
gboolean GetTextActivated(GtkWidget* widget) {
  if (g_handler.get() && g_handler->GetBrowserHwnd())
    RunGetTextTest(g_handler->GetBrowser());

  return FALSE;  // Don't stop this message.
}

// Callback for Debug > JS Binding... menu item.
gboolean JSBindngActivated(GtkWidget* widget) {
  if (g_handler.get() && g_handler->GetBrowserHwnd())
    RunBindingTest(g_handler->GetBrowser());

  return FALSE;  // Don't stop this message.
}

// Callback for Debug > JS Extension... menu item.
gboolean JSExtensionActivated(GtkWidget* widget) {
  if (g_handler.get() && g_handler->GetBrowserHwnd())
    RunExtensionTest(g_handler->GetBrowser());

  return FALSE;  // Don't stop this message.
}

// Callback for Debug > JS Execute... menu item.
gboolean JSExecuteActivated(GtkWidget* widget) {
  if (g_handler.get() && g_handler->GetBrowserHwnd())
    RunJavaScriptExecuteTest(g_handler->GetBrowser());

  return FALSE;  // Don't stop this message.
}

// Callback for Debug > Performance Tests... menu item.
gboolean PerformanceActivated(GtkWidget* widget) {
  if (g_handler.get() && g_handler->GetBrowserHwnd())
    performance_test::RunTest(g_handler->GetBrowser());

  return FALSE;  // Don't stop this message.
}

// Callback for Debug > Request... menu item.
gboolean RequestActivated(GtkWidget* widget) {
  if (g_handler.get() && g_handler->GetBrowserHwnd())
    RunRequestTest(g_handler->GetBrowser());

  return FALSE;  // Don't stop this message.
}

// Callback for Debug > Local Storage... menu item.
gboolean LocalStorageActivated(GtkWidget* widget) {
  if (g_handler.get() && g_handler->GetBrowserHwnd())
    RunLocalStorageTest(g_handler->GetBrowser());

  return FALSE;  // Don't stop this message.
}

// Callback for Debug > XMLHttpRequest... menu item.
gboolean XMLHttpRequestActivated(GtkWidget* widget) {
  if (g_handler.get() && g_handler->GetBrowserHwnd())
    RunXMLHTTPRequestTest(g_handler->GetBrowser());

  return FALSE;  // Don't stop this message.
}

// Callback for Debug > WebURLRequest... menu item.
gboolean WebURLRequestActivated(GtkWidget* widget) {
  if (g_handler.get() && g_handler->GetBrowserHwnd())
    RunWebURLRequestTest(g_handler->GetBrowser());

  return FALSE;  // Don't stop this message.
}

// Callback for Debug > DOM Access... menu item.
gboolean DOMAccessActivated(GtkWidget* widget) {
  if (g_handler.get() && g_handler->GetBrowserHwnd())
    RunDOMAccessTest(g_handler->GetBrowser());

  return FALSE;  // Don't stop this message.
}

// Callback for Debug > Scheme Handler... menu item.
gboolean SchemeHandlerActivated(GtkWidget* widget) {
  if (g_handler.get() && g_handler->GetBrowserHwnd())
    RunSchemeTest(g_handler->GetBrowser());

  return FALSE;  // Don't stop this message.
}

// Callback for Debug > Popup Window... menu item.
gboolean PopupWindowActivated(GtkWidget* widget) {
  if (g_handler.get() && g_handler->GetBrowserHwnd())
    RunPopupTest(g_handler->GetBrowser());

  return FALSE;  // Don't stop this message.
}

// Callback for Debug > Accelerated 2D Canvas:... menu item.
gboolean Accelerated2DCanvasActivated(GtkWidget* widget) {
  if (g_handler.get() && g_handler->GetBrowserHwnd())
    RunAccelerated2DCanvasTest(g_handler->GetBrowser());

  return FALSE;  // Don't stop this message.
}

// Callback for Debug > Accelerated Layers:... menu item.
gboolean AcceleratedLayersActivated(GtkWidget* widget) {
  if (g_handler.get() && g_handler->GetBrowserHwnd())
    RunAcceleratedLayersTest(g_handler->GetBrowser());

  return FALSE;  // Don't stop this message.
}

// Callback for Debug > WebGL:... menu item.
gboolean WebGLActivated(GtkWidget* widget) {
  if (g_handler.get() && g_handler->GetBrowserHwnd())
    RunWebGLTest(g_handler->GetBrowser());

  return FALSE;  // Don't stop this message.
}

// Callback for Debug > Zoom In... menu item.
gboolean ZoomInActivated(GtkWidget* widget) {
  if (g_handler.get() && g_handler->GetBrowserHwnd()) {
    CefRefPtr<CefBrowser> browser = g_handler->GetBrowser();
    browser->SetZoomLevel(browser->GetZoomLevel() + 0.5);
  }

  return FALSE;  // Don't stop this message.
}

// Callback for Debug > Zoom Out... menu item.
gboolean ZoomOutActivated(GtkWidget* widget) {
  if (g_handler.get() && g_handler->GetBrowserHwnd()) {
    CefRefPtr<CefBrowser> browser = g_handler->GetBrowser();
    browser->SetZoomLevel(browser->GetZoomLevel() - 0.5);
  }

  return FALSE;  // Don't stop this message.
}

// Callback for Debug > Zoom Reset... menu item.
gboolean ZoomResetActivated(GtkWidget* widget) {
  if (g_handler.get() && g_handler->GetBrowserHwnd()) {
    CefRefPtr<CefBrowser> browser = g_handler->GetBrowser();
    browser->SetZoomLevel(0.0);
  }

  return FALSE;  // Don't stop this message.
}

gboolean DragDropActivated(GtkWidget* widget) {
  if (g_handler.get() && g_handler->GetBrowserHwnd()) {
    CefRefPtr<CefBrowser> browser = g_handler->GetBrowser();
    RunDragDropTest(browser);
  }

  return FALSE;  // Don't stop this message.
}

gboolean GeolocationActivated(GtkWidget* widget) {
  if (g_handler.get() && g_handler->GetBrowserHwnd()) {
    CefRefPtr<CefBrowser> browser = g_handler->GetBrowser();
    RunGeolocationTest(browser);
  }

  return FALSE;  // Don't stop this message.
}

gboolean ShowDevtoolsActivated(GtkWidget* widget) {
  if (g_handler.get() && g_handler->GetBrowserHwnd()) {
    CefRefPtr<CefBrowser> browser = g_handler->GetBrowser();
    browser->ShowDevTools();
  }

  return FALSE;  // Don't stop this message.
}

// Callback for Debug > Plugin Info... menu item.
gboolean PluginInfoActivated(GtkWidget* widget) {
  if (g_handler.get() && g_handler->GetBrowserHwnd())
    RunPluginInfoTest(g_handler->GetBrowser());

  return FALSE;  // Don't stop this message.
}

// Callback for when you click the back button.
void BackButtonClicked(GtkButton* button) {
  if (g_handler.get() && g_handler->GetBrowserHwnd())
    g_handler->GetBrowser()->GoBack();
}

// Callback for when you click the forward button.
void ForwardButtonClicked(GtkButton* button) {
  if (g_handler.get() && g_handler->GetBrowserHwnd())
    g_handler->GetBrowser()->GoForward();
}

// Callback for when you click the stop button.
void StopButtonClicked(GtkButton* button) {
  if (g_handler.get() && g_handler->GetBrowserHwnd())
    g_handler->GetBrowser()->StopLoad();
}

// Callback for when you click the reload button.
void ReloadButtonClicked(GtkButton* button) {
  if (g_handler.get() && g_handler->GetBrowserHwnd())
    g_handler->GetBrowser()->Reload();
}

// Callback for when you press enter in the URL box.
void URLEntryActivate(GtkEntry* entry) {
  if (!g_handler.get() || !g_handler->GetBrowserHwnd())
    return;

  const gchar* url = gtk_entry_get_text(entry);
  g_handler->GetBrowser()->GetMainFrame()->LoadURL(std::string(url).c_str());
}

// GTK utility functions ----------------------------------------------

GtkWidget* AddMenuEntry(GtkWidget* menu_widget, const char* text,
                        GCallback callback) {
  GtkWidget* entry = gtk_menu_item_new_with_label(text);
  g_signal_connect(entry, "activate", callback, NULL);
  gtk_menu_shell_append(GTK_MENU_SHELL(menu_widget), entry);
  return entry;
}

GtkWidget* CreateMenu(GtkWidget* menu_bar, const char* text) {
  GtkWidget* menu_widget = gtk_menu_new();
  GtkWidget* menu_header = gtk_menu_item_new_with_label(text);
  gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_header), menu_widget);
  gtk_menu_shell_append(GTK_MENU_SHELL(menu_bar), menu_header);
  return menu_widget;
}

GtkWidget* CreateMenuBar() {
  GtkWidget* menu_bar = gtk_menu_bar_new();
  GtkWidget* debug_menu = CreateMenu(menu_bar, "Tests");

  AddMenuEntry(debug_menu, "Get Source",
               G_CALLBACK(GetSourceActivated));
  AddMenuEntry(debug_menu, "Get Text",
               G_CALLBACK(GetTextActivated));
  AddMenuEntry(debug_menu, "JS Binding",
               G_CALLBACK(JSBindngActivated));
  AddMenuEntry(debug_menu, "JS Extension",
               G_CALLBACK(JSExtensionActivated));
  AddMenuEntry(debug_menu, "JS Execute",
               G_CALLBACK(JSExecuteActivated));
  AddMenuEntry(debug_menu, "Performance Tests",
               G_CALLBACK(PerformanceActivated));
  AddMenuEntry(debug_menu, "Request",
               G_CALLBACK(RequestActivated));
  AddMenuEntry(debug_menu, "Local Storage",
               G_CALLBACK(LocalStorageActivated));
  AddMenuEntry(debug_menu, "XMLHttpRequest",
               G_CALLBACK(XMLHttpRequestActivated));
  AddMenuEntry(debug_menu, "DOM Access",
               G_CALLBACK(DOMAccessActivated));
  AddMenuEntry(debug_menu, "Scheme Handler",
               G_CALLBACK(SchemeHandlerActivated));
  AddMenuEntry(debug_menu, "Popup Window",
               G_CALLBACK(PopupWindowActivated));
  AddMenuEntry(debug_menu, "Accelerated 2D Canvas",
               G_CALLBACK(Accelerated2DCanvasActivated));
  AddMenuEntry(debug_menu, "Accelerated Layers",
               G_CALLBACK(AcceleratedLayersActivated));
  AddMenuEntry(debug_menu, "WebGL",
               G_CALLBACK(WebGLActivated));
  AddMenuEntry(debug_menu, "Zoom In",
               G_CALLBACK(ZoomInActivated));
  AddMenuEntry(debug_menu, "Zoom Out",
               G_CALLBACK(ZoomOutActivated));
  AddMenuEntry(debug_menu, "Zoom Reset",
               G_CALLBACK(ZoomResetActivated));
  AddMenuEntry(debug_menu, "Drag & Drop",
               G_CALLBACK(DragDropActivated));
  AddMenuEntry(debug_menu, "Geolocation",
               G_CALLBACK(GeolocationActivated));
  AddMenuEntry(debug_menu, "Show DevTools",
               G_CALLBACK(ShowDevtoolsActivated));
  AddMenuEntry(debug_menu, "Plugin Info",
               G_CALLBACK(PluginInfoActivated));

  return menu_bar;
}

// WebViewDelegate::TakeFocus in the test webview delegate.
static gboolean HandleFocus(GtkWidget* widget,
                            GdkEventFocus* focus) {
  if (g_handler.get() && g_handler->GetBrowserHwnd()) {
    // Give focus to the browser window.
    g_handler->GetBrowser()->SetFocus(true);
  }

  return TRUE;
}

int main(int argc, char *argv[]) {
  if (!getcwd(szWorkingDir, sizeof (szWorkingDir)))
    return -1;

  GtkWidget* window;

  gtk_init(&argc, &argv);

  // Parse command line arguments.
  AppInitCommandLine(argc, argv);

  CefSettings settings;
  CefRefPtr<CefApp> app;

  // Populate the settings based on command line arguments.
  AppGetSettings(settings, app);

  // Initialize CEF.
  CefInitialize(settings, app);

  // Register the V8 extension handler.
  InitExtensionTest();

  // Register the scheme handler.
  InitSchemeTest();

  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_window_set_default_size(GTK_WINDOW(window), 800, 600);

  g_signal_connect(window, "focus", G_CALLBACK(&HandleFocus), NULL);

  GtkWidget* vbox = gtk_vbox_new(FALSE, 0);

  GtkWidget* menu_bar = CreateMenuBar();

  gtk_box_pack_start(GTK_BOX(vbox), menu_bar, FALSE, FALSE, 0);

  GtkWidget* toolbar = gtk_toolbar_new();
  // Turn off the labels on the toolbar buttons.
  gtk_toolbar_set_style(GTK_TOOLBAR(toolbar), GTK_TOOLBAR_ICONS);

  GtkToolItem* back = gtk_tool_button_new_from_stock(GTK_STOCK_GO_BACK);
  g_signal_connect(back, "clicked",
                   G_CALLBACK(BackButtonClicked), NULL);
  gtk_toolbar_insert(GTK_TOOLBAR(toolbar), back, -1 /* append */);

  GtkToolItem* forward = gtk_tool_button_new_from_stock(GTK_STOCK_GO_FORWARD);
  g_signal_connect(forward, "clicked",
                   G_CALLBACK(ForwardButtonClicked), NULL);
  gtk_toolbar_insert(GTK_TOOLBAR(toolbar), forward, -1 /* append */);

  GtkToolItem* reload = gtk_tool_button_new_from_stock(GTK_STOCK_REFRESH);
  g_signal_connect(reload, "clicked",
                   G_CALLBACK(ReloadButtonClicked), NULL);
  gtk_toolbar_insert(GTK_TOOLBAR(toolbar), reload, -1 /* append */);

  GtkToolItem* stop = gtk_tool_button_new_from_stock(GTK_STOCK_STOP);
  g_signal_connect(stop, "clicked",
                   G_CALLBACK(StopButtonClicked), NULL);
  gtk_toolbar_insert(GTK_TOOLBAR(toolbar), stop, -1 /* append */);

  GtkWidget* m_editWnd = gtk_entry_new();
  g_signal_connect(G_OBJECT(m_editWnd), "activate",
                   G_CALLBACK(URLEntryActivate), NULL);

  GtkToolItem* tool_item = gtk_tool_item_new();
  gtk_container_add(GTK_CONTAINER(tool_item), m_editWnd);
  gtk_tool_item_set_expand(tool_item, TRUE);
  gtk_toolbar_insert(GTK_TOOLBAR(toolbar), tool_item, -1);  // append

  gtk_box_pack_start(GTK_BOX(vbox), toolbar, FALSE, FALSE, 0);

  g_signal_connect(G_OBJECT(window), "destroy",
                   G_CALLBACK(gtk_widget_destroyed), &window);
  g_signal_connect(G_OBJECT(window), "destroy",
                   G_CALLBACK(destroy), NULL);

  // Create the handler.
  g_handler = new ClientHandler();
  g_handler->SetMainHwnd(vbox);
  g_handler->SetEditHwnd(m_editWnd);
  g_handler->SetButtonHwnds(GTK_WIDGET(back), GTK_WIDGET(forward),
                            GTK_WIDGET(reload), GTK_WIDGET(stop));

  // Create the browser view.
  CefWindowInfo window_info;
  CefBrowserSettings browserSettings;

  // Populate the settings based on command line arguments.
  AppGetBrowserSettings(browserSettings);

  window_info.SetAsChild(vbox);

  CefBrowser::CreateBrowserSync(window_info,
                                static_cast<CefRefPtr<CefClient> >(g_handler),
                                g_handler->GetStartupURL(), browserSettings);

  gtk_container_add(GTK_CONTAINER(window), vbox);
  gtk_widget_show_all(GTK_WIDGET(window));

  // Install an signal handler so we clean up after ourselves.
  signal(SIGINT, TerminationSignalHandler);
  signal(SIGTERM, TerminationSignalHandler);

  CefRunMessageLoop();

  CefShutdown();

  return 0;
}

// Global functions

std::string AppGetWorkingDirectory() {
  return szWorkingDir;
}


text:
'use strict';

/*!
 * V4Fire Client Core
 * https://github.com/V4Fire/Client
 *
 * Released under the MIT license
 * https://github.com/V4Fire/Client/blob/master/LICENSE
 */

const
	$C = require('collection.js'),
	Snakeskin = require('snakeskin');

const
	{validators} = require('@pzlr/build-core'),
	{isV4Prop} = include('build/snakeskin/filters/const');

const
	componentParams = include('build/graph/component-params');

const
	tagFilters = include('build/snakeskin/filters/tag'),
	tagNameFilters = include('build/snakeskin/filters/tag-name'),
	bemFilters = include('build/snakeskin/filters/bem');

const bind = {
	bind: [
		(o) => o.getVar('$attrs'),
		'typeof rootTag !== "undefined" ? rootTag : undefined'
	]
};

Snakeskin.importFilters({
	tagFilter,
	tagNameFilter: Snakeskin.setFilterParams(tagNameFilter, bind),
	bemFilter: Snakeskin.setFilterParams(bemFilter, bind)
});

function tagFilter({name, attrs = {}}) {
	$C(tagFilters).forEach((filter) => {
		filter({name, attrs});
	});

	if (name !== 'component' && !attrs[':instance-of'] && !validators.blockName(name)) {
		return;
	}

	let
		componentName;

	if (attrs[':instance-of']) {
		componentName = attrs[':instance-of'][0].camelize(false);
		delete attrs[':instance-of'];

	} else {
		componentName = name === 'component' ? 'iBlock' : name.camelize(false);
	}

	const
		component = componentParams[componentName],
		props = component ? component.props : Object.create(null);

	const
		smartProps = [attrs['v-func-placeholder'], delete attrs['v-func-placeholder']][0] && component && component.functional,
		funcMode = [attrs['v-func'], delete attrs['v-func']][0];

	let
		isFunctional = false;

	if (component && component.functional === true) {
		isFunctional = true;

	} else if (!funcMode) {
		isFunctional = $C(smartProps).every((el, key) => {
			key = key.dasherize(true);

			if (!isV4Prop.test(key)) {
				key = `:${key}`;
			}

			let
				attr = attrs[key] && attrs[key][0];

			try {
				// eslint-disable-next-line no-new-func
				attr = Function(`return ${attr}`)();

			} catch {}

			if (Object.isArray(el)) {
				if (!Object.isArray(el[0])) {
					return $C(el).includes(attr);
				}

				return Object.fastCompare(el[0], attr);
			}

			if (Object.isRegExp(el)) {
				return el.test(attr);
			}

			if (Object.isFunction(el)) {
				return el(attr);
			}

			return Object.fastCompare(el, attr);
		});
	}

	if ((isFunctional || funcMode) && smartProps) {
		if (funcMode) {
			attrs[':is'] = [`'${attrs['is'][0]}' + (${funcMode[0]} ? '-functional' : '')`];
			delete attrs['is'];

		} else {
			attrs['is'] = [`${attrs['is'][0]}-functional`];
		}
	}

	if (component) {
		$C(attrs).forEach((el, key) => {
			if (key[0] !== ':') {
				return;
			}

			const
				basePropName = key.slice(1).camelize(false),
				directPropName = `${basePropName}Prop`;

			let
				resolvedPropName = basePropName,
				alternative = component.deprecatedProps[resolvedPropName];

			if (!props[basePropName] && props[directPropName]) {
				resolvedPropName = directPropName;
				alternative = component.deprecatedProps[resolvedPropName];

				if (!alternative) {
					attrs[`:${directPropName.dasherize(true)}`] = el;
				}

				delete attrs[key];
			}

			if (alternative) {
				attrs[`:${alternative.dasherize(true)}`] = el;
				delete attrs[key];
			}
		});

		if (component.inheritMods !== false && !attrs[':mods-prop']) {
			attrs[':mods-prop'] = ['provide.mods()'];
		}
	}
}

// eslint-disable-next-line default-param-last
function tagNameFilter(tag, attrs = {}, rootTag) {
	tag = $C(tagNameFilters)
		.to(tag)
		.reduce((tag, filter) => filter(tag, attrs, rootTag));

	const
		nm = tag.camelize(false),
		component = componentParams[nm];

	if (component != null && !Object.isBoolean(component.functional)) {
		Object.assign(attrs, {
			':instance-of': [nm],
			'v-func-placeholder': [true],
			is: [tag]
		});

		return 'component';
	}

	return tag;
}

// eslint-disable-next-line default-param-last
function bemFilter(block, attrs = {}, rootTag, value) {
	return $C(bemFilters)
		.to('')
		.reduce((res, filter) => res + filter(block, attrs, rootTag, value));
}


text:
.class public Landroid/net/wifi/WifiScanner$ChannelSpec;
.super Ljava/lang/Object;
.source "WifiScanner.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/net/wifi/WifiScanner;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x9
    name = "ChannelSpec"
.end annotation

# instance fields
.field public dwellTimeMS:I

.field public frequency:I

.field public passive:Z

# direct methods
.method public constructor <init>(I)V
    .locals 1
    .param p1, "frequency"    # I

    .prologue
    const/4 v0, 0x0

    .line 132
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 133
    iput p1, p0, Landroid/net/wifi/WifiScanner$ChannelSpec;->frequency:I

    .line 134
    iput-boolean v0, p0, Landroid/net/wifi/WifiScanner$ChannelSpec;->passive:Z

    .line 135
    iput v0, p0, Landroid/net/wifi/WifiScanner$ChannelSpec;->dwellTimeMS:I

    .line 136
    return-void
.end method


text:
#include "play.h"

void
play_uri (const gchar * uri)
{
  GstStateChangeReturn sret;
  GstElement *playbin;
  GstElement *audiosink;
  GstElement *videosink;
  GstMessage *msg = NULL;
  GstBus *bus;

  g_print ("Trying to play %s ...\n", uri);

  playbin = gst_element_factory_make ("playbin", "playbin");
  if (playbin == NULL)
    goto no_playbin;

  /* get playbin's bus - we'll watch it for messages */
  bus = gst_pipeline_get_bus (GST_PIPELINE (playbin));

  /* set audio sink */
  audiosink = gst_element_factory_make ("autoaudiosink", "audiosink");
  if (audiosink == NULL)
    goto no_autoaudiosink;
  g_object_set (playbin, "audio-sink", audiosink, NULL);

  /* set video sink */
  videosink = gst_element_factory_make ("autovideosink", "videosink");
  if (videosink == NULL)
    goto no_autovideosink;
  g_object_set (playbin, "video-sink", videosink, NULL);

  /* set URI to play back */
  g_object_set (playbin, "uri", uri, NULL);

  /* and GO GO GO! */
  gst_element_set_state (GST_ELEMENT (playbin), GST_STATE_PLAYING);

  /* wait (blocks!) until state change either completes or fails */
  sret = gst_element_get_state (GST_ELEMENT (playbin), NULL, NULL, -1);

  switch (sret) {
    case GST_STATE_CHANGE_FAILURE:{
      msg = gst_bus_poll (bus, GST_MESSAGE_ERROR, 0);
      goto got_error_message;
    }
    case GST_STATE_CHANGE_SUCCESS:{
      GstMessage *msg;

      g_print ("Playing ...\n");

      while (1) {
        gint64 dur, pos;

        if (gst_element_query_duration (playbin, GST_FORMAT_TIME, &dur) &&
            gst_element_query_position (playbin, GST_FORMAT_TIME, &pos)) {
          g_print ("  %" GST_TIME_FORMAT " / %" GST_TIME_FORMAT "\n",
              GST_TIME_ARGS (pos), GST_TIME_ARGS (dur));
        }

        /* check if we finished or if there was an error,
         * but don't wait/block if neither is the case */
        msg = gst_bus_poll (bus, GST_MESSAGE_EOS | GST_MESSAGE_ERROR, 0);

        if (msg && GST_MESSAGE_TYPE (msg) == GST_MESSAGE_ERROR)
          goto got_error_message;

        if (msg && GST_MESSAGE_TYPE (msg) == GST_MESSAGE_EOS) {
          g_print ("Finished.\n");
          break;
        }

        /* sleep for one second */
        g_usleep (G_USEC_PER_SEC * 1);
      }
      break;
    }
    default:
      g_assert_not_reached ();
  }

  /* shut down and free everything */
  gst_element_set_state (playbin, GST_STATE_NULL);
  gst_object_unref (playbin);
  gst_object_unref (bus);
  return;

/* ERRORS */
got_error_message:
  {
    if (msg) {
      GError *err = NULL;
      gchar *dbg_str = NULL;

      gst_message_parse_error (msg, &err, &dbg_str);
      g_printerr ("FAILED to play %s: %s\n%s\n", uri, err->message,
          (dbg_str) ? dbg_str : "(no debugging information)");
      g_error_free (err);
      g_free (dbg_str);
      gst_message_unref (msg);
    } else {
      g_printerr ("FAILED to play %s: unknown error\n", uri);
    }

    /* shut down and free everything */
    gst_element_set_state (playbin, GST_STATE_NULL);
    gst_object_unref (playbin);
    gst_object_unref (bus);
    return;
  }

no_playbin:
  {
    g_error ("Could not create GStreamer 'playbin' element. "
        "Please install it");
    /* not reached, g_error aborts */
    return;
  }

no_autoaudiosink:
  {
    g_error ("Could not create GStreamer 'autoaudiosink' element. "
        "Please install it");
    /* not reached, g_error aborts */
    return;
  }

no_autovideosink:
  {
    g_error ("Could not create GStreamer 'autovideosink' element. "
        "Please install it");
    /* not reached, g_error aborts */
    return;
  }
}


text:
using power::OriginPowerMap;
using power::OriginPowerMapFactory;

class BrowserProcessPowerTest : public BrowserWithTestWindowTest {
 public:
  BrowserProcessPowerTest() {}
  virtual ~BrowserProcessPowerTest() {}

  virtual void SetUp() OVERRIDE {
    BrowserWithTestWindowTest::SetUp();
    collector.reset(new ProcessPowerCollector);

#if defined(OS_CHROMEOS)
    power_manager::PowerSupplyProperties prop;
    prop.set_external_power(power_manager::PowerSupplyProperties::AC);
    prop.set_battery_state(power_manager::PowerSupplyProperties::DISCHARGING);
    prop.set_battery_percent(20.00);
    prop.set_battery_discharge_rate(1);
    collector->PowerChanged(prop);
#endif

    profile_manager_.reset(
        new TestingProfileManager(TestingBrowserProcess::GetGlobal()));
    ASSERT_TRUE(profile_manager_->SetUp());
  }

  virtual void TearDown() OVERRIDE {
    collector.reset();
    BrowserWithTestWindowTest::TearDown();
  }

  // Mocks out CPU usage for all processes as |value| percent.
  double ReturnCpuAsConstant(double value, base::ProcessHandle handle) {
    return value;
  }

 protected:
  content::MockRenderProcessHost* GetProcess(Browser* browser) {
    return static_cast<content::MockRenderProcessHost*>(
        browser->tab_strip_model()
            ->GetActiveWebContents()
            ->GetRenderViewHost()
            ->GetProcess());
  }

  scoped_ptr<base::ProcessHandle> MakeProcessHandle(int process_id) {
    scoped_ptr<base::ProcessHandle> proc_handle(new base::ProcessHandle(
#if defined(OS_WIN)
        reinterpret_cast<HANDLE>(process_id))
#else
        process_id)
#endif
                                                );
    return proc_handle.Pass();
  }

  scoped_ptr<ProcessPowerCollector> collector;
  scoped_ptr<TestingProfileManager> profile_manager_;
};

class TestAppWindowContents : public extensions::AppWindowContents {
 public:
  explicit TestAppWindowContents(content::WebContents* web_contents)
      : web_contents_(web_contents) {}

  // apps:AppWindowContents
  virtual void Initialize(content::BrowserContext* context,
                          const GURL& url) OVERRIDE {}
  virtual void LoadContents(int32 creator_process_id) OVERRIDE {}
  virtual void NativeWindowChanged(
      extensions::NativeAppWindow* native_app_window) OVERRIDE {}
  virtual void NativeWindowClosed() OVERRIDE {}
  virtual void DispatchWindowShownForTests() const OVERRIDE {}
  virtual content::WebContents* GetWebContents() const OVERRIDE {
    return web_contents_.get();
  }

 private:
  scoped_ptr<content::WebContents> web_contents_;
};

TEST_F(BrowserProcessPowerTest, NoSite) {
  collector->UpdatePowerConsumptionForTesting();
  EXPECT_EQ(0u, collector->metrics_map_for_testing()->size());
}

TEST_F(BrowserProcessPowerTest, OneSite) {
  GURL url("http://www.google.com");
  AddTab(browser(), url);
  collector->UpdatePowerConsumptionForTesting();
  ProcessPowerCollector::ProcessMetricsMap* metrics_map =
      collector->metrics_map_for_testing();
  EXPECT_EQ(1u, metrics_map->size());

  // Create fake process numbers.
  GetProcess(browser())->SetProcessHandle(MakeProcessHandle(1).Pass());

  OriginPowerMap* origin_power_map =
      OriginPowerMapFactory::GetForBrowserContext(profile());
  EXPECT_EQ(0, origin_power_map->GetPowerForOrigin(url));

  collector->set_cpu_usage_callback_for_testing(
      base::Bind(&BrowserProcessPowerTest::ReturnCpuAsConstant,
                 base::Unretained(this),
                 5));
  EXPECT_DOUBLE_EQ(5, collector->UpdatePowerConsumptionForTesting());
  EXPECT_EQ(100, origin_power_map->GetPowerForOrigin(url));
}

TEST_F(BrowserProcessPowerTest, MultipleSites) {
  Browser::CreateParams native_params(profile(),
                                      chrome::HOST_DESKTOP_TYPE_NATIVE);
  GURL url1("http://www.google.com");
  GURL url2("http://www.example.com");
  GURL url3("https://www.google.com");
  scoped_ptr<Browser> browser2(
      chrome::CreateBrowserWithTestWindowForParams(&native_params));
  scoped_ptr<Browser> browser3(
      chrome::CreateBrowserWithTestWindowForParams(&native_params));
  AddTab(browser(), url1);
  AddTab(browser2.get(), url2);
  AddTab(browser3.get(), url3);

  // Create fake process numbers.
  GetProcess(browser())->SetProcessHandle(MakeProcessHandle(1).Pass());
  GetProcess(browser2.get())->SetProcessHandle(MakeProcessHandle(2).Pass());
  GetProcess(browser3.get())->SetProcessHandle(MakeProcessHandle(3).Pass());

  collector->UpdatePowerConsumptionForTesting();
  ProcessPowerCollector::ProcessMetricsMap* metrics_map =
      collector->metrics_map_for_testing();
  EXPECT_EQ(3u, metrics_map->size());

  // Since all handlers are uninitialized, this should be 0.
  EXPECT_DOUBLE_EQ(0, collector->UpdatePowerConsumptionForTesting());
  OriginPowerMap* origin_power_map =
      OriginPowerMapFactory::GetForBrowserContext(profile());
  EXPECT_EQ(0, origin_power_map->GetPowerForOrigin(url1));
  EXPECT_EQ(0, origin_power_map->GetPowerForOrigin(url2));
  EXPECT_EQ(0, origin_power_map->GetPowerForOrigin(url3));

  collector->set_cpu_usage_callback_for_testing(
      base::Bind(&BrowserProcessPowerTest::ReturnCpuAsConstant,
                 base::Unretained(this),
                 5));
  EXPECT_DOUBLE_EQ(15, collector->UpdatePowerConsumptionForTesting());
  EXPECT_EQ(33, origin_power_map->GetPowerForOrigin(url1));
  EXPECT_EQ(33, origin_power_map->GetPowerForOrigin(url2));
  EXPECT_EQ(33, origin_power_map->GetPowerForOrigin(url3));

  // Close some tabs and verify that they are removed from the metrics map.
  chrome::CloseTab(browser2.get());
  chrome::CloseTab(browser3.get());

  collector->UpdatePowerConsumptionForTesting();
  EXPECT_EQ(1u, metrics_map->size());
}

TEST_F(BrowserProcessPowerTest, IncognitoDoesntRecordPowerUsage) {
  Browser::CreateParams native_params(profile()->GetOffTheRecordProfile(),
                                      chrome::HOST_DESKTOP_TYPE_NATIVE);
  scoped_ptr<Browser> incognito_browser(
      chrome::CreateBrowserWithTestWindowForParams(&native_params));
  GURL url("http://www.google.com");
  AddTab(browser(), url);

  GURL hidden_url("http://foo.com");
  AddTab(incognito_browser.get(), hidden_url);

  // Create fake process numbers.
  GetProcess(browser())->SetProcessHandle(MakeProcessHandle(1).Pass());
  GetProcess(incognito_browser.get())
      ->SetProcessHandle(MakeProcessHandle(2).Pass());

  EXPECT_DOUBLE_EQ(0, collector->UpdatePowerConsumptionForTesting());
  ProcessPowerCollector::ProcessMetricsMap* metrics_map =
      collector->metrics_map_for_testing();
  EXPECT_EQ(1u, metrics_map->size());

  OriginPowerMap* origin_power_map =
      OriginPowerMapFactory::GetForBrowserContext(profile());
  EXPECT_EQ(0, origin_power_map->GetPowerForOrigin(url));

  collector->set_cpu_usage_callback_for_testing(
      base::Bind(&BrowserProcessPowerTest::ReturnCpuAsConstant,
                 base::Unretained(this),
                 5));
  EXPECT_DOUBLE_EQ(5, collector->UpdatePowerConsumptionForTesting());

  // Verify that the incognito data was not stored.
  EXPECT_EQ(100, origin_power_map->GetPowerForOrigin(url));
  EXPECT_EQ(0, origin_power_map->GetPowerForOrigin(hidden_url));

  chrome::CloseTab(incognito_browser.get());
}

TEST_F(BrowserProcessPowerTest, MultipleProfilesRecordSeparately) {
  scoped_ptr<Profile> other_profile(CreateProfile());
  Browser::CreateParams native_params(other_profile.get(),
                                      chrome::HOST_DESKTOP_TYPE_NATIVE);
  scoped_ptr<Browser> other_user(
      chrome::CreateBrowserWithTestWindowForParams(&native_params));

  GURL url("http://www.google.com");
  AddTab(browser(), url);

  GURL hidden_url("http://foo.com");
  AddTab(other_user.get(), hidden_url);

  // Create fake process numbers.
  GetProcess(browser())->SetProcessHandle(MakeProcessHandle(1).Pass());
  GetProcess(other_user.get())->SetProcessHandle(MakeProcessHandle(2).Pass());

  EXPECT_DOUBLE_EQ(0, collector->UpdatePowerConsumptionForTesting());
  EXPECT_EQ(2u, collector->metrics_map_for_testing()->size());

  collector->set_cpu_usage_callback_for_testing(
      base::Bind(&BrowserProcessPowerTest::ReturnCpuAsConstant,
                 base::Unretained(this),
                 5));
  EXPECT_DOUBLE_EQ(10, collector->UpdatePowerConsumptionForTesting());

  // profile() should have an entry for |url| but not |hidden_url|.
  OriginPowerMap* origin_power_map_first =
      OriginPowerMapFactory::GetForBrowserContext(profile());
  EXPECT_EQ(100, origin_power_map_first->GetPowerForOrigin(url));
  EXPECT_EQ(0, origin_power_map_first->GetPowerForOrigin(hidden_url));

  // |other_profile| should have an entry for |hidden_url| but not |url|.
  OriginPowerMap* origin_power_map_second =
      OriginPowerMapFactory::GetForBrowserContext(other_profile.get());
  EXPECT_EQ(0, origin_power_map_second->GetPowerForOrigin(url));
  EXPECT_EQ(100, origin_power_map_second->GetPowerForOrigin(hidden_url));

  // Clean up
  chrome::CloseTab(other_user.get());
}

TEST_F(BrowserProcessPowerTest, AppsRecordPowerUsage) {
// Install an app (an extension*).
#if defined(OS_WIN)
  base::FilePath extension_path(FILE_PATH_LITERAL("c:\\foo"));
#elif defined(OS_POSIX)
  base::FilePath extension_path(FILE_PATH_LITERAL("/foo"));
#endif
  base::DictionaryValue manifest;
  manifest.SetString("name", "Fake Name");
  manifest.SetString("version", "1");
  std::string error;
  char kTestAppId[] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
  scoped_refptr<extensions::Extension> extension(
      extensions::Extension::Create(extension_path,
                                    extensions::Manifest::INTERNAL,
                                    manifest,
                                    extensions::Extension::NO_FLAGS,
                                    kTestAppId,
                                    &error));
  EXPECT_TRUE(extension.get()) << error;

  Profile* current_profile =
      profile_manager_->CreateTestingProfile("Test user");
  GURL url("chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
  extensions::AppWindow* window = new extensions::AppWindow(
      current_profile, new ChromeAppDelegate(scoped_ptr<ScopedKeepAlive>()),
      extension.get());
  content::WebContents* web_contents(
      content::WebContents::Create(content::WebContents::CreateParams(
          current_profile,
          content::SiteInstance::CreateForURL(current_profile, url))));
  window->SetAppWindowContentsForTesting(
      scoped_ptr<extensions::AppWindowContents>(
          new TestAppWindowContents(web_contents)));
  extensions::AppWindowRegistry* app_registry =
      extensions::AppWindowRegistry::Get(current_profile);
  app_registry->AddAppWindow(window);

  collector->set_cpu_usage_callback_for_testing(
      base::Bind(&BrowserProcessPowerTest::ReturnCpuAsConstant,
                 base::Unretained(this),
                 5));
  collector->UpdatePowerConsumptionForTesting();
  EXPECT_EQ(1u, collector->metrics_map_for_testing()->size());

  // Clear the AppWindowContents before trying to close.
  window->SetAppWindowContentsForTesting(
      scoped_ptr<extensions::AppWindowContents>());
  window->OnNativeClose();
  collector->UpdatePowerConsumptionForTesting();
  EXPECT_EQ(0u, collector->metrics_map_for_testing()->size());
}