/**
 *
 */
package com.github.mrcritical.ironcache.internal.http;

import java.io.IOException;

import lombok.extern.slf4j.Slf4j;

import com.github.mrcritical.ironcache.model.HTTPException;
import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpUnsuccessfulResponseHandler;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.util.ExponentialBackOff;

/**
 * Response initializer that registers itself as to handle unsuccessful
 * responses. This will ensure a {@link HTTPException} is thrown instead of the
 * default exception type.
 *
 * @author pjarrell
 *
 */
@Slf4j
public class ResponseInitializer implements HttpRequestInitializer, HttpUnsuccessfulResponseHandler {

	private final JsonFactory jsonFactory;

	private final String token;

	/**
	 * Create a response initializer that uses the authentication token
	 * provided.
	 *
	 * @param token
	 *            is the authentication token
	 * @param jsonFactory
	 *            is the JSON factory to use
	 */
	public ResponseInitializer(final String token, final JsonFactory jsonFactory) {
		this.token = token;
		this.jsonFactory = jsonFactory;
	}

	/**
	 * Configures each request. This does 3 things:
	 *

	 *
Adds the authorization token to each request

	 *
Adds the JSON factory to the request

	 *
Adds exponential back off capability

	 *

	 *
	 * @param request
	 *            is the request to configure
	 */
	protected void configure(final HttpRequest request) {
		request.getHeaders().setAuthorization(String.format("OAuth %s", token));
		request.setParser(new JsonObjectParser(jsonFactory));

		final ExponentialBackOff backoff = new ExponentialBackOff.Builder().setInitialIntervalMillis(500)
				.setMaxElapsedTimeMillis(60000).setMaxIntervalMillis(30000).setMultiplier(1.5)
				.setRandomizationFactor(0.5).build();
		request.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff));
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.google.api.client.http.HttpUnsuccessfulResponseHandler#handleResponse
	 * (com.google.api.client.http.HttpRequest,
	 * com.google.api.client.http.HttpResponse, boolean)
	 */
	@Override
	public boolean handleResponse(final HttpRequest request, final HttpResponse response, final boolean supportsRetry)
			throws IOException {
		log.trace("HTTP request {} resulted in {} with response {} and headers {}", request.getUrl().toString(),
				response.getStatusCode(), response.getStatusMessage(), response.getHeaders().toString());
		throw new HTTPException(response.getStatusCode(), response.getStatusMessage());
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.google.api.client.http.HttpRequestInitializer#initialize(com.google
	 * .api.client.http.HttpRequest)
	 */
	@Override
	public void initialize(final HttpRequest request) throws IOException {
		configure(request);
		request.setUnsuccessfulResponseHandler(this);
	}

}


package org.criteria4jpa.projection;

import org.criteria4jpa.Criteria;
import org.criteria4jpa.impl.CriteriaQueryBuilder;

/**
 *
 * Class representing a "distinct" projection.
 * It is recommended to use the static factory methods
 * of {@link Projections} to created instances of this class.
 *
 * @see Projections
 *
 * @author Christian Kaltepoth
 *
 */
public class DistinctProjection implements Projection {

  private final Projection projection;

  /**
   * creates a new "distinct" projection for a wrapped projection.
   *
   * @param projection wrapped projection
   */
  public DistinctProjection(Projection projection) {
    this.projection = projection;
  }

  /*
   * @see org.criteria4jpa.projection.Projection#toQueryString(org.criteria4jpa.Criteria, org.criteria4jpa.impl.CriteriaQueryBuilder)
   */
  public String toQueryString(Criteria criteria, CriteriaQueryBuilder queryBuilder) {
    return new StringBuilder()
      .append("DISTINCT ")
      .append( projection.toQueryString(criteria, queryBuilder) )
      .toString();
  }

  /*
   * @see org.criteria4jpa.projection.Projection#toGroupByString(org.criteria4jpa.Criteria, org.criteria4jpa.impl.CriteriaQueryBuilder)
   */
  public String toGroupByString(Criteria criteria, CriteriaQueryBuilder queryBuilder) {
    return null;
  }

}


/*******************************************************************************
 * <copyright>
 *
 * Copyright (c) 2014 Eteration A.S.
 * All rights reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *     Unless required by applicable law or agreed to in writing, software
 *     distributed under the License is distributed on an "AS IS" BASIS,
 *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *     See the License for the specific language governing permissions and
 *     limitations under the License.
 *
 *
 *     Derivative Works
 *     Parts of this program are derived from content from Eclipse Foundation
 *     that are made available under the terms of the Eclipse Public License v1.0.
 *      http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Naci Dai, Eteration A.S. - initial API, implementation and documentation
 *
 * </copyright>
 *
 *******************************************************************************/
package org.glassmaker.ui.views;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.TreeMap;

import org.eclipse.draw2d.geometry.Point;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.Tool;
import org.eclipse.gef.palette.PaletteDrawer;
import org.eclipse.gef.palette.PaletteRoot;
import org.eclipse.gef.palette.ToolEntry;
import org.eclipse.gef.ui.palette.PaletteViewer;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.jface.text.templates.Template;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.glassmaker.ui.GlassmakerUIPlugin;
import org.glassmaker.ui.editor.CardEditor;

public class PaletteView extends ViewPart {

	private PaletteViewer viewer;
	private TreeMap<String, List<IPaletteItem>> items = new TreeMap<String, List<IPaletteItem>>();
	private HashMap<HTMLPaletteEntry, IPaletteItem> tools = new HashMap<HTMLPaletteEntry, IPaletteItem>();

	public PaletteView() {

		Template[] templates = GlassmakerUIPlugin.getDefault().getTemplateStore().getTemplates();
		ImageRegistry imageRegistry = GlassmakerUIPlugin.getDefault().getImageRegistry();
		for(Template t: templates){
			String imageId = "org.glassmaker.ui.templates."+t.getName().replace(" ", "").toLowerCase();
			addPaletteItem("Card Types",new DefaultPaletteItem(t.getName(),
					imageRegistry.getDescriptor(imageId),
					t.getPattern()));
		}
	}

	/**
	 * create controls and apply configurations.
	 */
	public void createPartControl(Composite parent) {
		viewer = new PaletteViewer();
		viewer.createControl(parent);

		PaletteRoot root = new PaletteRoot();

		String[] category = getCategories();
		for(int i=0;i<category.length;i++){
			PaletteDrawer group = new PaletteDrawer(category[i]);
			IPaletteItem[] items = getPaletteItems(category[i]);
			for(int j=0;j<items.length;j++){
				HTMLPaletteEntry entry = new HTMLPaletteEntry(items[j].getLabel(),null,items[j].getImageDescriptor());
				tools.put(entry,items[j]);
				group.add(entry);
			}
			root.add(group);
		}

		viewer.setPaletteRoot(root);

		viewer.getControl().addMouseListener(new MouseAdapter(){
			@Override
			public void mouseDoubleClick(MouseEvent e) {

//				IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
//				IEditorPart editorPart = page.getActiveEditor();
//				if(editorPart!=null){
//					editorPart.setFocus();
//				}
				if (e.button == 1) {
					EditPart part = PaletteView.this.viewer.findObjectAt(new Point(e.x, e.y));
					IPaletteItem item = null;
					if (part != null) {
						if (part.getModel() instanceof HTMLPaletteEntry)
							item = tools.get(part.getModel());
					}
					if (item != null)
						insert(item);
				}

			}
		});

	}

	private void insert(IPaletteItem item) {
		if(item == null)
			return;
		IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
		IEditorPart editorPart = page.getActiveEditor();
		// execute processing of the palette item
		if(editorPart!=null){
			if(editorPart instanceof CardEditor){
				item.execute((CardEditor)editorPart);
			}
			else if(editorPart instanceof IPaletteTarget){
				item.execute(((IPaletteTarget)editorPart).getPaletteTarget());
			}
		}
	}

	/**
	 * Adds PaletteItem to the specified category.
	 *
	 * @param category the category
	 * @param item the item
	 */
	private void addPaletteItem(String category,IPaletteItem item){
		if(items.get(category)==null){
			List<IPaletteItem> list = new ArrayList<IPaletteItem>();
			items.put(category,list);
		}
		List<IPaletteItem> list = items.get(category);
		list.add(item);
	}

	/**
	 * Returns PaletteItems which are contained by the specified category.
	 *
	 * @param category the category
	 * @return the array of items which are contained by the category
	 */
	private IPaletteItem[] getPaletteItems(String category){
		List<IPaletteItem> list = items.get(category);
		if(list==null){
			return new IPaletteItem[0];
		}
		return list.toArray(new IPaletteItem[list.size()]);
	}

	/**
	 * Returns all categories.
	 *
	 * @return the array which contains all categories
	 */
	private String[] getCategories(){
		return items.keySet().toArray(new String[0]);
	}

	public void setFocus() {
		viewer.getControl().setFocus();
	}

	/** ToolEntry for HTML tag palette */
	private class HTMLPaletteEntry extends ToolEntry {

		public HTMLPaletteEntry(String label, String shortDescription, ImageDescriptor icon) {
			super(label, shortDescription, icon, icon);
		}

		public Tool createTool() {
			return null;
		}
	}

}


/*******************************************************************************
 * <copyright>
 *
 * Copyright (c) 2014 Eteration A.S.
 * All rights reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *     Unless required by applicable law or agreed to in writing, software
 *     distributed under the License is distributed on an "AS IS" BASIS,
 *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *     See the License for the specific language governing permissions and
 *     limitations under the License.
 *
 *
 *     Derivative Works
 *     Parts of this program are derived from content from Eclipse Foundation
 *     that are made available under the terms of the Eclipse Public License v1.0.
 *      http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Naci Dai, Eteration A.S. - initial API, implementation and documentation
 *
 * </copyright>
 *
 *******************************************************************************/
package org.glassmaker.ui.editor.wizards;

import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.preference.PreferenceDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.jface.text.templates.DocumentTemplateContext;
import org.eclipse.jface.text.templates.Template;
import org.eclipse.jface.text.templates.TemplateBuffer;
import org.eclipse.jface.text.templates.TemplateContext;
import org.eclipse.jface.text.templates.TemplateContextType;
import org.eclipse.jface.text.templates.persistence.TemplateStore;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.dialogs.PreferencesUtil;
import org.eclipse.wst.html.ui.StructuredTextViewerConfigurationHTML;
import org.eclipse.wst.html.ui.internal.preferences.HTMLUIPreferenceNames;
import org.eclipse.wst.sse.core.StructuredModelManager;
import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
import org.eclipse.wst.sse.ui.StructuredTextViewerConfiguration;
import org.eclipse.wst.sse.ui.internal.StructuredTextViewer;
import org.eclipse.wst.sse.ui.internal.provisional.style.LineStyleProvider;
import org.glassmaker.ui.GlassmakerUIPlugin;
import org.glassmaker.ui.editor.CardContextType;

/**
 * Templates page in new file wizard. Allows users to select a new file
 * template to be applied in new file.
 *
 */
public class NewCardTemplatesWizardPage extends WizardPage {

	/**
	 * Content provider for templates
	 */
	private class TemplateContentProvider implements IStructuredContentProvider {
		/** The template store. */
		private TemplateStore fStore;

		/*
		 * @see IContentProvider#dispose()
		 */
		public void dispose() {
			fStore = null;
		}

		/*
		 * @see IStructuredContentProvider#getElements(Object)
		 */
		public Object[] getElements(Object input) {
			return fStore.getTemplates(CardContextType.CONTEXT_TYPE);
		}

		/*
		 * @see IContentProvider#inputChanged(Viewer, Object, Object)
		 */
		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
			fStore = (TemplateStore) newInput;
		}
	}

	/**
	 * Label provider for templates.
	 */
	private class TemplateLabelProvider extends LabelProvider implements ITableLabelProvider {

		/*
		 * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object,
		 *      int)
		 */
		public Image getColumnImage(Object element, int columnIndex) {
			return null;
		}

		/*
		 * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object,
		 *      int)
		 */
		public String getColumnText(Object element, int columnIndex) {
			Template template = (Template) element;

			switch (columnIndex) {
				case 0 :
					return template.getName();
				case 1 :
					return template.getDescription();
				default :
					return ""; //$NON-NLS-1$
			}
		}
	}

	/** Last selected template name */
	private String fLastSelectedTemplateName;
	/** The viewer displays the pattern of selected template. */
	private SourceViewer fPatternViewer;
	/** The table presenting the templates. */
	private TableViewer fTableViewer;
	/** Image preview of the template */
	private Label fImage;
	/** Template store used by this wizard page */
	private TemplateStore fTemplateStore;
	/** Checkbox for using templates. */
	private Button fUseTemplateButton;

	private ImageRegistry imageRegistry;

	public NewCardTemplatesWizardPage() {
		super("NewHTMLTemplatesWizardPage", "Card Templates", null); //$NON-NLS-1$
		setDescription("Card Templates");
	}

	/**
	 * Correctly resizes the table so no phantom columns appear
	 *
	 * @param parent
	 *            the parent control
	 * @param buttons
	 *            the buttons
	 * @param table
	 *            the table
	 * @param column1
	 *            the first column
	 * @param column2
	 *            the second column
	 * @param column3
	 *            the third column
	 */
	private void configureTableResizing(final Composite parent, final Table table, final TableColumn column1, final TableColumn column2) {
		parent.addControlListener(new ControlAdapter() {
			public void controlResized(ControlEvent e) {
				Rectangle area = parent.getClientArea();
				Point preferredSize = table.computeSize(SWT.DEFAULT, SWT.DEFAULT);
				int width = area.width - 2 * table.getBorderWidth();
				if (preferredSize.y > area.height) {
					// Subtract the scrollbar width from the total column
					// width
					// if a vertical scrollbar will be required
					Point vBarSize = table.getVerticalBar().getSize();
					width -= vBarSize.x;
				}

				Point oldSize = table.getSize();
				if (oldSize.x > width) {
					// table is getting smaller so make the columns
					// smaller first and then resize the table to
					// match the client area width
					column1.setWidth(width / 2);
					column2.setWidth(width / 2);
					table.setSize(width, area.height);
				}
				else {
					// table is getting bigger so make the table
					// bigger first and then make the columns wider
					// to match the client area width
					table.setSize(width, area.height);
					column1.setWidth(width / 2);
					column2.setWidth(width / 2);
				}
			}
		});
	}

	public void createControl(Composite ancestor) {
		Composite parent = new Composite(ancestor, SWT.NONE);
		GridLayout layout = new GridLayout();
		layout.numColumns = 2;
		parent.setLayout(layout);

		imageRegistry=GlassmakerUIPlugin.getDefault().getImageRegistry();

		// create checkbox for user to use HTML Template
		fUseTemplateButton = new Button(parent, SWT.CHECK);
		fUseTemplateButton.setText("User Card Template");
		GridData data = new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1);
		fUseTemplateButton.setLayoutData(data);
		fUseTemplateButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				enableTemplates();
			}
		});

		// create composite for Templates table
		Composite innerParent = new Composite(parent, SWT.NONE);
		GridLayout innerLayout = new GridLayout();
		innerLayout.numColumns = 2;
		innerLayout.marginHeight = 0;
		innerLayout.marginWidth = 0;
		innerParent.setLayout(innerLayout);
		GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1);
		innerParent.setLayoutData(gd);

		Label label = new Label(innerParent, SWT.NONE);
		label.setText("Templates");

		data = new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1);
		label.setLayoutData(data);

		// create table that displays templates
		Table table = new Table(innerParent, SWT.BORDER | SWT.FULL_SELECTION);

		data = new GridData(GridData.FILL_BOTH);
		data.widthHint = convertWidthInCharsToPixels(2);
		data.heightHint = convertHeightInCharsToPixels(10);
		data.horizontalSpan = 2;
		table.setLayoutData(data);
		table.setHeaderVisible(true);
		table.setLinesVisible(true);
		TableLayout tableLayout = new TableLayout();
		table.setLayout(tableLayout);

		TableColumn column1 = new TableColumn(table, SWT.NONE);
		column1.setText("Name");

		TableColumn column2 = new TableColumn(table, SWT.NONE);
		column2.setText("Description");

		fTableViewer = new TableViewer(table);
		fTableViewer.setLabelProvider(new TemplateLabelProvider());
		fTableViewer.setContentProvider(new TemplateContentProvider());

		fTableViewer.setSorter(new ViewerSorter() {
			public int compare(Viewer viewer, Object object1, Object object2) {
				if ((object1 instanceof Template) && (object2 instanceof Template)) {
					Template left = (Template) object1;
					Template right = (Template) object2;
					int result = left.getName().compareToIgnoreCase(right.getName());
					if (result != 0)
						return result;
					return left.getDescription().compareToIgnoreCase(right.getDescription());
				}
				return super.compare(viewer, object1, object2);
			}

			public boolean isSorterProperty(Object element, String property) {
				return true;
			}
		});

		fTableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
			public void selectionChanged(SelectionChangedEvent e) {
				updateViewerInput();
			}
		});

		// create viewer that displays currently selected template's contents

		fPatternViewer = doCreateViewer(parent);
		fTemplateStore = GlassmakerUIPlugin.getDefault().getTemplateStore();
		fTableViewer.setInput(fTemplateStore);

		// // Create linked text to just to templates preference page
		// Link link = new Link(parent, SWT.NONE);
		// link.setText("Templates are 'New Card' templates found in the HTML Templates preference page.");
		// data = new GridData(SWT.END, SWT.FILL, true, false, 2, 1);
		// link.setLayoutData(data);
		// link.addSelectionListener(new SelectionAdapter() {
		// public void widgetSelected(SelectionEvent e) {
		// linkClicked();
		// }
		// });

		configureTableResizing(innerParent, table, column1, column2);
		loadLastSavedPreferences();
		Dialog.applyDialogFont(parent);
		setControl(parent);
	}

	/**
	 * Creates, configures and returns a source viewer to present the template
	 * pattern on the preference page. Clients may override to provide a
	 * custom source viewer featuring e.g. syntax coloring.
	 *
	 * @param parent
	 *            the parent control
	 * @return a configured source viewer
	 */
	private SourceViewer createViewer(Composite parent) {
		SourceViewerConfiguration sourceViewerConfiguration = new StructuredTextViewerConfiguration() {
			StructuredTextViewerConfiguration baseConfiguration = new StructuredTextViewerConfigurationHTML();

			public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) {
				return baseConfiguration.getConfiguredContentTypes(sourceViewer);
			}

			public LineStyleProvider[] getLineStyleProviders(ISourceViewer sourceViewer, String partitionType) {
				return baseConfiguration.getLineStyleProviders(sourceViewer, partitionType);
			}
		};
		SourceViewer viewer = new StructuredTextViewer(parent, null, null, false, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
		viewer.getTextWidget().setFont(JFaceResources.getFont("org.eclipse.wst.sse.ui.textfont")); //$NON-NLS-1$
		IStructuredModel scratchModel = StructuredModelManager.getModelManager().createUnManagedStructuredModelFor("org.glassmaker.ui.editor.CardContent");
		IDocument document = scratchModel.getStructuredDocument();
		viewer.configure(sourceViewerConfiguration);
		viewer.setDocument(document);
		return viewer;
	}

	private SourceViewer doCreateViewer(Composite parent) {
		Label label = new Label(parent, SWT.NONE);
		label.setText("Preview");
		GridData data = new GridData();
		data.horizontalSpan = 2;
		label.setLayoutData(data);

		SourceViewer viewer = createViewer(parent);
		viewer.setEditable(false);

		Control control = viewer.getControl();
		data = new GridData(GridData.FILL_BOTH);
		data.horizontalSpan = 1;
		data.verticalSpan=2;
		data.heightHint = convertHeightInCharsToPixels(5);
		// [261274] - source viewer was growing to fit the max line width of the template
		data.widthHint = convertWidthInCharsToPixels(2);
		control.setLayoutData(data);

		fImage=new Label(parent, SWT.NONE);
		fImage.setLayoutData(data);

		return viewer;
	}

	/**
	 * Enable/disable controls in page based on fUseTemplateButton's current
	 * state.
	 */
	void enableTemplates() {
		boolean enabled = fUseTemplateButton.getSelection();

		if (!enabled) {
			// save last selected template
			Template template = getSelectedTemplate();
			if (template != null)
				fLastSelectedTemplateName = template.getName();
			else
				fLastSelectedTemplateName = ""; //$NON-NLS-1$

			fTableViewer.setSelection(null);
		}
		else {
			setSelectedTemplate(fLastSelectedTemplateName);
		}

		fTableViewer.getControl().setEnabled(enabled);
		fPatternViewer.getControl().setEnabled(enabled);
	}

	/**
	 * Return the template preference page id
	 *
	 * @return
	 */
	private String getPreferencePageId() {
		return "org.eclipse.wst.html.ui.preferences.templates"; //$NON-NLS-1$
	}

	/**
	 * Get the currently selected template.
	 *
	 * @return
	 */
	private Template getSelectedTemplate() {
		Template template = null;
		IStructuredSelection selection = (IStructuredSelection) fTableViewer.getSelection();

		if (selection.size() == 1) {
			template = (Template) selection.getFirstElement();
		}
		return template;
	}

	/**
	 * Returns template string to insert.
	 *
	 * @return String to insert or null if none is to be inserted
	 */
	String getTemplateString() {
		String templateString = null;

		Template template = getSelectedTemplate();
		if (template != null) {
			TemplateContextType contextType = GlassmakerUIPlugin.getDefault().getTemplateContextRegistry().getContextType(CardContextType.CONTEXT_TYPE);
			IDocument document = new Document();
			TemplateContext context = new DocumentTemplateContext(contextType, document, 0, 0);
			try {
				TemplateBuffer buffer = context.evaluate(template);
				templateString = buffer.getString();
			}
			catch (Exception e) {
				GlassmakerUIPlugin.logError("Could not create template for new html", e);
			}
		}

		return templateString;
	}

	void linkClicked() {
		String pageId = getPreferencePageId();
		PreferenceDialog dialog = PreferencesUtil.createPreferenceDialogOn(getShell(), pageId, new String[]{pageId}, null);
		dialog.open();
		fTableViewer.refresh();
	}

	/**
	 * Load the last template name used in New HTML File wizard.
	 */
	private void loadLastSavedPreferences() {
		fLastSelectedTemplateName = ""; //$NON-NLS-1$
		boolean setSelection = false;
		String templateName = GlassmakerUIPlugin.getDefault().getPreferenceStore().getString(HTMLUIPreferenceNames.NEW_FILE_TEMPLATE_NAME);
		if (templateName == null || templateName.length() == 0) {
			templateName = GlassmakerUIPlugin.getDefault().getPreferenceStore().getString(HTMLUIPreferenceNames.NEW_FILE_TEMPLATE_ID);
			if (templateName != null && templateName.length() > 0) {
				Template template = fTemplateStore.findTemplateById(templateName);
				if (template != null) {
					fLastSelectedTemplateName = template.getName();
					setSelection = true;
				}
			}
		}
		else {
			fLastSelectedTemplateName = templateName;
			setSelection = true;
		}
		fUseTemplateButton.setSelection(setSelection);
		enableTemplates();
	}

	/**
	 * Save template name used for next call to New HTML File wizard.
	 */
	void saveLastSavedPreferences() {
		String templateName = ""; //$NON-NLS-1$

		Template template = getSelectedTemplate();
		if (template != null) {
			templateName = template.getName();
		}

		GlassmakerUIPlugin.getDefault().getPreferenceStore().setValue("newFileTemplateName", templateName);
		GlassmakerUIPlugin.getDefault().savePluginPreferences();
	}

	/**
	 * Select a template in the table viewer given the template name. If
	 * template name cannot be found or templateName is null, just select
	 * first item in table. If no items in table select nothing.
	 *
	 * @param templateName
	 */
	private void setSelectedTemplate(String templateName) {
		Object template = null;

		if (templateName != null && templateName.length() > 0) {
			// pick the last used template
			template = fTemplateStore.findTemplate(templateName, CardContextType.CONTEXT_TYPE);
		}

		// no record of last used template so just pick first element
		if (template == null) {
			// just pick first element
			template = fTableViewer.getElementAt(0);
		}

		if (template != null) {
			IStructuredSelection selection = new StructuredSelection(template);
			fTableViewer.setSelection(selection, true);
		}
	}

	/**
	 * Updates the pattern viewer.
	 */
	void updateViewerInput() {
		Template template = getSelectedTemplate();
		if (template != null) {
			fPatternViewer.getDocument().set(template.getPattern());
			String imageId = "org.glassmaker.ui.templates."+template.getName().replace(" ", "").toLowerCase();
			ImageDescriptor desc = imageRegistry.getDescriptor(imageId);
			if(desc != null){
				fImage.setImage(desc.createImage());
			}else{
				fImage.setImage(null);
			}

		}
		else {
			fPatternViewer.getDocument().set(""); //$NON-NLS-1$
		}
	}
}


package com.github.mrcritical.ironcache.internal.serializers;

import java.io.IOException;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

/**
 * Serialize a Joda {@link LocalDateTime}.
 *
 * @author pjarrell
 *
 */
public class JodaDateTimeSerializer extends StdSerializer<DateTime> {

	private final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").withZone(
			DateTimeZone.UTC);

	public JodaDateTimeSerializer() {
		super(DateTime.class);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.codehaus.jackson.map.JsonSerializer#serialize(java.lang.Object,
	 * org.codehaus.jackson.JsonGenerator,
	 * org.codehaus.jackson.map.SerializerProvider)
	 */
	@Override
	public void serialize(final DateTime value, final JsonGenerator jgen, final SerializerProvider provider)
			throws IOException, JsonProcessingException {
		jgen.writeString(value.toString(formatter));
	}

}


package org.criteria4jpa.criterion;

import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;

import org.criteria4jpa.Criteria;

/**
 *
 *

 * Factory class for {@link Criterion} instances that can be added
 * to a criteria by calling {@link Criteria#add(Criterion)}.
 *

 *
 *

 * Note that most path expressions are relative, meaning that they
 * are rooted at the entity of the criteria they are added to. In this
 * cases there is no need to add any kind of alias to the
 * path expression because this is already done by the framework.
 *

 *
 * @author Christian Kaltepoth
 *
 */
public class Restrictions {

  /**
   * Private constructor. No instance creation possible.
   */
  private Restrictions() {
  }

  /**
   * Adds an "equal" constraint to a persistent field or a
   * single-valued relationship field.
   *
   * @param relativePath relative path of the field
   * @param value The value to check equality against.
   * @return {@link Criterion} instance
   */
  public static SimpleExpression eq(String relativePath, Object value) {
    return new SimpleExpression(relativePath, value, "=");
  }

  /**
   * Adds a "not equal" constraint to a persistent field or a
   * single-valued relationship field.
   *
   * @param relativePath relative path of the field
   * @param value The value to check equality against.
   * @return {@link Criterion} instance
   */
  public static SimpleExpression ne(String relativePath, Object value) {
    return new SimpleExpression(relativePath, value, "<>");
  }

  /**
   * Adds a "like" constraint to a persistent field. This method
   * expects the value to already contain the required wildcard characters.
   * Alternatively you can call {@link #like(String, String, MatchMode)}
   * to let the restriction add the wildcards.
   *
   * @param relativePath relative path of the field
   * @param value the match string
   * @return {@link Criterion} instance
   */
  public static SimpleExpression like(String relativePath, String value) {
    return new SimpleExpression(relativePath, value, "LIKE");
  }

  /**
   * Adds a "like" constraint to a persistent field. This method
   * requires a {@link MatchMode} to specify how wildcards are added
   * to the value. You may also use {@link #like(String, String)} if you
   * want to manually specify the wildcards in the match string.
   *
   * @param relativePath relative path of the field
   * @param value the match string
   * @param matchMode specifies how to add wildcards to the value to create
   *   the LIKE expression
   * @return {@link Criterion} instance
   */
  public static SimpleExpression like(String relativePath, String value, MatchMode matchMode) {
    return new SimpleExpression(relativePath, matchMode.toMatchString(value), "LIKE" );
  }

  /**
   * Adds a case-insensitive "like" constraint to a persistent field.
   * This method expects the value to already contain the required wildcard characters.
   * Alternatively you can call {@link #ilike(String, String, MatchMode)}
   * to let the restriction add the wildcards.
   *
   * @param relativePath relative path of the string field
   * @param value the match string
   * @return {@link Criterion} instance
   */
  public static Criterion ilike(String relativePath, String value) {
    return new ILikeExpression(relativePath, value);
  }

  /**
   * Adds a case-insensitive "like" constraint to a persistent field.
   * This method requires a {@link MatchMode} to specify how wildcards are added
   * to the value. You may also use {@link #like(String, String)} if you
   * want to manually specify the wildcards in the match string.
   *
   * @param relativePath relative path of the string field
   * @param value the match string
   * @param matchMode specifies how to add wildcards to the value to create
   *   the LIKE expression
   * @return {@link Criterion} instance
   */
  public static Criterion ilike(String relativePath, String value, MatchMode matchMode) {
    return new ILikeExpression(relativePath, matchMode.toMatchString(value));
  }

  /**
   * Adds a "greater than" constraint to a persistent field.
   *
   * @param relativePath relative path of the field
   * @param value The value to check against.
   * @return {@link Criterion} instance
   */
  public static SimpleExpression gt(String relativePath, Object value) {
    return new SimpleExpression(relativePath, value, ">");
  }

  /**
   * Adds a "less than" constraint to a persistent field.
   *
   * @param relativePath relative path of the field
   * @param value The value to check against.
   * @return {@link Criterion} instance
   */
  public static SimpleExpression lt(String relativePath, Object value) {
    return new SimpleExpression(relativePath, value, "<");
  }

  /**
   * Adds a "less than or equal" constraint to a persistent field.
   *
   * @param relativePath relative path of the field
   * @param value The value to check against.
   * @return {@link Criterion} instance
   */
  public static SimpleExpression le(String relativePath, Object value) {
    return new SimpleExpression(relativePath, value, "<=");
  }

  /**
   * Adds a "greater than or equal" constraint to a persistent field.
   *
   * @param relativePath relative path of the field
   * @param value The value to check against.
   * @return {@link Criterion} instance
   */
  public static SimpleExpression ge(String relativePath, Object value) {
    return new SimpleExpression(relativePath, value, ">=");
  }

  /**
   * Adds a "between" constraint to a persistent field.
   *
   * @param relativePath relative path of the field
   * @param lo the low end of the "between" expression
   * @param hi the high end of the "between" expression
   * @return {@link Criterion} instance
   */
  public static Criterion between(String relativePath, Object lo, Object hi) {
    return new BetweenExpression(relativePath, lo, hi, false);
  }

  /**
   * Adds a "not between" constraint to a persistent field.
   *
   * @param relativePath relative path of the field
   * @param lo the low end of the "not between" expression
   * @param hi the high end of the "not between" expression
   * @return {@link Criterion} instance
   */
  public static Criterion notBetween(String relativePath, Object lo, Object hi) {
    return new BetweenExpression(relativePath, lo, hi, true);
  }

  /**
   * Adds a "is null" constraint to a persistent field or a
   * single-valued relationship field.
   *
   * @param relativePath relative path of the field
   * @return {@link Criterion} instance
   */
  public static Criterion isNull(String relativePath) {
    return new IsNullExpression(relativePath, false);
  }

  /**
   * Adds a "is not null" constraint to a persistent field or a
   * single-valued relationship field.
   *
   * @param relativePath relative path of the field
   * @return {@link Criterion} instance
   */
  public static Criterion isNotNull(String relativePath) {
    return new IsNullExpression(relativePath, true);
  }

  /**
   * Creates a group for multiple restrictions that are connected by a
   * conjunction. The group generates multiple expressions joined
   * by a logical AND. You can add restrictions to the group by calling
   * {@link Conjunction#add(Criterion)} on the returned object.
   * As the {@link Conjunction} itself is a restriction, it can be added
   * to a criteria instance via {@link Criteria#add(Criterion)}.
   *
   * @return {@link Conjunction} instance
   */
  public static Conjunction conjunction() {
    return new Conjunction();
  }

  /**
   * Creates a group for multiple restrictions that are connected by a
   * disjunction. The group generates multiple expressions joined
   * by a logical OR. You can add restrictions to the group by calling
   * {@link Disjunction#add(Criterion)} on the returned object.
   * As the {@link Disjunction} itself is a restriction, it can be added
   * to a criteria instance via {@link Criteria#add(Criterion)}.
   *
   * @return {@link Disjunction} instance
   */
  public static Disjunction disjunction() {
    return new Disjunction();
  }

  /**
   * Adds a "is empty" constraint to a collection-valued relationship field.
   *
   * @param relativePath relative path of the collection
   * @return {@link Criterion} instance
   */
  public static Criterion isEmpty(String relativePath) {
    return new IsEmptyExpression(relativePath, false);
  }

  /**
   * Adds a "is not empty" constraint to a collection-valued relationship field.
   *
   * @param relativePath relative path of the collection
   * @return {@link Criterion} instance
   */
  public static Criterion isNotEmpty(String relativePath) {
    return new IsEmptyExpression(relativePath, true);
  }

  /**
   * Creates a "not" restriction. Creates a negated version of the
   * supplied restriction.
   *
   * @param criterion Restriction to negate
   * @return {@link Criterion} instance
   */
  public static Criterion not(Criterion criterion) {
    return new NotExpression(criterion);
  }

  /**
   * Connects multiple restrictions with an logical conjunction.
   * Calling this method is a shortcut for creating a {@link Conjunction}
   * by calling {@link #conjunction()} and adding all restrictions
   * to it.
   *
   * @param criterionList The restrictions to add to the conjunction.
   * @return {@link Conjunction} instance
   */
  public static Conjunction and(Criterion... criterionList) {
    Conjunction junction = new Conjunction();
    for( Criterion criterion : criterionList ) {
      junction.add( criterion );
    }
    return junction;
  }

  /**
   * Connects multiple restrictions with an logical disjunction.
   * Calling this method is a shortcut for creating a {@link Disjunction}
   * by calling {@link #disjunction()} and adding all restrictions
   * to it.
   *
   * @param criterionList The restrictions to add to the disjunction.
   * @return {@link Disjunction} instance
   */
  public static Disjunction or(Criterion... criterionList) {
    Disjunction junction = new Disjunction();
    for( Criterion criterion : criterionList ) {
      junction.add( criterion );
    }
    return junction;
  }

  /**
   * Adds an "in" restriction to a persistent field.
   *
   * @param relativePath relative path of the persistent field
   * @param values expected values of the field
   * @return {@link Criterion} instance
   */
  public static Criterion in(String relativePath, Object[] values) {
    return new InExpression(relativePath, values);
  }

  /**
   * Adds an "in" restriction to a persistent field.
   *
   * @param relativePath relative path of the persistent field
   * @param values expected values of the field
   * @return {@link Criterion} instance
   */
  public static Criterion in(String relativePath, Collection<?> values) {
    return new InExpression(relativePath, values.toArray());
  }

  /**
   *

   * Creates a conjunction of "equals" restrictions for each
   * entry in the map.
   *

   *
   *

   * Same as manually creating a conjunction via {@link #conjunction()}
   * and adding an equals restriction via {@link #eq(String, Object)} for
   * each map entry.
   *

   *
   * @param values Map containing property name to value mappings
   * @return {@link Conjunction} of "equal" constraints
   */
  public static Criterion allEq(Map<String,Object> values) {
    Conjunction conjunction = new Conjunction();
    for( Entry<String, Object> entry : values.entrySet() ) {
      conjunction.add( eq(entry.getKey(), entry.getValue()) );
    }
    return conjunction;
  }

  /**
   *

   * This method allows to create a restriction from a custom
   * JPQL query fragment.
   *

   *
   *

   * You may use the following set of variables in the query.
   * They will be replaced by the correct values when the query
   * is generated.
   *

   *
   *

   *

   *     {alias}: The alias of the criteria's entity that the
   *       restriction is added to.
   *

   *

   *     {1}, {2}, {3}...:
   *       The positional parameters that are generated for the supplied
   *       parameter values.
   *

   *

   *
   *
Example:

   *
   *

   * Restrictions.jpqlRestriction(
   *   "{alias}.firstname LIKE {1} AND {alias}.age BETWEEN {2} AND {3}", "Chr%", 40, 80)
   *

   *
   * @param jpql The JPQL query fragment
   * @param value The parameters to add to the generated query
   * @return new {@link Criterion} instance
   */
  public static Criterion jpqlRestriction(String jpql, Object... value) {
    return new JPQLExpression(jpql, value );
  }

  /**
   * Creates a "member of" restriction.
   *
   * @param relativePath relative path of a collection
   * @param value The value to check membership for
   * @return new {@link Criterion} instance
   */
  public static Criterion memberOf(String relativePath, Object value) {
    return new MemberOfExpression(relativePath, value, false);
  }

  /**
   * Creates a "not member of" restriction.
   *
   * @param relativePath relative path of a collection
   * @param value The value to check membership for
   * @return new {@link Criterion} instance
   */
  public static Criterion notMemberOf(String relativePath, Object value) {
    return new MemberOfExpression(relativePath, value, true);
  }

}


package org.criteria4jpa.projection;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.criteria4jpa.Criteria;
import org.criteria4jpa.impl.CriteriaQueryBuilder;

/**
 *
 * Simple class for <i>projection lists</i> that wrap other projections.
 * It is recommended to use the static factory methods
 * of {@link Projections} to created instances of this class.
 *
 * @see Projections
 *
 * @author Christian Kaltepoth
 *
 */
public class ProjectionList implements Projection {

  private List<Projection> projectionList = new ArrayList<Projection>();

  /**
   * empty default constructor
   */
  public ProjectionList() {
    // empty
  }

  /*
   * @see org.criteria4jpa.projection.Projection#toQueryString(org.criteria4jpa.Criteria, org.criteria4jpa.impl.CriteriaQueryBuilder)
   */
  public String toQueryString(Criteria criteria, CriteriaQueryBuilder queryBuilder) {

    // check whether list is empty
    if( projectionList.isEmpty() ) {
      throw new IllegalStateException("A projection list must have at least one child.");
    }

    // query builder
    StringBuilder builder = new StringBuilder();

    // iterate over all projections from the list
    Iterator<Projection> iter = projectionList.iterator();
    while( iter.hasNext() ) {
      Projection projection = iter.next();

      // call toQueryString() on child
      builder.append( projection.toQueryString(criteria, queryBuilder) );

      // append comma if more projections follow
      if(iter.hasNext()) {
        builder.append(",");
      }
    }

    // return result
    return builder.toString();
  }

  /*
   * @see org.criteria4jpa.projection.Projection#toGroupByString(org.criteria4jpa.Criteria, org.criteria4jpa.impl.CriteriaQueryBuilder)
   */
  public String toGroupByString(Criteria criteria, CriteriaQueryBuilder queryBuilder) {

    // query builder
    StringBuilder builder = new StringBuilder();

    // iterate over all projections from the list
    Iterator<Projection> iter = projectionList.iterator();
    while( iter.hasNext() ) {
      Projection projection = iter.next();

      // call toGroupByString() on child
      String groupBy = projection.toGroupByString(criteria, queryBuilder);

      // add only if result is not null
      if(groupBy != null && groupBy.trim().length() > 0) {

        // first add a comma if the builder already contains something
        if(builder.length() > 0) {
          builder.append(",");
        }

        // add group by expression of child
        builder.append(groupBy);

      }

    }

    // return result if something has been written to the builder
    String result = builder.toString().trim();
    if(result.length() > 0) {
      return result;
    }

    return null;
  }

  /**
   * Adds another projection to the list of wrapped projections.
   *
   * @param projection projection to wrap
   * @return this (builder pattern)
   */
  public ProjectionList add(Projection projection) {
    projectionList.add( projection );
    return this;
  }

}


/*******************************************************************************
 * <copyright>
 *
 * Copyright (c) 2014 Eteration A.S.
 * All rights reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *     Unless required by applicable law or agreed to in writing, software
 *     distributed under the License is distributed on an "AS IS" BASIS,
 *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *     See the License for the specific language governing permissions and
 *     limitations under the License.
 *
 *
 *     Derivative Works
 *     Parts of this program are derived from content from Eclipse Foundation
 *     that are made available under the terms of the Eclipse Public License v1.0.
 *      http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Naci Dai, Eteration A.S. - initial API, implementation and documentation
 *
 * </copyright>
 *
 *******************************************************************************/
package org.glassmaker.ui.editor.preferences;

import org.eclipse.jface.preference.*;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.IWorkbench;
import org.glassmaker.ui.GlassmakerUIPlugin;

public class LoginPreferencePage
	extends FieldEditorPreferencePage
	implements IWorkbenchPreferencePage {

	public LoginPreferencePage() {
		super(GRID);
		setPreferenceStore(GlassmakerUIPlugin.getDefault().getPreferenceStore());
		setDescription("Glassmaker preferences");
	}

	/**
	 * Creates the field editors. Field editors are abstractions of
	 * the common GUI blocks needed to manipulate various types
	 * of preferences. Each field editor knows how to save and
	 * restore itself.
	 */
	public void createFieldEditors() {
		addField(new StringFieldEditor(PreferenceConstants.CLIENT_ID, "Google API Client Id:", getFieldEditorParent()));
		addField(new StringFieldEditor(PreferenceConstants.CLIENT_SECRET, "Google API Client Secret:", getFieldEditorParent()));
	}

	/* (non-Javadoc)
	 * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
	 */
	public void init(IWorkbench workbench) {
	}

}


package org.criteria4jpa.projection;

import org.criteria4jpa.Criteria;
import org.criteria4jpa.impl.CriteriaQueryBuilder;

/**
 *
 * Simple class for all projections that refer to a persistent field
 * or a single-valued relationship field using a path expression.
 * It is recommended to use the static factory methods
 * of {@link Projections} to created instances of this class.
 *
 * @see Projections
 *
 * @author Christian Kaltepoth
 *
 */
public class PathProjection implements Projection {

  private final String path;
  private final boolean absolute;
  private final boolean grouped;

  /**
   * Creates a new instance of a path projection.
   *
   * @param path relative or absolute path of the field
   * @param absolute true if path is an absolute path,
   *    false if path is relative
   */
  public PathProjection(String path, boolean absolute, boolean grouped) {
    this.path = path;
    this.absolute = absolute;
    this.grouped = grouped;
  }

  /*
   * @see org.criteria4jpa.projection.Projection#toQueryString(org.criteria4jpa.Criteria, org.criteria4jpa.impl.CriteriaQueryBuilder)
   */
  public String toQueryString(Criteria criteria, CriteriaQueryBuilder queryBuilder) {
    if(absolute) {
      return path;
    } else {
      return queryBuilder.getAbsolutePath(criteria, path);
    }
  }

  /*
   * @see org.criteria4jpa.projection.Projection#toGroupByString(org.criteria4jpa.Criteria, org.criteria4jpa.impl.CriteriaQueryBuilder)
   */
  public String toGroupByString(Criteria criteria, CriteriaQueryBuilder queryBuilder) {
    if(grouped) {
      if(absolute) {
        return path;
      } else {
        return queryBuilder.getAbsolutePath(criteria, path);
      }
    }
    return null;
  }

}


package org.criteria4jpa.criterion;

import org.criteria4jpa.Criteria;
import org.criteria4jpa.impl.CriteriaQueryBuilder;

/**
 *
 * Class representing a "(not) member of" restriction.
 * It is recommended to use the static factory methods of
 * {@link Restrictions} to created instances of this class.
 *
 * @see Restrictions#memberOf(String, Object)
 * @see Restrictions#notMemberOf(String, Object)
 *
 * @author Christian Kaltepoth
 *
 */
public class MemberOfExpression implements Criterion {

  private final String relativePath;
  private final Object value;
  private final boolean negate;

  /**
   * Creates a "(not) member of" expression
   *
   * @param relativePath relative path of a collection.
   * @param value The value to check membership in the collection for
   * @param negate create negated version of restriction
   */
  public MemberOfExpression(String relativePath, Object value, boolean negate) {
    this.relativePath = relativePath;
    this.value = value;
    this.negate = negate;
  }

  /*
   * @see org.criteria4jpa.criterion.Criterion#toQueryString(org.criteria4jpa.Criteria, org.criteria4jpa.impl.CriteriaQueryBuilder)
   */
  public String toQueryString(Criteria criteria, CriteriaQueryBuilder queryBuilder) {
    StringBuilder builder = new StringBuilder();
    builder.append( queryBuilder.createPositionalParameter() );
    if( negate ) {
      builder.append(" NOT");
    }
    builder.append( " MEMBER OF " );
    builder.append( queryBuilder.getAbsolutePath(criteria, relativePath) );
    return builder.toString();
  }

  /*
   * @see org.criteria4jpa.criterion.Criterion#getParameterValues()
   */
  public Object[] getParameterValues() {
    return new Object[] { value };
  }

}


package org.criteria4jpa.util;

import java.util.Locale;

/**
 *
 * Small helper class
 *
 * @author Christian Kaltepoth
 *
 */
public class StringUtils {

  /**
   * Method to create unique aliases for JPA identifiers. Each alias
   * consists of two parts. The basename should be a human
   * readable string that helps to identify which entity is referred.
   * The counter is unique number that is added to the
   * alias to make the alias unique. It is recommended to use each
   * counter value one once independently from the basename used.
   *
   * @param basename a base name that will be used for alias creation
   * @param counter A unique number
   * @param fallback An optional fallback name
   * @return the generated JPQL alias
   */
  public static String generateAlias(String basename, int counter, String fallback) {

    // build trimmed and lower case version of the base name
    String lowerCaseBaseName = basename.trim().toLowerCase(Locale.ENGLISH);

    // use only simple characters for the alias
    StringBuilder builder = new StringBuilder();
    for( char c : lowerCaseBaseName.toCharArray() ) {
      if( c >= 'a' && c <= 'z' ) {
        builder.append( c );
      }
    }

    // add some default keyword, if builder is still empty
    if( builder.length() == 0 ) {
      if(fallback != null && fallback.length() > 0) {
        builder.append( fallback );
      } else {
        builder.append( "default" );
      }
    }

    // finally append the counter to get uniqueness
    builder.append( counter );

    // return the result
    return builder.toString();
  }

  /**
   * Returns the last component of a dot-separated path.
   *
   * @param path relative or absolute path expression
   * @return last component of path expression
   */
  public static String getLastPathComponent(String path) {

    // find last '.' character
    int pos = path.lastIndexOf('.');

    // return the last path component
    // or the complete path, if no '.' chars were found
    return pos >= 0 ? path.substring(pos + 1) : path;
  }

}


package org.criteria4jpa.projection;

import org.criteria4jpa.Criteria;
import org.criteria4jpa.impl.CriteriaQueryBuilder;

/**
 *
 * Class representing a constructor projection. It is recommended to use the
 * static factory methods of {@link Projections} to created instances of this
 * class.
 *
 * @author Christian Kaltepoth
 *
 * @since 0.3
 *
 */
public class ConstructorProjection implements Projection {

  /**
   * The type to create the constructor projection for
   */
  private final Class<?> clazz;

  /**
   * The child projection
   */
  private final ProjectionList projectionList = new ProjectionList();

  /**
   * creates a new constructor projection for a wrapped projection.
   *
   * @param clazz type of the constructor projection
   */
  public ConstructorProjection(Class<?> clazz) {
    this.clazz = clazz;
  }

  /*
   * @see org.criteria4jpa.projection.Projection#toQueryString(org.criteria4jpa.Criteria, org.criteria4jpa.impl.CriteriaQueryBuilder)
   */
  public String toQueryString(Criteria criteria, CriteriaQueryBuilder queryBuilder) {

    StringBuilder builder = new StringBuilder();
    builder.append( "NEW " );
    builder.append( clazz.getName() );
    builder.append( '(' );
    builder.append( projectionList.toQueryString(criteria, queryBuilder) );
    builder.append( ')' );
    return builder.toString();

  }

  /*
   * @see org.criteria4jpa.projection.Projection#toGroupByString(org.criteria4jpa.Criteria, org.criteria4jpa.impl.CriteriaQueryBuilder)
   */
  public String toGroupByString(Criteria criteria, CriteriaQueryBuilder queryBuilder) {
    return projectionList.toGroupByString(criteria, queryBuilder);
  }

  /**
   * Adds another projection to the list of projections for this constructor
   * projection.
   *
   * @param projection
   *          The projection to add
   * @return this (builder pattern)
   */
  public ConstructorProjection add(Projection projection) {
    projectionList.add( projection );
    return this;
  }

}


/*******************************************************************************
 * <copyright>
 *
 * Copyright (c) 2014 Eteration A.S.
 * All rights reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *     Unless required by applicable law or agreed to in writing, software
 *     distributed under the License is distributed on an "AS IS" BASIS,
 *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *     See the License for the specific language governing permissions and
 *     limitations under the License.
 *
 *
 *     Derivative Works
 *     Parts of this program are derived from content from Eclipse Foundation
 *     that are made available under the terms of the Eclipse Public License v1.0.
 *      http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Naci Dai, Eteration A.S. - initial API, implementation and documentation
 *
 * </copyright>
 *
 *******************************************************************************/
package org.glassmaker.ui.editor.wizards;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.content.IContentType;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.dialogs.WizardNewFileCreationPage;

public class NewCardFileWizardPage extends WizardNewFileCreationPage {

	private static final String defaultName = "NewFile"; //$NON-NLS-1$
	private IContentType fContentType;

	public NewCardFileWizardPage(String pageName, IStructuredSelection selection) {
		super(pageName, selection);
	}

	public void createControl(Composite parent) {
		// inherit default container and name specification widgets
		super.createControl(parent);
		setFileName(computeDefaultFileName());
		setPageComplete(validatePage());
	}

	protected String computeDefaultFileName() {
		int count = 0;
		String fileName = addDefaultExtension(defaultName);
		IPath containerFullPath = getContainerFullPath();
		if (containerFullPath != null) {
			while (true) {
				IPath path = containerFullPath.append(fileName);
				if (ResourcesPlugin.getWorkspace().getRoot().exists(path)) {
					count++;
					fileName = addDefaultExtension(defaultName + count);
				} else {
					break;
				}
			}
		}
		return fileName;
	}

	/**
	 * This method is overridden to set the selected folder to web contents
	 * folder if the current selection is outside the web contents folder.
	 */
	protected void initialPopulateContainerNameField() {
		super.initialPopulateContainerNameField();

		IPath fullPath = getContainerFullPath();
		IProject project = getProjectFromPath(fullPath);
		IPath root = ProjectUtils.getRootContainerForPath(project, fullPath);
		if (root != null) {
			return;
		}
		root = ProjectUtils.getDefaultRootContainer(project);
		if (root != null) {
			setContainerFullPath(root);
			return;
		}
	}

	/**
	 * This method is overridden to set additional validation specific to html
	 * files.
	 */
	protected boolean validatePage() {
		setMessage(null);
		setErrorMessage(null);

		if (!super.validatePage()) {
			return false;
		}

		String fileName = getFileName();
		IPath fullPath = getContainerFullPath();
		if ((fullPath != null) && (fullPath.isEmpty() == false) && (fileName != null)) {
			// check that filename does not contain invalid extension
			if (!extensionValidForContentType(fileName)) {
				setErrorMessage("Filename must end with .card");
				return false;
			}
			// no file extension specified so check adding default
			// extension doesn't equal a file that already exists
			if (fileName.lastIndexOf('.') == -1) {
				String newFileName = addDefaultExtension(fileName);
				IPath resourcePath = fullPath.append(newFileName);

				IWorkspace workspace = ResourcesPlugin.getWorkspace();
				IStatus result = workspace.validatePath(resourcePath.toString(), IResource.FOLDER);
				if (!result.isOK()) {
					// path invalid
					setErrorMessage(result.getMessage());
					return false;
				}

				if ((workspace.getRoot().getFolder(resourcePath).exists() || workspace.getRoot().getFile(resourcePath).exists())) {
					setErrorMessage("There is a card with that name");
					return false;
				}
			}

			// get the IProject for the selection path
			IProject project = getProjectFromPath(fullPath);
			// if inside web project, check if inside webContent folder
			if (project != null && isWebProject(project)) {
				// check that the path is inside the webContent folder
				IPath[] webContentPaths = ProjectUtils.getAcceptableRootPaths(project);
				boolean isPrefix = false;
				for (int i = 0; !isPrefix && i < webContentPaths.length; i++) {
					isPrefix |= webContentPaths[i].isPrefixOf(fullPath);
				}
				if (!isPrefix) {
					setMessage("Cards must be inside the web contents", WARNING);
				}
			}
		}

		return true;
	}

	/**
	 * Get content type associated with this new file wizard
	 *
	 * @return IContentType
	 */
	private IContentType getContentType() {
		if (fContentType == null)
			fContentType = Platform.getContentTypeManager().getContentType("org.glassmaker.ui.editor.CardContent");
		return fContentType;
	}

	/**
	 * Verifies if fileName is valid name for content type. Takes base content
	 * type into consideration.
	 *
	 * @param fileName
	 * @return true if extension is valid for this content type
	 */
	private boolean extensionValidForContentType(String fileName) {
		boolean valid = false;

		IContentType type = getContentType();
		// there is currently an extension
		if (fileName.lastIndexOf('.') != -1) {
			// check what content types are associated with current extension
			IContentType[] types = Platform.getContentTypeManager().findContentTypesFor(fileName);
			int i = 0;
			while (i < types.length && !valid) {
				valid = types[i].isKindOf(type);
				++i;
			}
		} else
			valid = true; // no extension so valid
		return valid;
	}

	/**
	 * Adds default extension to the filename
	 *
	 * @param filename
	 * @return
	 */
	String addDefaultExtension(String filename) {
		StringBuffer newFileName = new StringBuffer(filename);

		String ext = "card";

		newFileName.append("."); //$NON-NLS-1$
		newFileName.append(ext);

		return newFileName.toString();
	}

	/**
	 * Returns the project that contains the specified path
	 *
	 * @param path
	 *            the path which project is needed
	 * @return IProject object. If path is null the return value is
	 *         also null.
	 */
	private IProject getProjectFromPath(IPath path) {
		IWorkspace workspace = ResourcesPlugin.getWorkspace();
		IProject project = null;

		if (path != null) {
			if (workspace.validatePath(path.toString(), IResource.PROJECT).isOK()) {
				project = workspace.getRoot().getProject(path.toString());
			} else {
				project = workspace.getRoot().getFile(path).getProject();
			}
		}

		return project;
	}

	/**
	 * Checks if the specified project is a web project.
	 *
	 * @param project
	 *            project to be checked
	 * @return true if the project is web project, otherwise false
	 */
	private boolean isWebProject(IProject project) {
		return ProjectUtils.isWebProject(project);
	}

}


package org.criteria4jpa;

import javax.persistence.Entity;
import javax.persistence.EntityManager;

import org.criteria4jpa.criterion.Criterion;
import org.criteria4jpa.impl.CriteriaImpl;
import org.criteria4jpa.order.Order;
import org.criteria4jpa.projection.Projection;

/**
 *
 * Utility class to create new {@link Criteria} instances.
 *
 * @author Christian Kaltepoth
 *
 */
public class CriteriaUtils {

  /**
   *

   * Creates a new {@link Criteria} query for a entity class.
   *

   *
   *

   * Please note that the entity name is deduced from the unqualified class name.
   * You should use {@link #createCriteria(EntityManager, String)}
   * if you have changed the entity name by using the name attribute
   * of the {@link Entity} annotation.
   *

   *
   * @param entityManager {@link EntityManager} for query creation
   * @param persistentClass persistent class
   * @return new {@link Criteria} query
   */
  public static Criteria createCriteria(EntityManager entityManager,
      Class<?> persistentClass) {
    errorIfClosed(entityManager);
    return new CriteriaImpl( entityManager, persistentClass.getSimpleName() );
  }

  /**
   *

   * Creates a new {@link Criteria} query for a named entity.
   *

   *
   * @param entityManager {@link EntityManager} for query creation
   * @param entityName name of the entity
   * @return new {@link Criteria} query
   */
  public static Criteria createCriteria(EntityManager entityManager,
      String entityName) {
    errorIfClosed(entityManager);
    return new CriteriaImpl( entityManager, entityName );
  }

  /**
   *

   * Creates a new {@link Criteria} query for a entity class. Sets the
   * specified alias for the root entity. You may later use this alias to
   * refer to the  entity in {@link Criterion}, {@link Projection} and
   * {@link Order} instances.
   *

   *
   *

   * Please note that the entity name is deduced from the unqualified class name.
   * You should use {@link #createCriteria(EntityManager, Class, String)}
   * if you have changed the entity name by using the name attribute
   * of the {@link Entity} annotation.
   *

   *
   * @param entityManager {@link EntityManager} for query creation
   * @param persistentClass persistent class
   * @param alias alias to set for the criteria
   * @return new {@link Criteria} query
   */
  public static Criteria createCriteria(EntityManager entityManager,
      Class<?> persistentClass, String alias) {
    return new CriteriaImpl( entityManager, persistentClass.getSimpleName(), alias);
  }

  /**
   *

   * Creates a new {@link Criteria} query for a named entity. Sets the
   * specified alias for the root entity. You may later use this alias to
   * refer to the  entity in {@link Criterion}, {@link Projection} and
   * {@link Order} instances.
   *

   *
   * @param entityManager {@link EntityManager} for query creation
   * @param entityName name of the entity
   * @return new {@link Criteria} query
   */
  public static Criteria createCriteria(EntityManager entityManager,
      String entityName, String alias) {
    errorIfClosed(entityManager);
    return new CriteriaImpl( entityManager, entityName, alias);
  }

  /**
   *

   * Check if the specified {@link EntityManager} is still open.
   *

   */
  private static void errorIfClosed(EntityManager entityManager) {
    if(!entityManager.isOpen()) {
      throw new IllegalArgumentException("EntityManager not open!");
    }
  }
}


package org.criteria4jpa.criterion;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.criteria4jpa.Criteria;
import org.criteria4jpa.impl.CriteriaQueryBuilder;

/**
 *
 * Base class for {@link Conjunction} and {@link Disjunction}
 *
 * @author Christian Kaltepoth
 *
 */
public class Junction implements Criterion {

  private final String op;
  private List<Criterion> criterionList = new ArrayList<Criterion>();

  /**
   * Creates the {@link Junction} using the specified operator
   * @param op AND or OR operator
   */
  public Junction(String op) {
    this.op = op;
  }

  /**
   * Add a new child to this junction. All children will be joined
   * using the operator if this junction instance.
   *
   * @param criterion the criterion to add as a child to the junction
   * @return this (builder pattern)
   */
  public Junction add(Criterion criterion) {
    this.criterionList.add( criterion );
    return this;
  }

  /*
   * @see org.criteria4jpa.criterion.Criterion#toQueryString(org.criteria4jpa.Criteria, org.criteria4jpa.impl.CriteriaQueryBuilder)
   */
  public String toQueryString(Criteria criteria, CriteriaQueryBuilder queryBuilder) {

    // fallback for empty criteria list
    if( criterionList.isEmpty() ) {
      return "1=1";
    }

    // build junction
    StringBuilder builder = new StringBuilder();
    builder.append("(");

    Iterator<Criterion> critIter = criterionList.iterator();
    while( critIter.hasNext() ) {

      // add JPQL string
      builder.append( critIter.next().toQueryString(criteria, queryBuilder) );

      // add op if more entries follow
      if( critIter.hasNext() ) {
        builder.append(' ').append(op).append(' ');
      }

    }

    builder.append(")");
    return builder.toString();

  }

  /*
   * @see org.criteria4jpa.criterion.Criterion#getParameterValues()
   */
  public Object[] getParameterValues() {
    ArrayList<Object> values = new ArrayList<Object>();

    // process all criteria from criterionList
    for(Criterion criterion : criterionList) {

      // add all values from this criterion to result list
      for( Object value : criterion.getParameterValues()) {
        values.add(value);
      }

    }
    return values.toArray();
  }

}


/*******************************************************************************
 * <copyright>
 *
 * Copyright (c) 2014 Eteration A.S.
 * All rights reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *     Unless required by applicable law or agreed to in writing, software
 *     distributed under the License is distributed on an "AS IS" BASIS,
 *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *     See the License for the specific language governing permissions and
 *     limitations under the License.
 *
 * Contributors:
 *    Naci Dai, Eteration A.S. - initial API, implementation and documentation
 *
 * </copyright>
 *
 *******************************************************************************/
package org.glassmaker.spring.oauth;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.stereotype.Component;

import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;
import com.google.api.client.auth.oauth2.AuthorizationCodeTokenRequest;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.auth.oauth2.StoredCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.DataStore;
import com.google.api.client.util.store.MemoryDataStoreFactory;

@Component("oAuth2Util")
public class OAuth2Util {
	private static final Log logger = LogFactory.getLog(OAuth2EntryPoint.class);

	private DataStore<StoredCredential> inmemoryDatastore;

	@Value("${client_id}")
	private String clientId;
	@Value("${client_secret}")
	private String clientSecret;
	@Value("${oauthscope}")
	private String scope;
	@Value("${accesstype}")
	private String accessType;
	@Value("${callback}")
	private String callback;

	/**
	 * Creates and returns a new {@link AuthorizationCodeFlow} for this app.
	 */
	public AuthorizationCodeFlow newAuthorizationCodeFlow() throws IOException {

		return new GoogleAuthorizationCodeFlow.Builder(new NetHttpTransport(), new JacksonFactory(), clientId, clientSecret, Collections.singleton(scope)).setAccessType(accessType).setCredentialDataStore(getInMemoryDatastore()).build();
	}

	public AuthorizationCodeTokenRequest newTokenRequest(AuthorizationCodeFlow flow, String code) throws IOException {
		AuthorizationCodeTokenRequest tr = flow.newTokenRequest(code).setRedirectUri(callback);
		return tr;
	}

	/**
	 * Get the current user's ID from the session
	 *
	 * @return string user id or null if no one is logged in
	 */
	public String getUserId(HttpServletRequest request) {
		HttpSession session = request.getSession();
		return (String) session.getAttribute("userId");
	}

	public void setUserId(HttpServletRequest request, String userId) {
		HttpSession session = request.getSession();
		session.setAttribute("userId", userId);
	}

	public void clearUserId(HttpServletRequest request) throws IOException {
		// Delete the credential in the credential store
		String userId = getUserId(request);
		inmemoryDatastore.delete(userId);
		// Remove their ID from the local session
		request.getSession().removeAttribute("userId");
	}

	public Credential getCredential(String userId) throws IOException {
		if (userId == null) {
			return null;
		} else {
			return newAuthorizationCodeFlow().loadCredential(userId);
		}
	}

	public Credential getCredential(HttpServletRequest req) throws IOException {
		return newAuthorizationCodeFlow().loadCredential(getUserId(req));
	}

	public List<String> getAllUserIds() throws IOException {
		List<String> allUsers = new ArrayList<String>();
		for (String user : inmemoryDatastore.keySet()) {
			allUsers.add(user);
		}
		return allUsers;
	}

	public DataStore<StoredCredential> getInMemoryDatastore() {
		if (inmemoryDatastore == null) {
			try {
				inmemoryDatastore = MemoryDataStoreFactory.getDefaultInstance().getDataStore("ListableMemoryCredentialStore");
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
		}
		return inmemoryDatastore;
	}

	public boolean requiresAuthentication(HttpServletRequest request) {

		HttpSession session = request.getSession();
		if (session != null) {
			SecurityContext securityContext = (SecurityContext) session.getAttribute("SPRING_SECURITY_CONTEXT");
			if (securityContext != null) {
				Authentication auth = securityContext.getAuthentication();
				if (auth != null && auth.isAuthenticated())
					return false;
			}
		}

		String code = request.getParameter("code");
		// If we have a code, finish the OAuth 2.0 dance
		if (code == null) {
			return true;
		}
		return false;
	}
}


/*******************************************************************************
 * <copyright>
 *
 * Copyright (c) 2014 Eteration A.S.
 * All rights reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *     Unless required by applicable law or agreed to in writing, software
 *     distributed under the License is distributed on an "AS IS" BASIS,
 *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *     See the License for the specific language governing permissions and
 *     limitations under the License.
 *
 *
 *     Derivative Works
 *     Parts of this program are derived from content from Eclipse Foundation
 *     that are made available under the terms of the Eclipse Public License v1.0.
 *      http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Naci Dai, Eteration A.S. - initial API, implementation and documentation
 *
 * </copyright>
 *
 *******************************************************************************/
package org.glassmaker.ui.editor;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.RowData;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.part.MultiPageEditorPart;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.wst.sse.ui.StructuredTextEditor;
import org.glassmaker.login.GlassmakerClientProvider;
import org.glassmaker.ui.CardUtil;
import org.glassmaker.ui.GlassmakerUIPlugin;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.mirror.Mirror;
import com.google.api.services.mirror.model.TimelineItem;
import com.google.gdt.eclipse.login.GoogleLogin;

/**
 * Multi-page editor to create Card templates. This example has 3 pages:
 *

 *
page 0 contains a nested StructuredTextEditor.
 *
page 1 allows you to preview content of the card in a local browser
 *
page 2 previews the page on a glass
 *

 */
public class CardEditor extends MultiPageEditorPart implements IResourceChangeListener {

	/** The text editor. */
	private StructuredTextEditor textEditor;

	/** The Preview Browser */
	private Browser browser;

	/**
	 * Creates a multi-page editor example.
	 */
	public CardEditor() {
		super();
		ResourcesPlugin.getWorkspace().addResourceChangeListener(this);
	}

	/**
	 * Creates Structured Twext Editot of the multi-page editor, which contains an HTML editor.
	 */
	void createPage0() {
		try {
			textEditor = new StructuredTextEditor();
			int index = addPage(textEditor, getEditorInput());
			setPageText(index, "Source");
			setPartName(textEditor.getTitle());
		} catch (PartInitException e) {
			ErrorDialog.openError(getSite().getShell(), "Error creating nested text editor", null, e.getStatus());
		}
	}

	/**
	 * Creates page 1 of the multi-page editor, which is used to preview the page .
	 */
	void createPage1() {
		Composite composite = new Composite(getContainer(), SWT.NONE);

		RowLayout layout = new RowLayout();
		layout.wrap = false;
		layout.pack = true;
		layout.justify = true;
		layout.type = SWT.VERTICAL;
		layout.marginLeft = 5;
		layout.marginTop = 5;
		layout.marginRight = 5;
		layout.marginBottom = 5;
		layout.spacing = 0;
		composite.setLayout(layout);

		browser = new Browser(composite, SWT.NONE);
		browser.setLayoutData(new RowData(640, 360));

		Button previewOnGlass = new Button(composite, SWT.NONE);
		previewOnGlass.setText("#throughglass");

		previewOnGlass.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent event) {
				if(!setClientprovider()) {
					GoogleLogin.promptToLogIn("Glassmaker");
				}
				if (GoogleLogin.getInstance().isLoggedIn())
					previewOnGlass();
			}
		});

		int index = addPage(composite);
		setPageText(index, "Preview");

	}

	/**
	 * Creates the pages of the multi-page editor.
	 */
	protected void createPages() {
		createPage0();
		createPage1();
	}

	/**
	 * The MultiPageEditorPart implementation of this
	 * IWorkbenchPart method disposes all nested editors.
	 * Subclasses may extend.
	 */
	public void dispose() {
		ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
		super.dispose();
	}

	/**
	 * Saves the multi-page editor's document.
	 */
	public void doSave(IProgressMonitor monitor) {
		getEditor(0).doSave(monitor);
	}

	/**
	 * Saves the multi-page editor's document as another file. Also updates the
	 * text for page 0's tab, and updates this multi-page editor's input to
	 * correspond to the nested editor's.
	 */
	public void doSaveAs() {
		IEditorPart editor = getEditor(0);
		editor.doSaveAs();
		setPageText(0, editor.getTitle());
		setInput(editor.getEditorInput());
	}

	/*
	 * (non-Javadoc) Method declared on IEditorPart
	 */
	public void gotoMarker(IMarker marker) {
		setActivePage(0);
		IDE.gotoMarker(getEditor(0), marker);
	}

	/**
	 * The MultiPageEditorExample implementation of this method
	 * checks that the input is an instance of IFileEditorInput.
	 */
	public void init(IEditorSite site, IEditorInput editorInput) throws PartInitException {
		if (!(editorInput instanceof IFileEditorInput))
			throw new PartInitException("Invalid Input: Must be IFileEditorInput");
		super.init(site, editorInput);
	}

	/*
	 * (non-Javadoc) Method declared on IEditorPart.
	 */
	public boolean isSaveAsAllowed() {
		return true;
	}

	/**
	 * Calculates the contents of page 2 when the it is activated.
	 */
	protected void pageChange(int newPageIndex) {
		super.pageChange(newPageIndex);
		if (newPageIndex == 1) {
			showPage();
		}
	}

	/**
	 * Closes all project files on project close.
	 */
	public void resourceChanged(final IResourceChangeEvent event) {
		if (event.getType() == IResourceChangeEvent.PRE_CLOSE) {
			Display.getDefault().asyncExec(new Runnable() {
				public void run() {
					IWorkbenchPage[] pages = getSite().getWorkbenchWindow().getPages();
					for (int i = 0; i < pages.length; i++) {
						if (((FileEditorInput) textEditor.getEditorInput()).getFile().getProject().equals(event.getResource())) {
							IEditorPart editorPart = pages[i].findEditor(textEditor.getEditorInput());
							pages[i].closeEditor(editorPart, true);
						}
					}
				}
			});
		}
	}

	public IDocumentProvider getDocumentProvider() {
		return textEditor.getDocumentProvider();
	}

	public ISelectionProvider getSelectionProvider() {
		return textEditor.getSelectionProvider();
	}

	public void selectAndReveal(int i, int j) {
		textEditor.selectAndReveal(i, j);
	}

	/**
	 * Sorts the words in page 0, and shows them in page 2.
	 */
	void showPage() {

		String editorText = getDocumentProvider().getDocument(textEditor.getEditorInput()).get();
		deletePreviewFiles();

		File file = toPreviewFile(editorText);
		if (file != null) {
			PREVIEW_FILES_LIST.add(file);
			String s = "file://" + file.getAbsolutePath(); //$NON-NLS-1$
			browser.setJavascriptEnabled(true);
			browser.setUrl(s);

		} else {
			browser.setText(editorText, true);
		}

	}

	private List<File> PREVIEW_FILES_LIST = new ArrayList<File>();

	private void deletePreviewFiles() {
		for (File file : PREVIEW_FILES_LIST) {
			if (file != null && file.exists()) {
				file.delete();
			}
		}
		PREVIEW_FILES_LIST.clear();
	}

	public File getTempFile() {
		IFile file = ((FileEditorInput) this.getEditorInput()).getFile();
		return GlassmakerUIPlugin.getPreviewFile("." + file.getName() + ".html");
		//return new File(file.getLocation().makeAbsolute().toFile().getParentFile(), "." + file.getName() + ".html");
	}

	public File toPreviewFile(String result) {
		try {
			File file = getTempFile();
			if(file == null)
				return null;
			if (!file.exists()) {
				file.createNewFile();
			}

			String charset = "UTF-8";

			FileOutputStream fos = new FileOutputStream(file);
			PrintStream ps = new PrintStream(fos, true, charset);
			String wrappedHTML = CardUtil.wrapFragmantInPage(result.toString());
			ps.print(wrappedHTML);
			ps.close();
			fos.close();
			return file;
		} catch (IOException e) {
			return null;
		}
	}

	private void previewOnGlass() {
		try {
			Credential cred = GoogleLogin.getInstance().getCredential();
			cred.getAccessToken();
			Mirror m = new Mirror.Builder(GoogleNetHttpTransport.newTrustedTransport(), new JacksonFactory(), cred)
			.setApplicationName("Glassmaker Plugin")
			.build();

			String editorText = getDocumentProvider().getDocument(textEditor.getEditorInput()).get();
			deletePreviewFiles();
			TimelineItem timelineItem =  CardUtil.createTimeline(editorText);
			Mirror.Timeline timeline = m.timeline();
			timeline.insert(timelineItem).execute();

		} catch (Exception e) {
			GlassmakerUIPlugin.logError(e.getMessage(), e);
		}
	}

	private boolean setClientprovider() {
		GlassmakerClientProvider cp = new GlassmakerClientProvider();
		if(!GoogleLogin.getInstance().fetchOAuth2ClientId().equals(cp.getId())){
			try {
				Field csecret = GoogleLogin.class.getDeclaredField("clientSecret");
				Field cclientid= GoogleLogin.class.getDeclaredField("clientId");
				csecret.setAccessible(true);
				cclientid.setAccessible(true);
				csecret.set(GoogleLogin.getInstance(), cp.getSecret());
				cclientid.set(GoogleLogin.getInstance(), cp.getId());
				if(GoogleLogin.getInstance().isLoggedIn())
					GoogleLogin.getInstance().logOut(false);
			} catch (Exception e) {
				GlassmakerUIPlugin.logError("Failed to set client provider",e);
			}
		}
		return GoogleLogin.getInstance().isLoggedIn();
	}

}


package org.criteria4jpa.util;

import java.util.Iterator;
import java.util.List;

/**
 *
 * Helper class to generate logging information
 *
 * @author Christian Kaltepoth
 *
 */
public class QueryLogHelper {

  /**
   * Method to create a human readable log message regarding a generated query.
   *
   * @param query the JPQL query string
   * @param parameterValues the parameter values of the query
   * @return log string
   */
  public static String createQueryLogMessage(String query, List<Object> parameterValues) {

    // builder for log message
    StringBuilder builder = new StringBuilder();

    // log the JPQL query string
    builder.append("Query: \"");
    builder.append(query);
    builder.append("\"");

    // append parameter value list
    if(parameterValues != null && parameterValues.size() > 0) {

      builder.append(", parameters: { ");

      // parameter value iterator
      Iterator<Object> parameterIterator = parameterValues.iterator();

      // iterate over all parameter values
      while (parameterIterator.hasNext()) {

        // use private helper to create string representation
        builder.append( objectToString( parameterIterator.next() ) );

        // append comma if more values follow
        if( parameterIterator.hasNext() ) {
          builder.append(", ");
        }

      }

      // closing bracket
      builder.append(" }");

    }

    // return result
    return builder.toString();
  }

  /**
   * Helper method to create a string representation of an object.
   *
   * @param obj the object to print
   * @return a string representation of the object
   */
  private static String objectToString(Object obj) {

    // handle 'null'
    if(obj == null) {
      return "null";
    }

    // enclose Strings in quotes
    if(obj instanceof CharSequence) {
      return "\""+obj.toString()+"\"";
    }

    // use toString() for all other objects
    return obj.toString();
  }

}


/*******************************************************************************
 * <copyright>
 *
 * Copyright (c) 2014 Eteration A.S.
 * All rights reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *     Unless required by applicable law or agreed to in writing, software
 *     distributed under the License is distributed on an "AS IS" BASIS,
 *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *     See the License for the specific language governing permissions and
 *     limitations under the License.
 *
 * Contributors:
 *    Naci Dai, Eteration A.S. - initial API, implementation and documentation
 *
 * </copyright>
 *
 *******************************************************************************/
package org.glassmaker.spring.web;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.ByteArrayContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.mirror.Mirror;
import com.google.api.services.mirror.model.Attachment;
import com.google.api.services.mirror.model.Contact;
import com.google.api.services.mirror.model.ContactsListResponse;
import com.google.api.services.mirror.model.Subscription;
import com.google.api.services.mirror.model.SubscriptionsListResponse;
import com.google.api.services.mirror.model.TimelineItem;
import com.google.api.services.mirror.model.TimelineListResponse;
import com.google.common.io.ByteStreams;

@Component("mirrorTemplate")
public class MirrorTemplate {
	private static final Log logger = LogFactory.getLog(MirrorTemplate.class);

	@Autowired
	private TemplateMerger templateMerger;

	public Mirror getMirror() {
		return new Mirror.Builder(new NetHttpTransport(), new JacksonFactory(), getCredential())
		.setApplicationName("Glassmaker Plugin")
		.build();
	}

	public Contact insertContact(Contact contact) throws IOException {
		Mirror.Contacts contacts = getMirror().contacts();
		return contacts.insert(contact).execute();
	}

	public void deleteContact(String contactId) throws IOException {
		Mirror.Contacts contacts = getMirror().contacts();
		contacts.delete(contactId).execute();
	}

	public ContactsListResponse listContacts() throws IOException {
		Mirror.Contacts contacts = getMirror().contacts();
		return contacts.list().execute();
	}

	public Contact getContact(String id) throws IOException {
		try {
			Mirror.Contacts contacts = getMirror().contacts();
			return contacts.get(id).execute();
		} catch (GoogleJsonResponseException e) {
			logger.warn("Could not find contact with ID " + id);
			return null;
		}
	}

	public TimelineListResponse listItems(long count) throws IOException {
		Mirror.Timeline timelineItems = getMirror().timeline();
		Mirror.Timeline.List list = timelineItems.list();
		list.setMaxResults(count);
		return list.execute();
	}

	public Subscription insertSubscription(String callbackUrl, String collection) throws IOException {
		String userId = getUserId();

		logger.info("Attempting to subscribe verify_token " + userId + " with callback " + callbackUrl);

		// Rewrite "appspot.com" to "Appspot.com" as a workaround for
		// http://b/6909300.
		callbackUrl = callbackUrl.replace("appspot.com", "Appspot.com");

		Subscription subscription = new Subscription();
		// Alternatively, subscribe to "locations"
		subscription.setCollection(collection);
		subscription.setCallbackUrl(callbackUrl);
		subscription.setUserToken(userId);

		return getMirror().subscriptions().insert(subscription).execute();
	}

	/**
	 * Subscribes to notifications on the user's timeline.
	 */
	public void deleteSubscription(String id) throws IOException {
		getMirror().subscriptions().delete(id).execute();
	}

	public SubscriptionsListResponse listSubscriptions(Credential credential) throws IOException {
		Mirror.Subscriptions subscriptions = getMirror().subscriptions();
		return subscriptions.list().execute();
	}

	/**
	 * Inserts a simple timeline item.
	 *
	 * @param getCredential
	 *            (credential) the user's credential
	 * @param item
	 *            the item to insert
	 */
	public TimelineItem insertTimelineItem(TimelineItem item) throws IOException {
		return getMirror().timeline().insert(item).execute();
	}

	/**
	 * Inserts an item with an attachment provided as a byte array.
	 *
	 * @param item
	 *            the item to insert
	 * @param attachmentContentType
	 *            the MIME type of the attachment (or null if none)
	 * @param attachmentData
	 *            data for the attachment (or null if none)
	 */
	public void insertTimelineItem(TimelineItem item, String attachmentContentType, byte[] attachmentData) throws IOException {
		Mirror.Timeline timeline = getMirror().timeline();
		timeline.insert(item, new ByteArrayContent(attachmentContentType, attachmentData)).execute();

	}

	/**
	 * Inserts an item with an attachment provided as an input stream.
	 *
	 * @param item
	 *            the item to insert
	 * @param attachmentContentType
	 *            the MIME type of the attachment (or null if none)
	 * @param attachmentInputStream
	 *            input stream for the attachment (or null if none)
	 */
	public void insertTimelineItem(TimelineItem item, String attachmentContentType, InputStream attachmentInputStream) throws IOException {
		insertTimelineItem(item, attachmentContentType, ByteStreams.toByteArray(attachmentInputStream));
	}

	public InputStream getAttachmentInputStream(String timelineItemId, String attachmentId) throws IOException {
		Mirror mirrorService = getMirror();
		Mirror.Timeline.Attachments attachments = mirrorService.timeline().attachments();
		Attachment attachmentMetadata = attachments.get(timelineItemId, attachmentId).execute();
		HttpResponse resp = mirrorService.getRequestFactory().buildGetRequest(new GenericUrl(attachmentMetadata.getContentUrl())).execute();
		return resp.getContent();
	}

	public String getAttachmentContentType(String timelineItemId, String attachmentId) throws IOException {
		Mirror.Timeline.Attachments attachments = getMirror().timeline().attachments();
		Attachment attachmentMetadata = attachments.get(timelineItemId, attachmentId).execute();
		return attachmentMetadata.getContentType();
	}

	public void deleteTimelineItem(String timelineItemId) throws IOException {
		getMirror().timeline().delete(timelineItemId).execute();
	}

	private Credential getCredential() {
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) auth;
		String accessToken = (String) token.getDetails();
		GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken);
		return credential;
	}

	private String getUserId() {
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) auth;
		String userId = (String) token.getPrincipal();
		return userId;
	}

	public TimelineItem render(ModelAndView mav) throws Exception {
		TimelineItem timelineItem = new TimelineItem();
		String article = templateMerger.merge(mav.getViewName(), mav.getModelMap());
		timelineItem.setHtml(article);
		return timelineItem;
	}

//	public void batchSend(TimelineItem allUsersItem) throws IOException {
//		BatchRequest batch = getMirror().batch();
//
////		BatchCallback callback = new BatchCallback();
////		for (String user : users) {
////			Credential userCredential = AuthUtil.getCredential(user);
////			MirrorClient.getMirror(userCredential).timeline().insert(allUsersItem).queue(batch, callback);
////		}
//
//		batch.execute();
//	}
//
//	private final class BatchCallback extends JsonBatchCallback<TimelineItem> {
//
//		@Override
//		public void onSuccess(TimelineItem item, HttpHeaders headers) throws IOException {
//			logger.info("Successfully sent an item: ");
//		}
//
//		@Override
//		public void onFailure(GoogleJsonError error, HttpHeaders headers) throws IOException {
//			logger.info("Failed to insert item: " + error.getMessage());
//		}
//	}

}