repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
skyvers/skyve
skyve-web/src/main/java/org/skyve/impl/web/faces/charts/config/DoughnutChartRenderer.java
627
package org.skyve.impl.web.faces.charts.config; import java.io.IOException; import javax.faces.context.FacesContext; import org.primefaces.component.donutchart.DonutChartRenderer; import org.primefaces.model.charts.ChartModel; import org.skyve.impl.sail.mock.MockFacesContext; public class DoughnutChartRenderer extends DonutChartRenderer { public String encodeConfig(ChartModel model) throws IOException { FacesContext fc = new MockFacesContext(); try (ResponseWriter writer = new ResponseWriter()) { fc.setResponseWriter(writer); encodeConfig(fc, model); return ChartConfigRenderer.spruce(writer); } } }
lgpl-2.1
skyvers/skyve
skyve-core/src/main/java/org/skyve/impl/metadata/view/reference/ReferenceProcessor.java
3765
package org.skyve.impl.metadata.view.reference; import org.skyve.impl.bind.BindUtil; import org.skyve.metadata.customer.Customer; import org.skyve.metadata.model.document.Document; import org.skyve.metadata.model.document.Relation; import org.skyve.metadata.module.Module; import org.skyve.metadata.view.Action; import org.skyve.metadata.view.View; import org.skyve.metadata.view.View.ViewType; import org.skyve.util.Binder.TargetMetaData; import org.skyve.web.UserAgentType; public abstract class ReferenceProcessor { public final void process(Reference reference) { if (reference instanceof ActionReference) { processActionReference((ActionReference) reference); } else if (reference instanceof ContentReference) { processContentReference((ContentReference) reference); } else if (reference instanceof DefaultListViewReference) { processDefaultListViewReference((DefaultListViewReference) reference); } else if (reference instanceof EditViewReference) { processEditViewReference((EditViewReference) reference); } else if (reference instanceof ExternalReference) { processExternalReference((ExternalReference) reference); } else if (reference instanceof ImplicitActionReference) { processImplicitActionReference((ImplicitActionReference) reference); } else if (reference instanceof QueryListViewReference) { processQueryListViewReference((QueryListViewReference) reference); } else if (reference instanceof ReportReference) { processReportReference((ReportReference) reference); } else if (reference instanceof ResourceReference) { processResourceReference((ResourceReference) reference); } else if (reference != null) { throw new IllegalStateException("Reference Type " + reference.getClass() + " is not catered for"); } } public abstract void processActionReference(ActionReference reference); public abstract void processContentReference(ContentReference reference); public abstract void processDefaultListViewReference(DefaultListViewReference reference); public abstract void processEditViewReference(EditViewReference reference); public abstract void processExternalReference(ExternalReference reference); public abstract void processImplicitActionReference(ImplicitActionReference reference); public abstract void processQueryListViewReference(QueryListViewReference reference); public abstract void processReportReference(ReportReference reference); public abstract void processResourceReference(ResourceReference reference); public static final Action obtainActionForActionReference(ActionReference reference, Customer customer, Module module, Document document, String dataWidgetBinding, UserAgentType userAgentType) { final TargetMetaData listTarget = BindUtil.getMetaDataForBinding(customer, module, document, dataWidgetBinding); final Document listDocument; // Figure out the document type of the relation. if (listTarget.getAttribute() instanceof Relation) { final String documentName = ((Relation) listTarget.getAttribute()).getDocumentName(); listDocument = module.getDocument(customer, documentName); } else { listDocument = listTarget.getDocument(); } final ViewType[] viewTypesToSearch = new ViewType[] { ViewType.edit, ViewType.create }; Action result = null; for (ViewType viewType : viewTypesToSearch) { final View listDocumentView = listDocument.getView(userAgentType.name(), customer, viewType.name()); if (listDocumentView == null) { continue; } result = listDocumentView.getAction(reference.getActionName()); if (result != null) { // Found the action, we can stop looking. break; } } return result; } }
lgpl-2.1
syncer/swingx
swingx-core/src/main/java/org/jdesktop/swingx/auth/LoginEvent.java
1488
/* * $Id: LoginEvent.java 648 2005-11-30 05:21:56Z rbair $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx.auth; import java.util.EventObject; /** * This is an event object that is passed to login listener methods * * @author Shai Almog */ public class LoginEvent extends EventObject { private Throwable cause; public LoginEvent(Object source) { this(source, null); } /** Creates a new instance of LoginEvent */ public LoginEvent(Object source, Throwable cause) { super(source); this.cause = cause; } public Throwable getCause() { return cause; } }
lgpl-2.1
ggiudetti/opencms-core
src/org/opencms/workplace/explorer/menu/CmsMirEditControlcode.java
5721
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software GmbH & Co. KG, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.workplace.explorer.menu; import org.opencms.file.CmsObject; import org.opencms.file.CmsResourceFilter; import org.opencms.lock.CmsLock; import org.opencms.main.CmsException; import org.opencms.main.OpenCms; import org.opencms.security.CmsPermissionSet; import org.opencms.security.CmsRole; import org.opencms.workplace.explorer.CmsResourceUtil; /** * Defines a menu item rule that sets the visibility for the "Edit controlcode" context menu entry, * depending on the project and lock state of the resource.<p> * * @since 6.9.2 */ public class CmsMirEditControlcode extends A_CmsMenuItemRule { /** * @see org.opencms.workplace.explorer.menu.I_CmsMenuItemRule#getVisibility(org.opencms.file.CmsObject, CmsResourceUtil[]) */ @Override public CmsMenuItemVisibilityMode getVisibility(CmsObject cms, CmsResourceUtil[] resourceUtil) { try { if (resourceUtil[0].isInsideProject() && !cms.getRequestContext().getCurrentProject().isOnlineProject()) { // we are in the correct offline project and resource is not deleted CmsLock lock = resourceUtil[0].getLock(); boolean lockedForPublish = resourceUtil[0].getProjectState().isLockedForPublishing(); if (lock.isNullLock()) { // resource is not locked, check autolock if (!lockedForPublish && OpenCms.getWorkplaceManager().autoLockResources() && !resourceUtil[0].getResource().getState().isDeleted()) { if (OpenCms.getRoleManager().hasRole(cms, CmsRole.DEVELOPER) && cms.hasPermissions( resourceUtil[0].getResource(), CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.ALL)) { return CmsMenuItemVisibilityMode.VISIBILITY_ACTIVE; } } else if (OpenCms.getRoleManager().hasRole(cms, CmsRole.DEVELOPER)) { if (resourceUtil[0].getResource().getState().isDeleted()) { return CmsMenuItemVisibilityMode.VISIBILITY_INACTIVE.addMessageKey( Messages.GUI_CONTEXTMENU_TITLE_INACTIVE_DELETED_0); } return CmsMenuItemVisibilityMode.VISIBILITY_INACTIVE.addMessageKey( Messages.GUI_CONTEXTMENU_TITLE_INACTIVE_PERM_WRITE_0); } } if (!lockedForPublish && !lock.isShared() && lock.isOwnedInProjectBy( cms.getRequestContext().getCurrentUser(), cms.getRequestContext().getCurrentProject())) { // resource is exclusively locked by the current user if (OpenCms.getRoleManager().hasRole(cms, CmsRole.DEVELOPER)) { if (!resourceUtil[0].getResource().getState().isDeleted() && cms.hasPermissions( resourceUtil[0].getResource(), CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.ALL)) { return CmsMenuItemVisibilityMode.VISIBILITY_ACTIVE; } else { if (resourceUtil[0].getResource().getState().isDeleted()) { return CmsMenuItemVisibilityMode.VISIBILITY_INACTIVE.addMessageKey( Messages.GUI_CONTEXTMENU_TITLE_INACTIVE_DELETED_0); } return CmsMenuItemVisibilityMode.VISIBILITY_INACTIVE.addMessageKey( Messages.GUI_CONTEXTMENU_TITLE_INACTIVE_PERM_WRITE_0); } } } } } catch (CmsException e) { // should not happen, anyway invisible is returned } // current user cannot see the entry return CmsMenuItemVisibilityMode.VISIBILITY_INVISIBLE; } /** * @see org.opencms.workplace.explorer.menu.I_CmsMenuItemRule#matches(org.opencms.file.CmsObject, CmsResourceUtil[]) */ public boolean matches(CmsObject cms, CmsResourceUtil[] resourceUtil) { // this rule always matches return true; } }
lgpl-2.1
naver/checkstyle
src/test/java/com/puppycrawl/tools/checkstyle/checks/whitespace/MethodParamPadCheckTest.java
5544
//////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2015 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.whitespace; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Before; import org.junit.Test; import static com.puppycrawl.tools.checkstyle.checks.whitespace.MethodParamPadCheck.LINE_PREVIOUS; import static com.puppycrawl.tools.checkstyle.checks.whitespace.MethodParamPadCheck .WS_NOT_PRECEDED; import static com.puppycrawl.tools.checkstyle.checks.whitespace.MethodParamPadCheck.WS_PRECEDED; public class MethodParamPadCheckTest extends BaseCheckTestSupport { private DefaultConfiguration checkConfig; @Before public void setUp() { checkConfig = createCheckConfig(MethodParamPadCheck.class); } @Test public void testDefault() throws Exception { final String[] expected = { "11:32: " + getCheckMessage(WS_PRECEDED, "("), "13:15: " + getCheckMessage(WS_PRECEDED, "("), "17:9: " + getCheckMessage(LINE_PREVIOUS, "("), "20:13: " + getCheckMessage(LINE_PREVIOUS, "("), "27:24: " + getCheckMessage(WS_PRECEDED, "("), "32:9: " + getCheckMessage(LINE_PREVIOUS, "("), "36:39: " + getCheckMessage(WS_PRECEDED, "("), "38:13: " + getCheckMessage(LINE_PREVIOUS, "("), "42:16: " + getCheckMessage(WS_PRECEDED, "("), "44:13: " + getCheckMessage(LINE_PREVIOUS, "("), "50:21: " + getCheckMessage(WS_PRECEDED, "("), "52:13: " + getCheckMessage(LINE_PREVIOUS, "("), "56:18: " + getCheckMessage(WS_PRECEDED, "("), "58:13: " + getCheckMessage(LINE_PREVIOUS, "("), "61:36: " + getCheckMessage(WS_PRECEDED, "("), "63:13: " + getCheckMessage(LINE_PREVIOUS, "("), }; verify(checkConfig, getPath("whitespace/InputMethodParamPad.java"), expected); } @Test public void testAllowLineBreaks() throws Exception { checkConfig.addAttribute("allowLineBreaks", "true"); final String[] expected = { "11:32: " + getCheckMessage(WS_PRECEDED, "("), "13:15: " + getCheckMessage(WS_PRECEDED, "("), "27:24: " + getCheckMessage(WS_PRECEDED, "("), "36:39: " + getCheckMessage(WS_PRECEDED, "("), "42:16: " + getCheckMessage(WS_PRECEDED, "("), "50:21: " + getCheckMessage(WS_PRECEDED, "("), "56:18: " + getCheckMessage(WS_PRECEDED, "("), "61:36: " + getCheckMessage(WS_PRECEDED, "("), }; verify(checkConfig, getPath("whitespace/InputMethodParamPad.java"), expected); } @Test public void testSpaceOption() throws Exception { checkConfig.addAttribute("option", "space"); final String[] expected = { "6:31: " + getCheckMessage(WS_NOT_PRECEDED, "("), "8:14: " + getCheckMessage(WS_NOT_PRECEDED, "("), "17:9: " + getCheckMessage(LINE_PREVIOUS, "("), "20:13: " + getCheckMessage(LINE_PREVIOUS, "("), "23:23: " + getCheckMessage(WS_NOT_PRECEDED, "("), "32:9: " + getCheckMessage(LINE_PREVIOUS, "("), "35:58: " + getCheckMessage(WS_NOT_PRECEDED, "("), "38:13: " + getCheckMessage(LINE_PREVIOUS, "("), "41:15: " + getCheckMessage(WS_NOT_PRECEDED, "("), "44:13: " + getCheckMessage(LINE_PREVIOUS, "("), "47:28: " + getCheckMessage(WS_NOT_PRECEDED, "("), "49:20: " + getCheckMessage(WS_NOT_PRECEDED, "("), "52:13: " + getCheckMessage(LINE_PREVIOUS, "("), "54:56: " + getCheckMessage(WS_NOT_PRECEDED, "("), "55:17: " + getCheckMessage(WS_NOT_PRECEDED, "("), "58:13: " + getCheckMessage(LINE_PREVIOUS, "("), "60:35: " + getCheckMessage(WS_NOT_PRECEDED, "("), "63:13: " + getCheckMessage(LINE_PREVIOUS, "("), "66:25: " + getCheckMessage(WS_NOT_PRECEDED, "("), "69:66: " + getCheckMessage(WS_NOT_PRECEDED, "("), "70:57: " + getCheckMessage(WS_NOT_PRECEDED, "("), }; verify(checkConfig, getPath("whitespace/InputMethodParamPad.java"), expected); } @Test public void test1322879() throws Exception { checkConfig.addAttribute("option", PadOption.SPACE.toString()); final String[] expected = { }; verify(checkConfig, getPath("whitespace/InputWhitespaceAround.java"), expected); } }
lgpl-2.1
kingargyle/exist-1.4.x
src/org/exist/xquery/CommentConstructor.java
2572
/* * eXist Open Source Native XML Database * Copyright (C) 2001 Wolfgang M. Meier * wolfgang@exist-db.org * http://exist-db.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * $Id$ */ package org.exist.xquery; import org.exist.memtree.MemTreeBuilder; import org.exist.memtree.NodeImpl; import org.exist.xquery.util.ExpressionDumper; import org.exist.xquery.value.Item; import org.exist.xquery.value.Sequence; public class CommentConstructor extends NodeConstructor { private final String data; public CommentConstructor(XQueryContext context, String data) { super(context); this.data = data; } /* (non-Javadoc) * @see org.exist.xquery.Expression#analyze(org.exist.xquery.Expression) */ public void analyze(AnalyzeContextInfo contextInfo) throws XPathException { super.analyze(contextInfo); } /* (non-Javadoc) * @see org.exist.xquery.Expression#eval(org.exist.xquery.StaticContext, org.exist.dom.DocumentSet, org.exist.xquery.value.Sequence, org.exist.xquery.value.Item) */ public Sequence eval( Sequence contextSequence, Item contextItem) throws XPathException { if (newDocumentContext) context.pushDocumentContext(); try { MemTreeBuilder builder = context.getDocumentBuilder(); int nodeNr = builder.comment(data); NodeImpl node = builder.getDocument().getNode(nodeNr); return node; } finally { if (newDocumentContext) context.popDocumentContext(); } } /* (non-Javadoc) * @see org.exist.xquery.Expression#dump(org.exist.xquery.util.ExpressionDumper) */ public void dump(ExpressionDumper dumper) { dumper.nl().display("comment {").display(data).display("}"); } public String toString() { return "comment {" + data.toString() + "}"; } }
lgpl-2.1
google-code-export/flies
server/zanata-war/src/main/java/org/zanata/webtrans/client/AppView.java
5551
/* * Copyright 2010, Red Hat, Inc. and individual contributors as indicated by the * @author tags. See the copyright.txt file in the distribution for a full * listing of individual contributors. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF * site: http://www.fsf.org. */ package org.zanata.webtrans.client; import org.zanata.webtrans.shared.model.DocumentInfo; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.SpanElement; import com.google.gwt.dom.client.StyleInjector; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.HasClickHandlers; import com.google.gwt.layout.client.Layout.AnimationCallback; import com.google.gwt.layout.client.Layout.Layer; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.LayoutPanel; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; public class AppView extends Composite implements AppPresenter.Display { interface AppViewUiBinder extends UiBinder<LayoutPanel, AppView> { } private static AppViewUiBinder uiBinder = GWT.create(AppViewUiBinder.class); private final int NOTIFICATION_TIME = 2500; @UiField Anchor signOutLink, leaveLink, helpLink, documentsLink; @UiField Label notificationMessage; @UiField SpanElement user, selectedDocumentSpan, selectedDocumentPathSpan; @UiField LayoutPanel container, topPanel, filterPanelContainer; @UiField(provided = true) final Resources resources; private Widget documentListView; private Widget translationView; private Widget filterView; final WebTransMessages messages; @Inject public AppView(Resources resources, WebTransMessages messages) { this.resources = resources; this.messages = messages; StyleInjector.inject(resources.style().getText(), true); initWidget(uiBinder.createAndBindUi(this)); helpLink.setHref(messages.hrefHelpLink()); helpLink.setTarget("_BLANK"); } @Override public Widget asWidget() { return this; } @Override public void showInMainView(MainView view) { switch (view) { case Documents: container.setWidgetTopBottom(documentListView, 0, Unit.PX, 0, Unit.PX); container.setWidgetTopHeight(translationView, 0, Unit.PX, 0, Unit.PX); filterPanelContainer.setWidgetTopHeight(filterView, 0, Unit.PX, 0, Unit.PX); break; case Editor: container.setWidgetTopBottom(translationView, 0, Unit.PX, 0, Unit.PX); container.setWidgetTopHeight(documentListView, 0, Unit.PX, 0, Unit.PX); filterPanelContainer.setWidgetTopBottom(filterView, 0, Unit.PX, 0, Unit.PX); break; } } @Override public void setDocumentListView(Widget documentListView) { this.container.add(documentListView); this.documentListView = documentListView; } @Override public void setTranslationView(Widget editorView) { this.container.add(editorView); this.translationView = editorView; } @Override public void setFilterView(Widget filterView) { filterPanelContainer.clear(); filterPanelContainer.add(filterView); this.filterView = filterView; } @Override public HasClickHandlers getHelpLink() { return helpLink; } @Override public HasClickHandlers getLeaveWorkspaceLink() { return leaveLink; } @Override public HasClickHandlers getSignOutLink() { return signOutLink; } @Override public HasClickHandlers getDocumentsLink() { return documentsLink; } @Override public void setUserLabel(String userLabel) { user.setInnerText(userLabel); } @Override public void setWorkspaceNameLabel(String workspaceNameLabel) { documentsLink.setText(workspaceNameLabel); } @Override public void setSelectedDocument(DocumentInfo document) { String path = document.getPath() == null || document.getPath().isEmpty() ? "" : document.getPath() + "/"; selectedDocumentPathSpan.setInnerText(path); selectedDocumentSpan.setInnerText(document.getName()); } private final AnimationCallback callback = new AnimationCallback() { @Override public void onAnimationComplete() { notificationMessage.setText(""); } @Override public void onLayout(Layer layer, double progress) { } }; public void setNotificationMessage(String var) { topPanel.forceLayout(); notificationMessage.setText(var); topPanel.animate(NOTIFICATION_TIME, callback); } }
lgpl-2.1
ggiudetti/opencms-core
src/org/opencms/ui/report/CmsReportWidget.java
4445
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.ui.report; import org.opencms.report.A_CmsReportThread; import org.opencms.ui.shared.components.CmsReportWidgetState; import org.opencms.ui.shared.rpc.I_CmsReportClientRpc; import org.opencms.ui.shared.rpc.I_CmsReportServerRpc; import java.util.List; import com.google.common.collect.Lists; import com.google.gwt.event.shared.HandlerRegistration; import com.vaadin.ui.AbstractComponent; /** * A widget used to display an OpenCms report.<p> */ public class CmsReportWidget extends AbstractComponent implements I_CmsReportServerRpc { /** Serial version id. */ private static final long serialVersionUID = 1L; /** Handlers to execute when the report finishes while displaying the report widget. */ private List<Runnable> m_reportFinishedHandlers = Lists.newArrayList(); /** The report thread. */ private A_CmsReportThread m_thread; /** True if the report thread is finished. */ private boolean m_threadFinished; /** * Creates a new instance.<p> * Use in declarative layouts, remember to call .<p> * This does not start the report thread.<p> */ public CmsReportWidget() { registerRpc(this, I_CmsReportServerRpc.class); } /** * Creates a new instance.<p> * * This does not start the report thread. * * @param thread the report thread */ public CmsReportWidget(A_CmsReportThread thread) { this(); m_thread = thread; } /** * Adds an action that should be executed if the report is finished.<p> * * Note that this action will only be called if the report is finished while the report widget is actually * displayed. For example, if the user closes the browser window before the report is finished, this will not be executed. * * @param handler the handler * @return the handler registration */ public HandlerRegistration addReportFinishedHandler(final Runnable handler) { m_reportFinishedHandlers.add(handler); return new HandlerRegistration() { @SuppressWarnings("synthetic-access") public void removeHandler() { m_reportFinishedHandlers.remove(handler); } }; } /** * @see org.opencms.ui.shared.rpc.I_CmsReportServerRpc#requestReportUpdate() */ public void requestReportUpdate() { String reportUpdate = null; if (!m_threadFinished && (m_thread != null)) { // if thread is not alive at this point, there may still be report updates reportUpdate = m_thread.getReportUpdate(); if (!m_thread.isAlive()) { m_threadFinished = true; for (Runnable handler : m_reportFinishedHandlers) { handler.run(); } } } getRpcProxy(I_CmsReportClientRpc.class).handleReportUpdate(reportUpdate); } /** * Sets the report thread.<p> * * @param thread the report thread */ public void setReportThread(A_CmsReportThread thread) { m_thread = thread; } /** * @see com.vaadin.ui.AbstractComponent#getState() */ @Override protected CmsReportWidgetState getState() { return (CmsReportWidgetState)(super.getState()); } }
lgpl-2.1
google-code-export/flies
common/zanata-common-api/src/main/java/org/zanata/rest/dto/ContentTypeAdapter.java
514
package org.zanata.rest.dto; import javax.xml.bind.annotation.adapters.XmlAdapter; import org.zanata.common.ContentType; public class ContentTypeAdapter extends XmlAdapter<String, ContentType> { public ContentType unmarshal(String s) throws Exception { if (s == null) return null; return new ContentType(s); } public String marshal(ContentType contentType) throws Exception { if (contentType == null) return null; return contentType.toString(); } }
lgpl-2.1
gwoptics/gwoptics_plib
src/org/gwoptics/graphics/colourmap/EquationColourmap.java
4854
/** * Copyright notice * * This file is part of the Processing library `gwoptics' * http://www.gwoptics.org/processing/gwoptics_p5lib/ * * Copyright (C) 2009 onwards Daniel Brown and Andreas Freise * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 2.1 as published * by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.gwoptics.graphics.colourmap; import org.gwoptics.graphics.GWColour; /** * EquationColourmap implements the IColourmap interface to generate a colourmap * from an equation, rather than nodes as in the alternative RGBColourmap. The * equation that generates the map returns a Colour object as specified in * IColourmapEquation. * * <p>Before any values are read from the map, the map must have been generated * using generateColourmap() or a {@link MapNeedsGeneratingException} will be * thrown.</p> * * @author Daniel Brown 18/6/09 * @since 0.2.4 * @see GWColour * @see IColourmapEquation * @see IColourmap * @see RGBColourmap * @see MapNeedsGeneratingException */ public class EquationColourmap implements IColourmap { private GWColour[] _cColourmapLookup; private int[] _iColourmapLookup; private boolean _needsGenerating; private IColourmapEquation _eq; private float _dLoc; private boolean _isCentreAtZero; public boolean isCentreAtZero() { return _isCentreAtZero; } public void setCentreAtZero(boolean value) { _isCentreAtZero = value; } /** * Requires an equation object to be passed to it, which is not nullable * * @param eq Equation that generates the colourmap, is not nullable. */ public EquationColourmap(IColourmapEquation eq) { if (eq == null) { throw new NullPointerException("Object requires a non null IColourmapEquation."); } _cColourmapLookup = new GWColour[64]; _iColourmapLookup = new int[64]; _dLoc = 1.0f / (63); } /** * Additional constructor that allows a custom resolution of lookup table. * Values of 50 and greater are recommended for most uses. * * @param resolution defines number of steps in colourmap lookup table. * @param eq Equation that generates the colourmap, is not nullable. */ public EquationColourmap(int resolution, IColourmapEquation eq) { if (eq == null) { throw new NullPointerException("Object requires a non null IColourmapEquation."); } if (resolution < 1) { resolution = 1; } _eq = eq; _cColourmapLookup = new GWColour[resolution]; _iColourmapLookup = new int[resolution]; _dLoc = 1.0f / (resolution - 1); } public boolean isGenerated() { return !_needsGenerating; } /** * Use the supplied equation to generate colour values for each index in the * colourmap. Must be called before map is used. */ public void generateColourmap() { for (int i = 0; i < _cColourmapLookup.length; i++) { GWColour val = _eq.colourmapEquation(_dLoc * i); _cColourmapLookup[i] = val; _iColourmapLookup[i] = val.toInt(); } _needsGenerating = false; } /** * Returns a Colour object that relates to a normalised location on the * colourmap * * @param l Normalised location input (between 0.0f and 1.0f) * @return Colour at location. */ public GWColour getColourAtLocation(float l) { if (_needsGenerating) { throw new MapNeedsGeneratingException(); } float loc; if (l < 0.0f) { loc = 0.0f; } else if (l > 1.0f) { loc = 1.0f; } else { loc = l; } return _cColourmapLookup[Math.round(loc / _dLoc)]; } /** * Returns an integer that relates to a normalised location on the colourmap. * Integer is in a 4 byte format of ARGB. * * @param l Normalised location input (between 0.0f and 1.0f) * @return Integer value of colour at location. */ public int getIntAtLocation(float l) { if (_needsGenerating) { throw new MapNeedsGeneratingException(); } float loc; if (l < 0.0f) { loc = 0.0f; } else if (l > 1.0f) { loc = 1.0f; } else { loc = l; } return _iColourmapLookup[Math.round(loc / _dLoc)]; } }
lgpl-2.1
StefanoSalsano/alien-ofelia-conet-ccnx
javasrc/src/org/ccnx/ccn/test/io/CCNVersionedOutputStreamTest.java
7667
/* * A CCNx library test. * * Copyright (C) 2010, 2011, 2013 Palo Alto Research Center, Inc. * * This work is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as published by the * Free Software Foundation. * This work is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ package org.ccnx.ccn.test.io; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.DigestInputStream; import java.security.DigestOutputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Random; import java.util.logging.Level; import org.ccnx.ccn.CCNHandle; import org.ccnx.ccn.CCNInterestHandler; import org.ccnx.ccn.impl.support.DataUtils; import org.ccnx.ccn.impl.support.Log; import org.ccnx.ccn.io.CCNAbstractOutputStream; import org.ccnx.ccn.io.CCNVersionedInputStream; import org.ccnx.ccn.io.CCNVersionedOutputStream; import org.ccnx.ccn.protocol.ContentName; import org.ccnx.ccn.protocol.Interest; import org.ccnx.ccn.test.CCNTestHelper; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; public class CCNVersionedOutputStreamTest implements CCNInterestHandler { static CCNTestHelper testHelper = new CCNTestHelper(CCNVersionedOutputStreamTest.class); static CCNHandle readHandle; static CCNHandle writeHandle; static byte [] writeDigest; static int BUF_SIZE = 2048; static int FILE_SIZE = 65556; static Writer writer; public static class Writer extends Thread { protected static Random random = new Random(); protected CCNAbstractOutputStream _stream; protected int _fileLength; protected boolean _done = false; public Writer(CCNAbstractOutputStream stream, int fileLength) { _stream = stream; _fileLength = fileLength; } public synchronized boolean isDone() { return _done; } /** * @return The digest of the first segment of this stream */ public byte[] getFirstDigest() { return _stream.getFirstDigest(); } /** * @return The index of the first segment of stream data. */ public Long firstSegmentNumber() { return _stream.firstSegmentNumber(); } @Override public void run() { try { synchronized (this) { writeDigest = writeRandomFile(_stream, _fileLength, random); Log.info(Log.FAC_TEST, "Finished writing file of {0} bytes, digest {1}.", _fileLength, DataUtils.printHexBytes(writeDigest)); _done = true; this.notifyAll(); } } catch (IOException e) { Log.severe(Log.FAC_TEST, "Exception writing random file: " + e.getClass().getName() + ": " + e.getMessage()); Log.logStackTrace(Log.FAC_TEST, Level.SEVERE, e); Assert.fail("Exception in writeRandomFile: " + e); } } } @BeforeClass public static void setUpBeforeClass() throws Exception { try { readHandle = CCNHandle.open(); writeHandle = CCNHandle.open(); } catch (Exception e) { Log.severe("Exception in setUpBeforeClass: {0}: {1}", e.getClass().getName(), e); throw e; } } @AfterClass public static void cleanupAfterClass() { readHandle.close(); writeHandle.close(); } @Test public void testAddOutstandingInterest() throws Exception { // Let's express an Interest in some data, and see if the network managers can // handle the threading for us... ContentName streamName = new ContentName(testHelper.getTestNamespace("testAddOutstandingInterest"), "testFile.bin"); writeHandle.registerFilter(streamName, this); // Get the latest version when no versions exist. CCNVersionedInputStream vis = new CCNVersionedInputStream(streamName, readHandle); byte [] resultDigest = readFile(vis); Log.info("Finished reading, read result {0}", DataUtils.printHexBytes(resultDigest)); synchronized (this) { Assert.assertNotNull(writer); if (!writer.isDone()) { synchronized(writer) { while (!writer.isDone()) { writer.wait(500); } } } } Log.info("Finished writing, read result {0}, write result {1}", DataUtils.printHexBytes(resultDigest), DataUtils.printHexBytes(writeDigest)); Assert.assertArrayEquals(resultDigest, writeDigest); Assert.assertArrayEquals(writer.getFirstDigest(), vis.getFirstDigest()); Assert.assertEquals(writer.firstSegmentNumber(), (Long)vis.firstSegmentNumber()); } public static byte [] readFile(InputStream inputStream) throws IOException { DigestInputStream dis = null; try { dis = new DigestInputStream(inputStream, MessageDigest.getInstance("SHA1")); } catch (NoSuchAlgorithmException e) { Log.severe("No SHA1 available!"); Assert.fail("No SHA1 available!"); } int elapsed = 0; int read = 0; byte [] bytes = new byte[BUF_SIZE]; while (true) { read = dis.read(bytes); if (read < 0) { System.out.println("EOF read at " + elapsed + " bytes."); break; } else if (read == 0) { System.out.println("0 bytes read at " + elapsed + " bytes."); try { Thread.sleep(10); } catch (InterruptedException e) { } } elapsed += read; System.out.println(" read " + elapsed + " bytes."); } return dis.getMessageDigest().digest(); } public static byte [] writeRandomFile(OutputStream stream, int fileLength, Random randBytes) throws IOException { DigestOutputStream digestStreamWrapper = null; try { digestStreamWrapper = new DigestOutputStream(stream, MessageDigest.getInstance("SHA1")); } catch (NoSuchAlgorithmException e) { Log.severe("No SHA1 available!"); Assert.fail("No SHA1 available!"); } byte [] bytes = new byte[BUF_SIZE]; int elapsed = 0; int nextBufSize = 0; final double probFlush = .3; while (elapsed < fileLength) { nextBufSize = ((fileLength - elapsed) > BUF_SIZE) ? BUF_SIZE : (fileLength - elapsed); randBytes.nextBytes(bytes); digestStreamWrapper.write(bytes, 0, nextBufSize); elapsed += nextBufSize; if (randBytes.nextDouble() < probFlush) { System.out.println("Flushing buffers, have written " + elapsed + " bytes out of " + fileLength); digestStreamWrapper.flush(); } } digestStreamWrapper.close(); return digestStreamWrapper.getMessageDigest().digest(); } public boolean handleInterest(Interest interest) { if(interest.exclude()!=null && !interest.exclude().empty()) { Log.info("this interest is probably a gLV interest, this is what we are looking for"); } else { Log.info("this is not a gLV interest, dropping"); return false; } // we only deal with the first interest, at least for now synchronized (this) { if (null != writer) { Log.info("handleInterests: already writing stream, ignoring interest {0}", interest); return false; } } Log.info("handleInterests got interest {0}", interest); CCNVersionedOutputStream vos = null; try { vos = new CCNVersionedOutputStream(interest.name(), writeHandle); } catch (IOException e) { Log.severe("Exception in creating output stream: {0}", e); Log.logStackTrace(Level.SEVERE, e); Assert.fail("Exception creating output stream " + e); } vos.addOutstandingInterest(interest); synchronized (this) { writer = new Writer(vos, FILE_SIZE); writer.start(); } return true; } }
lgpl-2.1
Polyglotter/chrysalix
chrysalix-eclipse/plugins/org.polyglotter.eclipse/src/org/polyglotter/eclipse/view/WorkspaceView.java
995
package org.chrysalix.eclipse.view; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.ui.part.ViewPart; /** * The workspace view. */ public final class WorkspaceView extends ViewPart { /** * The workspace part identifier for this view. */ public static final String ID = WorkspaceView.class.getPackage().getName() + ".workspaceView"; /** * {@inheritDoc} * * @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite) */ @Override public void createPartControl( final Composite parent ) { // TODO implement createPartControl final Label temp = new Label( parent, SWT.NONE ); temp.setText( "Blah Blah Blah" ); } /** * {@inheritDoc} * * @see org.eclipse.ui.part.WorkbenchPart#setFocus() */ @Override public void setFocus() { // TODO implement setFocus } }
lgpl-2.1
dogjaw2233/tiu-s-mod
build/tmp/recompileMc/sources/net/minecraft/crash/CrashReportCategory.java
10639
package net.minecraft.crash; import com.google.common.collect.Lists; import java.util.List; import java.util.concurrent.Callable; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.util.BlockPos; public class CrashReportCategory { private final CrashReport crashReport; private final String name; private final List<CrashReportCategory.Entry> children = Lists.<CrashReportCategory.Entry>newArrayList(); private StackTraceElement[] stackTrace = new StackTraceElement[0]; public CrashReportCategory(CrashReport report, String name) { this.crashReport = report; this.name = name; } public static String getCoordinateInfo(double x, double y, double z) { return String.format("%.2f,%.2f,%.2f - %s", new Object[] {Double.valueOf(x), Double.valueOf(y), Double.valueOf(z), getCoordinateInfo(new BlockPos(x, y, z))}); } public static String getCoordinateInfo(BlockPos pos) { int i = pos.getX(); int j = pos.getY(); int k = pos.getZ(); StringBuilder stringbuilder = new StringBuilder(); try { stringbuilder.append(String.format("World: (%d,%d,%d)", new Object[] {Integer.valueOf(i), Integer.valueOf(j), Integer.valueOf(k)})); } catch (Throwable var17) { stringbuilder.append("(Error finding world loc)"); } stringbuilder.append(", "); try { int l = i >> 4; int i1 = k >> 4; int j1 = i & 15; int k1 = j >> 4; int l1 = k & 15; int i2 = l << 4; int j2 = i1 << 4; int k2 = (l + 1 << 4) - 1; int l2 = (i1 + 1 << 4) - 1; stringbuilder.append(String.format("Chunk: (at %d,%d,%d in %d,%d; contains blocks %d,0,%d to %d,255,%d)", new Object[] {Integer.valueOf(j1), Integer.valueOf(k1), Integer.valueOf(l1), Integer.valueOf(l), Integer.valueOf(i1), Integer.valueOf(i2), Integer.valueOf(j2), Integer.valueOf(k2), Integer.valueOf(l2)})); } catch (Throwable var16) { stringbuilder.append("(Error finding chunk loc)"); } stringbuilder.append(", "); try { int j3 = i >> 9; int k3 = k >> 9; int l3 = j3 << 5; int i4 = k3 << 5; int j4 = (j3 + 1 << 5) - 1; int k4 = (k3 + 1 << 5) - 1; int l4 = j3 << 9; int i5 = k3 << 9; int j5 = (j3 + 1 << 9) - 1; int i3 = (k3 + 1 << 9) - 1; stringbuilder.append(String.format("Region: (%d,%d; contains chunks %d,%d to %d,%d, blocks %d,0,%d to %d,255,%d)", new Object[] {Integer.valueOf(j3), Integer.valueOf(k3), Integer.valueOf(l3), Integer.valueOf(i4), Integer.valueOf(j4), Integer.valueOf(k4), Integer.valueOf(l4), Integer.valueOf(i5), Integer.valueOf(j5), Integer.valueOf(i3)})); } catch (Throwable var15) { stringbuilder.append("(Error finding world loc)"); } return stringbuilder.toString(); } /** * Adds a Crashreport section with the given name with the value set to the result of the given Callable; */ public void addCrashSectionCallable(String sectionName, Callable<String> callable) { try { this.addCrashSection(sectionName, callable.call()); } catch (Throwable throwable) { this.addCrashSectionThrowable(sectionName, throwable); } } /** * Adds a Crashreport section with the given name with the given value (convered .toString()) */ public void addCrashSection(String sectionName, Object value) { this.children.add(new CrashReportCategory.Entry(sectionName, value)); } /** * Adds a Crashreport section with the given name with the given Throwable */ public void addCrashSectionThrowable(String sectionName, Throwable throwable) { this.addCrashSection(sectionName, throwable); } /** * Resets our stack trace according to the current trace, pruning the deepest 3 entries. The parameter indicates * how many additional deepest entries to prune. Returns the number of entries in the resulting pruned stack trace. */ public int getPrunedStackTrace(int size) { StackTraceElement[] astacktraceelement = Thread.currentThread().getStackTrace(); if (astacktraceelement.length <= 0) { return 0; } else { int len = astacktraceelement.length - 3 - size; // Really Mojang, Still, god damn... if (len <= 0) len = astacktraceelement.length; this.stackTrace = new StackTraceElement[len]; System.arraycopy(astacktraceelement, astacktraceelement.length - len, this.stackTrace, 0, this.stackTrace.length); return this.stackTrace.length; } } /** * Do the deepest two elements of our saved stack trace match the given elements, in order from the deepest? */ public boolean firstTwoElementsOfStackTraceMatch(StackTraceElement s1, StackTraceElement s2) { if (this.stackTrace.length != 0 && s1 != null) { StackTraceElement stacktraceelement = this.stackTrace[0]; if (stacktraceelement.isNativeMethod() == s1.isNativeMethod() && stacktraceelement.getClassName().equals(s1.getClassName()) && stacktraceelement.getFileName().equals(s1.getFileName()) && stacktraceelement.getMethodName().equals(s1.getMethodName())) { if (s2 != null != this.stackTrace.length > 1) { return false; } else if (s2 != null && !this.stackTrace[1].equals(s2)) { return false; } else { this.stackTrace[0] = s1; return true; } } else { return false; } } else { return false; } } /** * Removes the given number entries from the bottom of the stack trace. */ public void trimStackTraceEntriesFromBottom(int amount) { StackTraceElement[] astacktraceelement = new StackTraceElement[this.stackTrace.length - amount]; System.arraycopy(this.stackTrace, 0, astacktraceelement, 0, astacktraceelement.length); this.stackTrace = astacktraceelement; } public void appendToStringBuilder(StringBuilder builder) { builder.append("-- ").append(this.name).append(" --\n"); builder.append("Details:"); for (CrashReportCategory.Entry crashreportcategory$entry : this.children) { builder.append("\n\t"); builder.append(crashreportcategory$entry.getKey()); builder.append(": "); builder.append(crashreportcategory$entry.getValue()); } if (this.stackTrace != null && this.stackTrace.length > 0) { builder.append("\nStacktrace:"); for (StackTraceElement stacktraceelement : this.stackTrace) { builder.append("\n\tat "); builder.append(stacktraceelement.toString()); } } } public StackTraceElement[] getStackTrace() { return this.stackTrace; } public static void addBlockInfo(CrashReportCategory category, final BlockPos pos, final Block blockIn, final int blockData) { final int i = Block.getIdFromBlock(blockIn); category.addCrashSectionCallable("Block type", new Callable<String>() { public String call() throws Exception { try { return String.format("ID #%d (%s // %s)", new Object[] {Integer.valueOf(i), blockIn.getUnlocalizedName(), blockIn.getClass().getCanonicalName()}); } catch (Throwable var2) { return "ID #" + i; } } }); category.addCrashSectionCallable("Block data value", new Callable<String>() { public String call() throws Exception { if (blockData < 0) { return "Unknown? (Got " + blockData + ")"; } else { String s = String.format("%4s", new Object[] {Integer.toBinaryString(blockData)}).replace(" ", "0"); return String.format("%1$d / 0x%1$X / 0b%2$s", new Object[] {Integer.valueOf(blockData), s}); } } }); category.addCrashSectionCallable("Block location", new Callable<String>() { public String call() throws Exception { return CrashReportCategory.getCoordinateInfo(pos); } }); } public static void addBlockInfo(CrashReportCategory category, final BlockPos pos, final IBlockState state) { category.addCrashSectionCallable("Block", new Callable<String>() { public String call() throws Exception { return state.toString(); } }); category.addCrashSectionCallable("Block location", new Callable<String>() { public String call() throws Exception { return CrashReportCategory.getCoordinateInfo(pos); } }); } static class Entry { private final String key; private final String value; public Entry(String key, Object value) { this.key = key; if (value == null) { this.value = "~~NULL~~"; } else if (value instanceof Throwable) { Throwable throwable = (Throwable)value; this.value = "~~ERROR~~ " + throwable.getClass().getSimpleName() + ": " + throwable.getMessage(); } else { this.value = value.toString(); } } public String getKey() { return this.key; } public String getValue() { return this.value; } } }
lgpl-2.1
Polyglotter/chrysalix
modelspace/modelspace-engine/src/main/java/org/modelspace/Modelspace.java
13745
/* * Chrysalix * See the COPYRIGHT.txt file distributed with this work for information * regarding copyright ownership. Some portions may be licensed * to Red Hat, Inc. under one or more contributor license agreements. * See the AUTHORS.txt file in the distribution for a full listing of * individual contributors. * * Chrysalix is free software. Unless otherwise indicated, all code in Chrysalix * is licensed to you under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * Chrysalix is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.modelspace; import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import org.chrysalix.common.Logger; import org.modelspace.internal.ModelspaceImpl; /** * */ public interface Modelspace extends AutoCloseable { /** * */ Logger LOGGER = Logger.logger( ModelspaceI18n.class ); /** * @return the path to the configuration for the embedded repository supplied when this Modelspace was instantiated. */ String configurationPath(); /** * * @param path * the path of the model being deleted (cannot be <code>null</code> or empty) * @return <code>true</code> if deleted or <code>false</code> if node at that path does not exist * @throws ModelspaceException * if node is not a model at that path */ boolean deleteModel( String path ) throws ModelspaceException; /** * @param model * a workspace model * @param file * a file to which the supplied model should be exported * @throws ModelspaceException * if any problem occurs */ void export( Model model, File file ) throws ModelspaceException; /** * @param model * a workspace model * @param stream * an output stream to which the supplied model should be exported * @throws ModelspaceException * if any problem occurs */ void export( Model model, OutputStream stream ) throws ModelspaceException; /** * @param model * a workspace model * @param url * a URL to which the supplied model should be exported * @throws ModelspaceException * if any problem occurs */ void export( Model model, URL url ) throws ModelspaceException; /** * @param dataPath * the workspace path to the data; must not be empty. * @param modelPath * the workspace path where the model should be created * @return a new model using a metamodel determined by the data's content, and if the data is a file, its file extension; never * <code>null</code> * @throws ModelspaceException * if any problem occurs */ Model generateModel( final String dataPath, final String modelPath ) throws ModelspaceException; /** * @param dataPath * the workspace path to the data; must not be empty. * @param modelPath * the workspace path where the model should be created * @param metamodel * the metamodel of model to be created for the supplied data; may be <code>null</code>. * @return a new model of the supplied metamodel; never <code>null</code> * @throws ModelspaceException * if any problem occurs */ Model generateModel( final String dataPath, final String modelPath, final Metamodel metamodel ) throws ModelspaceException; /** * @param file * the file to be imported. Must not be <code>null</code>. * @param workspaceFolder * the parent path where the file should be imported * @return the workspace path the to imported data * @throws ModelspaceException * if any problem occurs */ String importData( final File file, final String workspaceFolder ) throws ModelspaceException; /** * @param file * the file to be imported. Must not be <code>null</code>. * @param workspaceFolder * the parent path where the file should be imported * @param workspaceName * the name of the file in the workspace. If <code>null</code> or empty, the name of the supplied file will be used. * @return the workspace path the to imported data * @throws ModelspaceException * if any problem occurs */ String importData( final File file, final String workspaceFolder, final String workspaceName ) throws ModelspaceException; /** * @param stream * the data's content to be imported. Must not be <code>null</code>. * @param workspacePath * the path where the data should be imported * @return the workspace path the to imported data * @throws ModelspaceException * if any problem occurs */ String importData( final InputStream stream, final String workspacePath ) throws ModelspaceException; /** * @param url * the name of the data as it should be stored in the workspace. Must not be empty. * @param workspaceFolder * the parent path where the data should be imported * @return the workspace path the to imported data * @throws ModelspaceException * if any problem occurs */ String importData( final URL url, final String workspaceFolder ) throws ModelspaceException; /** * @param url * the name of the data as it should be stored in the workspace. Must not be empty. * @param workspaceFolder * the parent path where the data should be imported * @param workspaceName * the name of the data in the workspace. If <code>null</code> or empty, the last segment of the supplied URL will be * used. * @return the workspace path the to imported data * @throws ModelspaceException * if any problem occurs */ String importData( final URL url, final String workspaceFolder, final String workspaceName ) throws ModelspaceException; /** * Creates a model with the name of the supplied file. * * @param file * the file to be imported. Must not be <code>null</code>. * @param modelFolder * the parent path where the model should be created * @param metamodel * the metamodel of model to be created for the supplied data; may be <code>null</code>. * @return a new model of the supplied metamodel; never <code>null</code> * @throws ModelspaceException * if any problem occurs */ Model importModel( final File file, final String modelFolder, final Metamodel metamodel ) throws ModelspaceException; /** * Creates a model with the name of the supplied file. * * @param file * the file to be imported. Must not be <code>null</code>. * @param modelFolder * the parent path where the model should be created * @param modelName * the name of the model. If <code>null</code> or empty, the name of the supplied file will be used. * @param metamodel * the metamodel of model to be created for the supplied data; may be <code>null</code>. * @return a new model of the supplied metamodel; never <code>null</code> * @throws ModelspaceException * if any problem occurs */ Model importModel( final File file, final String modelFolder, final String modelName, final Metamodel metamodel ) throws ModelspaceException; /** * @param stream * the data's content to be imported. Must not be <code>null</code>. * @param modelPath * the path where the model should be created * @param metamodel * the metamodel of model to be created for the supplied data; may be <code>null</code>. * @return a new model of the supplied metamodel; never <code>null</code> * @throws ModelspaceException * if any problem occurs */ Model importModel( final InputStream stream, final String modelPath, final Metamodel metamodel ) throws ModelspaceException; /** * @param dataUrl * the URL of an data; must not be <code>null</code>. * @param modelFolder * the parent path where the model should be created * @param metamodel * the metamodel of model to be created for the supplied data; may be <code>null</code>. * @return a new model of the supplied metamodel; never <code>null</code> * @throws ModelspaceException * if any problem occurs */ Model importModel( final URL dataUrl, final String modelFolder, final Metamodel metamodel ) throws ModelspaceException; /** * @param dataUrl * the URL of an data; must not be <code>null</code>. * @param modelFolder * the parent path where the model should be created * @param modelName * the name of the model. If <code>null</code> or empty, the name of the supplied file will be used. * @param metamodel * the metamodel of model to be created for the supplied data; may be <code>null</code>. * @return a new model of the supplied metamodel; never <code>null</code> * @throws ModelspaceException * if any problem occurs */ Model importModel( final URL dataUrl, final String modelFolder, final String modelName, final Metamodel metamodel ) throws ModelspaceException; /** * @return the metamodel manager * @throws ModelspaceException * if any error occurs */ MetamodelManager metamodelManager() throws ModelspaceException; /** * @param path * a workspace path for a model * @return the model at the supplied path, or <code>null</code> if not found * @throws ModelspaceException * if any error occurs */ Model model( final String path ) throws ModelspaceException; /** * Creates a new model or returns an existing one. * * @param modelPath * the workspace path where the model should be created (cannot be <code>null</code> or empty) * @param metamodelId * the metamodel identifier (cannot be <code>null</code> or empty) * @return the new model or the existing one (never <code>null</code>) * @throws ModelspaceException * if the path already exists and the node is not a model with the specified metamodel ID */ Model newModel( final String modelPath, final String metamodelId ) throws ModelspaceException; /** * Creates a new model or returns an existing one. * * @param modelPath * the workspace path where the model should be created (cannot be <code>null</code> or empty) * @param metamodelId * the metamodel identifier (cannot be <code>null</code> or empty) * @param override * <code>true</code> if an existing model is found and should be replaced * @return the new model or the existing one (never <code>null</code>) * @throws ModelspaceException * when not in override mode, if the path already exists and the node is not a model with the specified metamodel ID */ Model newModel( final String modelPath, final String metamodelId, boolean override ) throws ModelspaceException; /** * @return the path to the folder that should contain the repository store */ String repositoryStoreParentPath(); /** * */ class Factory { /** * Uses a default configuration. * * @param repositoryStoreParentPath * the path to the folder that should contain the repository store * @return a new Modelspace with a default configuration */ public static Modelspace instance( final String repositoryStoreParentPath ) { return instance( repositoryStoreParentPath ); } /** * @param repositoryStoreParentPath * the path to the folder that should contain the repository store * @param configurationPath * the path to a configuration file * @return a new Modelspace */ public static Modelspace instance( final String repositoryStoreParentPath, final String configurationPath ) { return new ModelspaceImpl( repositoryStoreParentPath, configurationPath ); } } }
lgpl-2.1
guyue123/ly
ly-editor/src/name/huliqing/editor/tiles/AxisLine.java
2109
/* * LuoYing is a program used to make 3D RPG game. * Copyright (c) 2014-2016 Huliqing <31703299@qq.com> * * This file is part of LuoYing. * * LuoYing is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * LuoYing is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with LuoYing. If not, see <http://www.gnu.org/licenses/>. */ package name.huliqing.editor.tiles; import com.jme3.math.ColorRGBA; import com.jme3.math.Vector3f; import com.jme3.scene.Geometry; import com.jme3.scene.Node; import com.jme3.scene.shape.Line; import com.jme3.util.TempVars; import name.huliqing.luoying.utils.MaterialUtils; /** * * @author huliqing */ public class AxisLine extends Node { private final Geometry line; public AxisLine() { Line lineShape = new Line(new Vector3f(0, 0, -10000) , new Vector3f(0, 0, 10000)); line = new Geometry("debugLine", lineShape); line.setMaterial(MaterialUtils.createUnshaded()); attachChild(line); } public void setDirection(Vector3f direction) { TempVars tv = TempVars.get(); tv.quat1.lookAt(direction, Vector3f.UNIT_Y); if (getParent() != null) { tv.quat2.set(getParent().getWorldRotation()).inverseLocal(); tv.quat2.multLocal(tv.quat1); tv.quat2.normalizeLocal(); setLocalRotation(tv.quat2); } else { setLocalRotation(tv.quat1); } tv.release(); } public void setColor(ColorRGBA color) { line.getMaterial().setColor("Color", color); } }
lgpl-3.0
OldShatterhand77/Portofino
elements/src/main/java/com/manydesigns/elements/annotations/DecimalFormat.java
1596
/* * Copyright (C) 2005-2015 ManyDesigns srl. All rights reserved. * http://www.manydesigns.com/ * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package com.manydesigns.elements.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /* * @author Paolo Predonzani - paolo.predonzani@manydesigns.com * @author Angelo Lupo - angelo.lupo@manydesigns.com * @author Giampiero Granatella - giampiero.granatella@manydesigns.com * @author Alessio Stalla - alessio.stalla@manydesigns.com */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.METHOD}) public @interface DecimalFormat { public static final String copyright = "Copyright (c) 2005-2015, ManyDesigns srl"; String value(); }
lgpl-3.0
dresden-ocl/dresdenocl
plugins/org.dresdenocl.tools.CWM/src/orgomg/cwm/management/warehouseprocess/datatype/DatatypeFactory.java
967
/** * <copyright> * </copyright> * * $Id$ */ package orgomg.cwm.management.warehouseprocess.datatype; import org.eclipse.emf.ecore.EFactory; /** * <!-- begin-user-doc --> * The <b>Factory</b> for the model. * It provides a create method for each non-abstract class of the model. * <!-- end-user-doc --> * @see orgomg.cwm.management.warehouseprocess.datatype.DatatypePackage * @generated */ public interface DatatypeFactory extends EFactory { /** * The singleton instance of the factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ DatatypeFactory eINSTANCE = orgomg.cwm.management.warehouseprocess.datatype.impl.DatatypeFactoryImpl.init(); /** * Returns the package supported by this factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the package supported by this factory. * @generated */ DatatypePackage getDatatypePackage(); } //DatatypeFactory
lgpl-3.0
ever-been/everBeen
debug-assistant/src/main/java/cz/cuni/mff/d3s/been/debugassistant/DebugListItem.java
1562
package cz.cuni.mff.d3s.been.debugassistant; import java.io.Serializable; /** * Debug item. * * @author Kuba Břečka */ public class DebugListItem implements Serializable { private String taskId; private String hostName; private int debugPort; private boolean suspended; /** * Whether the task is suspended. * * @return Whether the task is suspended. */ public boolean isSuspended() { return suspended; } /** * Sets suspended flag. * * @param suspended * the flag */ public void setSuspended(boolean suspended) { this.suspended = suspended; } /** * Returns taskId of the listening task * * @return taskId of the listening task */ public String getTaskId() { return taskId; } /** * Returns host name of the listening task * * @return host name of the listening task */ public String getHostName() { return hostName; } /** * Returns debug port of the listening task * * @return debug port of the listening task */ public int getDebugPort() { return debugPort; } /** * Creates new DebugListItem. * * @param taskId * ID of the listening task * @param hostName * host name where the task is * @param debugPort * port the task listens on * @param suspended * whether the task was suspended on start */ public DebugListItem(String taskId, String hostName, int debugPort, boolean suspended) { this.taskId = taskId; this.hostName = hostName; this.debugPort = debugPort; this.suspended = suspended; } }
lgpl-3.0
MineServerProject/RedstoneLamp
src/main/java/net/redstonelamp/inventory/SavableInventory.java
1289
/* * This file is part of RedstoneLamp. * * RedstoneLamp is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * RedstoneLamp is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with RedstoneLamp. If not, see <http://www.gnu.org/licenses/>. */ package net.redstonelamp.inventory; /** * An Inventory that can be saved and loaded from byte arrays. * * @author RedstoneLamp Team */ public interface SavableInventory extends Inventory{ /** * Saves this inventory into a ByteArray. * * @return The ByteArray representation of this Inventory. */ byte[] saveToBytes(); /** * Loads this inventory from a ByteArray. * * @param bytes The ByteArray representation of this Inventory that will be loaded * from. */ void loadFromBytes(byte[] bytes); }
lgpl-3.0
simeshev/parabuild-ci
3rdparty/rome08/samples/src/java/com/sun/syndication/samples/FeedReader.java
1754
/* * Copyright 2004 Sun Microsystems, Inc. * * 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. * */ package com.sun.syndication.samples; import com.sun.syndication.feed.synd.SyndFeed; import com.sun.syndication.io.SyndFeedInput; import com.sun.syndication.io.XmlReader; import java.net.URL; /** * It Reads and prints any RSS/Atom feed type. * <p> * @author Alejandro Abdelnur * */ public class FeedReader { public static void main(String[] args) { boolean ok = false; if (args.length==1) { try { URL feedUrl = new URL(args[0]); SyndFeedInput input = new SyndFeedInput(); SyndFeed feed = input.build(new XmlReader(feedUrl)); System.out.println(feed); ok = true; } catch (Exception ex) { ex.printStackTrace(); System.out.println("ERROR: "+ex.getMessage()); } } if (!ok) { System.out.println(); System.out.println("FeedReader reads and prints any RSS/Atom feed type."); System.out.println("The first parameter must be the URL of the feed to read."); System.out.println(); } } }
lgpl-3.0
simeshev/parabuild-ci
3rdparty/findbugs086src/src/tools/edu/umd/cs/findbugs/tools/patcomp/SimpleNode.java
2968
/* Generated By:JJTree: Do not edit this line. SimpleNode.java */ package edu.umd.cs.findbugs.tools.patcomp; public class SimpleNode implements Node { protected Node parent; protected Node[] children; protected int id; protected PatternCompiler parser; /* DHH: added these fields to keep track of tokens */ private Token firstToken, lastToken; public SimpleNode(int i) { id = i; } public SimpleNode(PatternCompiler p, int i) { this(i); parser = p; } /** Get the id of this node. */ public int getId() { return id; } /** Set first token. */ public void setFirstToken(Token t) { if (t == null) throw new IllegalStateException(); this.firstToken = t; } /** Get the first token. */ public Token getFirstToken() { return firstToken; } /** Set last token. */ public void setLastToken(Token t) { if (t == null) throw new IllegalStateException(); this.lastToken = t; } /** Get the last token. */ public Token getLastToken() { return lastToken; } /** Get number of tokens. */ public int getNumTokens() { int count = 0; Token cur = firstToken; while (cur != lastToken) { ++count; cur = cur.next; } return count; } /** * Get <i>n</i>th token. * Returns null if there are fewer than <i>n+1</i> tokens. */ public Token getToken(int n) { Token t = firstToken; int count = 0; while (t != null) { if (count == n) break; ++count; t = t.next; } return t; } public void jjtOpen() { } public void jjtClose() { } public void jjtSetParent(Node n) { parent = n; } public Node jjtGetParent() { return parent; } public void jjtAddChild(Node n, int i) { if (children == null) { children = new Node[i + 1]; } else if (i >= children.length) { Node c[] = new Node[i + 1]; System.arraycopy(children, 0, c, 0, children.length); children = c; } children[i] = n; } public Node jjtGetChild(int i) { return children[i]; } public int jjtGetNumChildren() { return (children == null) ? 0 : children.length; } /* You can override these two methods in subclasses of SimpleNode to customize the way the node appears when the tree is dumped. If your output uses more than one line you should override toString(String), otherwise overriding toString() is probably all you need to do. */ public String toString() { return PatternCompilerTreeConstants.jjtNodeName[id]; } public String toString(String prefix) { return prefix + toString(); } /* Override this method if you want to customize how the node dumps out its children. */ public void dump(String prefix) { System.out.println(toString(prefix)); if (children != null) { for (int i = 0; i < children.length; ++i) { SimpleNode n = (SimpleNode)children[i]; if (n != null) { n.dump(prefix + " "); } } } } }
lgpl-3.0
ari-zah/gaiasky
core/src/gaia/cu9/ari/gaiaorbit/util/coord/NslSun.java
7407
package gaia.cu9.ari.gaiaorbit.util.coord; import gaia.cu9.ari.gaiaorbit.util.Nature; import gaia.cu9.ari.gaiaorbit.util.math.Quaterniond; import gaia.cu9.ari.gaiaorbit.util.math.Vector3d; /** * Analytical representation of the Nominal Sun for the Gaia NSL. * * Uses a low precision formula for the solar longitude (apparent longitude) * valid for the period 1980-2020 with an accuracy of 0.005 deg. * * The reference frame is the ecliptic equinox J2000. * * The analytical formula for calculating the longitude is written in terms of * the number of days since J2000.0(TCB). Since the zero point for GaiaTime (the * Mission Reference Epoch, see GAIA-CA-SP-ARI-BAS-003-06, rev. 1, Sect. 3.5) is * different from J2000.0 (actually it is J2010.0), it is necessary to add the * number of days from J2000.0 to the Mission Reference Epoch before doing the * calculation. This number is given by missionReferenceEpochDaysFromJ2000. * * Since the time may be specified as the number of elapsed ns since a time * origin that is a settable attribute of the attitude data server, the NslSun * has a field timeOriginDaysFromJ2000 that can be set with setTimeOrigin(). By * default the origin time is the Mission Reference Epoch. * */ public class NslSun { // the zero point for mission reference static final double missionReferenceEpoch = 0l; static final double piHalf = Math.PI / 2.0; static final double NOMINALSUN_ORBITALECCENTRICITY_J2000 = 0.01671; static final double NOMINALSUN_MEANLONGITUDE_J2000 = 280.4665;// [deg] static final double NOMINALSUN_MEANLONGITUDERATE_J2000 = 0.98560903; // [deg day^-1] static final double NOMINALSUN_ORBITALMEANANOMALY_J2000 = 357.529; // [deg] static final double NOMINALSUN_ORBITALMEANANOMALYRATE_J2000 = 0.98560020; // [deg day^-1] /** * Constants used in the approximate longitude formula calculated from * obliquity and eccentricity taken from GPDB */ static final double OBLIQUITY_DEG = Coordinates.OBLIQUITY_DEG_J2000; static final double e = NOMINALSUN_ORBITALECCENTRICITY_J2000; static final double d2e = Math.toDegrees(2. * e); static final double d5_2e2 = Math.toDegrees(2.5 * e * e); static final double sineObliquity = Math.sin(Coordinates.OBLIQUITY_RAD_J2000); static final double cosineObliquity = Math.cos(Coordinates.OBLIQUITY_RAD_J2000); static final double ABERRATION_CONSTANT_J2000 = 20.49122; // static final double ABERRATION_CONSTANT_J2000 = // GaiaParam.Nature.ABERRATION_CONSTANT_J2000; private final double timeOriginDaysFromJ2000 = missionReferenceEpoch - (AstroUtils.JD_J2000 - AstroUtils.JD_J2010); private final double timeOriginNsFromJ2000 = missionReferenceEpoch - (AstroUtils.JD_J2000 - AstroUtils.JD_J2010) * Nature.D_TO_NS; /** Unit vectors **/ static final Vector3d X_AXIS = Vector3d.getUnitX(); static final Vector3d Y_AXIS = Vector3d.getUnitY(); static final Vector3d Z_AXIS = Vector3d.getUnitZ(); /** * Time dependent variables */ private double sLon, sLonMod4Pi, sLonDot, sineLon, cosineLon; /** * Constructor */ public NslSun() { } /** * Calculate all fields for a given julian date. * @param julianDate The julian date. */ public void setTime(double julianDate) { long tNs = (long) ((julianDate - AstroUtils.JD_J2000) * Nature.D_TO_NS); setTime(tNs); } /** * Calculate all fields for a given time * * Author: F. Mignard * * @param tNs * time in [ns] since the time origin */ public void setTime(long tNs) { final double daysFromJ2000 = timeOriginDaysFromJ2000 + (double) tNs * Nature.NS_TO_D; // Mean apparent Sun longitude: final double xl = NOMINALSUN_MEANLONGITUDE_J2000 - ABERRATION_CONSTANT_J2000 / 3600.0 + NOMINALSUN_MEANLONGITUDERATE_J2000 * daysFromJ2000; // Mean Sun anomaly: final double xm = NOMINALSUN_ORBITALMEANANOMALY_J2000 + NOMINALSUN_ORBITALMEANANOMALYRATE_J2000 * daysFromJ2000; final double sm = Math.sin(Math.toRadians(xm)); final double cm = Math.cos(Math.toRadians(xm)); // Longitude accurate to O(e^3) final double lon = xl + sm * (d2e + d5_2e2 * cm); this.sLonDot = Math .toRadians(NOMINALSUN_MEANLONGITUDERATE_J2000 + NOMINALSUN_ORBITALMEANANOMALYRATE_J2000 * Math.toRadians(d2e * cm + d5_2e2 * (cm * cm - sm * sm))); this.sLon = Math.toRadians(lon); this.sLonMod4Pi = Math.toRadians(lon % (2. * 360.0)); this.sineLon = Math.sin(this.sLonMod4Pi); this.cosineLon = Math.cos(this.sLonMod4Pi); } /** * @return solar longitude in [rad] */ public double getSolarLongitude() { return this.sLon; } /** * @return solar longitude in [rad], modulo 4*PI */ public double getSolarLongitudeMod4Pi() { return this.sLonMod4Pi; } /** * @return time derivative of solar longitude in [rad/day] */ public double getSolarLongitudeDot() { return sLonDot; } /** * @param out The output vector. * @return The output vector containing the solar direction as a unit 3-vector in BCRS. */ public Vector3d getSolarDirection(Vector3d out) { return out.set(cosineLon, sineLon * cosineObliquity, sineLon * sineObliquity); } /** * Method to convert heliotropic angles to quaternion * * @param t * time [ns] * @param xi * revolving angle (solar aspect angle) [rad] * @param nu * revolving phase [rad] * @param Omega * spin phase [rad] * @return attitude quaternion */ public Quaterniond heliotropicToQuaternion(long t, double xi, double nu, double Omega) { setTime(t); double sLon = getSolarLongitude(); /** SOME AXES NEED TO BE SWAPPED TO ALIGN WITH OUR REF SYS: * GLOBAL -> GAIASANDBOX * Z -> Y * X -> Z * Y -> X */ Quaterniond q = new Quaterniond(Z_AXIS, OBLIQUITY_DEG); q.mul(new Quaterniond(Y_AXIS, Math.toDegrees(sLon))); q.mul(new Quaterniond(Z_AXIS, Math.toDegrees(nu - piHalf))); q.mul(new Quaterniond(X_AXIS, Math.toDegrees(piHalf - xi))); q.mul(new Quaterniond(Y_AXIS, Math.toDegrees(Omega))); return q; } /** * Puts an angle in the base interval [ 0, nRev*2*PI ) * * @param x * angle [rad] * @param nRev * number of revolutions in base interval * @return angle in base interval [rad] */ public double angleBase(double x, int nRev) { double x1 = x; double base = (double) nRev * 2.0 * Math.PI; while (x1 >= base) { x1 -= base; } while (x1 < 0.0) { x1 += base; } return x1; } }
lgpl-3.0
dukeboard/kevoree-modeling-framework
addons/org.kevoree.modeling.microframework.addons.swing/src/main/java/org/kevoree/modeling/framework/addons/swing/GraphBuilder.java
3703
package org.kevoree.modeling.framework.addons.swing; import org.graphstream.graph.Edge; import org.graphstream.graph.Graph; import org.graphstream.graph.Node; import org.graphstream.graph.implementations.SingleGraph; import org.kevoree.modeling.KCallback; import org.kevoree.modeling.meta.KMeta; import org.kevoree.modeling.traversal.visitor.KModelVisitor; import org.kevoree.modeling.KObject; import org.kevoree.modeling.traversal.visitor.KVisitResult; import org.kevoree.modeling.memory.struct.segment.KMemorySegment; import org.kevoree.modeling.memory.manager.AccessMode; import org.kevoree.modeling.meta.KMetaReference; /** * Created by duke on 7/1/14. */ public class GraphBuilder { public static void graphFrom(KObject modelRoot, KCallback<Graph> cb) { final Graph graph = new SingleGraph("Model_" + modelRoot.metaClass().metaName()); graph.setStrict(false); createNode(graph, modelRoot); modelRoot.visit(new KModelVisitor() { @Override public KVisitResult visit(KObject elem) { createNode(graph, elem); return KVisitResult.CONTINUE; } }, new KCallback<Throwable>() { @Override public void on(Throwable throwable) { modelRoot.visit(new KModelVisitor() { @Override public KVisitResult visit(KObject elem) { createEdges(graph, elem); return KVisitResult.CONTINUE; } }, new KCallback<Throwable>() { @Override public void on(Throwable throwable) { createEdges(graph, modelRoot); graph.addAttribute("ui.antialias"); graph.addAttribute("ui.quality"); graph.addAttribute("ui.stylesheet", styleSheet); cb.on(graph); } }); } }); } private static void createNode(Graph graph, KObject elem) { Node n = graph.addNode(elem.uuid() + ""); n.addAttribute("ui.label", elem.uuid() + ":" + elem.metaClass().metaName()); } private static void createEdges(Graph graph, KObject elem) { KMemorySegment rawPayload = elem.manager().segment(elem.universe(),elem.now(),elem.uuid(),AccessMode.RESOLVE, elem.metaClass(),null); for (KMeta meta : elem.metaClass().metaElements()) { if (meta instanceof KMetaReference) { KMetaReference metaRef = (KMetaReference) meta; long[] relatedElems = rawPayload.getRef(metaRef.index(), elem.metaClass()); if (relatedElems != null) { for (int i = 0; i < relatedElems.length; i++) { Edge e = graph.addEdge(elem.uuid() + "_" + relatedElems[i] + "_" + metaRef.metaName(), elem.uuid() + "", relatedElems[i] + ""); if (e != null) { e.addAttribute("ui.label", metaRef.metaName()); } } } } } } protected static String styleSheet = "graph { padding: 100px; stroke-width: 2px; }" + "node { fill-color: orange; fill-mode: dyn-plain; }" + "edge { fill-color: grey; }" + "edge .containmentReference { fill-color: blue; }" + "node:selected { fill-color: red; fill-mode: dyn-plain; }" + "node:clicked { fill-color: blue; fill-mode: dyn-plain; }" + "node .modelRoot { fill-color: grey, yellow, purple; fill-mode: dyn-plain; }"; }
lgpl-3.0
premium-minds/pm-wicket-utils
core/src/test/java/com/premiumminds/webapp/wicket/drawer/DrawerTest.java
1951
/** * Copyright (C) 2016 Premium Minds. * * This file is part of pm-wicket-utils. * * pm-wicket-utils is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * pm-wicket-utils is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with pm-wicket-utils. If not, see <http://www.gnu.org/licenses/>. */ package com.premiumminds.webapp.wicket.drawer; import static org.junit.Assert.*; import org.junit.Test; import com.premiumminds.webapp.wicket.testing.AbstractComponentTest; public class DrawerTest extends AbstractComponentTest { private class TestDrawer extends AbstractDrawer { private static final long serialVersionUID = 1L; } @Test public void testDrawerCreation() { AbstractDrawer d = new TestDrawer(); assertEquals("drawer", d.getId()); } @Test public void testManagerManagement() { AbstractDrawer d = new TestDrawer(); DrawerManager m = new DrawerManager("test"); d.setManager(m); assertEquals(m, d.getManager()); } @Test public void testAllowCloseManagement() { AbstractDrawer d = new TestDrawer(); assertTrue(d.isAllowClose()); d.setAllowClose(false); assertFalse(d.isAllowClose()); d.setAllowClose(true); assertTrue(d.isAllowClose()); } @Test public void testEmptyOnClose() { AbstractDrawer d = new TestDrawer(); startTest(d); replayAll(); d.beforeClose(getTarget()); verifyAll(); } @Test public void testInitialization() { TestDrawer d = new TestDrawer(); startTest(d); replayAll(); verifyAll(); } }
lgpl-3.0
eponvert/texnlp
src/main/java/texnlp/io/PipeSepReader.java
3219
/////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2007 Jason Baldridge, The University of Texas at Austin // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ////////////////////////////////////////////////////////////////////////////// package texnlp.io; import java.io.EOFException; import java.io.File; import java.io.IOException; /** * Wrapper for reading in information from a file which has one * sentence per line with each word and associated tags separated by * the pipe |. E.g., the native format for the C&C tools: * * Pierre|NNP|N/N Vinken|NNP|N ,|,|, 61|CD|N/N years|NNS|N old|JJ|(S[adj]\NP)\NP ,|,|, will|MD|(S[dcl]\NP)/(S[b]\NP) join|VB|((S[b]\NP)/PP)/NP the|DT|NP[nb]/N board|NN|N as|IN|PP/NP a|DT|NP[nb]/N nonexecutive|JJ|N/N director|NN|N Nov.|NNP|((S\NP)\(S\NP))/N[num] 29|CD|N[num] .|.|. * * @author Jason Baldridge * @version $Revision: 1.53 $, $Date: 2006/10/12 21:20:44 $ */ public class PipeSepReader extends DataReader { private String[][] currentSequence = null; private int currentIndex = 0; public PipeSepReader(File f) throws IOException { super(f); } public String[] nextToken() throws IOException, EOFException { if (currentSequence == null || currentIndex == currentSequence.length) { currentSequence = nextSequence(); currentIndex = 0; } return currentSequence[currentIndex++]; } public String[][] nextSequence() throws IOException, EOFException { String[][] sequence; String line = inputReader.readLine(); if (line == null) throw new EOFException(); line = line.trim(); if (line.length() == 0) return nextSequence(); String[] items = line.split(" "); sequence = new String[items.length][]; for (int i = 0; i < items.length; i++) sequence[i] = items[i].split("\\|"); return sequence; } public String[] nextOutputSequence() throws IOException, EOFException { String[] sequence; String line = inputReader.readLine(); if (line == null) throw new EOFException(); line = line.trim(); if (line.length() == 0) return nextOutputSequence(); String[] items = line.split(" "); sequence = new String[items.length]; for (int i = 0; i < items.length; i++) sequence[i] = items[i].split("\\|")[0]; return sequence; } }
lgpl-3.0
loftuxab/community-edition-old
projects/repository/source/java/org/alfresco/repo/workflow/WorkflowPropertyHandlerRegistry.java
2873
/* * Copyright (C) 2005-2011 Alfresco Software Limited. * * This file is part of Alfresco * * Alfresco is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Alfresco is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Alfresco. If not, see <http://www.gnu.org/licenses/>. */ package org.alfresco.repo.workflow; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.alfresco.service.cmr.dictionary.TypeDefinition; import org.alfresco.service.namespace.QName; /** * @author Nick Smith * @since 3.4.e */ public class WorkflowPropertyHandlerRegistry { private final Map<QName, WorkflowPropertyHandler> handlers = new HashMap<QName, WorkflowPropertyHandler>(); private final WorkflowPropertyHandler defaultHandler; private final WorkflowQNameConverter qNameConverter; /** * @param defaultHandler * @param qNameConverter */ public WorkflowPropertyHandlerRegistry(WorkflowPropertyHandler defaultHandler, WorkflowQNameConverter qNameConverter) { this.defaultHandler = defaultHandler; this.qNameConverter = qNameConverter; } public void registerHandler(QName key, WorkflowPropertyHandler handler) { handlers.put(key, handler); } public void clear() { handlers.clear(); } public Map<String, Object> handleVariablesToSet(Map<QName, Serializable> properties, TypeDefinition type, Object object, Class<?> objectType) { Map<String, Object> variablesToSet = new HashMap<String, Object>(); for (Entry<QName, Serializable> entry : properties.entrySet()) { QName key = entry.getKey(); Serializable value = entry.getValue(); WorkflowPropertyHandler handler = handlers.get(key); if (handler == null) { handler = defaultHandler; } Object result = handler.handleProperty(key, value, type, object, objectType); if (WorkflowPropertyHandler.DO_NOT_ADD.equals(result)==false) { String keyStr = qNameConverter.mapQNameToName(key); variablesToSet.put(keyStr, result); } } return variablesToSet; } }
lgpl-3.0
1024122298/bergamot
bergamot-timerange/src/main/java/com/intrbiz/bergamot/timerange/parser/TimeRangeParserInternalConstants.java
975
/* Generated By:JavaCC: Do not edit this line. TimeRangeParserInternalConstants.java */ package com.intrbiz.bergamot.timerange.parser; /** * Token literal values and constants. * Generated by org.javacc.parser.OtherFilesGen#start() */ public interface TimeRangeParserInternalConstants { /** End of File. */ int EOF = 0; /** RegularExpression Id. */ int DIGITS = 6; /** RegularExpression Id. */ int COLON = 7; /** RegularExpression Id. */ int MINUS = 8; /** RegularExpression Id. */ int COMMA = 9; /** RegularExpression Id. */ int DAY = 10; /** RegularExpression Id. */ int DAYOFWEEK = 11; /** RegularExpression Id. */ int MONTH = 12; /** Lexical state. */ int DEFAULT = 0; /** Literal token values. */ String[] tokenImage = { "<EOF>", "\" \"", "\"\\t\"", "\"\\n\"", "\"\\r\"", "\"\\r\\n\"", "<DIGITS>", "\":\"", "\"-\"", "\",\"", "\"day\"", "<DAYOFWEEK>", "<MONTH>", }; }
lgpl-3.0
PierreR/sonarqube
server/sonar-server/src/main/java/org/sonar/server/computation/issue/TrackerRawInputFactory.java
5567
/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2014 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.computation.issue; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.sonar.api.issue.Issue; import org.sonar.api.rule.RuleKey; import org.sonar.api.utils.KeyValueFormat; import org.sonar.api.utils.log.Loggers; import org.sonar.batch.protocol.output.BatchReport; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.issue.tracking.Input; import org.sonar.core.issue.tracking.LazyInput; import org.sonar.core.issue.tracking.LineHashSequence; import org.sonar.core.util.CloseableIterator; import org.sonar.server.computation.batch.BatchReportReader; import org.sonar.server.computation.component.Component; import org.sonar.server.computation.component.TreeRootHolder; import org.sonar.server.computation.issue.commonrule.CommonRuleEngine; import org.sonar.server.rule.CommonRuleKeys; public class TrackerRawInputFactory { private final TreeRootHolder treeRootHolder; private final BatchReportReader reportReader; private final CommonRuleEngine commonRuleEngine; public TrackerRawInputFactory(TreeRootHolder treeRootHolder, BatchReportReader reportReader, CommonRuleEngine commonRuleEngine) { this.treeRootHolder = treeRootHolder; this.reportReader = reportReader; this.commonRuleEngine = commonRuleEngine; } public Input<DefaultIssue> create(Component component) { return new RawLazyInput(component); } private class RawLazyInput extends LazyInput<DefaultIssue> { private final Component component; private RawLazyInput(Component component) { this.component = component; } @Override protected LineHashSequence loadLineHashSequence() { Iterable<String> lines; if (component.getType() == Component.Type.FILE) { lines = Lists.newArrayList(reportReader.readFileSource(component.getRef())); } else { lines = Collections.emptyList(); } return LineHashSequence.createForLines(lines); } @Override protected List<DefaultIssue> loadIssues() { List<DefaultIssue> result = new ArrayList<>(); for (DefaultIssue commonRuleIssue : commonRuleEngine.process(component)) { result.add(init(commonRuleIssue)); } try (CloseableIterator<BatchReport.Issue> reportIssues = reportReader.readComponentIssues(component.getRef())) { // optimization - do not load line hashes if there are no issues -> getLineHashSequence() is executed // as late as possible while (reportIssues.hasNext()) { BatchReport.Issue reportIssue = reportIssues.next(); if (isIssueOnUnsupportedCommonRule(reportIssue)) { DefaultIssue issue = toIssue(getLineHashSequence(), reportIssue); result.add(issue); } else { Loggers.get(getClass()).debug("Ignored issue from analysis report on rule {}:{}", reportIssue.getRuleRepository(), reportIssue.getRuleKey()); } } } return result; } private boolean isIssueOnUnsupportedCommonRule(BatchReport.Issue issue) { // issues on batch common rules are ignored. This feature // is natively supported by compute engine since 5.2. return !issue.getRuleRepository().startsWith(CommonRuleKeys.REPOSITORY_PREFIX); } private DefaultIssue toIssue(LineHashSequence lineHashSeq, BatchReport.Issue reportIssue) { DefaultIssue issue = new DefaultIssue(); init(issue); issue.setRuleKey(RuleKey.of(reportIssue.getRuleRepository(), reportIssue.getRuleKey())); if (reportIssue.hasLine()) { issue.setLine(reportIssue.getLine()); issue.setChecksum(lineHashSeq.getHashForLine(reportIssue.getLine())); } else { issue.setChecksum(""); } if (reportIssue.hasMsg()) { issue.setMessage(reportIssue.getMsg()); } if (reportIssue.hasSeverity()) { issue.setSeverity(reportIssue.getSeverity().name()); } if (reportIssue.hasEffortToFix()) { issue.setEffortToFix(reportIssue.getEffortToFix()); } if (reportIssue.hasAttributes()) { issue.setAttributes(KeyValueFormat.parse(reportIssue.getAttributes())); } return issue; } private DefaultIssue init(DefaultIssue issue) { issue.setResolution(null); issue.setStatus(Issue.STATUS_OPEN); issue.setComponentUuid(component.getUuid()); issue.setComponentKey(component.getKey()); issue.setProjectUuid(treeRootHolder.getRoot().getUuid()); issue.setProjectKey(treeRootHolder.getRoot().getKey()); return issue; } } }
lgpl-3.0
thumx/community-edition
projects/repository/source/java/org/alfresco/repo/invitation/activiti/SendNominatedInviteDelegate.java
1866
/* * Copyright (C) 2005-2011 Alfresco Software Limited. * * This file is part of Alfresco * * Alfresco is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Alfresco is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Alfresco. If not, see <http://www.gnu.org/licenses/>. */ package org.alfresco.repo.invitation.activiti; import java.util.Map; import org.activiti.engine.delegate.DelegateExecution; import org.alfresco.repo.workflow.activiti.ActivitiConstants; /** * Activiti delegate that is executed when a invitation request has * been sent. * * @author Nick Smith * @author Frederik Heremans * @since 4.0 */ public class SendNominatedInviteDelegate extends AbstractInvitationDelegate { public static final String EMAIL_TEMPLATE_XPATH = "app:company_home/app:dictionary/app:email_templates/cm:invite/cm:invite-email.html.ftl"; public static final String EMAIL_SUBJECT_KEY = "invitation.invitesender.email.subject"; @Override public void execute(DelegateExecution execution) throws Exception { String invitationId = ActivitiConstants.ENGINE_ID + "$" + execution.getProcessInstanceId(); Map<String, Object> variables = execution.getVariables(); inviteHelper.sendNominatedInvitation(invitationId, EMAIL_TEMPLATE_XPATH, EMAIL_SUBJECT_KEY, variables); } }
lgpl-3.0
SoftwareEngineeringToolDemos/FSE-2011-EvoSuite
client/src/main/java/org/evosuite/symbolic/solver/cvc4/ConstraintToCVC4Visitor.java
3574
/** * Copyright (C) 2010-2015 Gordon Fraser, Andrea Arcuri and EvoSuite * contributors * * This file is part of EvoSuite. * * EvoSuite is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser Public License as published by the * Free Software Foundation, either version 3.0 of the License, or (at your * option) any later version. * * EvoSuite is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser Public License for more details. * * You should have received a copy of the GNU Lesser Public License along * with EvoSuite. If not, see <http://www.gnu.org/licenses/>. */ package org.evosuite.symbolic.solver.cvc4; import java.util.HashSet; import java.util.Set; import org.evosuite.symbolic.expr.Comparator; import org.evosuite.symbolic.expr.ConstraintVisitor; import org.evosuite.symbolic.expr.Expression; import org.evosuite.symbolic.expr.IntegerConstraint; import org.evosuite.symbolic.expr.RealConstraint; import org.evosuite.symbolic.expr.StringConstraint; import org.evosuite.symbolic.solver.SmtExprBuilder; import org.evosuite.symbolic.solver.smt.SmtExpr; final class ConstraintToCVC4Visitor implements ConstraintVisitor<SmtExpr, Void> { private final Set<String> stringConstants = new HashSet<String>(); private final ExprToCVC4Visitor exprVisitor; public ConstraintToCVC4Visitor() { this(false); } public ConstraintToCVC4Visitor(boolean rewriteNonLinearConstraints) { this.exprVisitor = new ExprToCVC4Visitor(rewriteNonLinearConstraints); } @Override public SmtExpr visit(IntegerConstraint c, Void arg) { Expression<?> leftOperand = c.getLeftOperand(); Expression<?> rightOperand = c.getRightOperand(); Comparator cmp = c.getComparator(); return visit(leftOperand, cmp, rightOperand); } private SmtExpr visit(Expression<?> leftOperand, Comparator cmp, Expression<?> rightOperand) { SmtExpr left = leftOperand.accept(exprVisitor, null); SmtExpr right = rightOperand.accept(exprVisitor, null); if (left == null || right == null) { return null; } return mkComparison(left, cmp, right); } @Override public SmtExpr visit(RealConstraint c, Void arg) { Expression<?> leftOperand = c.getLeftOperand(); Expression<?> rightOperand = c.getRightOperand(); Comparator cmp = c.getComparator(); return visit(leftOperand, cmp, rightOperand); } @Override public SmtExpr visit(StringConstraint c, Void arg) { Expression<?> leftOperand = c.getLeftOperand(); Expression<?> rightOperand = c.getRightOperand(); Comparator cmp = c.getComparator(); return visit(leftOperand, cmp, rightOperand); } private static SmtExpr mkComparison(SmtExpr left, Comparator cmp, SmtExpr right) { switch (cmp) { case LT: { SmtExpr lt = SmtExprBuilder.mkLt(left, right); return lt; } case LE: { SmtExpr le = SmtExprBuilder.mkLe(left, right); return le; } case GT: { SmtExpr gt = SmtExprBuilder.mkGt(left, right); return gt; } case GE: { SmtExpr ge = SmtExprBuilder.mkGe(left, right); return ge; } case EQ: { SmtExpr ge = SmtExprBuilder.mkEq(left, right); return ge; } case NE: { SmtExpr ge = SmtExprBuilder.mkEq(left, right); SmtExpr ne = SmtExprBuilder.mkNot(ge); return ne; } default: { throw new RuntimeException("Unknown comparator for constraint " + cmp.toString()); } } } public Set<String> getStringConstants() { return stringConstants; } }
lgpl-3.0
ryanbauman/bulkioInterfaces
libsrc/java/src/bulkio/OutUShortPort.java
1357
/* * This file is protected by Copyright. Please refer to the COPYRIGHT file * distributed with this source distribution. * * This file is part of REDHAWK bulkioInterfaces. * * REDHAWK bulkioInterfaces is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * REDHAWK bulkioInterfaces is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package bulkio; import org.apache.log4j.Logger; /** * */ public class OutUShortPort extends OutUInt16Port { /** * @generated */ public OutUShortPort(String portName) { super(portName ); } public OutUShortPort(String portName, Logger logger) { super(portName, logger ); } public OutUShortPort(String portName, Logger logger, ConnectionEventListener eventCB ) { super(portName, logger, eventCB ); } }
lgpl-3.0
Letractively/open-tides
src/org/opentides/persistence/impl/FileInfoDAOJpaImpl.java
1391
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. */ package org.opentides.persistence.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import org.opentides.bean.FileInfo; import org.opentides.persistence.FileInfoDAO; public class FileInfoDAOJpaImpl extends BaseEntityDAOJpaImpl<FileInfo, Long> implements FileInfoDAO { public List<FileInfo> findFileInfoByFullPath(String fullPath) { Map<String, Object> params = new HashMap<String, Object>(); params.put("path", fullPath.trim()); List<FileInfo> result = findByNamedQuery("jpql.fileInfo.findFileInfoByFullPath", params); return result; } }
apache-2.0
apache/incubator-systemml
src/main/java/org/apache/sysds/hops/codegen/opt/InterestingPoint.java
2908
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ package org.apache.sysds.hops.codegen.opt; import org.apache.sysds.hops.codegen.template.CPlanMemoTable.MemoTableEntry; import org.apache.sysds.runtime.util.UtilFunctions; /** * Interesting decision point with regard to materialization of intermediates. * These points are defined by a type, as well as hop ID for consumer-producer * relationships. Equivalence is defined solely on the hop IDs, to simplify * their processing and avoid redundant enumeration. * */ public class InterestingPoint { public enum DecisionType { MULTI_CONSUMER, TEMPLATE_CHANGE, } private final DecisionType _type; public final long _fromHopID; //consumers public final long _toHopID; //producers public InterestingPoint(DecisionType type, long fromHopID, long toHopID) { _type = type; _fromHopID = fromHopID; _toHopID = toHopID; } public DecisionType getType() { return _type; } public long getFromHopID() { return _fromHopID; } public long getToHopID() { return _toHopID; } public static boolean isMatPoint(InterestingPoint[] list, long from, MemoTableEntry me, boolean[] plan) { for(int i=0; i<plan.length; i++) { if( !plan[i] ) continue; InterestingPoint p = list[i]; if( p._fromHopID!=from ) continue; for( int j=0; j<3; j++ ) if( p._toHopID==me.input(j) ) return true; } return false; } public static boolean isMatPoint(InterestingPoint[] list, long from, long to) { for(int i=0; i<list.length; i++) { InterestingPoint p = list[i]; if( p._fromHopID==from && p._toHopID==to ) return true; } return false; } @Override public int hashCode() { return UtilFunctions.longHashCode(_fromHopID, _toHopID); } @Override public boolean equals(Object o) { if( !(o instanceof InterestingPoint) ) return false; InterestingPoint that = (InterestingPoint) o; return _fromHopID == that._fromHopID && _toHopID == that._toHopID; } @Override public String toString() { String stype = (_type==DecisionType.MULTI_CONSUMER) ? "M" : "T"; return "(" + stype+ ":" + _fromHopID + "->" + _toHopID + ")"; } }
apache-2.0
looker-open-source/java-spanner
google-cloud-spanner/src/main/java/com/google/cloud/spanner/AsyncRunner.java
2639
/* * Copyright 2020 Google LLC * * 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. */ package com.google.cloud.spanner; import com.google.api.core.ApiFuture; import com.google.cloud.Timestamp; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; public interface AsyncRunner { /** * Functional interface for executing a read/write transaction asynchronously that returns a * result of type R. */ @FunctionalInterface interface AsyncWork<R> { /** * Performs a single transaction attempt. All reads/writes should be performed using {@code * txn}. * * <p>Implementations of this method should not attempt to commit the transaction directly: * returning normally will result in the runner attempting to commit the transaction once the * returned future completes, retrying on abort. * * <p>In most cases, the implementation will not need to catch {@code SpannerException}s from * Spanner operations, instead letting these propagate to the framework. The transaction runner * will take appropriate action based on the type of exception. In particular, implementations * should never catch an exception of type {@link SpannerErrors#isAborted}: these indicate that * some reads may have returned inconsistent data and the transaction attempt must be aborted. * * @param txn the transaction * @return future over the result of the work */ ApiFuture<R> doWorkAsync(TransactionContext txn); } /** Executes a read/write transaction asynchronously using the given executor. */ <R> ApiFuture<R> runAsync(AsyncWork<R> work, Executor executor); /** * Returns the timestamp at which the transaction committed. {@link ApiFuture#get()} will throw an * {@link ExecutionException} if the transaction did not commit. */ ApiFuture<Timestamp> getCommitTimestamp(); /** * Returns the {@link CommitResponse} of this transaction. {@link ApiFuture#get()} throws an * {@link ExecutionException} if the transaction did not commit. */ ApiFuture<CommitResponse> getCommitResponse(); }
apache-2.0
sundrio/sundrio
examples/builder/hello-world/src/main/java/io/sundr/examples/Person.java
1127
/** * Copyright 2015 The original authors. * * 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. * **/ package io.sundr.examples; import io.sundr.builder.annotations.Buildable; @Buildable public class Person { private final String firstName; private final String lastName; public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return this.firstName; } public String getLastName() { return this.lastName; } @Override public String toString() { return firstName + " " + lastName; } }
apache-2.0
HebaKhaled/bposs
src/com.mentor.nucleus.bp.io.mdl.test/src/com/mentor/nucleus/bp/io/mdl/test/ImportPasteElementsWithIPRTest.java
6238
//======================================================================== // //File: $RCSfile: ImportPasteElementsWithIPRTest.java,v $ //Version: $Revision: 1.4 $ //Modified: $Date: 2013/05/10 05:13:51 $ // //(c) Copyright 2007-2014 by Mentor Graphics Corp. 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. //======================================================================== // // This class is responsible to test IPR upon import and paste // package com.mentor.nucleus.bp.io.mdl.test; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ProjectScope; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.preferences.IScopeContext; import org.eclipse.swt.graphics.Point; import org.eclipse.ui.PlatformUI; import org.osgi.service.prefs.Preferences; import com.mentor.nucleus.bp.core.ComponentReference_c; import com.mentor.nucleus.bp.core.CorePlugin; import com.mentor.nucleus.bp.core.Gd_c; import com.mentor.nucleus.bp.core.Ooaofooa; import com.mentor.nucleus.bp.core.Package_c; import com.mentor.nucleus.bp.core.PackageableElement_c; import com.mentor.nucleus.bp.core.Pref_c; import com.mentor.nucleus.bp.core.common.ModelRoot; import com.mentor.nucleus.bp.core.ui.preferences.BridgePointProjectPreferences; import com.mentor.nucleus.bp.test.TestUtil; import com.mentor.nucleus.bp.test.common.BaseTest; import com.mentor.nucleus.bp.test.common.TestingUtilities; import com.mentor.nucleus.bp.test.common.UITestingUtilities; import com.mentor.nucleus.bp.ui.graphics.editor.GraphicalEditor; import com.mentor.nucleus.bp.ui.graphics.editor.ModelEditor; import com.mentor.nucleus.bp.utilities.ui.CanvasUtilities; public class ImportPasteElementsWithIPRTest extends BaseTest { private String projectName = "System"; public ImportPasteElementsWithIPRTest(String testName) throws Exception { super("System",testName); } @Override protected void setUp() throws Exception { super.setUp(); } public void test_ImportModelWithIPR() throws CoreException{ final IProject project = ResourcesPlugin.getWorkspace().getRoot() .getProject(projectName); m_sys = getSystemModel(project.getName()); TestUtil.yesToDialog(5000); TestingUtilities.importModelUsingWizardConvertToGenerics(m_sys, m_workspace_path + "models/" + projectName+".xtuml", false); CorePlugin.enableParseAllOnResourceChange(); TestingUtilities.allowJobCompletion(); // TODO - the m_sys2 here is not the same as the m_sys we got earlier and imported into. // But the data we just imported is now connected to m_sys2 and not m_sys. Don't know if this // is a testing issue or a real problem. m_sys = getSystemModel(project.getName()); Package_c pkg = Package_c.getOneEP_PKGOnR1401(m_sys); ComponentReference_c imported = ComponentReference_c.getOneCL_ICOnR8001(PackageableElement_c.getOnePE_PEOnR8000(pkg)); assertNotNull(imported); assertFalse(imported.getAssignedcomp_id() == Gd_c.Null_unique_id()); } public void testCopyPasteElementWithIPR() { // create new package to paste Component reference in m_sys.Newpackage(); setIPRPreference(projectName, false); ModelRoot [] roots = Ooaofooa.getInstancesUnderSystem(projectName); // Copy the component reference ComponentReference_c cpElement = null; for(ModelRoot root : roots) { cpElement = ComponentReference_c.ComponentReferenceInstance(root); if(cpElement != null) { break; } } assertNotNull(cpElement); assertFalse(cpElement.getAssignedcomp_id() == Gd_c.Null_unique_id()); // select source and destination packages Package_c[] pkgs = Package_c.getManyEP_PKGsOnR1401(m_sys); Package_c source = null; Package_c dest = null; for (Package_c packageC : pkgs) { if ( packageC.getName().equals("System")){ source = packageC; } else if ( packageC.getName().equals("Unnamed Package")){ dest = packageC; } } CanvasUtilities.openCanvasEditor(source); GraphicalEditor ce = ((ModelEditor) PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage().getActiveEditor()) .getGraphicalEditor(); // copy element UITestingUtilities.copyElement(cpElement, ce); CanvasUtilities.openCanvasEditor(dest); ce = ((ModelEditor) PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage().getActiveEditor()) .getGraphicalEditor(); TestUtil.yesToDialog(5000); // paste element UITestingUtilities.pasteClipboardContents(new Point(700, 100), ce); // Verification ComponentReference_c pasted = ComponentReference_c.getOneCL_ICOnR8001(PackageableElement_c.getOnePE_PEOnR8000(dest)); assertNotNull(pasted); assertFalse(pasted.getAssignedcomp_id() == Gd_c.Null_unique_id()); } public boolean setIPRPreference(String projectName, boolean bool) { boolean preferenceIPR = false; IProject selectedProject = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName); if (selectedProject != null) { IScopeContext projectScope = new ProjectScope(selectedProject); Preferences projectNode = projectScope.getNode(BridgePointProjectPreferences.BP_PROJECT_PREFERENCES_ID); preferenceIPR = Pref_c.Getsystemboolean( "com.mentor.nucleus.bp.ui.project.references" ,projectName); projectNode.putBoolean("com.mentor.nucleus.bp.ui.project.references", bool); } return preferenceIPR; } }
apache-2.0
kevinearls/camel
components/camel-zookeeper/src/main/java/org/apache/camel/component/zookeeper/cluster/ZooKeeperClusterView.java
6694
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ package org.apache.camel.component.zookeeper.cluster; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.apache.camel.RuntimeCamelException; import org.apache.camel.cluster.CamelClusterMember; import org.apache.camel.cluster.CamelClusterService; import org.apache.camel.component.zookeeper.ZooKeeperCuratorConfiguration; import org.apache.camel.support.cluster.AbstractCamelClusterView; import org.apache.camel.util.ObjectHelper; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.leader.LeaderSelector; import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter; import org.apache.curator.framework.recipes.leader.Participant; import org.apache.zookeeper.KeeperException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; final class ZooKeeperClusterView extends AbstractCamelClusterView { private static final Logger LOGGER = LoggerFactory.getLogger(ZooKeeperClusterView.class); private final ZooKeeperCuratorConfiguration configuration; private final CuratorFramework client; private final CuratorLocalMember localMember; private volatile LeaderSelector leaderSelector; public ZooKeeperClusterView(CamelClusterService cluster, ZooKeeperCuratorConfiguration configuration, CuratorFramework client, String namespace) { super(cluster, namespace); this.localMember = new CuratorLocalMember(); this.configuration = configuration; this.client = client; } @Override public CamelClusterMember getLocalMember() { return this.localMember; } @Override public Optional<CamelClusterMember> getLeader() { if (leaderSelector == null || isStoppingOrStopped()) { return Optional.empty(); } try { Participant participant = leaderSelector.getLeader(); return ObjectHelper.equal(participant.getId(), localMember.getId()) ? Optional.of(localMember) : Optional.of(new CuratorClusterMember(participant)); } catch (KeeperException.NoNodeException e) { LOGGER.debug("Failed to get get master because node '{}' does not yet exist (error: '{}')", configuration.getBasePath(), e.getMessage()); return Optional.empty(); } catch (Exception e) { throw new RuntimeCamelException(e); } } @Override public List<CamelClusterMember> getMembers() { if (leaderSelector == null) { return Collections.emptyList(); } try { return leaderSelector.getParticipants() .stream() .map(CuratorClusterMember::new) .collect(Collectors.toList()); } catch (KeeperException.NoNodeException e) { LOGGER.debug("Failed to get members because node '{}' does not yet exist (error: '{}')", configuration.getBasePath(), e.getMessage()); return Collections.emptyList(); } catch (Exception e) { throw new RuntimeCamelException(e); } } @Override protected void doStart() throws Exception { if (leaderSelector == null) { leaderSelector = new LeaderSelector(client, configuration.getBasePath(), new CamelLeaderElectionListener()); leaderSelector.setId(getClusterService().getId()); leaderSelector.start(); } else { leaderSelector.requeue(); } } @Override protected void doStop() throws Exception { if (leaderSelector != null) { leaderSelector.interruptLeadership(); fireLeadershipChangedEvent(getLeader()); } } @Override protected void doShutdown() throws Exception { if (leaderSelector != null) { leaderSelector.close(); } } // *********************************************** // // *********************************************** private final class CamelLeaderElectionListener extends LeaderSelectorListenerAdapter { @Override public void takeLeadership(CuratorFramework curatorFramework) throws Exception { fireLeadershipChangedEvent(Optional.of(localMember)); while (isRunAllowed()) { try { Thread.sleep(5000); } catch (InterruptedException e) { Thread.interrupted(); break; } } fireLeadershipChangedEvent(getLeader()); } } private final class CuratorLocalMember implements CamelClusterMember { @Override public boolean isLeader() { return leaderSelector != null ? leaderSelector.hasLeadership() : false; } @Override public boolean isLocal() { return true; } @Override public String getId() { return getClusterService().getId(); } } private final class CuratorClusterMember implements CamelClusterMember { private final Participant participant; CuratorClusterMember(Participant participant) { this.participant = participant; } @Override public String getId() { return participant.getId(); } @Override public boolean isLocal() { return (participant.getId() != null) ? ObjectHelper.equal(participant.getId(), localMember.getId()) : false; } @Override public boolean isLeader() { try { return leaderSelector.getLeader().equals(this.participant); } catch (Exception e) { LOGGER.debug("", e); return false; } } } }
apache-2.0
apache/tapestry3
tapestry-framework/src/org/apache/tapestry/valid/PatternDelegate.java
1588
// Copyright 2004 The Apache Software Foundation // // 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. package org.apache.tapestry.valid; /** * Implementations of this interface will provide pattern utility services. * * @author Harish Krishnaswamy * @version $Id$ * @since 3.0 */ public interface PatternDelegate { /** * Answers the question whether the input string fulfills the pattern string provided. * * @param patternString The pattern that the input string is compared against. * @param input The string under test. * @return Returns true if the pattern exists in the input string; returns false otherwise. */ public boolean contains(String patternString, String input); /** * Returns the escaped sequence of characters representing the pattern string provided. * * @param patternString The raw sequence of characters that represent the pattern. * @return The escaped sequence of characters that represent the pattern. */ public String getEscapedPatternString(String patternString); }
apache-2.0
bruceadowns/amza
amza-service/src/test/java/com/jivesoftware/os/amza/service/POCTakerCornerCases.java
18097
/* * Copyright 2016 jonathan.colt. * * 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. */ package com.jivesoftware.os.amza.service; import com.jivesoftware.os.jive.utils.ordered.id.ConstantWriterIdProvider; import com.jivesoftware.os.jive.utils.ordered.id.OrderIdProvider; import com.jivesoftware.os.jive.utils.ordered.id.OrderIdProviderImpl; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Random; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentNavigableMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.testng.annotations.Test; /** * * @author jonathan.colt */ public class POCTakerCornerCases { /* A-U1-T1,B-U2-T2,C-U3-T3 A-U1-T1,B-U2-T3,C-U3-T2 A-U1-T2,B-U2-T3,C-U3-T1 A-U1-T2,B-U2-T1,C-U3-T3 A-U1-T3,B-U2-T2,C-U3-T1 A-U1-T3,B-U2-T1,C-U3-T2 A1,B2,C3 - [A1,B2,C3], [A1,B2,C3], [A1,B2,C3] A1,B2,C3 - [A1, , ], [A1,B2, ], [ ,B2, ] A1,B2,C3 - [A1,B3, ], [A1,B2, ], [ ,B2, ] A1,B3,C2 A2,B3,C1 A2,B1,C3 A3,B2,C1 A3,B1,C2 */ /* Workload % Read % Scans % Inserts R 95 0 5 RW 50 0 50 W 1 0 99 RS 47 47 6 RSW 25 25 50 (YCSB) Our data set consists of records with a single alphanumeric key with a length of 25 bytes and 5 value fields each with 10 bytes. Thus, a single record has a raw size of 75 bytes. */ static Set<Long> actualyAdded = Collections.newSetFromMap(new ConcurrentHashMap<>()); static boolean magicEnabled = true; @Test(enabled = true) public void takerCornerCases() throws Exception { Random rand = new Random(1234); ExecutorService executorService = Executors.newCachedThreadPool(); int nodeCount = 10; int numIds = 200; int pause = 10; int maxId = nodeCount * numIds; List<Node> nodes = new ArrayList<>(); for (int i = 0; i < 10; i++) { OrderIdProvider idProvider = new OrderIdProviderImpl(new ConstantWriterIdProvider(i)); long stbAfterNAdds = (i % 2 == 0) ? 100 : Long.MAX_VALUE; nodes.add(new Node(rand, idProvider, "node-" + i, 0, i, nodeCount, maxId, pause, stbAfterNAdds, nodes)); } List<Future> futures = new ArrayList<>(); for (Node node : nodes) { futures.add(executorService.submit(node)); } Set<NodeKey> validated = new HashSet<>(); startTakingThread("all", executorService, validated, nodes, maxId); for (Future future : futures) { future.get(); } for (Node node : nodes) { node.walEntryStreamed = 0; node.walHighwaterStreamed = 0; } Node node = nodes.get(0); node.clear(); node.version = 1; validated.clear(); startTakingThread("lose a node", executorService, validated, nodes, maxId); } private void startTakingThread(String phaseName, ExecutorService executorService, Set<NodeKey> validated, List<Node> nodes, int maxId) throws Exception { Future<?> takingFuture = executorService.submit(() -> { int invalid = nodes.size(); while (invalid > 0) { try { invalid = 0; for (Node node : nodes) { if (!validated.contains(new NodeKey(node.name, node.version))) { invalid++; } node.take(); } Thread.sleep(10); } catch (Exception x) { x.printStackTrace(); } } }); while (validated.size() < nodes.size()) { for (Node node : nodes) { if (node.isValid(maxId)) { validated.add(new NodeKey(node.name, node.version)); } } System.out.println("---------------------------------------------"); System.out.println("----------- " + phaseName + "----------------"); System.out.println("---------------------------------------------"); Thread.sleep(1000); } takingFuture.get(); } static class Node implements Callable, TakeStream { ConcurrentHashMap<Long, Long> index = new ConcurrentHashMap<>(); final ConcurrentNavigableMap<Long, Integer> txIdToWalIndex = new ConcurrentSkipListMap<>(); final List<Object> wal = new ArrayList<>(); Map<NodeKey, Long> highwaters = new ConcurrentSkipListMap(); Random rand; OrderIdProvider txIdProvider; String name; long version; long start; long step; long stop; long stbAfterNAdds; long pauseBetweenAdds; long added = 0; long walEntryStreamed = 0; long walHighwaterStreamed = 0; long highestTxId = 0; long highestReplicatedTxId = 0; Object stblock = new Object(); List<Node> nodes; boolean failureStart = false; public void clear() { index.clear(); txIdToWalIndex.clear(); wal.clear(); highwaters.clear(); added = 0; walEntryStreamed = 0; walHighwaterStreamed = 0; highestReplicatedTxId = 0; } public Node(Random rand, OrderIdProvider txIdProvider, String name, long version, long start, long step, long stop, long pauseBetweenAdds, long stbAfterNAdds, List<Node> nodes) { this.rand = rand; this.txIdProvider = txIdProvider; this.name = name; this.version = version; this.start = start; this.step = step; this.stop = stop; this.pauseBetweenAdds = pauseBetweenAdds; this.stbAfterNAdds = stbAfterNAdds; this.nodes = nodes; } Set<Long> walToMissingSet(long max) { Set<Long> walSet = new TreeSet<>(); for (long i = 0; i < max; i++) { walSet.add(i); } synchronized (wal) { for (Object object : wal) { if (object instanceof WALEntry) { walSet.remove(((WALEntry) object).entry); } } } return walSet; } boolean isValid(long max) { Set<Long> set = new HashSet<>(); synchronized (wal) { for (Object object : wal) { if (object instanceof WALEntry) { WALEntry we = (WALEntry) object; if (set.contains(we.entry)) { return false; } set.add(we.entry); } } } System.out.println(name + ":" + version + " " + set.size() + "/" + max + " hightestTxId:" + highestTxId + " we:" + walEntryStreamed + " wh:" + walHighwaterStreamed + " wal=" + walToMissingSet(max) + " start=" + start + " step=" + step + " stop=" + stop ); for (Node node : nodes) { if (node == this) { continue; } Long got = highwaters.get(new NodeKey(node.name, node.version)); if (got == null) { System.out.println(name + " does not have highwaters for " + node.name); return false; } else if (got < node.highestTxId) { System.out.println(name + " need to catchup " + got + " < " + node.highestTxId); return false; } } return set.size() == max; } @Override public Void call() throws InterruptedException { int stb = 0; for (long i = start; i < stop; i += step) { actualyAdded.add(i); long txId = add(i); if (stb == stbAfterNAdds) { while (highestReplicatedTxId < txId) { Thread.sleep(10); } synchronized (stblock) { System.out.println("//////// STB ///////"); clear(); version++; failureStart = true; } } stb++; Thread.sleep(pauseBetweenAdds); } return null; } private long add(long entry) { long[] txId = new long[1]; index.computeIfAbsent(entry, (key) -> { synchronized (wal) { txId[0] = txIdProvider.nextId(); highestTxId = Math.max(highestTxId, txId[0]); int index = wal.size(); wal.add(new WALEntry(txId[0], entry)); txIdToWalIndex.put(txId[0], index); added++; } if (added % 100 == 0) { synchronized (wal) { wal.add(new WALHighwater(highwaters)); } } return key; }); return txId[0]; } public void take() { synchronized (stblock) { int i = 0; for (Node node : nodes) { if (node == this) { break; } i++; } Node next = nodes.get((i + 1) % nodes.size()); if (!failureStart) { this.take(next, new TakeCursors(next.highwaters), next); } } } private void take(Node node, TakeCursors cursors, TakeStream takeStream) { WALHighwater highwatersCopy; long highestTxIdCopy; int count; synchronized (wal) { highwatersCopy = new WALHighwater(highwaters); highestTxIdCopy = highestTxId; count = wal.size(); } Long highwaterTxId = cursors.highwaters.get(new NodeKey(name, version)); Long firstKey = (txIdToWalIndex.isEmpty()) ? null : txIdToWalIndex.firstKey(); if (firstKey == null) { stream(count, count, highwatersCopy, highestTxIdCopy, takeStream); } else if (magicEnabled && (version == 1 && (highwaterTxId == null || highwaterTxId < firstKey))) { int index = 0; DONE: for (int i = 0; i < count; i++) { Object object = wal.get(i); if (object instanceof WALHighwater) { WALHighwater walHighwater = (WALHighwater) object; if (!walHighwater.highwaters.isEmpty()) { int matched = 0; for (NodeKey nodeKey : walHighwater.highwaters.keySet()) { if (nodeKey.equals(new NodeKey(name, version))) { continue; } if (nodeKey.equals(new NodeKey(node.name, node.version))) { continue; } matched++; Long local = walHighwater.highwaters.get(nodeKey); Long cursor = cursors.highwaters.get(nodeKey); if (cursor == null || local > cursor) { break DONE; } } if (matched > 0) { index = i; } else { break DONE; } } } } System.out.println("Magic " + index); stream(index, (int) count, highwatersCopy, highestTxIdCopy, takeStream); } else { //System.out.println("Normal"); long index = 0; if (highwaterTxId != null) { Long txId = txIdToWalIndex.higherKey(highwaterTxId); if (txId != null) { index = txIdToWalIndex.get(txId); } else { index = count; } } //System.out.println(node.name + " took from " + index + " to " + count); stream(index, count, highwatersCopy, highestTxIdCopy, takeStream); } } private boolean stream(long offset, long length, WALHighwater walhighwaters, long highestTxId, TakeStream takeStream) { NodeKey nodeKey = new NodeKey(name, version); for (long i = offset; i < length; i++) { Object w = wal.get((int) i); if (w instanceof WALEntry) { if (!takeStream.stream(nodeKey, (WALEntry) w, null, null)) { return false; } } else if (!takeStream.stream(nodeKey, null, (WALHighwater) w, null)) { return false; } } takeStream.stream(nodeKey, null, walhighwaters, highestTxId); highestReplicatedTxId = Math.max(highestReplicatedTxId, highestTxId); return true; } @Override public boolean stream(NodeKey nodeKey, WALEntry walEntry, WALHighwater walHighwater, Long highestTxId) { NodeKey self = new NodeKey(name, version); if (walEntry != null) { walEntryStreamed++; highwaters.compute(nodeKey, (key, currentTxId) -> Math.max(walEntry.txId, (currentTxId == null) ? -1 : currentTxId)); add(walEntry.entry); } if (walHighwater != null) { walHighwaterStreamed++; for (Map.Entry<NodeKey, Long> walObject : walHighwater.highwaters.entrySet()) { if (walObject.getKey().equals(self)) { continue; } highwaters.compute(walObject.getKey(), (key, currentTxId) -> Math.max(walObject.getValue(), (currentTxId == null) ? -1 : currentTxId)); } } if (highestTxId != null) { highwaters.compute(nodeKey, (key, currentTxId) -> Math.max(highestTxId, (currentTxId == null) ? -1 : currentTxId)); failureStart = false; } return true; } } static interface TakeStream { boolean stream(NodeKey nodeKey, WALEntry wal, WALHighwater highwater, Long highestTxId); } static class WALEntry { long txId; long entry; public WALEntry(long txId, long entry) { this.txId = txId; this.entry = entry; } } static class WALHighwater { Map<NodeKey, Long> highwaters; public WALHighwater(Map<NodeKey, Long> highwaters) { this.highwaters = new HashMap<>(highwaters); } } static class TakeCursors { Map<NodeKey, Long> highwaters; public TakeCursors(Map<NodeKey, Long> highwaters) { this.highwaters = new HashMap<>(highwaters); } } static class NodeKey implements Comparable<NodeKey> { String name; long version; public NodeKey(String name, long version) { this.name = name; this.version = version; } @Override public String toString() { return name + ":" + version; } @Override public int compareTo(NodeKey o) { int c = name.compareTo(o.name); if (c != 0) { return c; } return Long.compare(version, o.version); } @Override public int hashCode() { int hash = 7; hash = 11 * hash + Objects.hashCode(this.name); hash = 11 * hash + (int) (this.version ^ (this.version >>> 32)); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final NodeKey other = (NodeKey) obj; if (this.version != other.version) { return false; } if (!Objects.equals(this.name, other.name)) { return false; } return true; } } }
apache-2.0
gargamelcat/ONE4
src/oca/java/src/org/opennebula/client/OneResponse.java
3021
/******************************************************************************* * Copyright 2002-2013, OpenNebula Project (OpenNebula.org), C12G Labs * * 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. ******************************************************************************/ package org.opennebula.client; /** * This class encapsulates OpenNebula's XML-RPC responses. Each response * carries a boolean indicating if it is an error. It can also contain a * success message, or an error message. */ public class OneResponse{ /** * Creates a new response. * * @param success Indicates if the call was successful, and if * the message is an error or an information string. * @param message String containing the response message, or * the error message. */ public OneResponse(boolean success, String message) { this.success = success; this.msg = message; } /** * Returns true if the call resulted in error. * * @return True if the call resulted in error. */ public boolean isError() { return !success; } /** * Returns a string containing the error message, or null * if the response isn't an error. * * @return A string containing the error message, or null * if the response isn't an error. */ public String getErrorMessage() { return success ? null : msg; } /** * Returns a string containing the response information, or * null if the response was an error. Note that the success * message could be also null. * * @return A string containing the response information, or * null if the response was an error. Note that the success * message could be also null. */ public String getMessage() { return success ? msg : null; } /** * Parses the string returned by getMessage * * @return The parsed int, or Integer.MIN_VALUE in case of error * * @see #getMessage */ public int getIntMessage() { int ret = Integer.MIN_VALUE; try { ret = Integer.parseInt( getMessage() ); } catch (NumberFormatException e) {} return ret; } // ------------------------------------------------------------------------ // PRIVATE ATTRIBUTES // ------------------------------------------------------------------------ private boolean success; private String msg; }
apache-2.0
daxfrost/daxtop
daxtop/trunk/dp-projects/Daxtop/src/com/dax/DaxtopProfileData.java
711
package com.dax; import java.io.Serializable; import java.util.HashMap; /** * @author Dax Frost * * This class is the generic profile data class */ public class DaxtopProfileData implements Serializable { /** Configuration data with key and value */ public HashMap<String, Object> configurationData = new HashMap<String, Object>(); /** Get daxtop profile attribute - returns null if no profile attribute is found or set */ public Object GetAttribute(String attributeName, Object defaultValue) { if (configurationData.containsKey(attributeName)) { return configurationData.get(attributeName); } else return defaultValue; } }
apache-2.0
dubex/concourse
concourse-integration-tests/src/test/java/com/cinchapi/concourse/bugrepro/CON469.java
1353
/* * Copyright (c) 2013-2017 Cinchapi Inc. * * 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. */ package com.cinchapi.concourse.bugrepro; import java.util.Set; import org.junit.Assert; import org.junit.Test; import com.cinchapi.concourse.test.ConcourseIntegrationTest; import com.google.common.collect.Sets; /** * Unit test that attempts to reproduce the issue described in CON-469. * * @author Raghav Babu */ public class CON469 extends ConcourseIntegrationTest { @Test public void reproGetInventory() { client.stage(); client.add("name", "Sachin", 1); Set<Long> expected = Sets.newHashSet(); expected.addAll(client.find("name", "Sachin")); Assert.assertEquals(expected, client.inventory()); client.abort(); Assert.assertNotEquals(expected, client.inventory()); } }
apache-2.0
yida-lxw/solr-5.3.1
lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/IDFValueSource.java
2743
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ package org.apache.lucene.queries.function.valuesource; import org.apache.lucene.index.*; import org.apache.lucene.queries.function.FunctionValues; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.similarities.PerFieldSimilarityWrapper; import org.apache.lucene.search.similarities.Similarity; import org.apache.lucene.search.similarities.TFIDFSimilarity; import org.apache.lucene.util.BytesRef; import java.io.IOException; import java.util.Map; /** * Function that returns {@link TFIDFSimilarity #idf(long, long)} * for every document. * <p> * Note that the configured Similarity for the field must be * a subclass of {@link TFIDFSimilarity} * @lucene.internal */ public class IDFValueSource extends DocFreqValueSource { public IDFValueSource(String field, String val, String indexedField, BytesRef indexedBytes) { super(field, val, indexedField, indexedBytes); } @Override public String name() { return "idf"; } @Override public FunctionValues getValues(Map context, LeafReaderContext readerContext) throws IOException { IndexSearcher searcher = (IndexSearcher)context.get("searcher"); TFIDFSimilarity sim = asTFIDF(searcher.getSimilarity(true), field); if (sim == null) { throw new UnsupportedOperationException("requires a TFIDFSimilarity (such as DefaultSimilarity)"); } int docfreq = searcher.getIndexReader().docFreq(new Term(indexedField, indexedBytes)); float idf = sim.idf(docfreq, searcher.getIndexReader().maxDoc()); return new ConstDoubleDocValues(idf, this); } // tries extra hard to cast the sim to TFIDFSimilarity static TFIDFSimilarity asTFIDF(Similarity sim, String field) { while (sim instanceof PerFieldSimilarityWrapper) { sim = ((PerFieldSimilarityWrapper)sim).get(field); } if (sim instanceof TFIDFSimilarity) { return (TFIDFSimilarity)sim; } else { return null; } } }
apache-2.0
ptupitsyn/ignite
modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsOneClientNodeTest.java
4900
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ package org.apache.ignite.internal.processors.igfs; import java.util.concurrent.Callable; import org.apache.ignite.cache.CacheWriteSynchronizationMode; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.FileSystemConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.igfs.IgfsException; import org.apache.ignite.igfs.IgfsGroupDataBlocksKeyMapper; import org.apache.ignite.igfs.IgfsPath; import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi; import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder; import org.apache.ignite.testframework.GridTestUtils; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import org.jetbrains.annotations.NotNull; import org.junit.Test; import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL; import static org.apache.ignite.cache.CacheMode.PARTITIONED; /** * Test for igfs with one node in client mode. */ public class IgfsOneClientNodeTest extends GridCommonAbstractTest { /** Regular cache name. */ private static final String CACHE_NAME = "cache"; /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName); cfg.setCacheConfiguration(cacheConfiguration(CACHE_NAME)); cfg.setClientMode(true); cfg.setDiscoverySpi(new TcpDiscoverySpi() .setForceServerMode(true) .setIpFinder(new TcpDiscoveryVmIpFinder(true))); FileSystemConfiguration igfsCfg = new FileSystemConfiguration(); igfsCfg.setName("igfs"); igfsCfg.setMetaCacheConfiguration(cacheConfiguration(DEFAULT_CACHE_NAME)); igfsCfg.setDataCacheConfiguration(cacheConfiguration(DEFAULT_CACHE_NAME)); cfg.setFileSystemConfiguration(igfsCfg); return cfg; } /** {@inheritDoc} */ protected CacheConfiguration cacheConfiguration(@NotNull String cacheName) { CacheConfiguration cacheCfg = defaultCacheConfiguration(); cacheCfg.setName(cacheName); cacheCfg.setCacheMode(PARTITIONED); cacheCfg.setBackups(0); cacheCfg.setAffinityMapper(new IgfsGroupDataBlocksKeyMapper(128)); cacheCfg.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC); cacheCfg.setAtomicityMode(TRANSACTIONAL); return cacheCfg; } /** {@inheritDoc} */ @Override protected void beforeTest() throws Exception { startGrids(1); } /** {@inheritDoc} */ @Override protected void afterTest() throws Exception { stopAllGrids(); } /** * @throws Exception If failed. */ @Test public void testStartIgfs() throws Exception { final IgfsImpl igfs = (IgfsImpl) grid(0).fileSystem("igfs"); GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { IgfsAbstractSelfTest.create(igfs, new IgfsPath[]{new IgfsPath("/dir")}, null); return null; } }, IgfsException.class, "Failed to execute operation because there are no IGFS metadata nodes."); GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { IgfsPath FILE = new IgfsPath(new IgfsPath("/dir"), "file"); igfs.delete(FILE, false); return null; } }, IgfsException.class, "Failed to execute operation because there are no IGFS metadata nodes."); GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { IgfsPath FILE = new IgfsPath(new IgfsPath("/dir"), "file"); igfs.append(FILE, true); return null; } }, IgfsException.class, "Failed to execute operation because there are no IGFS metadata nodes."); } }
apache-2.0
nterry/aws-sdk-java
aws-java-sdk-ses/src/main/java/com/amazonaws/services/simpleemail/model/GetIdentityMailFromDomainAttributesResult.java
5794
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ package com.amazonaws.services.simpleemail.model; import java.io.Serializable; /** * <p> * Represents the custom MAIL FROM attributes for a list of identities. * </p> */ public class GetIdentityMailFromDomainAttributesResult implements Serializable, Cloneable { /** * <p> * A map of identities to custom MAIL FROM attributes. * </p> */ private com.amazonaws.internal.SdkInternalMap<String, IdentityMailFromDomainAttributes> mailFromDomainAttributes; /** * <p> * A map of identities to custom MAIL FROM attributes. * </p> * * @return A map of identities to custom MAIL FROM attributes. */ public java.util.Map<String, IdentityMailFromDomainAttributes> getMailFromDomainAttributes() { if (mailFromDomainAttributes == null) { mailFromDomainAttributes = new com.amazonaws.internal.SdkInternalMap<String, IdentityMailFromDomainAttributes>(); } return mailFromDomainAttributes; } /** * <p> * A map of identities to custom MAIL FROM attributes. * </p> * * @param mailFromDomainAttributes * A map of identities to custom MAIL FROM attributes. */ public void setMailFromDomainAttributes( java.util.Map<String, IdentityMailFromDomainAttributes> mailFromDomainAttributes) { this.mailFromDomainAttributes = mailFromDomainAttributes == null ? null : new com.amazonaws.internal.SdkInternalMap<String, IdentityMailFromDomainAttributes>( mailFromDomainAttributes); } /** * <p> * A map of identities to custom MAIL FROM attributes. * </p> * * @param mailFromDomainAttributes * A map of identities to custom MAIL FROM attributes. * @return Returns a reference to this object so that method calls can be * chained together. */ public GetIdentityMailFromDomainAttributesResult withMailFromDomainAttributes( java.util.Map<String, IdentityMailFromDomainAttributes> mailFromDomainAttributes) { setMailFromDomainAttributes(mailFromDomainAttributes); return this; } public GetIdentityMailFromDomainAttributesResult addMailFromDomainAttributesEntry( String key, IdentityMailFromDomainAttributes value) { if (null == this.mailFromDomainAttributes) { this.mailFromDomainAttributes = new com.amazonaws.internal.SdkInternalMap<String, IdentityMailFromDomainAttributes>(); } if (this.mailFromDomainAttributes.containsKey(key)) throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided."); this.mailFromDomainAttributes.put(key, value); return this; } /** * Removes all the entries added into MailFromDomainAttributes. &lt;p> * Returns a reference to this object so that method calls can be chained * together. */ public GetIdentityMailFromDomainAttributesResult clearMailFromDomainAttributesEntries() { this.mailFromDomainAttributes = null; return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getMailFromDomainAttributes() != null) sb.append("MailFromDomainAttributes: " + getMailFromDomainAttributes()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof GetIdentityMailFromDomainAttributesResult == false) return false; GetIdentityMailFromDomainAttributesResult other = (GetIdentityMailFromDomainAttributesResult) obj; if (other.getMailFromDomainAttributes() == null ^ this.getMailFromDomainAttributes() == null) return false; if (other.getMailFromDomainAttributes() != null && other.getMailFromDomainAttributes().equals( this.getMailFromDomainAttributes()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getMailFromDomainAttributes() == null) ? 0 : getMailFromDomainAttributes().hashCode()); return hashCode; } @Override public GetIdentityMailFromDomainAttributesResult clone() { try { return (GetIdentityMailFromDomainAttributesResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException( "Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
apache-2.0
ESamir/elasticsearch
core/src/main/java/org/elasticsearch/index/percolator/ExtractQueryTermsService.java
9800
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you 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. */ package org.elasticsearch.index.percolator; import org.apache.lucene.document.Field; import org.apache.lucene.document.FieldType; import org.apache.lucene.index.Fields; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.MultiFields; import org.apache.lucene.index.Term; import org.apache.lucene.index.Terms; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.queries.TermsQuery; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.BoostQuery; import org.apache.lucene.search.ConstantScoreQuery; import org.apache.lucene.search.PhraseQuery; import org.apache.lucene.search.Query; import org.apache.lucene.search.TermQuery; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.BytesRefBuilder; import org.elasticsearch.common.logging.LoggerMessageFormat; import org.elasticsearch.index.mapper.ParseContext; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Utility to extract query terms from queries and create queries from documents. */ public final class ExtractQueryTermsService { private static final byte FIELD_VALUE_SEPARATOR = 0; // nul code point private ExtractQueryTermsService() { } /** * Extracts all terms from the specified query and adds it to the specified document. * @param query The query to extract terms from * @param document The document to add the extracted terms to * @param queryTermsFieldField The field in the document holding the extracted terms * @param unknownQueryField The field used to mark a document that not all query terms could be extracted. For example * the query contained an unsupported query (e.g. WildcardQuery). * @param fieldType The field type for the query metadata field */ public static void extractQueryTerms(Query query, ParseContext.Document document, String queryTermsFieldField, String unknownQueryField, FieldType fieldType) { Set<Term> queryTerms; try { queryTerms = extractQueryTerms(query); } catch (UnsupportedQueryException e) { document.add(new Field(unknownQueryField, new BytesRef(), fieldType)); return; } for (Term term : queryTerms) { BytesRefBuilder builder = new BytesRefBuilder(); builder.append(new BytesRef(term.field())); builder.append(FIELD_VALUE_SEPARATOR); builder.append(term.bytes()); document.add(new Field(queryTermsFieldField, builder.toBytesRef(), fieldType)); } } /** * Extracts all query terms from the provided query and adds it to specified list. * * From boolean query with no should clauses or phrase queries only the longest term are selected, * since that those terms are likely to be the rarest. Boolean query's must_not clauses are always ignored. * * If from part of the query, no query terms can be extracted then term extraction is stopped and * an UnsupportedQueryException is thrown. */ static Set<Term> extractQueryTerms(Query query) { // TODO: add support for the TermsQuery when it has methods to access the actual terms it encapsulates // TODO: add support for span queries if (query instanceof TermQuery) { return Collections.singleton(((TermQuery) query).getTerm()); } else if (query instanceof PhraseQuery) { Term[] terms = ((PhraseQuery) query).getTerms(); if (terms.length == 0) { return Collections.emptySet(); } // the longest term is likely to be the rarest, // so from a performance perspective it makes sense to extract that Term longestTerm = terms[0]; for (Term term : terms) { if (longestTerm.bytes().length < term.bytes().length) { longestTerm = term; } } return Collections.singleton(longestTerm); } else if (query instanceof BooleanQuery) { List<BooleanClause> clauses = ((BooleanQuery) query).clauses(); boolean hasRequiredClauses = false; for (BooleanClause clause : clauses) { if (clause.isRequired()) { hasRequiredClauses = true; break; } } if (hasRequiredClauses) { Set<Term> bestClause = null; for (BooleanClause clause : clauses) { if (clause.isRequired() == false) { // skip must_not clauses, we don't need to remember the things that do *not* match... // skip should clauses, this bq has must clauses, so we don't need to remember should clauses, since they are completely optional. continue; } Set<Term> temp = extractQueryTerms(clause.getQuery()); bestClause = selectTermListWithTheLongestShortestTerm(temp, bestClause); } if (bestClause != null) { return bestClause; } else { return Collections.emptySet(); } } else { Set<Term> terms = new HashSet<>(); for (BooleanClause clause : clauses) { if (clause.isProhibited()) { // we don't need to remember the things that do *not* match... continue; } terms.addAll(extractQueryTerms(clause.getQuery())); } return terms; } } else if (query instanceof ConstantScoreQuery) { Query wrappedQuery = ((ConstantScoreQuery) query).getQuery(); return extractQueryTerms(wrappedQuery); } else if (query instanceof BoostQuery) { Query wrappedQuery = ((BoostQuery) query).getQuery(); return extractQueryTerms(wrappedQuery); } else { throw new UnsupportedQueryException(query); } } static Set<Term> selectTermListWithTheLongestShortestTerm(Set<Term> terms1, Set<Term> terms2) { if (terms1 == null) { return terms2; } else if (terms2 == null) { return terms1; } else { int terms1ShortestTerm = minTermLength(terms1); int terms2ShortestTerm = minTermLength(terms2); // keep the clause with longest terms, this likely to be rarest. if (terms1ShortestTerm >= terms2ShortestTerm) { return terms1; } else { return terms2; } } } private static int minTermLength(Set<Term> terms) { int min = Integer.MAX_VALUE; for (Term term : terms) { min = Math.min(min, term.bytes().length); } return min; } /** * Creates a boolean query with a should clause for each term on all fields of the specified index reader. */ public static Query createQueryTermsQuery(IndexReader indexReader, String queryMetadataField, String unknownQueryField) throws IOException { List<Term> extractedTerms = new ArrayList<>(); extractedTerms.add(new Term(unknownQueryField)); Fields fields = MultiFields.getFields(indexReader); for (String field : fields) { Terms terms = fields.terms(field); if (terms == null) { continue; } BytesRef fieldBr = new BytesRef(field); TermsEnum tenum = terms.iterator(); for (BytesRef term = tenum.next(); term != null ; term = tenum.next()) { BytesRefBuilder builder = new BytesRefBuilder(); builder.append(fieldBr); builder.append(FIELD_VALUE_SEPARATOR); builder.append(term); extractedTerms.add(new Term(queryMetadataField, builder.toBytesRef())); } } return new TermsQuery(extractedTerms); } /** * Exception indicating that none or some query terms couldn't extracted from a percolator query. */ public static class UnsupportedQueryException extends RuntimeException { private final Query unsupportedQuery; public UnsupportedQueryException(Query unsupportedQuery) { super(LoggerMessageFormat.format("no query terms can be extracted from query [{}]", unsupportedQuery)); this.unsupportedQuery = unsupportedQuery; } /** * The actual Lucene query that was unsupported and caused this exception to be thrown. */ public Query getUnsupportedQuery() { return unsupportedQuery; } } }
apache-2.0
jisqyv/appinventor-sources
appinventor/components/src/com/google/appinventor/components/annotations/Asset.java
948
// -*- mode: java; c-basic-offset: 2; -*- // Copyright 2020 MIT, All rights reserved // Released under the Apache License, Version 2.0 // http://www.apache.org/licenses/LICENSE-2.0 package com.google.appinventor.components.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation used to mark a parameter as accepting an asset string. This can be used to upgrade old * components (ie components that were released before this was released). It can also be included * in new components. */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.PARAMETER}) public @interface Asset { /** * If specified, a list of extensions used to filter the asset list by. * * @return an empty array (the default) or an array of file extensions used to filter the assets */ String[] value() default {}; }
apache-2.0
prestodb/presto
presto-main/src/main/java/com/facebook/presto/operator/repartition/LongArrayBlockEncodingBuffer.java
6201
/* * 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. */ package com.facebook.presto.operator.repartition; import com.facebook.presto.common.block.ArrayAllocator; import com.facebook.presto.common.block.Block; import com.google.common.annotations.VisibleForTesting; import io.airlift.slice.SliceOutput; import org.openjdk.jol.info.ClassLayout; import static com.facebook.presto.common.array.Arrays.ExpansionFactor.LARGE; import static com.facebook.presto.common.array.Arrays.ExpansionOption.PRESERVE; import static com.facebook.presto.common.array.Arrays.ensureCapacity; import static com.facebook.presto.operator.UncheckedByteArrays.setLongUnchecked; import static com.google.common.base.MoreObjects.toStringHelper; import static io.airlift.slice.SizeOf.SIZE_OF_INT; import static java.util.Objects.requireNonNull; import static sun.misc.Unsafe.ARRAY_LONG_INDEX_SCALE; public class LongArrayBlockEncodingBuffer extends AbstractBlockEncodingBuffer { @VisibleForTesting static final int POSITION_SIZE = Long.BYTES + Byte.BYTES; private static final String NAME = "LONG_ARRAY"; private static final int INSTANCE_SIZE = ClassLayout.parseClass(LongArrayBlockEncodingBuffer.class).instanceSize(); private byte[] valuesBuffer; private int valuesBufferIndex; private int estimatedValueBufferMaxCapacity; public LongArrayBlockEncodingBuffer(ArrayAllocator bufferAllocator, boolean isNested) { super(bufferAllocator, isNested); } @Override public void accumulateSerializedRowSizes(int[] serializedRowSizes) { throw new UnsupportedOperationException("accumulateSerializedRowSizes is not supported for fixed width types"); } @Override public void appendDataInBatch() { if (batchSize == 0) { return; } appendValuesToBuffer(); appendNulls(); bufferedPositionCount += batchSize; } @Override public void serializeTo(SliceOutput output) { writeLengthPrefixedString(output, NAME); output.writeInt(bufferedPositionCount); serializeNullsTo(output); if (valuesBufferIndex > 0) { output.appendBytes(valuesBuffer, 0, valuesBufferIndex); } } @Override public void resetBuffers() { bufferedPositionCount = 0; valuesBufferIndex = 0; flushed = true; resetNullsBuffer(); } @Override public void noMoreBatches() { super.noMoreBatches(); if (flushed && valuesBuffer != null) { bufferAllocator.returnArray(valuesBuffer); valuesBuffer = null; } } @Override public long getRetainedSizeInBytes() { return INSTANCE_SIZE; } @Override public long getSerializedSizeInBytes() { return NAME.length() + SIZE_OF_INT + // NAME SIZE_OF_INT + // positionCount getNullsBufferSerializedSizeInBytes() + // nulls buffer valuesBufferIndex; // values buffer } @Override public String toString() { return toStringHelper(this) .add("super", super.toString()) .add("estimatedValueBufferMaxCapacity", estimatedValueBufferMaxCapacity) .add("valuesBufferCapacity", valuesBuffer == null ? 0 : valuesBuffer.length) .add("valuesBufferIndex", valuesBufferIndex) .toString(); } @VisibleForTesting public int getEstimatedValueBufferMaxCapacity() { return estimatedValueBufferMaxCapacity; } @Override protected void setupDecodedBlockAndMapPositions(DecodedBlockNode decodedBlockNode, int partitionBufferCapacity, double decodedBlockPageSizeFraction) { requireNonNull(decodedBlockNode, "decodedBlockNode is null"); decodedBlock = (Block) mapPositionsToNestedBlock(decodedBlockNode).getDecodedBlock(); double targetBufferSize = partitionBufferCapacity * decodedBlockPageSizeFraction; setEstimatedNullsBufferMaxCapacity(getEstimatedBufferMaxCapacity(targetBufferSize, Byte.BYTES, POSITION_SIZE)); estimatedValueBufferMaxCapacity = getEstimatedBufferMaxCapacity(targetBufferSize, Long.BYTES, POSITION_SIZE); } @Override protected void accumulateSerializedRowSizes(int[] positionOffsets, int positionCount, int[] serializedRowSizes) { for (int i = 0; i < positionCount; i++) { serializedRowSizes[i] += (positionOffsets[i + 1] - positionOffsets[i]) * POSITION_SIZE; } } private void appendValuesToBuffer() { valuesBuffer = ensureCapacity(valuesBuffer, valuesBufferIndex + batchSize * ARRAY_LONG_INDEX_SCALE, estimatedValueBufferMaxCapacity, LARGE, PRESERVE, bufferAllocator); int[] positions = getPositions(); if (decodedBlock.mayHaveNull()) { for (int i = positionsOffset; i < positionsOffset + batchSize; i++) { int position = positions[i]; int newIndex = setLongUnchecked(valuesBuffer, valuesBufferIndex, decodedBlock.getLong(position)); // Make sure the branch statement contains only one instruction, so that JVM can compile to a conditional move (cmov) if (!decodedBlock.isNull(position)) { valuesBufferIndex = newIndex; } } } else { for (int i = positionsOffset; i < positionsOffset + batchSize; i++) { valuesBufferIndex = setLongUnchecked(valuesBuffer, valuesBufferIndex, decodedBlock.getLong(positions[i])); } } } }
apache-2.0
zhangminglei/flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/FsCheckpointStorageLocation.java
4499
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ package org.apache.flink.runtime.state.filesystem; import org.apache.flink.annotation.VisibleForTesting; import org.apache.flink.core.fs.FileSystem; import org.apache.flink.core.fs.Path; import org.apache.flink.runtime.state.CheckpointMetadataOutputStream; import org.apache.flink.runtime.state.CheckpointStorageLocation; import org.apache.flink.runtime.state.CheckpointStorageLocationReference; import java.io.IOException; import static org.apache.flink.util.Preconditions.checkArgument; import static org.apache.flink.util.Preconditions.checkNotNull; /** * A storage location for checkpoints on a file system. */ public class FsCheckpointStorageLocation extends FsCheckpointStreamFactory implements CheckpointStorageLocation { private final FileSystem fileSystem; private final Path checkpointDirectory; private final Path sharedStateDirectory; private final Path taskOwnedStateDirectory; private final Path metadataFilePath; private final CheckpointStorageLocationReference reference; private final int fileStateSizeThreshold; public FsCheckpointStorageLocation( FileSystem fileSystem, Path checkpointDir, Path sharedStateDir, Path taskOwnedStateDir, CheckpointStorageLocationReference reference, int fileStateSizeThreshold) { super(fileSystem, checkpointDir, sharedStateDir, fileStateSizeThreshold); checkArgument(fileStateSizeThreshold >= 0); this.fileSystem = checkNotNull(fileSystem); this.checkpointDirectory = checkNotNull(checkpointDir); this.sharedStateDirectory = checkNotNull(sharedStateDir); this.taskOwnedStateDirectory = checkNotNull(taskOwnedStateDir); this.reference = checkNotNull(reference); this.metadataFilePath = new Path(checkpointDir, AbstractFsCheckpointStorage.METADATA_FILE_NAME); this.fileStateSizeThreshold = fileStateSizeThreshold; } // ------------------------------------------------------------------------ // Properties // ------------------------------------------------------------------------ public Path getCheckpointDirectory() { return checkpointDirectory; } public Path getSharedStateDirectory() { return sharedStateDirectory; } public Path getTaskOwnedStateDirectory() { return taskOwnedStateDirectory; } public Path getMetadataFilePath() { return metadataFilePath; } // ------------------------------------------------------------------------ // checkpoint metadata // ------------------------------------------------------------------------ @Override public CheckpointMetadataOutputStream createMetadataOutputStream() throws IOException { return new FsCheckpointMetadataOutputStream(fileSystem, metadataFilePath, checkpointDirectory); } @Override public void disposeOnFailure() throws IOException { // on a failure, no chunk in the checkpoint directory needs to be saved, so // we can drop it as a whole fileSystem.delete(checkpointDirectory, true); } @Override public CheckpointStorageLocationReference getLocationReference() { return reference; } // ------------------------------------------------------------------------ // Utilities // ------------------------------------------------------------------------ @Override public String toString() { return "FsCheckpointStorageLocation {" + "fileSystem=" + fileSystem + ", checkpointDirectory=" + checkpointDirectory + ", sharedStateDirectory=" + sharedStateDirectory + ", taskOwnedStateDirectory=" + taskOwnedStateDirectory + ", metadataFilePath=" + metadataFilePath + ", reference=" + reference + ", fileStateSizeThreshold=" + fileStateSizeThreshold + '}'; } @VisibleForTesting FileSystem getFileSystem() { return fileSystem; } }
apache-2.0
kenneththo/incubator-falcon
prism/src/main/java/org/apache/falcon/FalconWebException.java
3723
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ package org.apache.falcon; import org.apache.falcon.resource.APIResult; import org.apache.falcon.resource.InstancesResult; import org.apache.falcon.resource.InstancesSummaryResult; import org.apache.hadoop.security.authorize.AuthorizationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.PrintWriter; import java.io.StringWriter; /** * Exception for REST APIs. */ public class FalconWebException extends WebApplicationException { private static final Logger LOG = LoggerFactory.getLogger(FalconWebException.class); public static FalconWebException newException(Throwable e, Response.Status status) { if (e instanceof AuthorizationException) { status = Response.Status.FORBIDDEN; } return newException(e.getMessage(), status); } public static FalconWebException newInstanceException(Throwable e, Response.Status status) { return newInstanceException(getMessage(e), status); } public static FalconWebException newInstanceSummaryException(Throwable e, Response.Status status) { String message = getMessage(e); LOG.error("Action failed: {}\nError: {}", status, message); APIResult result = new InstancesSummaryResult(APIResult.Status.FAILED, message); return new FalconWebException(Response.status(status).entity(result).type(MediaType.TEXT_XML_TYPE).build()); } public static FalconWebException newException(APIResult result, Response.Status status) { LOG.error("Action failed: {}\nError: {}", status, result.getMessage()); return new FalconWebException(Response.status(status). entity(result).type(MediaType.TEXT_XML_TYPE).build()); } public static FalconWebException newException(String message, Response.Status status) { LOG.error("Action failed: {}\nError: {}", status, message); APIResult result = new APIResult(APIResult.Status.FAILED, message); return new FalconWebException(Response.status(status). entity(result).type(MediaType.TEXT_XML_TYPE).build()); } public static FalconWebException newInstanceException(String message, Response.Status status) { LOG.error("Action failed: {}\nError: {}", status, message); APIResult result = new InstancesResult(APIResult.Status.FAILED, message); return new FalconWebException(Response.status(status).entity(result).type(MediaType.TEXT_XML_TYPE).build()); } private static String getMessage(Throwable e) { StringWriter errors = new StringWriter(); e.printStackTrace(new PrintWriter(errors)); return errors.toString(); } public FalconWebException(Response response) { super(response); } }
apache-2.0
apache/commons-jcs
commons-jcs-core/src/main/java/org/apache/commons/jcs3/engine/CacheInfo.java
1596
package org.apache.commons.jcs3.engine; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import java.rmi.dgc.VMID; /** * This is a static variable holder for the distribution auxiliaries that need something like a vmid. */ public final class CacheInfo { /** shouldn't be instantiated */ private CacheInfo() { } /** * Used to identify a client, so we can run multiple clients off one host. * Need since there is no way to identify a client other than by host in * rmi. * <p> * TODO: may have some trouble in failover mode if the cache keeps its old * id. We may need to reset this when moving into failover. */ private static final VMID vmid = new VMID(); /** By default this is the hashcode of the VMID */ public static final long listenerId = vmid.hashCode(); }
apache-2.0
locationtech/geowave
core/cli/src/main/java/org/locationtech/geowave/core/cli/exceptions/TargetNotFoundException.java
756
/** * Copyright (c) 2013-2020 Contributors to the Eclipse Foundation * * <p> See the NOTICE file distributed with this work for additional information regarding copyright * ownership. All rights reserved. This program and the accompanying materials are made available * under the terms of the Apache License, Version 2.0 which accompanies this distribution and is * available at http://www.apache.org/licenses/LICENSE-2.0.txt */ package org.locationtech.geowave.core.cli.exceptions; public class TargetNotFoundException extends Exception { /** * */ private static final long serialVersionUID = 1L; public TargetNotFoundException() { super(); } public TargetNotFoundException(final String message) { super(message); } }
apache-2.0
anjalshireesh/gluster-ovirt-poc
backend/manager/modules/dal/src/main/java/org/ovirt/engine/core/dao/StorageDomainDAODbFacadeImpl.java
12940
package org.ovirt.engine.core.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import org.ovirt.engine.core.common.businessentities.StorageDomainSharedStatus; import org.ovirt.engine.core.common.businessentities.StorageDomainStatus; import org.ovirt.engine.core.common.businessentities.StorageDomainType; import org.ovirt.engine.core.common.businessentities.StorageFormatType; import org.ovirt.engine.core.common.businessentities.StorageType; import org.ovirt.engine.core.common.businessentities.image_group_storage_domain_map; import org.ovirt.engine.core.common.businessentities.storage_domains; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.NGuid; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.simple.ParameterizedRowMapper; import org.springframework.jdbc.core.simple.SimpleJdbcTemplate; /** * <code>StorageDomainDAODbFacadeImpl</code> provides an implementation of {@link StorageDomainDAO} based on code from * {@link org.ovirt.engine.core.dal.dbbroker.DbFacade}. * * */ public class StorageDomainDAODbFacadeImpl extends BaseDAODbFacade implements StorageDomainDAO { @Override public Guid getMasterStorageDomainIdForPool(Guid pool) { Guid returnValue = Guid.Empty; List<storage_domains> domains = getAllForStoragePool(pool); for (storage_domains domain : domains) { if (domain.getstorage_domain_type() == StorageDomainType.Master) { returnValue = domain.getid(); break; } } return returnValue; } @Override public storage_domains get(Guid id) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("id", id); ParameterizedRowMapper<storage_domains> mapper = new StorageDomainRowMapper(); return getCallsHandler().executeRead("Getstorage_domains_By_id", mapper, parameterSource); } @Override public storage_domains getForStoragePool(Guid id, NGuid storagepool) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("id", id).addValue("storage_pool_id", storagepool); ParameterizedRowMapper<storage_domains> mapper = new StorageDomainRowMapper(); return getCallsHandler().executeRead("Getstorage_domains_By_id_and_by_storage_pool_id",mapper ,parameterSource); } @SuppressWarnings("unchecked") @Override public List<storage_domains> getAllForConnection(String connection) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("connection", connection); ParameterizedRowMapper<storage_domains> mapper = new StorageDomainRowMapper(); return getCallsHandler().executeReadList("Getstorage_domains_By_connection", mapper, parameterSource); } @SuppressWarnings("unchecked") @Override public List<storage_domains> getAllForStoragePool(Guid pool) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("storage_pool_id", pool); ParameterizedRowMapper<storage_domains> mapper = new StorageDomainRowMapper(); return getCallsHandler().executeReadList("Getstorage_domains_By_storagePoolId", mapper, parameterSource); } @SuppressWarnings("unchecked") @Override public List<storage_domains> getAllForImageGroup(NGuid group) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("image_group_id", group); ParameterizedRowMapper<storage_domains> mapper = new StorageDomainRowMapper(); return getCallsHandler().executeReadList("Getstorage_domains_By_imageGroupId", mapper, parameterSource); } @SuppressWarnings("unchecked") @Override public List<storage_domains> getAllForStorageDomain(Guid id) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("storage_domain_id", id); ParameterizedRowMapper<storage_domains> mapper = new StorageDomainRowMapper(); return getCallsHandler().executeReadList("Getstorage_domains_List_By_storageDomainId", mapper, parameterSource); } @Override public List<storage_domains> getAllWithQuery(String query) { ParameterizedRowMapper<storage_domains> mapper = new StorageDomainRowMapper(); return new SimpleJdbcTemplate(jdbcTemplate).query(query, mapper); } @SuppressWarnings("unchecked") @Override public List<storage_domains> getAll() { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource(); ParameterizedRowMapper<storage_domains> mapper = new StorageDomainRowMapper(); return getCallsHandler().executeReadList("GetAllFromstorage_domains", mapper, parameterSource); } @SuppressWarnings("unchecked") @Override public List<Guid> getAllStorageDomainsByImageGroup(Guid imageGroupId) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("image_group_id", imageGroupId); ParameterizedRowMapper<Guid> mapper = new ParameterizedRowMapper<Guid>() { @Override public Guid mapRow(ResultSet rs, int rowNum) throws SQLException { return Guid.createGuidFromString(rs.getString("storage_id")); } }; return getCallsHandler().executeReadList("Getstorage_domainsId_By_imageGroupId", mapper, parameterSource); } @Override public void remove(Guid id) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("storage_domain_id", id); getCallsHandler().executeModification("Force_Delete_storage_domain", parameterSource); } @Override public image_group_storage_domain_map getImageGroupStorageDomainMapForImageGroupAndStorageDomain(image_group_storage_domain_map image_group_storage_domain_map) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("image_group_id", image_group_storage_domain_map.getimage_group_id()).addValue("storage_domain_id", image_group_storage_domain_map.getstorage_domain_id()); ParameterizedRowMapper<image_group_storage_domain_map> mapper = new ParameterizedRowMapper<image_group_storage_domain_map>() { @Override public image_group_storage_domain_map mapRow(ResultSet rs, int rowNum) throws SQLException { image_group_storage_domain_map entity = new image_group_storage_domain_map(); entity.setimage_group_id(Guid.createGuidFromString(rs.getString("image_group_id"))); entity.setstorage_domain_id(Guid.createGuidFromString(rs.getString("storage_domain_id"))); return entity; } }; return getCallsHandler().executeRead("Getimage_grp_storage_domain_mapByimg_grp_idAndstorage_domain", mapper, parameterSource); } @Override public void addImageGroupStorageDomainMap(image_group_storage_domain_map image_group_storage_domain_map) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("image_group_id", image_group_storage_domain_map.getimage_group_id()).addValue("storage_domain_id", image_group_storage_domain_map.getstorage_domain_id()); getCallsHandler().executeModification("Insertimage_group_storage_domain_map", parameterSource); } @Override public void removeImageGroupStorageDomainMap(image_group_storage_domain_map image_group_storage_domain_map) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("image_group_id", image_group_storage_domain_map.getimage_group_id()).addValue("storage_domain_id", image_group_storage_domain_map.getstorage_domain_id()); getCallsHandler().executeModification("Deleteimage_group_storage_domain_map", parameterSource); } @SuppressWarnings("unchecked") @Override public List<image_group_storage_domain_map> getAllImageGroupStorageDomainMapsForStorageDomain(Guid storage_domain_id) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("storage_domain_id", storage_domain_id); ParameterizedRowMapper<image_group_storage_domain_map> mapper = new ParameterizedRowMapper<image_group_storage_domain_map>() { @Override public image_group_storage_domain_map mapRow(ResultSet rs, int rowNum) throws SQLException { image_group_storage_domain_map entity = new image_group_storage_domain_map(); entity.setimage_group_id(Guid.createGuidFromString(rs.getString("image_group_id"))); entity.setstorage_domain_id(Guid.createGuidFromString(rs.getString("storage_domain_id"))); return entity; } }; return getCallsHandler().executeReadList("Getimage_group_storage_domain_mapBystorage_domain_id", mapper, parameterSource); } @SuppressWarnings("unchecked") @Override public List<image_group_storage_domain_map> getAllImageGroupStorageDomainMapsForImage(Guid image_group_id) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("image_group_id", image_group_id); ParameterizedRowMapper<image_group_storage_domain_map> mapper = new ParameterizedRowMapper<image_group_storage_domain_map>() { @Override public image_group_storage_domain_map mapRow(ResultSet rs, int rowNum) throws SQLException { image_group_storage_domain_map entity = new image_group_storage_domain_map(); entity.setimage_group_id(Guid.createGuidFromString(rs.getString("image_group_id"))); entity.setstorage_domain_id(Guid.createGuidFromString(rs.getString("storage_domain_id"))); return entity; } }; return getCallsHandler().executeReadList("Getimage_group_storage_domain_mapByimage_group_id", mapper, parameterSource); } /** * Row mapper to map a returned row to a {@link storage_domains} object. */ private final class StorageDomainRowMapper implements ParameterizedRowMapper<storage_domains> { @Override public storage_domains mapRow(ResultSet rs, int rowNum) throws SQLException { storage_domains entity = new storage_domains(); entity.setid(Guid.createGuidFromString(rs.getString("id"))); entity.setstorage(rs.getString("storage")); entity.setstorage_name(rs.getString("storage_name")); entity.setstorage_pool_id(NGuid.createGuidFromString(rs.getString("storage_pool_id"))); entity.setstorage_type(StorageType.forValue(rs.getInt("storage_type"))); entity.setstorage_pool_name(rs.getString("storage_pool_name")); entity.setstorage_domain_type(StorageDomainType.forValue(rs.getInt("storage_domain_type"))); entity.setStorageFormat(StorageFormatType.forValue(rs.getString("storage_domain_format_type"))); entity.setavailable_disk_size((Integer) rs.getObject("available_disk_size")); entity.setused_disk_size((Integer) rs.getObject("used_disk_size")); entity.setcommitted_disk_size(rs.getInt("commited_disk_size")); entity.setstatus(StorageDomainStatus.forValue(rs.getInt("status"))); entity.setstorage_domain_shared_status( StorageDomainSharedStatus.forValue(rs.getInt("storage_domain_shared_status"))); return entity; } } @SuppressWarnings("unchecked") @Override public List<storage_domains> getAllByStoragePoolAndConnection(Guid storagePoolId, String connection) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("storage_pool_id", storagePoolId) .addValue("connection", connection); ParameterizedRowMapper<storage_domains> mapper = new StorageDomainRowMapper(); return getCallsHandler().executeReadList("Getstorage_domains_By_storage_pool_id_and_connection", mapper, parameterSource); } }
apache-2.0
chenjianping99/CradCool
src/com/jiubang/goscreenlock/theme/cjpcardcool/weather/bean/ForecastInfo.java
3991
package com.jiubang.goscreenlock.theme.cjpcardcool.weather.bean; import com.jiubang.goscreenlock.theme.cjpcardcool.weather.common.CommonConstants; /** * 未来七天的天气预报 * * @author liuwenqin * */ public class ForecastInfo { /** * 预报日期(由mLongDate代替) */ @Deprecated private String mDate; /** * 星期几 */ private String mWeekDate; /** * 天气状态:晴、雨等 */ private String mStatus; /** * 各种天气状态对应的天气类型 */ private int mStatusType; /** * 最高温度 */ private float mHigh; /** * 最低温度 */ private float mLow; /** * 风向 */ private String mWindDir; /** * 风力 */ private String mWindStrength; /** * 风力数值 */ private float mWindStrengthValue; /** * 自定义风向类型 */ private int mWindDirType; /** * 降水概率 */ private int mPop; /** * 白天天气预报描述 */ private String mDayStatus; /** * 夜晚天气预报描述 */ private String mNightStatus; /** * 预报时间,包括年份。以当地时间为准 */ private String mLongDate; public ForecastInfo() { // 默认为无效天气信息 mDate = CommonConstants.UNKNOWN_VALUE_STRING; mWeekDate = CommonConstants.UNKNOWN_VALUE_STRING; mStatus = CommonConstants.UNKNOWN_VALUE_STRING; mStatusType = CommonConstants.UNKNOWN_WEATHER_TYPE; mHigh = CommonConstants.UNKNOWN_VALUE_INT; mLow = CommonConstants.UNKNOWN_VALUE_INT; mWindDir = CommonConstants.UNKNOWN_VALUE_STRING; mWindDirType = CommonConstants.UNKNOWN_WIND_DIR_TYPE; mWindStrength = CommonConstants.UNKNOWN_VALUE_STRING; mWindStrengthValue = CommonConstants.UNKNOWN_VALUE_FLOAT; mPop = CommonConstants.UNKNOWN_VALUE_INT; } public float getWindStrengthValue() { return mWindStrengthValue; } /** 设置风力数值 */ public void setWindStrengthInt(float windStrengthValue) { this.mWindStrengthValue = windStrengthValue; } public int getWindDirType() { return mWindDirType; } /** 设置风向类型 */ public void setWindDirType(int wind_dir_type) { this.mWindDirType = wind_dir_type; } /** * 设置风向 */ public void setWindDir(String wind_dir) { this.mWindDir = wind_dir; } public String getWindDir() { return this.mWindDir; } /** * 设置风力 */ public void setWindStrength(String wind_strength) { this.mWindStrength = wind_strength; } public String getWindStrength() { return this.mWindStrength; } public String getDate() { // getDate2 return mDate; } public void setDate(String date) { this.mDate = date; } public String getWeekDate() { return mWeekDate; } public void setWeekDate(String week_date) { this.mWeekDate = week_date; } public String getStatus() { return mStatus; } public void setStatus(String status) { this.mStatus = status; } public int getStatusType() { return mStatusType; } public void setStatusType(int status_type) { this.mStatusType = status_type; } public float getHigh() { return mHigh; } public void setHigh(float high) { this.mHigh = high; } public float getLow() { return mLow; } public void setLow(float low) { this.mLow = low; } public void setPop(int pop) { this.mPop = pop; } public int getPop() { return this.mPop; } public String getDayStatus() { return mDayStatus; } public void setDayStatus(String dayStatus) { this.mDayStatus = dayStatus; } public String getNightStatus() { return mNightStatus; } public void setNightStatus(String nightStatus) { this.mNightStatus = nightStatus; } public String getLongDate() { return mLongDate; } public void setLongDate(String longDate) { this.mLongDate = longDate; } }
apache-2.0
MathieuDuponchelle/gdx
tests/gdx-tests/src/com/badlogic/gdx/tests/IsoCamTest.java
4696
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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. ******************************************************************************/ package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputAdapter; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Intersector; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Plane; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.math.collision.Ray; import com.badlogic.gdx.tests.utils.GdxTest; public class IsoCamTest extends GdxTest { private static final int TARGET_WIDTH = 480; private static final float UNIT_TO_PIXEL = TARGET_WIDTH * 0.15f; Texture texture; OrthographicCamera cam; SpriteBatch batch; final Sprite[][] sprites = new Sprite[10][10]; final Matrix4 matrix = new Matrix4(); @Override public void create () { texture = new Texture(Gdx.files.internal("data/badlogicsmall.jpg")); float unitsOnX = (float)Math.sqrt(2) * TARGET_WIDTH / (UNIT_TO_PIXEL); float pixelsOnX = Gdx.graphics.getWidth() / unitsOnX; float unitsOnY = Gdx.graphics.getHeight() / pixelsOnX; cam = new OrthographicCamera(unitsOnX, unitsOnY, 25); cam.position.scl(30); cam.near = 1; cam.far = 1000; matrix.setToRotation(new Vector3(1, 0, 0), 90); for (int z = 0; z < 10; z++) { for (int x = 0; x < 10; x++) { sprites[x][z] = new Sprite(texture); sprites[x][z].setPosition(x, z); sprites[x][z].setSize(1, 1); } } batch = new SpriteBatch(); Gdx.input.setInputProcessor(new IsoCamController(cam)); } @Override public void dispose () { texture.dispose(); batch.dispose(); } @Override public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); cam.update(); batch.setProjectionMatrix(cam.combined); batch.setTransformMatrix(matrix); batch.begin(); for (int z = 0; z < 10; z++) { for (int x = 0; x < 10; x++) { sprites[x][z].draw(batch); } } batch.end(); checkTileTouched(); } final Plane xzPlane = new Plane(new Vector3(0, 1, 0), 0); final Vector3 intersection = new Vector3(); Sprite lastSelectedTile = null; private void checkTileTouched () { if (Gdx.input.justTouched()) { Ray pickRay = cam.getPickRay(Gdx.input.getX(), Gdx.input.getY()); Intersector.intersectRayPlane(pickRay, xzPlane, intersection); System.out.println(intersection); int x = (int)intersection.x; int z = (int)intersection.z; if (x >= 0 && x < 10 && z >= 0 && z < 10) { if (lastSelectedTile != null) lastSelectedTile.setColor(1, 1, 1, 1); Sprite sprite = sprites[x][z]; sprite.setColor(1, 0, 0, 1); lastSelectedTile = sprite; } } } public class IsoCamController extends InputAdapter { final Plane xzPlane = new Plane(new Vector3(0, 1, 0), 0); final Vector3 intersection = new Vector3(); final Vector3 curr = new Vector3(); final Vector3 last = new Vector3(-1, -1, -1); final Vector3 delta = new Vector3(); final Camera camera; public IsoCamController (Camera camera) { this.camera = camera; } @Override public boolean touchDragged (int x, int y, int pointer) { Ray pickRay = camera.getPickRay(x, y); Intersector.intersectRayPlane(pickRay, xzPlane, curr); if (!(last.x == -1 && last.y == -1 && last.z == -1)) { pickRay = camera.getPickRay(last.x, last.y); Intersector.intersectRayPlane(pickRay, xzPlane, delta); delta.sub(curr); camera.position.add(delta.x, 0, delta.z); } last.set(x, y, 0); return false; } @Override public boolean touchUp (int x, int y, int pointer, int button) { last.set(-1, -1, -1); return false; } } @Override public boolean needsGL20 () { return false; } }
apache-2.0
nsriram/No-Food-Waste
android/app/src/main/java/com/food/nofoodwaste/utils/AppSharedPreferences.java
1738
package com.food.nofoodwaste.utils; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; /** * Created by RamakrishnaAS on 7/23/2015. */ public class AppSharedPreferences { private SharedPreferences _sharedPrefs; private SharedPreferences.Editor _prefsEditor; public AppSharedPreferences(Context context) { this._sharedPrefs = context.getSharedPreferences(MyConstants.PREF_NAME_GLOBAL, Activity.MODE_PRIVATE); } public void removePreferences(String key) { editPrefs(); _prefsEditor.remove(key); commitPrefs(); } public AppSharedPreferences(Context context, String prefname) { this._sharedPrefs = context.getSharedPreferences(prefname, Activity.MODE_PRIVATE); } public void editPrefs() { this._prefsEditor = _sharedPrefs.edit(); } public String getStringPreferences(String key) { String mStringPrefs = _sharedPrefs.getString(key, ""); return mStringPrefs; } public boolean getBooleanPreferences(String key) { boolean mBoleanPrefs = _sharedPrefs.getBoolean(key, false); return mBoleanPrefs; } public void saveStringPreferences(String key, String value) { Log.v("String App Preferences", "Pref Val: " + value); editPrefs(); _prefsEditor.putString(key, value); commitPrefs(); } public void saveBooleanPreferences(String key, Boolean value) { Log.v("Boolean App Preferences", "Pref Val: " + value); editPrefs(); _prefsEditor.putBoolean(key, value); commitPrefs(); } public void commitPrefs() { _prefsEditor.commit(); } }
apache-2.0
deleidos/digitaledge-platform
webapp-tenantapi/src/main/java/com/deleidos/rtws/webapp/tenantapi/worker/SystemRequestWorker.java
13628
/** * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "{}" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright {yyyy} {name of copyright owner} * * 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. */ package com.deleidos.rtws.webapp.tenantapi.worker; import org.apache.log4j.Logger; import com.deleidos.rtws.webapp.tenantapi.worker.executor.AbstractRequestExecutor; import com.deleidos.rtws.webapp.tenantapi.worker.executor.RequestExecutorFactory; import com.deleidos.rtws.webapp.tenantapi.worker.queue.QueueManager; import com.deleidos.rtws.webapp.tenantapi.worker.request.AbstractSystemRequest; /** * This worker is in charge of executing request on the delay system request queue. */ public class SystemRequestWorker implements Runnable { private Logger logger = Logger.getLogger(SystemRequestWorker.class); @Override public void run() { logger.info("System request worker [thread-" + Thread.currentThread().getId() + "] is currently running."); while (true) { AbstractSystemRequest request = QueueManager.getSystemRequestQueue().getRequest(); if (request == null) continue; logger.debug("Processing request: " + request); AbstractRequestExecutor executor = null; boolean success = false; try { executor = RequestExecutorFactory.createSystemExecutor(request); success = executor.execute(request); } catch (Exception ex) { logger.debug("Execute system request " + request + " failed. Message: " + ex.getMessage()); } if (success || request.isRetriesExhausted()) { try { executor.releaseResource(request); } catch (Exception ex) { logger.debug("Release resource " + request + " failed. Message: " + ex.getMessage()); } QueueManager.getSystemRequestQueue().removeRequest(request.getDomain()); } else { QueueManager.getSystemRequestQueue().retryRequest(request); } } } }
apache-2.0
emergentone/10-dependencies
src/test/java/org/gradle/tests8/Test8_2.java
161
package org.gradle.tests8; import org.junit.Test; public class Test8_2 { @Test public void myTest() throws Exception { Thread.sleep(5); } }
apache-2.0
medicayun/medicayundicom
dcm4chee-web/tags/DCM4CHEE_WEB_3_0_3/dcm4chee-web-ejb/src/main/java/org/dcm4chee/web/dao/tc/TCQueryLocal.java
2986
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is part of dcm4che, an implementation of DICOM(TM) in * Java(TM), hosted at http://sourceforge.net/projects/dcm4che. * * The Initial Developer of the Original Code is * Agfa-Gevaert AG. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor(s): * See listed authors below. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ package org.dcm4chee.web.dao.tc; import java.util.List; import java.util.Map; import javax.ejb.Local; import org.dcm4chee.archive.entity.Instance; import org.dcm4chee.archive.entity.Series; import org.dcm4chee.archive.entity.Study; /** * @author Bernhard Ableitinger <bernhard.ableitinger@agfa.com> * @version $Revision$ $Date$ * @since May 05, 2011 */ @Local public interface TCQueryLocal { String JNDI_NAME = "dcm4chee-web-ear/TCListBean/local"; int countMatchingInstances(TCQueryFilter filter, List<String> roles, List<String> restrictedSourceAETs); List<Instance> findMatchingInstances(TCQueryFilter filter, List<String> roles, List<String> restrictedSourceAETs); Study findStudyByUID(String stuid); Series findSeriesByUID(String suid); Instance findInstanceByUID(String uid); Map<String, Integer> getInstanceNumbers(String suid); Map<String, Integer> findMultiframeInstances(String stuid); Map<String, Integer> findMultiframeInstances(String stuid, String suid); Map<String, Integer> findMultiframeInstances( String stuid, String suid, String...iuids); }
apache-2.0
thomsonreuters/springfox
springfox-swagger2/src/main/java/springfox/documentation/swagger2/mappers/EnumMapper.java
3746
/* * * Copyright 2015 the original author or authors. * * 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. * * */ package springfox.documentation.swagger2.mappers; import com.google.common.base.Function; import com.google.common.base.Optional; import io.swagger.models.ModelImpl; import io.swagger.models.parameters.SerializableParameter; import io.swagger.models.properties.IntegerProperty; import io.swagger.models.properties.LongProperty; import io.swagger.models.properties.Property; import io.swagger.models.properties.StringProperty; import springfox.documentation.service.AllowableListValues; import springfox.documentation.service.AllowableValues; import java.util.List; import static com.google.common.base.Optional.*; import static com.google.common.collect.FluentIterable.*; import static com.google.common.collect.Lists.*; public class EnumMapper { static ModelImpl maybeAddEnumValues(ModelImpl toReturn, AllowableValues allowableValues) { if (allowableValues instanceof AllowableListValues) { toReturn.setEnum(((AllowableListValues) allowableValues).getValues()); } return toReturn; } static SerializableParameter maybeAddEnumValues(SerializableParameter toReturn, AllowableValues allowableValues) { if (allowableValues instanceof AllowableListValues) { toReturn.setEnum(((AllowableListValues) allowableValues).getValues()); } return toReturn; } static Property maybeAddEnumValues(Property property, AllowableValues allowableValues) { if (allowableValues instanceof AllowableListValues) { if (property instanceof StringProperty) { StringProperty stringProperty = (StringProperty) property; AllowableListValues listValues = (AllowableListValues) allowableValues; stringProperty.setEnum(listValues.getValues()); } else if (property instanceof IntegerProperty) { IntegerProperty integerProperty = (IntegerProperty) property; AllowableListValues listValues = (AllowableListValues) allowableValues; integerProperty.setEnum(convert(listValues.getValues(), Integer.class)); } else if (property instanceof LongProperty) { LongProperty longProperty = (LongProperty) property; AllowableListValues listValues = (AllowableListValues) allowableValues; longProperty.setEnum(convert(listValues.getValues(), Long.class)); } } return property; } private static <T extends Number> List<T> convert(List<String> values, Class<T> toType) { return newArrayList(presentInstances(from(values).transform(converterOfType(toType)))); } private static <T extends Number> Function<? super String, Optional<T>> converterOfType(final Class<T> toType) { return new Function<String, Optional<T>>() { @SuppressWarnings("unchecked") @Override public Optional<T> apply(String input) { try { if (Integer.class.equals(toType)) { return (Optional<T>) Optional.of(new Integer(input)); } else if (Long.class.equals(toType)) { return (Optional<T>) Optional.of(new Long(input)); } } catch (NumberFormatException ignored) { } return Optional.absent(); } }; } }
apache-2.0
shuliangtao/struts-1.3.10
src/extras/src/main/java/org/apache/struts/actions/ForwardAction.java
3643
/* * $Id: ForwardAction.java 471754 2006-11-06 14:55:09Z husted $ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ package org.apache.struts.actions; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * <p>An <strong>Action</strong> that forwards to the context-relative URI * specified by the <code>parameter</code> property of our associated * <code>ActionMapping</code>. This can be used to integrate Struts with * other business logic components that are implemented as servlets (or JSP * pages), but still take advantage of the Struts controller servlet's * functionality (such as processing of form beans).</p> * * <p>To configure the use of this Action in your <code>struts-config.xml</code> * file, create an entry like this:</p> * * <code> &lt;action path="/saveSubscription" type="org.apache.struts.actions.ForwardAction" * name="subscriptionForm" scope="request" input="/subscription.jsp" * parameter="/path/to/processing/servlet"/&gt; </code> * * <p>which will forward control to the context-relative URI specified by the * <code>parameter</code> attribute.</p> * * @version $Rev: 471754 $ $Date: 2005-08-14 17:24:39 -0400 (Sun, 14 Aug 2005) * $ */ public class ForwardAction extends BaseAction { // ----------------------------------------------------- Instance Variables /** * Process the specified HTTP request, and create the corresponding HTTP * response (or forward to another web component that will create it). * Return an <code>ActionForward</code> instance describing where and how * control should be forwarded, or <code>null</code> if the response has * already been completed. * * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * @return The forward to which control should be transferred, or * <code>null</code> if the response has been completed. * @throws Exception if an error occurs */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // Create a RequestDispatcher the corresponding resource String path = mapping.getParameter(); if (path == null) { throw new ServletException(messages.getMessage("forward.path")); } // Let the controller handle the request ActionForward retVal = new ActionForward(path); return retVal; } }
apache-2.0
jhrcek/kie-wb-common
kie-wb-common-stunner/kie-wb-common-stunner-core/kie-wb-common-stunner-commons/kie-wb-common-stunner-client-common/src/main/java/org/kie/workbench/common/stunner/core/client/command/CanvasCommandManagerImpl.java
6043
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * 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. */ package org.kie.workbench.common.stunner.core.client.command; import javax.enterprise.context.Dependent; import javax.enterprise.event.Event; import javax.inject.Inject; import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvasHandler; import org.kie.workbench.common.stunner.core.client.canvas.event.command.CanvasCommandAllowedEvent; import org.kie.workbench.common.stunner.core.client.canvas.event.command.CanvasCommandExecutedEvent; import org.kie.workbench.common.stunner.core.client.canvas.event.command.CanvasUndoCommandExecutedEvent; import org.kie.workbench.common.stunner.core.command.Command; import org.kie.workbench.common.stunner.core.command.CommandListener; import org.kie.workbench.common.stunner.core.command.CommandManager; import org.kie.workbench.common.stunner.core.command.CommandResult; import org.kie.workbench.common.stunner.core.command.DelegateCommandManager; import org.kie.workbench.common.stunner.core.command.HasCommandListener; import org.kie.workbench.common.stunner.core.command.impl.CommandManagerImpl; /** * The default canvas command manager implementation. * It operates with instances of type <code>CanvasCommand</code> and throw different context events. */ @Dependent public class CanvasCommandManagerImpl<H extends AbstractCanvasHandler> extends DelegateCommandManager<H, CanvasViolation> implements CanvasCommandManager<H>, HasCommandListener<CommandListener<H, CanvasViolation>> { private final Event<CanvasCommandAllowedEvent> isCanvasCommandAllowedEvent; private final Event<CanvasCommandExecutedEvent> canvasCommandExecutedEvent; private final Event<CanvasUndoCommandExecutedEvent> canvasUndoCommandExecutedEvent; private final CommandManager<H, CanvasViolation> commandManager; private CommandListener<H, CanvasViolation> listener; protected CanvasCommandManagerImpl() { this(null, null, null); } @Inject public CanvasCommandManagerImpl(final Event<CanvasCommandAllowedEvent> isCanvasCommandAllowedEvent, final Event<CanvasCommandExecutedEvent> canvasCommandExecutedEvent, final Event<CanvasUndoCommandExecutedEvent> canvasUndoCommandExecutedEvent) { this.isCanvasCommandAllowedEvent = isCanvasCommandAllowedEvent; this.canvasCommandExecutedEvent = canvasCommandExecutedEvent; this.canvasUndoCommandExecutedEvent = canvasUndoCommandExecutedEvent; this.commandManager = new CommandManagerImpl<>(); this.listener = null; } @Override protected CommandManager<H, CanvasViolation> getDelegate() { return commandManager; } @Override @SuppressWarnings("unchecked") protected void postAllow(final H context, final Command<H, CanvasViolation> command, final CommandResult<CanvasViolation> result) { super.postAllow(context, command, result); if (null != this.listener) { listener.onAllow(context, command, result); } if (null != result && null != isCanvasCommandAllowedEvent) { isCanvasCommandAllowedEvent.fire(new CanvasCommandAllowedEvent(context, command, result)); } } @Override @SuppressWarnings("unchecked") protected void postExecute(final H context, final Command<H, CanvasViolation> command, final CommandResult<CanvasViolation> result) { super.postExecute(context, command, result); if (null != this.listener) { listener.onExecute(context, command, result); } if (null != result && null != canvasCommandExecutedEvent) { canvasCommandExecutedEvent.fire(new CanvasCommandExecutedEvent(context, command, result)); } } @Override @SuppressWarnings("unchecked") protected void postUndo(final H context, final Command<H, CanvasViolation> command, final CommandResult<CanvasViolation> result) { super.postUndo(context, command, result); if (null != this.listener) { listener.onUndo(context, command, result); } if (null != canvasUndoCommandExecutedEvent) { canvasUndoCommandExecutedEvent.fire(new CanvasUndoCommandExecutedEvent(context, command, result)); } } @Override public void setCommandListener(final CommandListener<H, CanvasViolation> listener) { this.listener = listener; } }
apache-2.0
sll8192/wpan
app/src/main/java/com/xinyu/mwp/entity/WXUserInfoEntity.java
2171
package com.xinyu.mwp.entity; import java.util.List; /** * Created by Administrator on 2017/4/20. */ public class WXUserInfoEntity extends BaseEntity { /** * openid : OPENID * nickname : NICKNAME * sex : 1 * province : PROVINCE * city : CITY * country : COUNTRY * headimgurl : http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0 * privilege : ["PRIVILEGE1","PRIVILEGE2"] * unionid : o6_bmasdasdsad6_2sgVt7hMZOPfL */ private String openid; private String nickname; private int sex; //1为男性,2为女性 private String province; private String city; private String country; private String headimgurl; private String unionid; private List<String> privilege; public String getOpenid() { return openid; } public void setOpenid(String openid) { this.openid = openid; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public int getSex() { return sex; } public void setSex(int sex) { this.sex = sex; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getHeadimgurl() { return headimgurl; } public void setHeadimgurl(String headimgurl) { this.headimgurl = headimgurl; } public String getUnionid() { return unionid; } public void setUnionid(String unionid) { this.unionid = unionid; } public List<String> getPrivilege() { return privilege; } public void setPrivilege(List<String> privilege) { this.privilege = privilege; } }
apache-2.0
akdasari/SparkCore
spark-framework/src/main/java/org/sparkcommerce/core/workflow/BaseActivity.java
3006
/* * #%L * SparkCommerce Framework * %% * Copyright (C) 2009 - 2013 Spark Commerce * %% * 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. * #L% */ package org.sparkcommerce.core.workflow; import java.util.Map; import org.sparkcommerce.core.workflow.state.RollbackHandler; import org.springframework.core.Ordered; public abstract class BaseActivity<T extends ProcessContext<?>> implements Activity<T> { protected ErrorHandler errorHandler; protected String beanName; protected RollbackHandler<T> rollbackHandler; protected String rollbackRegion; protected Map<String, Object> stateConfiguration; protected boolean automaticallyRegisterRollbackHandler = false; protected int order = Ordered.LOWEST_PRECEDENCE; @Override public boolean shouldExecute(T context) { return true; } @Override public ErrorHandler getErrorHandler() { return errorHandler; } @Override public void setBeanName(final String beanName) { this.beanName = beanName; } @Override public void setErrorHandler(final ErrorHandler errorHandler) { this.errorHandler = errorHandler; } @Override public String getBeanName() { return beanName; } @Override public RollbackHandler<T> getRollbackHandler() { return rollbackHandler; } @Override public void setRollbackHandler(RollbackHandler<T> rollbackHandler) { this.rollbackHandler = rollbackHandler; } @Override public String getRollbackRegion() { return rollbackRegion; } @Override public void setRollbackRegion(String rollbackRegion) { this.rollbackRegion = rollbackRegion; } @Override public Map<String, Object> getStateConfiguration() { return stateConfiguration; } @Override public void setStateConfiguration(Map<String, Object> stateConfiguration) { this.stateConfiguration = stateConfiguration; } @Override public boolean getAutomaticallyRegisterRollbackHandler() { return automaticallyRegisterRollbackHandler; } @Override public void setAutomaticallyRegisterRollbackHandler(boolean automaticallyRegisterRollbackHandler) { this.automaticallyRegisterRollbackHandler = automaticallyRegisterRollbackHandler; } @Override public int getOrder() { return order; } public void setOrder(int order) { this.order = order; } }
apache-2.0
marubinotto/Piggydb
src/test/java/marubinotto/piggydb/model/fragments/relation/OneFragmentRelationTest.java
3968
package marubinotto.piggydb.model.fragments.relation; import static marubinotto.piggydb.model.Assert.assertClassificationEquals; import static marubinotto.util.CollectionUtils.set; import static marubinotto.util.time.DateTime.setCurrentTimeForTest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import marubinotto.piggydb.model.FragmentRelation; import marubinotto.piggydb.model.FragmentRepository; import marubinotto.piggydb.model.exception.DuplicateException; import marubinotto.piggydb.model.exception.NoSuchEntityException; import marubinotto.piggydb.model.fragments.FragmentRepositoryTestBase; import marubinotto.util.time.DateTime; import org.junit.Before; import org.junit.Test; public class OneFragmentRelationTest extends FragmentRepositoryTestBase { protected long id1; protected long id2; protected long relationId; protected DateTime relationCreationDateTime; public OneFragmentRelationTest(RepositoryFactory<FragmentRepository> factory) { super(factory); } @Before public void given() throws Exception { super.given(); // Two fragments this.id1 = this.object.register( newFragmentWithTitleAndTags("Piggydb", "project")); this.id2 = this.object.register( newFragmentWithTitleAndTags("What is Piggydb?", "project", "draft")); // And one relation (id1 -> id2) this.relationCreationDateTime = new DateTime(2008, 1, 1); setCurrentTimeForTest(this.relationCreationDateTime); this.relationId = this.object.createRelation(this.id1, this.id2, getPlainUser()); setCurrentTimeForTest(null); } @Test public void relationCountShouldBeOne() throws Exception { assertEquals(1, this.object.countRelations().longValue()); } @Test public void getRelation() throws Exception { // When FragmentRelation relation = this.object.getRelation(this.relationId); // Then // Relation object assertEquals(this.relationId, relation.getId().longValue()); assertEquals(this.relationCreationDateTime, relation.getCreationDatetime()); assertEquals(this.relationCreationDateTime, relation.getUpdateDatetime()); assertEquals(getPlainUser().getName(), relation.getCreator()); assertNull(relation.getUpdater()); // from assertEquals("Piggydb", relation.from.getTitle()); assertClassificationEquals(set("project"), relation.from.getClassification()); // to assertEquals("What is Piggydb?", relation.to.getTitle()); assertClassificationEquals(set("project", "draft"), relation.to.getClassification()); } @Test public void getRelationWithNonexistentId() throws Exception { assertNull(this.object.getRelation(12345)); } @Test(expected=NoSuchEntityException.class) public void createRelationWithNonexistentParent() throws Exception { this.object.createRelation(123, this.id1, getPlainUser()); } @Test(expected=NoSuchEntityException.class) public void createRelationWithNonexistentChild() throws Exception { this.object.createRelation(this.id1, 123, getPlainUser()); } @Test(expected=DuplicateException.class) public void createDuplicateRelation() throws Exception { this.object.createRelation(this.id1, this.id2, getPlainUser()); } @Test public void deleteRelation() throws Exception { // When this.object.deleteRelation(this.relationId, getPlainUser()); // Then assertNull(this.object.getRelation(this.relationId)); } @Test public void deleteParentFragment() throws Exception { // When this.object.delete(this.id1, getPlainUser()); // Then assertEquals(1, this.object.size()); assertNull(this.object.getRelation(this.relationId)); } @Test public void deleteChildFragment() throws Exception { // When this.object.delete(this.id2, getPlainUser()); // Then assertEquals(1, this.object.size()); assertNull(this.object.getRelation(this.relationId)); } }
apache-2.0
irshuLx/Android-WYSIWYG-Editor
laser-native-editor/src/main/java/com/github/irshulx/Components/MacroExtensions.java
7764
package com.github.irshulx.Components; import android.app.Activity; import android.graphics.Color; import android.text.TextUtils; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import com.github.irshulx.EditorCore; import com.github.irshulx.EditorComponent; import com.github.irshulx.R; import com.github.irshulx.Utilities.Utilities; import com.github.irshulx.models.EditorContent; import com.github.irshulx.models.EditorControl; import com.github.irshulx.models.EditorType; import com.github.irshulx.models.Node; import com.github.irshulx.models.RenderType; import org.jsoup.nodes.Attribute; import org.jsoup.nodes.Element; import java.util.HashMap; import java.util.List; import java.util.Map; public class MacroExtensions extends EditorComponent { private final EditorCore editorCore; public MacroExtensions(EditorCore editorCore) { super(editorCore); this.editorCore = editorCore; } public void insertMacro(String name, View view, Map<String, Object> settings, int index) { final FrameLayout frameLayout = new FrameLayout(editorCore.getContext()); frameLayout.addView(view); final FrameLayout overlay = new FrameLayout(frameLayout.getContext()); overlay.setVisibility(View.GONE); overlay.setPadding(0, 0, 20, 0); overlay.setBackgroundColor(Color.argb(50, 0, 0, 0)); ImageView imageView = new ImageView(overlay.getContext()); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(Utilities.dpToPx(frameLayout.getContext(), 40), Utilities.dpToPx(frameLayout.getContext(), 40)); params.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL; imageView.setLayoutParams(params); imageView.setImageResource(R.drawable.ic_close_white_36dp); overlay.addView(imageView); frameLayout.addView(overlay); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { editorCore.getParentView().removeView(frameLayout); } }); EditorControl control = editorCore.createTag(EditorType.macro); control.macroSettings = settings; control.macroName = name; if (index == -1) { index = editorCore.determineIndex(EditorType.macro); } frameLayout.setTag(control); // frameLayout.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // if(overlay.getVisibility()==View.VISIBLE){ // overlay.setVisibility(View.GONE); // }else{ // overlay.setVisibility(View.VISIBLE); // } // } // }); editorCore.getParentView().addView(frameLayout, index); if(editorCore.getRenderType() == RenderType.Renderer) return; view.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { int paddingTop = view.getPaddingTop(); int paddingBottom = view.getPaddingBottom(); int height = view.getHeight(); if (event.getY() < paddingTop) { editorCore.___onViewTouched(0, editorCore.getParentView().indexOfChild(frameLayout)); } else if (event.getY() > height - paddingBottom) { editorCore.___onViewTouched(1, editorCore.getParentView().indexOfChild(frameLayout)); } else { if (overlay.getVisibility() == View.VISIBLE) { overlay.setVisibility(View.GONE); } else { overlay.setVisibility(View.VISIBLE); } } return false; } return true;//hmmmm.... } }); frameLayout.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean b) { if(!b){ overlay.setVisibility(View.GONE); } } }); } @Override public Node getContent(View view) { Node node = this.getNodeInstance(view); EditorControl macroTag = (EditorControl) view.getTag(); node.content.add(macroTag.macroName); node.macroSettings = macroTag.macroSettings; return node; } @Override public String getContentAsHTML(Node node, EditorContent content) { return getAsHtml(node.content.get(0), node.macroSettings); } private String getAsHtml(String name, Map<String, Object> macroSettings){ String template = "<{{$tag}} data-tag=\"macro\" {{$settings}}></{{$tag}}>"; template = template.replace("{{$tag}}", name); StringBuilder dataTags = new StringBuilder(); for (Map.Entry<String, Object> item : macroSettings.entrySet()) { if(item.getKey().equalsIgnoreCase("data-tag")) continue; dataTags.append(" "); if(item.getKey().contains("data-")){ dataTags.append(item.getKey()); }else { dataTags.append("data-" + item.getKey()); } dataTags.append("=\"").append(String.valueOf(item.getValue())).append("\""); } if (TextUtils.isEmpty(dataTags)) { template = template.replace("{{$settings}}", ""); } else { template = template.replace("{{$settings}}", dataTags.toString()); } return template; } @Override public void renderEditorFromState(Node node, EditorContent content) { int index = editorCore.getChildCount(); View view = editorCore.getEditorListener().onRenderMacro(node.content.get(0), node.macroSettings, editorCore.getChildCount()); if(view == null) view = getEmptyMacro(node.content.get(0),node.macroSettings); insertMacro(node.content.get(0), view, node.macroSettings, index); } private View getEmptyMacro(String name, Map<String, Object> macroSettings){ final View layout = ((Activity) editorCore.getContext()).getLayoutInflater().inflate(R.layout.default_macro, null); TextView message = layout.findViewById(R.id.txtMessage); message.setText("Unhandled macro "+ "\""+getAsHtml(name,macroSettings)+"\""); return layout; } @Override public Node buildNodeFromHTML(Element element) { String tag = element.tagName().toLowerCase(); Node node = getNodeInstance(EditorType.macro); node.content.add(tag); List<Attribute> attrs = element.attributes().asList(); if (!attrs.isEmpty()) { node.macroSettings = new HashMap<>(); for (Attribute attr : attrs) { node.macroSettings.put(attr.getKey(), attr.getValue()); } } int index = editorCore.getChildCount(); View view = editorCore.getEditorListener().onRenderMacro(tag, node.macroSettings, editorCore.getChildCount()); if(view == null) view = getEmptyMacro(node.content.get(0), node.macroSettings); insertMacro(tag, view, node.macroSettings, index); return null; } @Override public void init(ComponentsWrapper componentsWrapper) { this.componentsWrapper = componentsWrapper; } }
apache-2.0
nvoron23/incubator-calcite
core/src/main/java/net/hydromatic/optiq/runtime/RecordEnumeratorCursor.java
2178
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to you 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. */ package net.hydromatic.optiq.runtime; import net.hydromatic.linq4j.Enumerator; import java.lang.reflect.Field; /** * Implementation of {@link net.hydromatic.avatica.Cursor} on top of an * {@link net.hydromatic.linq4j.Enumerator} that * returns a record for each row. The record is a synthetic class whose fields * are all public. * * @param <E> Element type */ public class RecordEnumeratorCursor<E> extends EnumeratorCursor<E> { private final Class<E> clazz; /** * Creates a RecordEnumeratorCursor. * * @param enumerator Enumerator * @param clazz Element type */ public RecordEnumeratorCursor( Enumerator<E> enumerator, Class<E> clazz) { super(enumerator); this.clazz = clazz; } protected Getter createGetter(int ordinal) { return new RecordEnumeratorGetter(clazz.getFields()[ordinal]); } /** Implementation of {@link Getter} that reads fields via reflection. */ class RecordEnumeratorGetter extends AbstractGetter { protected final Field field; public RecordEnumeratorGetter(Field field) { this.field = field; } public Object getObject() { Object o; try { o = field.get(current()); } catch (IllegalAccessException e) { throw new RuntimeException(e); } wasNull[0] = o == null; return o; } } } // End RecordEnumeratorCursor.java
apache-2.0
jdeppe-pivotal/geode
geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/command/ClientReady.java
3166
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You 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. */ package org.apache.geode.internal.cache.tier.sockets.command; import java.io.IOException; import org.jetbrains.annotations.NotNull; import org.apache.geode.annotations.Immutable; import org.apache.geode.distributed.internal.DistributionStats; import org.apache.geode.internal.cache.tier.Command; import org.apache.geode.internal.cache.tier.sockets.BaseCommand; import org.apache.geode.internal.cache.tier.sockets.CacheServerStats; import org.apache.geode.internal.cache.tier.sockets.Message; import org.apache.geode.internal.cache.tier.sockets.ServerConnection; import org.apache.geode.internal.security.SecurityService; public class ClientReady extends BaseCommand { @Immutable private static final ClientReady singleton = new ClientReady(); public static Command getCommand() { return singleton; } private ClientReady() {} @Override public void cmdExecute(final @NotNull Message clientMessage, final @NotNull ServerConnection serverConnection, final @NotNull SecurityService securityService, long start) throws IOException { CacheServerStats stats = serverConnection.getCacheServerStats(); { long oldStart = start; start = DistributionStats.getStatTime(); stats.incReadClientReadyRequestTime(start - oldStart); } try { String clientHost = serverConnection.getSocketHost(); int clientPort = serverConnection.getSocketPort(); if (logger.isDebugEnabled()) { logger.debug("{}: Received client ready request ({} bytes) from {} on {}:{}", serverConnection.getName(), clientMessage.getPayloadLength(), serverConnection.getProxyID(), clientHost, clientPort); } serverConnection.getAcceptor().getCacheClientNotifier() .readyForEvents(serverConnection.getProxyID()); long oldStart = start; start = DistributionStats.getStatTime(); stats.incProcessClientReadyTime(start - oldStart); writeReply(clientMessage, serverConnection); serverConnection.setAsTrue(RESPONDED); if (logger.isDebugEnabled()) { logger.debug(serverConnection.getName() + ": Processed client ready request from " + serverConnection.getProxyID() + " on " + clientHost + ":" + clientPort); } } finally { stats.incWriteClientReadyResponseTime(DistributionStats.getStatTime() - start); } } }
apache-2.0
nandakumar131/hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestApplicationClassLoader.java
5556
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ package org.apache.hadoop.util; import static org.apache.hadoop.util.ApplicationClassLoader.constructUrlsFromClasspath; import static org.apache.hadoop.util.ApplicationClassLoader.isSystemClass; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.List; import java.util.jar.JarOutputStream; import java.util.zip.ZipEntry; import org.apache.commons.io.IOUtils; import org.apache.hadoop.fs.FileUtil; import org.apache.hadoop.test.GenericTestUtils; import org.junit.Before; import org.junit.Test; import org.apache.hadoop.thirdparty.com.google.common.base.Splitter; public class TestApplicationClassLoader { private static File testDir = GenericTestUtils.getTestDir("appclassloader"); @Before public void setUp() { FileUtil.fullyDelete(testDir); testDir.mkdirs(); } @Test public void testConstructUrlsFromClasspath() throws Exception { File file = new File(testDir, "file"); assertTrue("Create file", file.createNewFile()); File dir = new File(testDir, "dir"); assertTrue("Make dir", dir.mkdir()); File jarsDir = new File(testDir, "jarsdir"); assertTrue("Make jarsDir", jarsDir.mkdir()); File nonJarFile = new File(jarsDir, "nonjar"); assertTrue("Create non-jar file", nonJarFile.createNewFile()); File jarFile = new File(jarsDir, "a.jar"); assertTrue("Create jar file", jarFile.createNewFile()); File nofile = new File(testDir, "nofile"); // don't create nofile StringBuilder cp = new StringBuilder(); cp.append(file.getAbsolutePath()).append(File.pathSeparator) .append(dir.getAbsolutePath()).append(File.pathSeparator) .append(jarsDir.getAbsolutePath() + "/*").append(File.pathSeparator) .append(nofile.getAbsolutePath()).append(File.pathSeparator) .append(nofile.getAbsolutePath() + "/*").append(File.pathSeparator); URL[] urls = constructUrlsFromClasspath(cp.toString()); assertEquals(3, urls.length); assertEquals(file.toURI().toURL(), urls[0]); assertEquals(dir.toURI().toURL(), urls[1]); assertEquals(jarFile.toURI().toURL(), urls[2]); // nofile should be ignored } @Test public void testIsSystemClass() { testIsSystemClassInternal(""); } @Test public void testIsSystemNestedClass() { testIsSystemClassInternal("$Klass"); } private void testIsSystemClassInternal(String nestedClass) { assertFalse(isSystemClass("org.example.Foo" + nestedClass, null)); assertTrue(isSystemClass("org.example.Foo" + nestedClass, classes("org.example.Foo"))); assertTrue(isSystemClass("/org.example.Foo" + nestedClass, classes("org.example.Foo"))); assertTrue(isSystemClass("org.example.Foo" + nestedClass, classes("org.example."))); assertTrue(isSystemClass("net.example.Foo" + nestedClass, classes("org.example.,net.example."))); assertFalse(isSystemClass("org.example.Foo" + nestedClass, classes("-org.example.Foo,org.example."))); assertTrue(isSystemClass("org.example.Bar" + nestedClass, classes("-org.example.Foo.,org.example."))); assertFalse(isSystemClass("org.example.Foo" + nestedClass, classes("org.example.,-org.example.Foo"))); assertFalse(isSystemClass("org.example.Foo" + nestedClass, classes("org.example.Foo,-org.example.Foo"))); } private List<String> classes(String classes) { return Lists.newArrayList(Splitter.on(',').split(classes)); } @Test public void testGetResource() throws IOException { URL testJar = makeTestJar().toURI().toURL(); ClassLoader currentClassLoader = getClass().getClassLoader(); ClassLoader appClassloader = new ApplicationClassLoader( new URL[] { testJar }, currentClassLoader, null); assertNull("Resource should be null for current classloader", currentClassLoader.getResourceAsStream("resource.txt")); InputStream in = appClassloader.getResourceAsStream("resource.txt"); assertNotNull("Resource should not be null for app classloader", in); assertEquals("hello", IOUtils.toString(in)); } private File makeTestJar() throws IOException { File jarFile = new File(testDir, "test.jar"); JarOutputStream out = new JarOutputStream(new FileOutputStream(jarFile)); ZipEntry entry = new ZipEntry("resource.txt"); out.putNextEntry(entry); out.write("hello".getBytes()); out.closeEntry(); out.close(); return jarFile; } }
apache-2.0
liorgins/old-regression-maven-compat
resources/jsystemRegressionBaseTests/tests/manualTests/massiveFixtures/Massive20.java
296
package manualTests.massiveFixtures; import jsystem.framework.fixture.Fixture; public class Massive20 extends Fixture { public Massive20(){ super(); setParentFixture(MassiveFixture.class); } public void setUp() { } public void tearDown() { } public void failTearDown() { } }
apache-2.0
wimarsha93/Digital-Pulz-for-Hospitals
HIS_Latest_Project_29-07-2016/Backend/NewWorkspace_2016/HIS_API/src/main/java/core/resources/api/user/AdminPermissionRequestResource.java
3803
package core.resources.api.user; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import lib.driver.api.driver_class.user.AdminPermissionrequestDBDriver; import lib.driver.api.driver_class.user.PermissionDBDriver; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import core.classes.api.user.AdminPermission; import core.classes.api.user.AdminPermissionrequest; import flexjson.JSONSerializer; @Path("AdminPermissionRequestService") public class AdminPermissionRequestResource { AdminPermissionrequestDBDriver permissionRequestDBDriver=new AdminPermissionrequestDBDriver(); /*** * Register a new permission into the system. * @param jsnObj is a JSON object that contains about new permission details * @return returns a string value.True if the permission registration successful else it returns false */ @POST @Path("/addNewPermissionRequest") @Produces(MediaType.TEXT_PLAIN) @Consumes(MediaType.APPLICATION_JSON) public String addNewPermissionRequest(JSONObject jsnObj){ String result="false"; boolean r=false; AdminPermissionrequest rpObj=new AdminPermissionrequest(); try{ rpObj.setReqestPermission(jsnObj.getString("permissionName")); r=permissionRequestDBDriver.inserPermissionRequest(rpObj); result=String.valueOf(r); return result; } catch(JSONException ex){ ex.printStackTrace(); return result; } } /*** * Update permission details. * @param jsnObj is a JSON object that contains new permission details. * @return returns a string value.True if the permissions updated successfully else it returns false */ @PUT @Path("/updatePermissionRequest") @Produces(MediaType.TEXT_PLAIN) @Consumes(MediaType.APPLICATION_JSON) public String permissionRequestUpdation(JSONObject jsnObj){ String result="false"; boolean r=false; AdminPermissionrequest rpObj=new AdminPermissionrequest(); try{ rpObj.setRequestId(jsnObj.getInt("requestId")); rpObj.setReqestPermission(jsnObj.getString("permissionRequest")); r=permissionRequestDBDriver.updatePermissionRequest(rpObj); result=String.valueOf(r); return result; } catch(JSONException ex){ ex.printStackTrace(); return result; } } /*** * Delete a particular permission from the system * @param jsnObj is JSON object that contains data about permission that going to delete * @return returns a string value.True if the permission deleted successfully else it returns false */ @DELETE @Path("/deletePermissionRequest") @Produces(MediaType.TEXT_PLAIN) @Consumes(MediaType.APPLICATION_JSON) public String deletePermissionRequest(JSONObject jsnObj){ String result="false"; boolean r=false; AdminPermissionrequest rpObj=new AdminPermissionrequest(); try{ rpObj.setRequestId(jsnObj.getInt("requestId")); r=permissionRequestDBDriver.delete(rpObj); result=String.valueOf(r); return result; } catch(JSONException ex){ ex.printStackTrace(); return result; } } /*** * Get all the permissions that registered in the system * @return returns a JSON object that contains all the registered permissions */ @GET @Path("/getAllPermissionRequests") @Produces(MediaType.APPLICATION_JSON) public String getAllPermissionRequests(){ String result=""; List<AdminPermissionrequest> permissionRequestList =permissionRequestDBDriver.getAllPermissionRequests(); JSONSerializer serializor=new JSONSerializer(); result = serializor.exclude("*.class").serialize(permissionRequestList); return result; } }
apache-2.0
bridje/bridje-framework
bridje-ioc/src/test/java/org/bridje/ioc/test/priority/PriorityComp3.java
855
/* * Copyright 2015 Bridje Framework. * * 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. */ package org.bridje.ioc.test.priority; import org.bridje.ioc.Component; import org.bridje.ioc.Priority; /** * * @author Gilberto */ @Component @Priority(0) public class PriorityComp3 implements PriorityService { }
apache-2.0
VHAINNOVATIONS/Mental-Health-eScreening
escreening/src/main/java/gov/va/escreening/vista/extractor/Orwu1NewlocExtractor.java
830
package gov.va.escreening.vista.extractor; import gov.va.escreening.vista.dto.VistaLocation; import org.apache.commons.lang3.StringUtils; public class Orwu1NewlocExtractor implements VistaRecordExtractor<VistaLocation> { /** * IEN^LOCATION NAME * 33232^AUDIOLOGY */ @Override public VistaLocation extractData(String record) { if (StringUtils.isBlank(record)) { return null; } String[] fields = StringUtils.splitPreserveAllTokens(record, '^'); VistaLocation vistaLocation = new VistaLocation(Long.parseLong(fields[0].trim()),fields[1]); // 1. IEN //vistaLocation.setIen(fields[0]); // 2. location/clinic Name //vistaLocation.setName(fields[1]); return vistaLocation; } }
apache-2.0
fengyouchao/sockslib
src/main/java/sockslib/server/msg/CommandMessage.java
7244
/* * Copyright 2015-2025 the original author or authors. * * 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. */ package sockslib.server.msg; import sockslib.common.AddressType; import sockslib.common.SocksCommand; import sockslib.common.SocksException; import sockslib.utils.SocksUtil; import sockslib.utils.StreamUtil; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.UnknownHostException; import java.nio.charset.Charset; import static sockslib.utils.StreamUtil.checkEnd; /** * The class <code>RequestCommandMessage</code> represents a SOCKS5 command message. * * @author Youchao Feng * @version 1.0 * @date Apr 6, 2015 11:10:12 AM */ public class CommandMessage implements ReadableMessage, WritableMessage { /** * Value of CONNECT command. */ protected static final int CMD_CONNECT = 0x01; /** * Value of BIND command. */ protected static final int CMD_BIND = 0x02; /** * Value of UDP ASSOCIATE command. */ protected static final int CMD_UDP_ASSOCIATE = 0x03; /** * Value of RESERVED field. */ private static final int RESERVED = 0x00; /** * Version. */ private int version; /** * IP address of destination. */ private InetAddress inetAddress; /** * Port of destination. */ private int port; /** * Host of destination. */ private String host; /** * SOCKS command. */ private SocksCommand command; /** * Reserved field. */ private int reserved; /** * Address type. */ private int addressType; /** * SOCKS exception in Command message. */ private SocksException socksException; @Override public int getLength() { byte[] bytes = getBytes(); return (bytes != null) ? bytes.length : 0; } @Override public byte[] getBytes() { byte[] bytes = null; switch (addressType) { case AddressType.IPV4: bytes = new byte[10]; byte[] ipv4Bytes = inetAddress.getAddress();// todo System.arraycopy(ipv4Bytes, 0, bytes, 4, ipv4Bytes.length); bytes[8] = SocksUtil.getFirstByteFromInt(port); bytes[9] = SocksUtil.getSecondByteFromInt(port); break; case AddressType.IPV6: bytes = new byte[22]; byte[] ipv6Bytes = inetAddress.getAddress();// todo System.arraycopy(ipv6Bytes, 0, bytes, 4, ipv6Bytes.length); bytes[20] = SocksUtil.getFirstByteFromInt(port); bytes[21] = SocksUtil.getSecondByteFromInt(port); break; case AddressType.DOMAIN_NAME: final int hostLength = host.getBytes().length; bytes = new byte[7 + hostLength]; bytes[4] = (byte) hostLength; for (int i = 0; i < hostLength; i++) { bytes[5 + i] = host.getBytes()[i]; } bytes[5 + hostLength] = SocksUtil.getFirstByteFromInt(port); bytes[6 + hostLength] = SocksUtil.getSecondByteFromInt(port); break; default: break; } if (bytes != null) { bytes[0] = (byte) version; bytes[1] = (byte) command.getValue(); bytes[2] = RESERVED; bytes[3] = (byte) addressType; } return bytes; } @Override public void read(InputStream inputStream) throws SocksException, IOException { version = checkEnd(inputStream.read()); int cmd = checkEnd(inputStream.read()); switch (cmd) { case CMD_CONNECT: command = SocksCommand.CONNECT; break; case CMD_BIND: command = SocksCommand.BIND; break; case CMD_UDP_ASSOCIATE: command = SocksCommand.UDP_ASSOCIATE; break; default: socksException = SocksException.serverReplyException(ServerReply.COMMAND_NOT_SUPPORTED); } reserved = checkEnd(inputStream.read()); addressType = checkEnd(inputStream.read()); if (!AddressType.isSupport(addressType) && socksException == null) { socksException = SocksException.serverReplyException(ServerReply.ADDRESS_TYPE_NOT_SUPPORTED); } // read address switch (addressType) { case AddressType.IPV4: byte[] addressBytes = StreamUtil.read(inputStream, 4); inetAddress = InetAddress.getByAddress(addressBytes); break; case AddressType.IPV6: byte[] addressBytes6 = StreamUtil.read(inputStream, 16); inetAddress = InetAddress.getByAddress(addressBytes6); break; case AddressType.DOMAIN_NAME: int domainLength = checkEnd(inputStream.read()); if (domainLength < 1) { throw new SocksException("Length of domain must great than 0"); } byte[] domainBytes = StreamUtil.read(inputStream, domainLength); host = new String(domainBytes, Charset.forName("UTF-8")); try { inetAddress = InetAddress.getByName(host); } catch (UnknownHostException e) { if (socksException == null) { socksException = SocksException.serverReplyException(ServerReply.HOST_UNREACHABLE); } } break; default: // TODO Implement later. break; } // Read port byte[] portBytes = StreamUtil.read(inputStream, 2); port = SocksUtil.bytesToInt(portBytes); } /** * Returns version. * * @return Version. */ public int getVersion() { return version; } /** * Sets version. * * @param version Version. */ public void setVersion(int version) { this.version = version; } public boolean hasSocksException() { return socksException != null; } public InetAddress getInetAddress() { return inetAddress; } public void setInetAddress(InetAddress inetAddress) { this.inetAddress = inetAddress; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public SocksCommand getCommand() { return command; } public void setCommand(SocksCommand command) { this.command = command; } public int getReserved() { return reserved; } public void setReserved(int reserved) { this.reserved = reserved; } public int getAddressType() { return addressType; } public void setAddressType(int addressType) { this.addressType = addressType; } public SocketAddress getSocketAddress() { return new InetSocketAddress(inetAddress, port); } public SocksException getSocksException() { return socksException; } public void setSocksException(SocksException socksException) { this.socksException = socksException; } }
apache-2.0
tpiotrow/afc
core/math/src/main/java/org/arakhne/afc/math/geometry/d3/i/Vector3i.java
8545
/* * $Id$ * This file is a part of the Arakhne Foundation Classes, http://www.arakhne.org/afc * * Copyright (c) 2000-2012 Stephane GALLAND. * Copyright (c) 2005-10, Multiagent Team, Laboratoire Systemes et Transports, * Universite de Technologie de Belfort-Montbeliard. * Copyright (c) 2013-2016 The original authors, and other authors. * * 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. */ package org.arakhne.afc.math.geometry.d3.i; import org.eclipse.xtext.xbase.lib.Pure; import org.arakhne.afc.math.geometry.d3.GeomFactory3D; import org.arakhne.afc.math.geometry.d3.Point3D; import org.arakhne.afc.math.geometry.d3.Tuple3D; import org.arakhne.afc.math.geometry.d3.UnmodifiableVector3D; import org.arakhne.afc.math.geometry.d3.Vector3D; import org.arakhne.afc.vmutil.asserts.AssertMessages; /** 2D Vector with 2 integer numbers. * * @author $Author: sgalland$ * @version $FullVersion$ * @mavengroupid $GroupId$ * @mavenartifactid $ArtifactId$ * @since 13.0 */ public class Vector3i extends Tuple3i<Vector3i> implements Vector3D<Vector3i, Point3i> { private static final long serialVersionUID = -7228108517874845303L; /** Construct a zero vector. */ public Vector3i() { // } /** Constructor by copy. * @param tuple is the tuple to copy. */ public Vector3i(Tuple3D<?> tuple) { super(tuple); } /** Constructor by copy. * @param tuple is the tuple to copy. */ public Vector3i(int[] tuple) { super(tuple); } /** Constructor by copy. * @param tuple is the tuple to copy. */ public Vector3i(double[] tuple) { super(tuple); } /** Constructor a vector with the given coordinates. * @param x x coordinate. * @param y y coordinate. * @param z z coordinate. */ public Vector3i(int x, int y, int z) { super(x, y, z); } /** Constructor a vector with the given coordinates. * @param x x coordinate. * @param y y coordinate. * @param z z coordinate. */ public Vector3i(float x, float y, float z) { super(x, y, z); } /** Constructor a vector with the given coordinates. * @param x x coordinate. * @param y y coordinate. * @param z z coordinate. */ public Vector3i(double x, double y, double z) { super(x, y, z); } /** Constructor a vector with the given coordinates. * @param x x coordinate. * @param y y coordinate. * @param z z coordinate. */ public Vector3i(long x, long y, long z) { super(x, y, z); } @Pure @Override public double dot(Vector3D<?, ?> vector) { assert vector != null : AssertMessages.notNullParameter(); return this.x * vector.getX() + this.y * vector.getY() + this.z * vector.getZ(); } @Pure @Override public double perp(Vector3D<?, ?> vector) { assert vector != null : AssertMessages.notNullParameter(); return this.x * vector.getY() + this.y * vector.getZ() + this.z * vector.getX() - this.z * vector.getY() - this.x * vector.getZ() - this.y * vector.getX(); } @Pure @Override public double getLength() { return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); } @Pure @Override public double getLengthSquared() { return this.x * this.x + this.y * this.y + this.z * this.z; } @Override public void add(Vector3D<?, ?> vector1, Vector3D<?, ?> vector2) { assert vector1 != null : AssertMessages.notNullParameter(0); assert vector2 != null : AssertMessages.notNullParameter(1); this.x = (int) Math.round(vector1.getX() + vector2.getX()); this.y = (int) Math.round(vector1.getY() + vector2.getY()); this.z = (int) Math.round(vector1.getZ() + vector2.getZ()); } @Override public void add(Vector3D<?, ?> vector) { assert vector != null : AssertMessages.notNullParameter(); this.x = (int) Math.round(this.x + vector.getX()); this.y = (int) Math.round(this.y + vector.getY()); this.z = (int) Math.round(this.z + vector.getZ()); } @Override public void scaleAdd(int scale, Vector3D<?, ?> vector1, Vector3D<?, ?> vector2) { assert vector1 != null : AssertMessages.notNullParameter(1); assert vector2 != null : AssertMessages.notNullParameter(2); this.x = (int) Math.round(scale * vector1.getX() + vector2.getX()); this.y = (int) Math.round(scale * vector1.getY() + vector2.getY()); this.z = (int) Math.round(scale * vector1.getZ() + vector2.getZ()); } @Override public void scaleAdd(double scale, Vector3D<?, ?> vector1, Vector3D<?, ?> vector2) { assert vector1 != null : AssertMessages.notNullParameter(1); assert vector2 != null : AssertMessages.notNullParameter(2); this.x = (int) Math.round(scale * vector1.getX() + vector2.getX()); this.y = (int) Math.round(scale * vector1.getY() + vector2.getY()); this.z = (int) Math.round(scale * vector1.getZ() + vector2.getZ()); } @Override public void scaleAdd(int scale, Vector3D<?, ?> vector) { assert vector != null : AssertMessages.notNullParameter(1); this.x = (int) Math.round(scale * this.x + vector.getX()); this.y = (int) Math.round(scale * this.y + vector.getY()); this.z = (int) Math.round(scale * this.z + vector.getZ()); } @Override public void scaleAdd(double scale, Vector3D<?, ?> vector) { assert vector != null : AssertMessages.notNullParameter(1); this.x = (int) Math.round(scale * this.x + vector.getX()); this.y = (int) Math.round(scale * this.y + vector.getY()); this.z = (int) Math.round(scale * this.z + vector.getZ()); } @Override public void sub(Vector3D<?, ?> vector1, Vector3D<?, ?> vector2) { assert vector1 != null : AssertMessages.notNullParameter(0); assert vector2 != null : AssertMessages.notNullParameter(1); this.x = (int) Math.round(vector1.getX() - vector2.getX()); this.y = (int) Math.round(vector1.getY() - vector2.getY()); this.z = (int) Math.round(vector1.getZ() - vector2.getZ()); } @Override public void sub(Point3D<?, ?> point1, Point3D<?, ?> point2) { assert point1 != null : AssertMessages.notNullParameter(0); assert point2 != null : AssertMessages.notNullParameter(1); this.x = (int) Math.round(point1.getX() - point2.getX()); this.y = (int) Math.round(point1.getY() - point2.getY()); this.z = (int) Math.round(point1.getZ() - point2.getZ()); } @Override public void sub(Vector3D<?, ?> vector) { assert vector != null : AssertMessages.notNullParameter(); this.x = (int) Math.round(this.x - vector.getX()); this.y = (int) Math.round(this.y - vector.getY()); this.z = (int) Math.round(this.z - vector.getZ()); } @Override public void setLength(double newLength) { final double l = getLength(); if (l != 0) { final double f = newLength / l; this.x = (int) Math.round(this.x * f); this.y = (int) Math.round(this.y * f); this.z = (int) Math.round(this.z * f); } else { this.x = (int) Math.round(newLength); this.y = 0; } } @Override public GeomFactory3i getGeomFactory() { return GeomFactory3i.SINGLETON; } @Pure @Override public UnmodifiableVector3D<Vector3i, Point3i> toUnmodifiable() { return new UnmodifiableVector3D<Vector3i, Point3i>() { private static final long serialVersionUID = 7684988962796497763L; @Override public GeomFactory3D<Vector3i, Point3i> getGeomFactory() { return Vector3i.this.getGeomFactory(); } @Override public Vector3i toUnitVector() { return Vector3i.this.toUnitVector(); } @Override @SuppressWarnings("checkstyle:superclone") public Vector3i clone() { return Vector3i.this.getGeomFactory().newVector( Vector3i.this.ix(), Vector3i.this.iy(), Vector3i.this.iz()); } @Override public double getX() { return Vector3i.this.getX(); } @Override public int ix() { return Vector3i.this.ix(); } @Override public double getY() { return Vector3i.this.getY(); } @Override public int iy() { return Vector3i.this.iy(); } @Override public double getZ() { return Vector3i.this.getZ(); } @Override public int iz() { return Vector3i.this.iz(); } }; } }
apache-2.0
q474818917/solr-5.2.0
lucene/core/src/test/org/apache/lucene/search/TestPrefixInBooleanQuery.java
3899
package org.apache.lucene.search; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.RandomIndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.store.Directory; import org.apache.lucene.util.LuceneTestCase; import org.junit.AfterClass; import org.junit.BeforeClass; /** * https://issues.apache.org/jira/browse/LUCENE-1974 * * represent the bug of * * BooleanScorer.score(Collector collector, int max, int firstDocID) * * Line 273, end=8192, subScorerDocID=11378, then more got false? */ public class TestPrefixInBooleanQuery extends LuceneTestCase { private static final String FIELD = "name"; private static Directory directory; private static IndexReader reader; private static IndexSearcher searcher; @BeforeClass public static void beforeClass() throws Exception { directory = newDirectory(); RandomIndexWriter writer = new RandomIndexWriter(random(), directory); Document doc = new Document(); Field field = newStringField(FIELD, "meaninglessnames", Field.Store.NO); doc.add(field); for (int i = 0; i < 5137; ++i) { writer.addDocument(doc); } field.setStringValue("tangfulin"); writer.addDocument(doc); field.setStringValue("meaninglessnames"); for (int i = 5138; i < 11377; ++i) { writer.addDocument(doc); } field.setStringValue("tangfulin"); writer.addDocument(doc); reader = writer.getReader(); searcher = newSearcher(reader); writer.close(); } @AfterClass public static void afterClass() throws Exception { searcher = null; reader.close(); reader = null; directory.close(); directory = null; } public void testPrefixQuery() throws Exception { Query query = new PrefixQuery(new Term(FIELD, "tang")); assertEquals("Number of matched documents", 2, searcher.search(query, 1000).totalHits); } public void testTermQuery() throws Exception { Query query = new TermQuery(new Term(FIELD, "tangfulin")); assertEquals("Number of matched documents", 2, searcher.search(query, 1000).totalHits); } public void testTermBooleanQuery() throws Exception { BooleanQuery query = new BooleanQuery(); query.add(new TermQuery(new Term(FIELD, "tangfulin")), BooleanClause.Occur.SHOULD); query.add(new TermQuery(new Term(FIELD, "notexistnames")), BooleanClause.Occur.SHOULD); assertEquals("Number of matched documents", 2, searcher.search(query, 1000).totalHits); } public void testPrefixBooleanQuery() throws Exception { BooleanQuery query = new BooleanQuery(); query.add(new PrefixQuery(new Term(FIELD, "tang")), BooleanClause.Occur.SHOULD); query.add(new TermQuery(new Term(FIELD, "notexistnames")), BooleanClause.Occur.SHOULD); assertEquals("Number of matched documents", 2, searcher.search(query, 1000).totalHits); } }
apache-2.0
mghosh4/druid
processing/src/main/java/org/apache/druid/segment/DimensionHandlerUtils.java
17659
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ package org.apache.druid.segment; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.primitives.Doubles; import com.google.common.primitives.Floats; import org.apache.druid.common.guava.GuavaUtils; import org.apache.druid.data.input.impl.DimensionSchema.MultiValueHandling; import org.apache.druid.java.util.common.IAE; import org.apache.druid.java.util.common.ISE; import org.apache.druid.java.util.common.guava.Comparators; import org.apache.druid.java.util.common.parsers.ParseException; import org.apache.druid.query.ColumnSelectorPlus; import org.apache.druid.query.dimension.ColumnSelectorStrategy; import org.apache.druid.query.dimension.ColumnSelectorStrategyFactory; import org.apache.druid.query.dimension.DimensionSpec; import org.apache.druid.query.extraction.ExtractionFn; import org.apache.druid.segment.column.ColumnCapabilities; import org.apache.druid.segment.column.ColumnCapabilitiesImpl; import org.apache.druid.segment.column.ValueType; import javax.annotation.Nullable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; public final class DimensionHandlerUtils { // use these values to ensure that convertObjectToLong(), convertObjectToDouble() and convertObjectToFloat() // return the same boxed object when returning a constant zero. public static final Double ZERO_DOUBLE = 0.0d; public static final Float ZERO_FLOAT = 0.0f; public static final Long ZERO_LONG = 0L; public static final ColumnCapabilities DEFAULT_STRING_CAPABILITIES = new ColumnCapabilitiesImpl().setType(ValueType.STRING) .setDictionaryEncoded(false) .setDictionaryValuesUnique(false) .setDictionaryValuesSorted(false) .setHasBitmapIndexes(false); public static final ConcurrentHashMap<String, DimensionHandlerProvider> DIMENSION_HANDLER_PROVIDERS = new ConcurrentHashMap<>(); public static void registerDimensionHandlerProvider(String type, DimensionHandlerProvider provider) { DIMENSION_HANDLER_PROVIDERS.compute(type, (key, value) -> { if (value == null) { return provider; } else { if (!value.getClass().getName().equals(provider.getClass().getName())) { throw new ISE( "Incompatible dimensionHandlerProvider for type[%s] already exists. Expected [%s], found [%s].", key, value.getClass().getName(), provider.getClass().getName() ); } else { return value; } } }); } private DimensionHandlerUtils() { } public static DimensionHandler<?, ?, ?> getHandlerFromCapabilities( String dimensionName, @Nullable ColumnCapabilities capabilities, @Nullable MultiValueHandling multiValueHandling ) { if (capabilities == null) { return new StringDimensionHandler(dimensionName, multiValueHandling, true, false); } multiValueHandling = multiValueHandling == null ? MultiValueHandling.ofDefault() : multiValueHandling; if (capabilities.getType() == ValueType.STRING) { if (!capabilities.isDictionaryEncoded().isTrue()) { throw new IAE("String column must have dictionary encoding."); } return new StringDimensionHandler( dimensionName, multiValueHandling, capabilities.hasBitmapIndexes(), capabilities.hasSpatialIndexes() ); } if (capabilities.getType() == ValueType.LONG) { return new LongDimensionHandler(dimensionName); } if (capabilities.getType() == ValueType.FLOAT) { return new FloatDimensionHandler(dimensionName); } if (capabilities.getType() == ValueType.DOUBLE) { return new DoubleDimensionHandler(dimensionName); } if (capabilities.getType() == ValueType.COMPLEX && capabilities.getComplexTypeName() != null) { DimensionHandlerProvider provider = DIMENSION_HANDLER_PROVIDERS.get(capabilities.getComplexTypeName()); if (provider == null) { throw new ISE("Can't find DimensionHandlerProvider for typeName [%s]", capabilities.getComplexTypeName()); } return provider.get(dimensionName); } // Return a StringDimensionHandler by default (null columns will be treated as String typed) return new StringDimensionHandler(dimensionName, multiValueHandling, true, false); } public static List<ValueType> getValueTypesFromDimensionSpecs(List<DimensionSpec> dimSpecs) { List<ValueType> types = new ArrayList<>(dimSpecs.size()); for (DimensionSpec dimSpec : dimSpecs) { types.add(dimSpec.getOutputType()); } return types; } /** * Convenience function equivalent to calling * {@link #createColumnSelectorPluses(ColumnSelectorStrategyFactory, List, ColumnSelectorFactory)} with a singleton * list of dimensionSpecs and then retrieving the only element in the returned array. * * @param <Strategy> The strategy type created by the provided strategy factory. * @param strategyFactory A factory provided by query engines that generates type-handling strategies * @param dimensionSpec column to generate a ColumnSelectorPlus object for * @param cursor Used to create value selectors for columns. * * @return A ColumnSelectorPlus object * * @see ColumnProcessors#makeProcessor which may replace this in the future */ public static <Strategy extends ColumnSelectorStrategy> ColumnSelectorPlus<Strategy> createColumnSelectorPlus( ColumnSelectorStrategyFactory<Strategy> strategyFactory, DimensionSpec dimensionSpec, ColumnSelectorFactory cursor ) { return createColumnSelectorPluses(strategyFactory, ImmutableList.of(dimensionSpec), cursor)[0]; } /** * Creates an array of ColumnSelectorPlus objects, selectors that handle type-specific operations within * query processing engines, using a strategy factory provided by the query engine. One ColumnSelectorPlus * will be created for each column specified in dimensionSpecs. * * The ColumnSelectorPlus provides access to a type strategy (e.g., how to group on a float column) * and a value selector for a single column. * * A caller should define a strategy factory that provides an interface for type-specific operations * in a query engine. See GroupByStrategyFactory for a reference. * * @param <Strategy> The strategy type created by the provided strategy factory. * @param strategyFactory A factory provided by query engines that generates type-handling strategies * @param dimensionSpecs The set of columns to generate ColumnSelectorPlus objects for * @param columnSelectorFactory Used to create value selectors for columns. * * @return An array of ColumnSelectorPlus objects, in the order of the columns specified in dimensionSpecs * * @see ColumnProcessors#makeProcessor which may replace this in the future */ public static <Strategy extends ColumnSelectorStrategy> ColumnSelectorPlus<Strategy>[] createColumnSelectorPluses( ColumnSelectorStrategyFactory<Strategy> strategyFactory, List<DimensionSpec> dimensionSpecs, ColumnSelectorFactory columnSelectorFactory ) { int dimCount = dimensionSpecs.size(); @SuppressWarnings("unchecked") ColumnSelectorPlus<Strategy>[] dims = new ColumnSelectorPlus[dimCount]; for (int i = 0; i < dimCount; i++) { final DimensionSpec dimSpec = dimensionSpecs.get(i); final String dimName = dimSpec.getDimension(); final ColumnValueSelector<?> selector = getColumnValueSelectorFromDimensionSpec( dimSpec, columnSelectorFactory ); Strategy strategy = makeStrategy( strategyFactory, dimSpec, columnSelectorFactory.getColumnCapabilities(dimSpec.getDimension()), selector ); final ColumnSelectorPlus<Strategy> selectorPlus = new ColumnSelectorPlus<>( dimName, dimSpec.getOutputName(), strategy, selector ); dims[i] = selectorPlus; } return dims; } private static ColumnValueSelector<?> getColumnValueSelectorFromDimensionSpec( DimensionSpec dimSpec, ColumnSelectorFactory columnSelectorFactory ) { String dimName = dimSpec.getDimension(); ColumnCapabilities capabilities = columnSelectorFactory.getColumnCapabilities(dimName); capabilities = getEffectiveCapabilities(dimSpec, capabilities); if (capabilities.getType() == ValueType.STRING) { return columnSelectorFactory.makeDimensionSelector(dimSpec); } return columnSelectorFactory.makeColumnValueSelector(dimSpec.getDimension()); } /** * When determining the capabilities of a column during query processing, this function * adjusts the capabilities for columns that cannot be handled as-is to manageable defaults * (e.g., treating missing columns as empty String columns) */ private static ColumnCapabilities getEffectiveCapabilities( DimensionSpec dimSpec, @Nullable ColumnCapabilities capabilities ) { if (capabilities == null) { capabilities = DEFAULT_STRING_CAPABILITIES; } // Complex dimension type is not supported if (capabilities.getType() == ValueType.COMPLEX) { capabilities = DEFAULT_STRING_CAPABILITIES; } // Currently, all extractionFns output Strings, so the column will return String values via a // DimensionSelector if an extractionFn is present. if (dimSpec.getExtractionFn() != null) { ExtractionFn fn = dimSpec.getExtractionFn(); capabilities = ColumnCapabilitiesImpl.copyOf(capabilities) .setType(ValueType.STRING) .setDictionaryValuesUnique( capabilities.isDictionaryEncoded().isTrue() && fn.getExtractionType() == ExtractionFn.ExtractionType.ONE_TO_ONE ) .setDictionaryValuesSorted( capabilities.isDictionaryEncoded().isTrue() && fn.preservesOrdering() ); } // DimensionSpec's decorate only operates on DimensionSelectors, so if a spec mustDecorate(), // we need to wrap selectors on numeric columns with a string casting DimensionSelector. if (ValueType.isNumeric(capabilities.getType())) { if (dimSpec.mustDecorate()) { capabilities = DEFAULT_STRING_CAPABILITIES; } } return capabilities; } private static <Strategy extends ColumnSelectorStrategy> Strategy makeStrategy( ColumnSelectorStrategyFactory<Strategy> strategyFactory, DimensionSpec dimSpec, @Nullable ColumnCapabilities capabilities, ColumnValueSelector<?> selector ) { capabilities = getEffectiveCapabilities(dimSpec, capabilities); return strategyFactory.makeColumnSelectorStrategy(capabilities, selector); } @Nullable public static String convertObjectToString(@Nullable Object valObj) { if (valObj == null) { return null; } return valObj.toString(); } @Nullable public static Long convertObjectToLong(@Nullable Object valObj) { return convertObjectToLong(valObj, false); } @Nullable public static Long convertObjectToLong(@Nullable Object valObj, boolean reportParseExceptions) { if (valObj == null) { return null; } if (valObj instanceof Long) { return (Long) valObj; } else if (valObj instanceof Number) { return ((Number) valObj).longValue(); } else if (valObj instanceof String) { Long ret = DimensionHandlerUtils.getExactLongFromDecimalString((String) valObj); if (reportParseExceptions && ret == null) { throw new ParseException("could not convert value [%s] to long", valObj); } return ret; } else { throw new ParseException("Unknown type[%s]", valObj.getClass()); } } @Nullable public static Float convertObjectToFloat(@Nullable Object valObj) { return convertObjectToFloat(valObj, false); } @Nullable public static Float convertObjectToFloat(@Nullable Object valObj, boolean reportParseExceptions) { if (valObj == null) { return null; } if (valObj instanceof Float) { return (Float) valObj; } else if (valObj instanceof Number) { return ((Number) valObj).floatValue(); } else if (valObj instanceof String) { Float ret = Floats.tryParse((String) valObj); if (reportParseExceptions && ret == null) { throw new ParseException("could not convert value [%s] to float", valObj); } return ret; } else { throw new ParseException("Unknown type[%s]", valObj.getClass()); } } @Nullable public static Comparable<?> convertObjectToType( @Nullable final Object obj, final ValueType type, final boolean reportParseExceptions ) { Preconditions.checkNotNull(type, "type"); switch (type) { case LONG: return convertObjectToLong(obj, reportParseExceptions); case FLOAT: return convertObjectToFloat(obj, reportParseExceptions); case DOUBLE: return convertObjectToDouble(obj, reportParseExceptions); case STRING: return convertObjectToString(obj); default: throw new IAE("Type[%s] is not supported for dimensions!", type); } } public static int compareObjectsAsType( @Nullable final Object lhs, @Nullable final Object rhs, final ValueType type ) { //noinspection unchecked return Comparators.<Comparable>naturalNullsFirst().compare( convertObjectToType(lhs, type), convertObjectToType(rhs, type) ); } @Nullable public static Comparable<?> convertObjectToType(@Nullable final Object obj, final ValueType type) { return convertObjectToType(obj, Preconditions.checkNotNull(type, "type"), false); } public static Function<Object, Comparable<?>> converterFromTypeToType( final ValueType fromType, final ValueType toType ) { if (fromType == toType) { //noinspection unchecked return (Function) Function.identity(); } else { return obj -> convertObjectToType(obj, toType); } } @Nullable public static Double convertObjectToDouble(@Nullable Object valObj) { return convertObjectToDouble(valObj, false); } @Nullable public static Double convertObjectToDouble(@Nullable Object valObj, boolean reportParseExceptions) { if (valObj == null) { return null; } if (valObj instanceof Double) { return (Double) valObj; } else if (valObj instanceof Number) { return ((Number) valObj).doubleValue(); } else if (valObj instanceof String) { Double ret = Doubles.tryParse((String) valObj); if (reportParseExceptions && ret == null) { throw new ParseException("could not convert value [%s] to double", valObj); } return ret; } else { throw new ParseException("Unknown type[%s]", valObj.getClass()); } } /** * Convert a string representing a decimal value to a long. * * If the decimal value is not an exact integral value (e.g. 42.0), or if the decimal value * is too large to be contained within a long, this function returns null. * * @param decimalStr string representing a decimal value * * @return long equivalent of decimalStr, returns null for non-integral decimals and integral decimal values outside * of the values representable by longs */ @Nullable public static Long getExactLongFromDecimalString(String decimalStr) { final Long val = GuavaUtils.tryParseLong(decimalStr); if (val != null) { return val; } BigDecimal convertedBD; try { convertedBD = new BigDecimal(decimalStr); } catch (NumberFormatException nfe) { return null; } try { return convertedBD.longValueExact(); } catch (ArithmeticException ae) { // indicates there was a non-integral part, or the BigDecimal was too big for a long return null; } } public static Double nullToZero(@Nullable Double number) { return number == null ? ZERO_DOUBLE : number; } public static Long nullToZero(@Nullable Long number) { return number == null ? ZERO_LONG : number; } public static Float nullToZero(@Nullable Float number) { return number == null ? ZERO_FLOAT : number; } }
apache-2.0
intel-analytics/BigDL
scala/friesian/src/main/java/com/intel/analytics/bigdl/friesian/serving/recall/faiss/swighnswlib/SWIGTYPE_p_std__functionT_void_fint_faiss__IndexBinary_pF_t.java
970
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 3.0.12 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package com.intel.analytics.bigdl.friesian.serving.recall.faiss.swighnswlib; public class SWIGTYPE_p_std__functionT_void_fint_faiss__IndexBinary_pF_t { private transient long swigCPtr; protected SWIGTYPE_p_std__functionT_void_fint_faiss__IndexBinary_pF_t(long cPtr, @SuppressWarnings("unused") boolean futureUse) { swigCPtr = cPtr; } protected SWIGTYPE_p_std__functionT_void_fint_faiss__IndexBinary_pF_t() { swigCPtr = 0; } protected static long getCPtr(SWIGTYPE_p_std__functionT_void_fint_faiss__IndexBinary_pF_t obj) { return (obj == null) ? 0 : obj.swigCPtr; } }
apache-2.0
chrisengelsma/jtk
core/src/test/java/edu/mines/jtk/opt/GaussNewtonSolverTest.java
10610
/**************************************************************************** Copyright 2003, Landmark Graphics and others. 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. ****************************************************************************/ package edu.mines.jtk.opt; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; import edu.mines.jtk.util.Almost; import org.testng.annotations.Test; import static org.testng.AssertJUnit.assertTrue; /** * Tests {@link edu.mines.jtk.opt.GaussNewtonSolver}. */ public class GaussNewtonSolverTest { private static final Logger LOG = Logger.getLogger("edu.mines.jtk.opt"); private static boolean printedUndisposed = false; private static boolean projectWasTested = false; private static final String NL = System.getProperty("line.separator"); // make sure Vects are disposed private static class TestVect extends ArrayVect1 { private static final long serialVersionUID = 1L; /** Visible only for tests. */ public static int max = 0; /** Visible only for tests. */ public static int total = 0; /** Visible only for tests. */ public static Map<Object,String> undisposed = Collections.synchronizedMap(new HashMap<Object,String>()); /** Visible only for tests. */ public String identity = "default"; @Override public void add(double scaleThis, double scaleOther, VectConst other) { assertSameType(other); super.add(scaleThis, scaleOther, other); } @Override public void project(double scaleThis, double scaleOther, VectConst other) { TestVect tv = (TestVect) other; if (!identity.equals(tv.identity)) {projectWasTested = true;} super.add(scaleThis, scaleOther, other); } @Override public double dot(VectConst other) { assertSameType(other); return super.dot(other); } private void assertSameType(VectConst other) { TestVect tv = (TestVect) other; if (!identity.equals(tv.identity)) { throw new IllegalArgumentException("different types"); } } /** Constructor. @param data @param variance @param identity */ public TestVect(double[] data, double variance, String identity) { super (data,variance); this.identity = identity; remember(this); } @Override public TestVect clone() { TestVect result = (TestVect) super.clone(); remember(result); return result; } private void remember(Object tv) { // remember where allocated synchronized (undisposed) { java.io.StringWriter sw = new java.io.StringWriter(); java.io.PrintWriter pw = new java.io.PrintWriter(sw); new Exception("This vector was never disposed").printStackTrace(pw); pw.flush(); undisposed.put(tv, sw.toString()); //LOG.info("**********************************************"); //LOG.info(sw.toString()); max = Math.max(max, undisposed.size()); total += 1; if (undisposed.size() > 12 && !printedUndisposed) { LOG.severe("**********************************************"); LOG.severe(getTraces()); LOG.severe("**********************************************"); printedUndisposed = true; } } } @Override public void dispose() { synchronized (undisposed) { super.dispose(); undisposed.remove(this); } } /** View traces for debugging @return printable version of traces */ public static String getTraces() { StringBuilder sb = new StringBuilder(); for (String s : undisposed.values()) { sb.append(s); sb.append(NL); } return sb.toString(); } } @Test public void testMain() throws Exception { GaussNewtonSolver.setExpensiveDebug(true); /* fit straight line to points (0,0) (1,8) (3,8) (4,20) */ final double[] coord = new double[] {0., 1., 3., 4.}; TestVect data = new TestVect(new double[] {0., 8., 8., 20.}, 0.0001, "data"); // model will be intercept and gradient LinearTransform linearTransform = new LinearTransform() { public void forward(Vect data1, VectConst model) { VectUtil.zero(data1); double[] d = ((ArrayVect1)data1).getData(); double[] m = ((ArrayVect1)model).getData(); for (int i=0; i< coord.length; ++i) { d[i] += m[0]; d[i] += coord[i]*m[1]; } } public void addTranspose(VectConst data1, Vect model) { double[] d = ((ArrayVect1)data1).getData(); double[] m = ((ArrayVect1)model).getData(); for (int i=0; i< coord.length; ++i) { m[0] += d[i]; m[1] += coord[i]*d[i]; } } public void inverseHessian(Vect model) {} public void adjustRobustErrors(Vect dataError) {} }; { // bad starting model, damp full model TestVect model = new TestVect(new double[]{-1., -1.}, 1., "model"); boolean dampOnlyPerturbation = false; int conjugateGradIterations = 2; ArrayVect1 result = (ArrayVect1) QuadraticSolver.solve (data, model, linearTransform, dampOnlyPerturbation, conjugateGradIterations, null); LOG.fine("data = "+data); LOG.fine("model = "+model); LOG.fine("result = "+result); assertTrue((new Almost(4)).equal(1., result.getData()[0])); assertTrue((new Almost(5)).equal(4., result.getData()[1])); model.dispose(); result.dispose(); } double[] dampPerturb = null; { // good starting model, damp perturbations only TestVect model = new TestVect(new double[]{0.9, 3.9}, 1., "model"); boolean dampOnlyPerturbation = true; int conjugateGradIterations = 2; ArrayVect1 result = (ArrayVect1) QuadraticSolver.solve (data, model, linearTransform, dampOnlyPerturbation, conjugateGradIterations, null); LOG.fine("data = "+data); LOG.fine("model = "+model); LOG.fine("result = "+result); dampPerturb = result.getData(); assertTrue((new Almost(4)).equal(1., result.getData()[0])); assertTrue((new Almost(5)).equal(4., result.getData()[1])); model.dispose(); result.dispose(); } { // good starting model, damp whole model, and compare to previous TestVect model = new TestVect(new double[]{0.9, 3.9}, 1., "model"); boolean dampOnlyPerturbation = false; int conjugateGradIterations = 2; ArrayVect1 result = (ArrayVect1) QuadraticSolver.solve (data, model, linearTransform, dampOnlyPerturbation, conjugateGradIterations, null); LOG.fine("data = "+data); LOG.fine("model = "+model); LOG.fine("result = "+result); double[] dampAll = result.getData(); assertTrue((new Almost(4)).equal(1., result.getData()[0])); assertTrue((new Almost(5)).equal(4., result.getData()[1])); assertTrue(dampAll[0] > dampPerturb[0]); assertTrue(dampAll[1] < dampPerturb[1]); { // double dampAll2 = 0.; double dampPerturb2 = 0.; for (int i=0; i<2; ++i) { dampAll2 += dampAll[i]*dampAll[i]; dampPerturb2 += dampPerturb[i]*dampPerturb[i]; } LOG.fine ("dampAll2="+dampAll2+" dampPerturb2="+dampPerturb2); assertTrue(dampAll2 < dampPerturb2); } model.dispose(); result.dispose(); } assertTrue(TestVect.max <=10); // use full interface for (int twice=0; twice<2; ++twice) { boolean project = (twice==1); TestVect perturb = new TestVect(new double[2], 1., "perturb"); { // Steepest descent: One conjugate gradient iteration and a line search TestVect model = new TestVect(new double[]{0.9, 3.9}, 1., "model"); boolean dampOnlyPerturbation = false; int linearizationIterations = 3; int lineSearchIterations = 20; double lineSearchError = 0.000001; int conjugateGradIterations = 1; Transform transform = new LinearTransformWrapper(linearTransform); ArrayVect1 result = (ArrayVect1) GaussNewtonSolver.solve (data, model, (project) ? perturb : null, transform, dampOnlyPerturbation, conjugateGradIterations, lineSearchIterations, linearizationIterations, lineSearchError, null); LOG.fine("data = "+data); LOG.fine("model = "+model); LOG.fine("result = "+result); assertTrue((new Almost(3)).equal(1., result.getData()[0])); assertTrue((new Almost(4)).equal(4., result.getData()[1])); model.dispose(); result.dispose(); } { // Make sure unnecessary iterations are not a problem TestVect model = new TestVect(new double[]{0.9, 3.9}, 1., "model"); boolean dampOnlyPerturbation = true; int linearizationIterations = 3; int lineSearchIterations = 30; double lineSearchError = 0.000001; int conjugateGradIterations = 2; Transform transform = new LinearTransformWrapper(linearTransform); ArrayVect1 result = (ArrayVect1) GaussNewtonSolver.solve (data, model, project ? perturb : null, transform, dampOnlyPerturbation, conjugateGradIterations, lineSearchIterations, linearizationIterations, lineSearchError, null); // new LogMonitor("Test inversion",LOG) LOG.fine("data = "+data); LOG.fine("model = "+model); LOG.fine("result = "+result); assertTrue((new Almost(4)).equal(1., result.getData()[0])); assertTrue((new Almost(5)).equal(4., result.getData()[1])); model.dispose(); result.dispose(); } perturb.dispose(); } data.dispose(); if (TestVect.undisposed.size() > 0) { throw new IllegalStateException(TestVect.getTraces()); } assertTrue(TestVect.max <=10); assertTrue(projectWasTested); GaussNewtonSolver.setExpensiveDebug(false); } }
apache-2.0
alittlemind/junior
chapter_002/Tracker/src/test/java/ru/evgenyhodz/StubInputTest.java
4471
package ru.evgenyhodz; import org.junit.Before; import org.junit.Test; import ru.evgenyhodz.models.Application; import ru.evgenyhodz.start.Input; import ru.evgenyhodz.start.StartUI; import ru.evgenyhodz.start.StubInput; import ru.evgenyhodz.start.Tracker; import static org.hamcrest.core.Is.is; import static org.junit.Assert.*; /** * Class to emulate user's behavior. */ public class StubInputTest { /** * Reference to application. */ private Application appForTests; /** * Set start parameters to new application object before tests. */ @Before public void setStartApp() { appForTests = new Application(null, null, null, null, null); } /** * User select "Add application", text name and exit. */ @Test public void whenUserChoose0ThenNewApplicationIsAddingToApplicationsRepositoryTest() { Tracker tracker = new Tracker(); Input input = new StubInput(new String[]{ "0", //Select Add. "Frodo", //Text name of application. "9", "y", //Exit. }); new StartUI(input, tracker).init(); assertThat(tracker.showByName("Frodo").getName(), is("Frodo")); } /** * User select "Edit application", type name, description, creation date and exit. */ @Test public void whenUserChoose1ToEditThenWeWillHaveTheEditedApplicationTest() { Tracker tracker = new Tracker(); tracker.addApp(appForTests); Input input = new StubInput(new String[]{"1", appForTests.getId(), "name", "desc", "1999", "1", "31", "9", "y"}); new StartUI(input, tracker).init(); assertThat(tracker.showByName("name").getComment(), is("31/1/1999")); } /** * User select "Create comment", type some phrase, and exit. */ @Test public void whenUserChoose2ThenWeWillHaveNewCommentForApplicationTest() { Tracker tracker = new Tracker(); tracker.addApp(appForTests); Input input = new StubInput(new String[]{"2", appForTests.getId(), "Comment for test", "9", "y"}); new StartUI(input, tracker).init(); assertThat(appForTests.getComment(), is("Comment for test")); } /** * User select 3 - delete application. */ @Test public void whenUserChoose3ThenWeShouldHaveDeletedApplicationTest() { Tracker tracker = new Tracker(); tracker.addApp(appForTests); Application[] forTest = {}; Input input = new StubInput(new String[]{"3", appForTests.getId(), "9", "y"}); new StartUI(input, tracker).init(); // assertThat(tracker.showApps(), is(forTest)); } /** * User choose "Show ALL Applications". */ @Test public void whenUserChoose4ThenWeWillGetAllApplicationTest() { Tracker tracker = new Tracker(); tracker.addApp(appForTests); Application[] forShowTest = {appForTests}; Input input = new StubInput(new String[]{"4", "9", "y"}); new StartUI(input, tracker).init(); // assertThat(tracker.showApps(), is(forShowTest)); } /** * Show application by id and exit. */ @Test public void whenUserChoose5ThenWeWillGetApplicationByIdTest() { Tracker tracker = new Tracker(); tracker.addApp(appForTests); appForTests.setId("id"); Input input = new StubInput(new String[]{"5", "id", "9", "y"}); new StartUI(input, tracker).init(); assertThat(tracker.showById("id"), is(appForTests)); } /** * User removes application by entering app's name. */ @Test public void whenUserChoose6ThenHeWillDeleteAppByNameTest() { Tracker tracker = new Tracker(); tracker.addApp(appForTests); appForTests.setName("name"); Application[] test = {}; Input input = new StubInput(new String[]{"6", "name", "9", "y"}); new StartUI(input, tracker).init(); // assertThat(tracker.showApps(), is(test)); } /** * User choose to show application by name. */ @Test public void whenUserChoose7ThenHeWillGetAppByNameTest() { Tracker tracker = new Tracker(); tracker.addApp(appForTests); appForTests.setName("Frodo"); Input input = new StubInput(new String[]{"7", "Frodo", "9", "y"}); new StartUI(input, tracker).init(); assertThat(tracker.showByName("Frodo"), is(appForTests)); } }
apache-2.0
ariatemplates/selenium-java-robot
src/main/java/com/ariatemplates/seleniumjavarobot/SeleniumJavaRobot.java
4409
/* * Copyright 2014 Amadeus s.a.s. * 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. */ package com.ariatemplates.seleniumjavarobot; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.openqa.selenium.Point; import com.ariatemplates.seleniumjavarobot.calibrator.Calibrator; import com.ariatemplates.seleniumjavarobot.executor.Executor; public class SeleniumJavaRobot { // Public options (not supposed to be changed after calling start): public String url; public boolean autoRestart; public IRobotizedBrowserFactory robotizedBrowserFactory; // Private fields: private final Thread mainThread = createMainThread(); private final ExecutorService quitExecutor = Executors.newSingleThreadExecutor(); private final Object lock = new Object(); // The previous lock object is a lock for the following 2 fields: private RobotizedBrowser robotizedBrowser; private boolean stopped = false; public void start() { mainThread.start(); } public void stop() throws InterruptedException { synchronized (lock) { if (!stopped && mainThread.isAlive()) { log("Closing ..."); } stopped = true; if (robotizedBrowser != null) { robotizedBrowser.stop(); } } mainThread.join(); } private Thread createMainThread() { Thread result = new Thread(new Runnable() { public void run() { do { RobotizedBrowser robotizedBrowser = null; try { synchronized (lock) { if (stopped) { break; } robotizedBrowser = robotizedBrowserFactory.createRobotizedBrowser(); SeleniumJavaRobot.this.robotizedBrowser = robotizedBrowser; } startDriver(robotizedBrowser, url); } catch (RuntimeException e) { e.printStackTrace(); } catch (InterruptedException e) { break; } finally { if (robotizedBrowser != null) { stopBrowserLater(robotizedBrowser); } } } while (autoRestart); quitExecutor.shutdown(); try { quitExecutor.awaitTermination(1, TimeUnit.MINUTES); } catch (InterruptedException e) { } SeleniumJavaRobot.log("End"); } }); result.setDaemon(false); return result; } private void stopBrowserLater(final RobotizedBrowser robotizedBrowser) { quitExecutor.execute(new Runnable() { public void run() { // Makes sure the driver is closed. This is done // asynchronously so that we don't loose too // much time when --auto-restart is used, // because the quit method can take a long time // to finish in case the browser crashed or was // terminated forcefully. robotizedBrowser.stop(); } }); } public static void startDriver(RobotizedBrowser robotizedBrowser, String url) throws InterruptedException { Point offset = Calibrator.calibrate(robotizedBrowser); log("Computed offset: " + offset); robotizedBrowser.browser.get(url); Executor executor = new Executor(robotizedBrowser, offset); executor.run(); } public static void log(String log) { System.out.println("[Selenium Java Robot] " + log); } }
apache-2.0
archord/svom
src/main/java/com/gwac/service/OtVarObserveRecordServiceImpl.java
14455
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.gwac.service; import com.gwac.activemq.OTCheckMessageCreator; import com.gwac.dao.DataProcessMachineDAO; import com.gwac.dao.FitsFileCutDAO; import com.gwac.dao.FitsFileCutRefDAO; import com.gwac.dao.FitsFileDAO; import com.gwac.dao.OTCatalogDao; import com.gwac.dao.ObservationSkyDao; import com.gwac.dao.OtLevel2Dao; import com.gwac.dao.OtNumberDao; import com.gwac.dao.OtObserveRecordDAO; import com.gwac.dao.UploadFileUnstoreDao; import com.gwac.model.FitsFile; import com.gwac.model.FitsFileCut; import com.gwac.model.FitsFileCutRef; import com.gwac.model.OTCatalog; import com.gwac.model.ObservationSky; import com.gwac.model.OtLevel2; import com.gwac.model.OtObserveRecord; import com.gwac.model.UploadFileUnstore; import java.util.Date; import java.util.List; import javax.jms.Destination; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.jms.core.JmsTemplate; import org.springframework.jms.core.MessageCreator; /** * 解析一级OT列表文件,计算二级OT,切图,模板切图。 * * @author xy */ public class OtVarObserveRecordServiceImpl implements OtObserveRecordService { private static final Log log = LogFactory.getLog(OtVarObserveRecordServiceImpl.class); private OTCatalogDao otcDao; private OtNumberDao otnDao; private OtLevel2Dao otLv2Dao; private FitsFileDAO ffDao; private FitsFileCutDAO ffcDao; private OtObserveRecordDAO otorDao; private DataProcessMachineDAO dpmDao; private FitsFileCutRefDAO ffcrDao; private ObservationSkyDao skyDao; private UploadFileUnstoreDao ufuDao; private String rootPath; private String cutIDir; private float errorBox; private int successiveImageNumber; private int firstNMarkNumber; private int occurNumber; private static boolean running = true; private Boolean isBeiJingServer; private Boolean isTestServer; private JmsTemplate jmsTemplate; private Destination otCheckDest; /** * 解析一级OT列表文件,得出二级OT,切图文件名称,二级OT模板切图名称 * * @param storePath * @param fileName */ @Override public void parseLevel1Ot(long ufuId, String storePath, String fileName) { if (storePath != null && fileName != null) { List<OTCatalog> otcs = otcDao.getOT1VarCatalog(rootPath + "/" + storePath + "/" + fileName); for (OTCatalog otc : otcs) { String otListPath = storePath; String orgImg = otc.getImageName(); //M2_03_140630_1_255020_0024.fit String ccdType = orgImg.substring(0, 1); //"M" String fileDate = orgImg.substring(6, 12); //140828 String dpmName = ccdType + orgImg.substring(3, 5); int dpmId = Integer.parseInt(orgImg.substring(3, 5)); //应该在数据库中通过dpmName查询 int number = Integer.parseInt(orgImg.substring(22, 26)); String skyName = orgImg.substring(6, 12); ObservationSky sky = skyDao.getByName(skyName); FitsFile ff = new FitsFile(); ff.setFileName(orgImg); ffDao.save(ff); OtLevel2 otLv2 = new OtLevel2(); otLv2.setRa(otc.getRaD()); otLv2.setDec(otc.getDecD()); otLv2.setFoundTimeUtc(otc.getDateUt()); otLv2.setIdentify(orgImg.substring(0, 21)); otLv2.setXtemp(otc.getXTemp()); otLv2.setYtemp(otc.getYTemp()); otLv2.setLastFfNumber(number); otLv2.setDpmId(dpmId); otLv2.setDateStr(fileDate); otLv2.setAllFileCutted(false); otLv2.setSkyId(sky.getSkyId()); otLv2.setDataProduceMethod('6'); //星表匹配变星 otLv2.setMag(otc.getMagAper()); OtObserveRecord oor = new OtObserveRecord(); oor.setOtId((long) 0); oor.setFfcId((long) 0); oor.setFfId(ff.getFfId()); oor.setRaD(otc.getRaD()); oor.setDecD(otc.getDecD()); oor.setX(otc.getX()); oor.setY(otc.getY()); oor.setXTemp(otc.getXTemp()); oor.setYTemp(otc.getYTemp()); oor.setDateUt(otc.getDateUt()); oor.setFlux(otc.getFlux()); oor.setFlag(otc.getFlag()); //oor.setFlagChb(otc.getFlagChb()); oor.setBackground(otc.getBackground()); oor.setThreshold(otc.getThreshold()); oor.setMagAper(otc.getMagAper()); oor.setMagerrAper(otc.getMagerrAper()); oor.setEllipticity(otc.getEllipticity()); oor.setClassStar(otc.getClassStar()); //oor.setOtFlag(otc.getOtFlag()); oor.setFfNumber(number); oor.setDateStr(fileDate); oor.setDpmId(dpmId); oor.setRequestCut(false); oor.setSuccessCut(false); oor.setSkyId(sky.getSkyId()); oor.setDataProduceMethod('6'); //星表匹配变星 oor.setDistance(otc.getDistance()); oor.setDeltamag(otc.getDeltamag()); //当前这条记录是与最近5幅之内的OT匹配,还是与当晚所有OT匹配,这里选择与当晚所有OT匹配 //existInLatestN与最近5幅比较 OtLevel2 tlv2 = otLv2Dao.existInAll(otLv2, errorBox); if (tlv2 != null) { if (tlv2.getFirstFfNumber() > number) { tlv2.setFirstFfNumber(number); } tlv2.setTotal(tlv2.getTotal() + 1); tlv2.setLastFfNumber(otLv2.getLastFfNumber()); tlv2.setXtemp(otLv2.getXtemp()); tlv2.setYtemp(otLv2.getYtemp()); tlv2.setRa(otLv2.getRa()); tlv2.setDec(otLv2.getDec()); tlv2.setMag(otLv2.getMag()); // otLv2Dao.update(tlv2); otLv2Dao.updateSomeRealTimeInfo(tlv2); if (false) { String cutImg = String.format("%s_%04d", tlv2.getName(), oor.getFfNumber()); FitsFileCut ffc = new FitsFileCut(); ffc.setStorePath(otListPath.substring(0, otListPath.lastIndexOf('/')) + "/" + cutIDir); ffc.setFileName(cutImg); ffc.setOtId(tlv2.getOtId()); ffc.setNumber(number); ffc.setFfId(ff.getFfId()); ffc.setDpmId((short) dpmId); ffc.setImgX(oor.getX()); ffc.setImgY(oor.getY()); ffc.setRequestCut(false); ffc.setSuccessCut(false); ffc.setIsMissed(false); ffcDao.save(ffc); oor.setFfcId(ffc.getFfcId()); } oor.setOtId(tlv2.getOtId()); otorDao.save(oor); } else { otorDao.save(oor); List<OtObserveRecord> oors = otorDao.matchLatestN(oor, errorBox, successiveImageNumber); if (oors.size() >= occurNumber) { OtObserveRecord oor1 = oors.get(0); int otNumber = otnDao.getNumberByDate(fileDate); String otName = String.format("%s%s_V%05d", ccdType, fileDate, otNumber); OtLevel2 tOtLv2 = new OtLevel2(); tOtLv2.setName(otName); tOtLv2.setRa(oor1.getRaD()); tOtLv2.setDec(oor1.getDecD()); tOtLv2.setFoundTimeUtc(oor1.getDateUt()); tOtLv2.setIdentify(otLv2.getIdentify()); tOtLv2.setXtemp(oor1.getXTemp()); tOtLv2.setYtemp(oor1.getYTemp()); tOtLv2.setLastFfNumber(oors.get(oors.size() - 1).getFfNumber()); //已有序列的最大一个编号(最后一个),数据库中查询时,按照升序排列 tOtLv2.setTotal(oors.size()); tOtLv2.setDpmId(oor1.getDpmId()); tOtLv2.setDateStr(fileDate); tOtLv2.setAllFileCutted(false); tOtLv2.setFirstFfNumber(oor1.getFfNumber()); //已有序列的最小一个编号(第一个) tOtLv2.setCuttedFfNumber(0); tOtLv2.setIsMatch((short) 0); tOtLv2.setSkyId(oor1.getSkyId()); tOtLv2.setDataProduceMethod('6'); //星表匹配变星 tOtLv2.setFoCount((short) 0); tOtLv2.setMag(oor1.getMagAper()); tOtLv2.setCvsMatch((short) 0); tOtLv2.setRc3Match((short) 0); tOtLv2.setMinorPlanetMatch((short) 0); tOtLv2.setOt2HisMatch((short) 0); tOtLv2.setOtherMatch((short) 0); tOtLv2.setUsnoMatch((short) 0); tOtLv2.setOtType((short) 0); tOtLv2.setLookBackResult((short) 0); tOtLv2.setFollowUpResult((short) 0); int firstRecordNumber = dpmDao.getFirstRecordNumber(dpmName); if (oor1.getFfNumber() - firstRecordNumber <= firstNMarkNumber) { tOtLv2.setFirstNMark(true); } else { tOtLv2.setFirstNMark(false); } otLv2Dao.save(tOtLv2); MessageCreator tmc = new OTCheckMessageCreator(tOtLv2); jmsTemplate.send(otCheckDest, tmc); String ffcrName = String.format("%s_%04d_ref", otName, tOtLv2.getFirstFfNumber()); log.debug("ffcrName=" + ffcrName); log.debug("otId=" + tOtLv2.getOtId()); if (false) { FitsFileCutRef ffcr = new FitsFileCutRef(); ffcr.setDpmId(Long.valueOf(tOtLv2.getDpmId())); ffcr.setFfId(ff.getFfId()); ffcr.setFileName(ffcrName); ffcr.setOtId(tOtLv2.getOtId()); ffcr.setStorePath(otListPath.substring(0, otListPath.lastIndexOf('/')) + "/" + cutIDir); ffcr.setRequestCut(false); ffcr.setSuccessCut(false); ffcrDao.save(ffcr); } for (OtObserveRecord tOor : oors) { if (tOor.getOtId() != 0) { continue; } if (false) { String cutImg = String.format("%s_%04d", tOtLv2.getName(), tOor.getFfNumber()); FitsFileCut ffc = new FitsFileCut(); ffc.setStorePath(otListPath.substring(0, otListPath.lastIndexOf('/')) + "/" + cutIDir); ffc.setFileName(cutImg); ffc.setOtId(tOtLv2.getOtId()); ffc.setNumber(tOor.getFfNumber()); ffc.setFfId(tOor.getFfId()); ffc.setDpmId((short) dpmId); ffc.setImgX(tOor.getX()); ffc.setImgY(tOor.getY()); ffc.setRequestCut(false); ffc.setSuccessCut(false); ffc.setIsMissed(false); ffcDao.save(ffc); tOor.setFfcId(ffc.getFfcId()); } tOor.setOtId(tOtLv2.getOtId()); otorDao.update(tOor); } } } } ufuDao.updateProcessDoneTime(ufuId); } } /** * @return the otorDao */ public OtObserveRecordDAO getOtorDao() { return otorDao; } /** * @param otorDao the otorDao to set */ public void setOtorDao(OtObserveRecordDAO otorDao) { this.otorDao = otorDao; } /** * @return the otcDao */ public OTCatalogDao getOtcDao() { return otcDao; } /** * @param otcDao the otcDao to set */ public void setOtcDao(OTCatalogDao otcDao) { this.otcDao = otcDao; } /** * @return the ffDao */ public FitsFileDAO getFfDao() { return ffDao; } /** * @param ffDao the ffDao to set */ public void setFfDao(FitsFileDAO ffDao) { this.ffDao = ffDao; } /** * @return the ffcDao */ public FitsFileCutDAO getFfcDao() { return ffcDao; } /** * @param ffcDao the ffcDao to set */ public void setFfcDao(FitsFileCutDAO ffcDao) { this.ffcDao = ffcDao; } /** * @return the otnDao */ public OtNumberDao getOtnDao() { return otnDao; } /** * @param otnDao the otnDao to set */ public void setOtnDao(OtNumberDao otnDao) { this.otnDao = otnDao; } /** * @return the dpmDao */ public DataProcessMachineDAO getDpmDao() { return dpmDao; } /** * @param dpmDao the dpmDao to set */ public void setDpmDao(DataProcessMachineDAO dpmDao) { this.dpmDao = dpmDao; } /** * @return the otLv2Dao */ public OtLevel2Dao getOtLv2Dao() { return otLv2Dao; } /** * @param otLv2Dao the otLv2Dao to set */ public void setOtLv2Dao(OtLevel2Dao otLv2Dao) { this.otLv2Dao = otLv2Dao; } /** * @return the rootPath */ public String getRootPath() { return rootPath; } /** * @param rootPath the rootPath to set */ public void setRootPath(String rootPath) { this.rootPath = rootPath; } /** * @param errorBox the errorBox to set */ public void setErrorBox(float errorBox) { this.errorBox = errorBox; } /** * @param successiveImageNumber the successiveImageNumber to set */ public void setSuccessiveImageNumber(int successiveImageNumber) { this.successiveImageNumber = successiveImageNumber; } /** * @param occurNumber the occurNumber to set */ public void setOccurNumber(int occurNumber) { this.occurNumber = occurNumber; } /** * @return the ffcrDao */ public FitsFileCutRefDAO getFfcrDao() { return ffcrDao; } /** * @param ffcrDao the ffcrDao to set */ public void setFfcrDao(FitsFileCutRefDAO ffcrDao) { this.ffcrDao = ffcrDao; } /** * @param isBeiJingServer the isBeiJingServer to set */ public void setIsBeiJingServer(Boolean isBeiJingServer) { this.isBeiJingServer = isBeiJingServer; } /** * @param isTestServer the isTestServer to set */ public void setIsTestServer(Boolean isTestServer) { this.isTestServer = isTestServer; } /** * @param firstNMarkNumber the firstNMarkNumber to set */ public void setFirstNMarkNumber(int firstNMarkNumber) { this.firstNMarkNumber = firstNMarkNumber; } /** * @param skyDao the skyDao to set */ public void setSkyDao(ObservationSkyDao skyDao) { this.skyDao = skyDao; } /** * @param cutIDir the cutIDir to set */ public void setCutIDir(String cutIDir) { this.cutIDir = cutIDir; } /** * @param ufuDao the ufuDao to set */ public void setUfuDao(UploadFileUnstoreDao ufuDao) { this.ufuDao = ufuDao; } /** * @param jmsTemplate the jmsTemplate to set */ public void setJmsTemplate(JmsTemplate jmsTemplate) { this.jmsTemplate = jmsTemplate; } /** * @param otCheckDest the otCheckDest to set */ public void setOtCheckDest(Destination otCheckDest) { this.otCheckDest = otCheckDest; } }
apache-2.0
Fabryprog/camel
tests/camel-itest/src/test/java/org/apache/camel/itest/jms/JmsPerformanceTest.java
4623
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ package org.apache.camel.itest.jms; import java.util.ArrayList; import java.util.List; import javax.jms.ConnectionFactory; import org.apache.camel.Header; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.jms.JmsComponent; import org.apache.camel.itest.CamelJmsTestHelper; import org.apache.camel.spi.Registry; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; import static org.apache.camel.component.jms.JmsComponent.jmsComponentAutoAcknowledge; public class JmsPerformanceTest extends CamelTestSupport { private List<Integer> receivedHeaders = new ArrayList<>(getMessageCount()); private List<Object> receivedMessages = new ArrayList<>(getMessageCount()); @Test public void testSendingAndReceivingMessages() throws Exception { log.info("Sending {} messages", getMessageCount()); sendLoop(getMessageCount()); log.info("Sending {} messages completed, now will assert on their content as well as the order of their receipt", getMessageCount()); // should wait a bit to make sure all messages have been received by the MyBean#onMessage() method // as this happens asynchronously, that's not inside the 'main' thread Thread.sleep(3000); assertExpectedMessagesReceived(); } protected int getMessageCount() { return 100; } protected void sendLoop(int messageCount) { for (int i = 1; i <= messageCount; i++) { sendMessage(i); } } protected void sendMessage(int messageCount) { template.sendBodyAndHeader("activemq:" + getQueueName(), "Hello:" + messageCount, "counter", messageCount); } protected String getQueueName() { return "testSendingAndReceivingMessages"; } protected void assertExpectedMessagesReceived() throws InterruptedException { // assert on the expected message count assertEquals("The expected message count does not match!", getMessageCount(), receivedMessages.size()); // assert on the expected message order List<Integer> expectedHeaders = new ArrayList<>(getMessageCount()); for (int i = 1; i <= getMessageCount(); i++) { expectedHeaders.add(i); } List<Object> expectedMessages = new ArrayList<>(getMessageCount()); for (int i = 1; i <= getMessageCount(); i++) { expectedMessages.add("Hello:" + i); } assertEquals("The expected header order does not match!", expectedHeaders, receivedHeaders); assertEquals("The expected message order does not match!", expectedMessages, receivedMessages); } @Override protected void bindToRegistry(Registry registry) throws Exception { // add AMQ client and make use of connection pooling we depend on because of the (large) number // of the JMS messages we do produce // add ActiveMQ with embedded broker ConnectionFactory connectionFactory = CamelJmsTestHelper.createConnectionFactory(); JmsComponent amq = jmsComponentAutoAcknowledge(connectionFactory); amq.setCamelContext(context); registry.bind("myBean", new MyBean()); registry.bind("activemq", amq); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() { from("activemq:" + getQueueName()).to("bean:myBean"); } }; } protected class MyBean { public void onMessage(@Header("counter") int counter, Object body) { // the invocation of this method happens inside the same thread so no need for a thread-safe list here receivedHeaders.add(counter); receivedMessages.add(body); } } }
apache-2.0
brmeyer/s-ramp
ui/src/main/java/org/artificer/ui/client/shared/beans/ArtifactFilterBean.java
10223
/* * Copyright 2013 JBoss Inc * * 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. */ package org.artificer.ui.client.shared.beans; import org.jboss.errai.common.client.api.annotations.Portable; import java.io.Serializable; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * All of the user's filter settings (configured on the left-hand sidebar of * the Artifacts page). * * @author eric.wittmann@redhat.com */ @Portable public class ArtifactFilterBean implements Serializable { private static final long serialVersionUID = 3789397680981626569L; private String keywords = ""; private String artifactType = ""; private String uuid = ""; private String name = ""; private Date dateCreatedFrom; private Date dateCreatedTo; private Date dateModifiedFrom; private Date dateModifiedTo; private String createdBy = ""; private String lastModifiedBy = ""; private ArtifactOriginEnum origin = ArtifactOriginEnum.ALL; /** * The classifiers selected by the user in the 'Classifiers' filter section. This is * a simple map of Ontology Base (URI) to Set of Ontology Class IDs. In other words, * each ontology in the UI will be a key, and the values will be the IDs of the classes * selected in the classifier selection dialog. */ private Map<String, Set<String>> classifiers = new HashMap<String, Set<String>>(); /** * The custom property filters. This is just a name/value pair. The user can specify * as many of these as she likes. */ private Map<String, String> customProperties = new HashMap<String, String>(); /** * Constructor. */ public ArtifactFilterBean() { } public String getKeywords() { return keywords; } /** * @return the artifactType */ public String getArtifactType() { return artifactType; } public String getUuid() { return uuid; } public String getName() { return name; } /** * @return the dateCreatedFrom */ public Date getDateCreatedFrom() { return dateCreatedFrom; } /** * @return the dateCreatedTo */ public Date getDateCreatedTo() { return dateCreatedTo; } /** * @return the dateModifiedFrom */ public Date getDateModifiedFrom() { return dateModifiedFrom; } /** * @return the dateModifiedTo */ public Date getDateModifiedTo() { return dateModifiedTo; } /** * @return the createdBy */ public String getCreatedBy() { return createdBy; } /** * @return the lastModifiedBy */ public String getLastModifiedBy() { return lastModifiedBy; } /** * @return the origin */ public ArtifactOriginEnum getOrigin() { return origin; } public ArtifactFilterBean setKeywords(String keywords) { this.keywords = keywords; return this; } /** * @param artifactType the artifactType to set */ public ArtifactFilterBean setArtifactType(String artifactType) { this.artifactType = artifactType; return this; } public ArtifactFilterBean setUuid(String uuid) { this.uuid = uuid; return this; } public ArtifactFilterBean setName(String name) { this.name = name; return this; } /** * @param dateCreatedFrom the dateCreatedFrom to set */ public ArtifactFilterBean setDateCreatedFrom(Date dateCreatedFrom) { this.dateCreatedFrom = dateCreatedFrom; return this; } /** * @param dateCreatedTo the dateCreatedTo to set */ public ArtifactFilterBean setDateCreatedTo(Date dateCreatedTo) { this.dateCreatedTo = dateCreatedTo; return this; } /** * @param dateModifiedFrom the dateModifiedFrom to set */ public ArtifactFilterBean setDateModifiedFrom(Date dateModifiedFrom) { this.dateModifiedFrom = dateModifiedFrom; return this; } /** * @param dateModifiedTo the dateModifiedTo to set */ public ArtifactFilterBean setDateModifiedTo(Date dateModifiedTo) { this.dateModifiedTo = dateModifiedTo; return this; } /** * @param createdBy the createdBy to set */ public ArtifactFilterBean setCreatedBy(String createdBy) { this.createdBy = createdBy; return this; } /** * @param lastModifiedBy the lastModifiedBy to set */ public ArtifactFilterBean setLastModifiedBy(String lastModifiedBy) { this.lastModifiedBy = lastModifiedBy; return this; } /** * @param origin the origin to set */ public ArtifactFilterBean setOrigin(ArtifactOriginEnum origin) { this.origin = origin; return this; } /** * @return the classifiers */ public Map<String, Set<String>> getClassifiers() { return classifiers; } /** * Sets the classifiers. */ public ArtifactFilterBean setClassifiers(Map<String, Set<String>> classifiers) { this.classifiers = classifiers; return this; } /** * @return the customProperties */ public Map<String, String> getCustomProperties() { return customProperties; } /** * @param customProperties the customProperties to set */ public void setCustomProperties(Map<String, String> customProperties) { this.customProperties = customProperties; } /** * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((keywords == null) ? 0 : keywords.hashCode()); result = prime * result + ((artifactType == null) ? 0 : artifactType.hashCode()); result = prime * result + ((uuid == null) ? 0 : uuid.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((createdBy == null) ? 0 : createdBy.hashCode()); result = prime * result + ((dateCreatedFrom == null) ? 0 : dateCreatedFrom.hashCode()); result = prime * result + ((dateCreatedTo == null) ? 0 : dateCreatedTo.hashCode()); result = prime * result + ((dateModifiedFrom == null) ? 0 : dateModifiedFrom.hashCode()); result = prime * result + ((dateModifiedTo == null) ? 0 : dateModifiedTo.hashCode()); result = prime * result + ((lastModifiedBy == null) ? 0 : lastModifiedBy.hashCode()); result = prime * result + ((origin == null) ? 0 : origin.hashCode()); result = prime * result + ((classifiers == null) ? 0 : classifiers.hashCode()); result = prime * result + ((customProperties == null) ? 0 : customProperties.hashCode()); return result; } /** * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ArtifactFilterBean other = (ArtifactFilterBean) obj; if (keywords == null) { if (other.keywords != null) return false; } else if (!keywords.equals(other.keywords)) return false; if (artifactType == null) { if (other.artifactType != null) return false; } else if (!artifactType.equals(other.artifactType)) return false; if (uuid == null) { if (other.uuid != null) return false; } else if (!uuid.equals(other.uuid)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (createdBy == null) { if (other.createdBy != null) return false; } else if (!createdBy.equals(other.createdBy)) return false; if (dateCreatedFrom == null) { if (other.dateCreatedFrom != null) return false; } else if (!dateCreatedFrom.equals(other.dateCreatedFrom)) return false; if (dateCreatedTo == null) { if (other.dateCreatedTo != null) return false; } else if (!dateCreatedTo.equals(other.dateCreatedTo)) return false; if (dateModifiedFrom == null) { if (other.dateModifiedFrom != null) return false; } else if (!dateModifiedFrom.equals(other.dateModifiedFrom)) return false; if (dateModifiedTo == null) { if (other.dateModifiedTo != null) return false; } else if (!dateModifiedTo.equals(other.dateModifiedTo)) return false; if (lastModifiedBy == null) { if (other.lastModifiedBy != null) return false; } else if (!lastModifiedBy.equals(other.lastModifiedBy)) return false; if (origin != other.origin) return false; if (classifiers == null) { if (other.classifiers != null) return false; } else if (!classifiers.equals(other.classifiers)) return false; if (customProperties == null) { if (other.customProperties != null) return false; } else if (!customProperties.equals(other.customProperties)) return false; return true; } }
apache-2.0
INAETICS/node-wiring-java
org.inaetics.remote.demo/src/org/inaetics/remote/demo/inaetics/datastore/impl/DataStoreImpl.java
175
package org.inaetics.remote.demo.inaetics.datastore.impl; import org.inaetics.remote.demo.inaetics.datastore.DataStore; public class DataStoreImpl implements DataStore { }
apache-2.0
Nike-Inc/cerberus-management-service
cerberus-web/src/main/java/com/nike/cerberus/service/AwsIamRoleService.java
2180
/* * Copyright (c) 2020 Nike, inc. * * 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. */ package com.nike.cerberus.service; import static com.nike.cerberus.service.AuthenticationService.SYSTEM_USER; import com.nike.cerberus.dao.AwsIamRoleDao; import com.nike.cerberus.record.AwsIamRoleRecord; import com.nike.cerberus.util.DateTimeSupplier; import com.nike.cerberus.util.UuidSupplier; import java.time.OffsetDateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; @Component public class AwsIamRoleService { private final AwsIamRoleDao awsIamRoleDao; private final UuidSupplier uuidSupplier; private final DateTimeSupplier dateTimeSupplier; @Autowired public AwsIamRoleService( AwsIamRoleDao awsIamRoleDao, UuidSupplier uuidSupplier, DateTimeSupplier dateTimeSupplier) { this.awsIamRoleDao = awsIamRoleDao; this.uuidSupplier = uuidSupplier; this.dateTimeSupplier = dateTimeSupplier; } @Transactional public AwsIamRoleRecord createIamRole(String iamPrincipalArn) { String iamRoleId = uuidSupplier.get(); OffsetDateTime dateTime = dateTimeSupplier.get(); AwsIamRoleRecord awsIamRoleRecord = new AwsIamRoleRecord(); awsIamRoleRecord.setId(iamRoleId); awsIamRoleRecord.setAwsIamRoleArn(iamPrincipalArn); awsIamRoleRecord.setCreatedBy(SYSTEM_USER); awsIamRoleRecord.setLastUpdatedBy(SYSTEM_USER); awsIamRoleRecord.setCreatedTs(dateTime); awsIamRoleRecord.setLastUpdatedTs(dateTime); awsIamRoleDao.createIamRole(awsIamRoleRecord); return awsIamRoleRecord; } }
apache-2.0
StyleTang/incubator-rocketmq-externals
rocketmq-connect-redis/src/main/java/org/apache/rocketmq/connect/redis/parser/LPushXParser.java
1347
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ package org.apache.rocketmq.connect.redis.parser; import io.openmessaging.connector.api.data.FieldType; import org.apache.rocketmq.connect.redis.pojo.KVEntry; import org.apache.rocketmq.connect.redis.pojo.RedisEntry; /** * LPUSHX key value */ public class LPushXParser extends AbstractCommandParser { @Override public KVEntry createBuilder() { return RedisEntry.newEntry(FieldType.STRING); } @Override public KVEntry handleValue(KVEntry builder, String[] args) { return builder.value(args[0]); } }
apache-2.0
codetplace/design-patterns-java
src/patterns/behavioral/command/example/Engine.java
162
package patterns.behavioral.command.example; // Invocador class Engine { // Execute void execute(Command command) { command.execute(); } }
apache-2.0
klisly/fingerpoetry
app/src/main/java/com/klisly/bookbox/adapter/ArticleViewHolder.java
1331
package com.klisly.bookbox.adapter; import android.net.Uri; import android.view.ViewGroup; import android.widget.TextView; import com.facebook.drawee.view.SimpleDraweeView; import com.jude.easyrecyclerview.adapter.BaseViewHolder; import com.klisly.bookbox.R; import com.klisly.bookbox.model.Article; import com.klisly.bookbox.model.BaseModel; import com.klisly.bookbox.utils.ActivityUtil; import com.klisly.bookbox.utils.DateUtil; import java.util.Date; import butterknife.Bind; import butterknife.ButterKnife; public class ArticleViewHolder extends BaseViewHolder<BaseModel> { @Bind(R.id.tv_title) TextView tvTitle; @Bind(R.id.tv_content) TextView tvContent; @Bind(R.id.tv_source) TextView tvSource; @Bind(R.id.tv_time) TextView tvDate; @Bind(R.id.iv_image) SimpleDraweeView ivImage; public ArticleViewHolder(ViewGroup parent) { super(parent, R.layout.item_pager); ButterKnife.bind(this, itemView); } @Override public void setData(final BaseModel entity) { Article article = (Article) entity; tvTitle.setText(article.getTitle()); tvSource.setText(article.getSite()); ivImage.setImageURI(Uri.parse(article.getImg())); tvDate.setText(DateUtil.getFriendlyTimeSpanByNow(new Date(article.getCreateAt()))); } }
apache-2.0
nowellpoint/nowellpoint-integration-platform-parent
nowellpoint-aws-sdk/src/main/java/com/nowellpoint/client/model/CollectionResource.java
189
package com.nowellpoint.client.model; import java.util.List; public interface CollectionResource<T extends Resource> extends Resource, Iterable<T> { int getSize(); List<T> getItems(); }
apache-2.0
ecberkeley/code
src/org/ecberkeley/css/lang/Initialization.java
1726
package org.ecberkeley.css.lang; /** Purpose of this class is to show how to move * shared initialization code out of constructors. */ public class Initialization { public Initialization() { init(DEFAULT_NAME, DEFAULT_AGE); } public Initialization(String name){ init(name, DEFAULT_AGE); } public Initialization(String name, int age){ init(name, age); } private void init(String name, int age){ this.name = name; this.age = age; //Potentially lots more work here... } public static final String DEFAULT_NAME = "anonymous"; public static final int DEFAULT_AGE = 0; private String name = null; public String getName(){ return name; } private int age = 0; public int getAge(){ return age; } private String pubField = ""; public String getPubField() { return pubField; } public void setPubField(String pubField) { this.pubField = pubField; } private static void print(String arg){ System.out.println(arg); } public static void main(String[] args) { print("Hello, World!"); if (args.length >= 1){ String name = args[0]; Initialization foo; if (args.length >= 2){ int i = Integer.parseInt(args[1]); foo = new Initialization(name, i); } else { foo = new Initialization(name); } print("initialized object: "+foo); } else { print("Usage: java org.ecberkeley.css.lang.Initialization {name}"); print(" where {name} is a String"); } System.exit(1); } }
apache-2.0
gkamal/Aeron
aeron-client/src/test/java/io/aeron/SubscriptionTest.java
4962
/* * Copyright 2014 - 2016 Real Logic Ltd. * * 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. */ package io.aeron; import org.junit.Before; import org.junit.Test; import io.aeron.logbuffer.FragmentHandler; import io.aeron.logbuffer.FrameDescriptor; import io.aeron.logbuffer.Header; import io.aeron.protocol.DataHeaderFlyweight; import org.agrona.concurrent.UnsafeBuffer; import org.mockito.InOrder; import org.mockito.Mockito; import java.nio.ByteBuffer; import java.util.concurrent.locks.Lock; import static junit.framework.TestCase.assertTrue; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.*; public class SubscriptionTest { private static final String CHANNEL = "aeron:udp?endpoint=localhost:40124"; private static final int STREAM_ID_1 = 2; private static final long SUBSCRIPTION_CORRELATION_ID = 100; private static final int READ_BUFFER_CAPACITY = 1024; private static final byte FLAGS = (byte)FrameDescriptor.UNFRAGMENTED; private static final int FRAGMENT_COUNT_LIMIT = Integer.MAX_VALUE; private static final int HEADER_LENGTH = DataHeaderFlyweight.HEADER_LENGTH; private final UnsafeBuffer atomicReadBuffer = new UnsafeBuffer(ByteBuffer.allocateDirect(READ_BUFFER_CAPACITY)); private final Lock conductorLock = mock(Lock.class); private final ClientConductor conductor = mock(ClientConductor.class); private final FragmentHandler fragmentHandler = mock(FragmentHandler.class); private final Image imageOneMock = mock(Image.class); private final Header header = mock(Header.class); private final Image imageTwoMock = mock(Image.class); private Subscription subscription; @Before public void setUp() { when(header.flags()).thenReturn(FLAGS); when(conductor.mainLock()).thenReturn(conductorLock); subscription = new Subscription(conductor, CHANNEL, STREAM_ID_1, SUBSCRIPTION_CORRELATION_ID); } @Test public void shouldEnsureTheSubscriptionIsOpenWhenPolling() { subscription.close(); assertTrue(subscription.isClosed()); final InOrder inOrder = Mockito.inOrder(conductorLock, conductor); inOrder.verify(conductorLock).lock(); inOrder.verify(conductor).releaseSubscription(subscription); inOrder.verify(conductorLock).unlock(); } @Test public void shouldReadNothingWhenNoImages() { assertThat(subscription.poll(fragmentHandler, 1), is(0)); } @Test public void shouldReadNothingWhenThereIsNoData() { subscription.addImage(imageOneMock); assertThat(subscription.poll(fragmentHandler, 1), is(0)); } @Test public void shouldReadData() { subscription.addImage(imageOneMock); when(imageOneMock.poll(any(FragmentHandler.class), anyInt())).then( (invocation) -> { final FragmentHandler handler = (FragmentHandler)invocation.getArguments()[0]; handler.onFragment(atomicReadBuffer, HEADER_LENGTH, READ_BUFFER_CAPACITY - HEADER_LENGTH, header); return 1; }); assertThat(subscription.poll(fragmentHandler, FRAGMENT_COUNT_LIMIT), is(1)); verify(fragmentHandler).onFragment( eq(atomicReadBuffer), eq(HEADER_LENGTH), eq(READ_BUFFER_CAPACITY - HEADER_LENGTH), any(Header.class)); } @Test public void shouldReadDataFromMultipleSources() { subscription.addImage(imageOneMock); subscription.addImage(imageTwoMock); when(imageOneMock.poll(any(FragmentHandler.class), anyInt())).then( (invocation) -> { final FragmentHandler handler = (FragmentHandler)invocation.getArguments()[0]; handler.onFragment(atomicReadBuffer, HEADER_LENGTH, READ_BUFFER_CAPACITY - HEADER_LENGTH, header); return 1; }); when(imageTwoMock.poll(any(FragmentHandler.class), anyInt())).then( (invocation) -> { final FragmentHandler handler = (FragmentHandler)invocation.getArguments()[0]; handler.onFragment(atomicReadBuffer, HEADER_LENGTH, READ_BUFFER_CAPACITY - HEADER_LENGTH, header); return 1; }); assertThat(subscription.poll(fragmentHandler, FRAGMENT_COUNT_LIMIT), is(2)); } }
apache-2.0
EMResearch/EMB
jdk_8_maven/cs/rest-gui/ocvn/forms/src/main/java/org/devgateway/toolkit/forms/wicket/components/form/GenericBootstrapFormComponent.java
8834
/******************************************************************************* * Copyright (c) 2015 Development Gateway, Inc and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License (MIT) * which accompanies this distribution, and is available at * https://opensource.org/licenses/MIT * * Contributors: * Development Gateway - initial API and implementation *******************************************************************************/ package org.devgateway.toolkit.forms.wicket.components.form; import de.agilecoders.wicket.core.markup.html.bootstrap.components.TooltipConfig; import de.agilecoders.wicket.core.markup.html.bootstrap.form.FormGroup; import de.agilecoders.wicket.core.markup.html.bootstrap.form.InputBehavior; import de.agilecoders.wicket.core.markup.html.bootstrap.form.InputBehavior.Size; import de.agilecoders.wicket.core.util.Attributes; import org.apache.log4j.Logger; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.attributes.AjaxRequestAttributes; import org.apache.wicket.ajax.attributes.ThrottlingSettings; import org.apache.wicket.ajax.form.AjaxFormChoiceComponentUpdatingBehavior; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; import org.apache.wicket.event.IEvent; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.CheckGroup; import org.apache.wicket.markup.html.form.FormComponent; import org.apache.wicket.markup.html.form.RadioGroup; import org.apache.wicket.model.IModel; import org.apache.wicket.model.ResourceModel; import org.apache.wicket.util.time.Duration; import org.devgateway.toolkit.forms.models.SubComponentWrapModel; import org.devgateway.toolkit.forms.models.ViewModeConverterModel; import org.devgateway.toolkit.forms.wicket.components.ComponentUtil; import org.devgateway.toolkit.forms.wicket.components.FieldPanel; import org.devgateway.toolkit.forms.wicket.components.TooltipLabel; /** * @author mpostelnicu * */ public abstract class GenericBootstrapFormComponent<TYPE, FIELD extends FormComponent<TYPE>> extends FieldPanel<TYPE> { private static final long serialVersionUID = -7051128382707812456L; protected static Logger logger = Logger.getLogger(GenericBootstrapFormComponent.class); protected FormGroup border; protected FIELD field; protected Label viewModeField; protected InputBehavior sizeBehavior; private TooltipConfig.OpenTrigger configWithTrigger = TooltipConfig.OpenTrigger.hover; protected TooltipLabel tooltipLabel; protected IModel<String> labelModel; //prevents repainting of select boxes and other problems with triggering the update even while the component js //is not done updating. private static final int THROTTLE_UPDATE_DELAY_MS = 200; @Override public void onEvent(final IEvent<?> event) { ComponentUtil.enableDisableEvent(this, event); } @SuppressWarnings("unchecked") protected IModel<TYPE> initFieldModel() { if (getDefaultModel() == null) { return new SubComponentWrapModel<TYPE>(this); } return (IModel<TYPE>) getDefaultModel(); } /** * use this behavior for choices/groups that are not one component in the * html but many. */ protected void getAjaxFormChoiceComponentUpdatingBehavior() { updatingBehaviorComponent().add(new AjaxFormChoiceComponentUpdatingBehavior() { private static final long serialVersionUID = 1L; @Override protected void updateAjaxAttributes(final AjaxRequestAttributes attributes) { attributes.setThrottlingSettings(new ThrottlingSettings( Duration.milliseconds(THROTTLE_UPDATE_DELAY_MS))); super.updateAjaxAttributes(attributes); } @Override protected void onUpdate(final AjaxRequestTarget target) { GenericBootstrapFormComponent.this.onUpdate(target); } }); } /** * This is the component that has to be updated with the * {@link #getAjaxFormChoiceComponentUpdatingBehavior()} or with * {@link #getAjaxFormComponentUpdatingBehavior()}. It usuall is the field, * but the field may be a wrapper, in which case you should override this * and provide the wrapped field. * * @return */ protected FormComponent<TYPE> updatingBehaviorComponent() { return field; } protected void getAjaxFormComponentUpdatingBehavior() { updatingBehaviorComponent().add(new AjaxFormComponentUpdatingBehavior(getUpdateEvent()) { private static final long serialVersionUID = -2696538086634114609L; @Override protected void updateAjaxAttributes(final AjaxRequestAttributes attributes) { attributes.setThrottlingSettings(new ThrottlingSettings( Duration.milliseconds(THROTTLE_UPDATE_DELAY_MS))); super.updateAjaxAttributes(attributes); } @Override protected void onUpdate(final AjaxRequestTarget target) { target.add(border); GenericBootstrapFormComponent.this.onUpdate(target); } @Override protected void onError(final AjaxRequestTarget target, final RuntimeException e) { target.add(border); } }); } public String getUpdateEvent() { return "blur"; } public GenericBootstrapFormComponent<TYPE, FIELD> type(final Class<?> clazz) { field.setType(clazz); return this; } public GenericBootstrapFormComponent<TYPE, FIELD> size(final Size size) { sizeBehavior.size(size); return this; } public GenericBootstrapFormComponent(final String id) { this(id, null); } public String getLabelKey() { return this.getId() + ".label"; } public GenericBootstrapFormComponent(final String id, final IModel<TYPE> model) { this(id, new ResourceModel(id + ".label"), model); } public GenericBootstrapFormComponent(final String id, final IModel<String> labelModel, final IModel<TYPE> model) { super(id, model); this.labelModel = labelModel; setOutputMarkupId(true); setOutputMarkupPlaceholderTag(true); border = new FormGroup("enclosing-field-group"); border.setOutputMarkupId(true); add(border); field = inputField("field", model); field.setVisibilityAllowed(!ComponentUtil.isViewMode()); field.setOutputMarkupId(true); sizeBehavior = new InputBehavior(InputBehavior.Size.Medium); field.add(sizeBehavior); border.add(field); field.setLabel(labelModel); tooltipLabel = new TooltipLabel("tooltipLabel", id); border.add(tooltipLabel); } @Override protected void onComponentTag(final ComponentTag tag) { super.onComponentTag(tag); // add a new class for required fields if (field.isRequired()) { Attributes.addClass(tag, "required"); } } public GenericBootstrapFormComponent<TYPE, FIELD> hideLabel() { field.setLabel(null); return this; } protected abstract FIELD inputField(String id, IModel<TYPE> model); public GenericBootstrapFormComponent<TYPE, FIELD> required() { field.setRequired(true); return this; } protected void onUpdate(final AjaxRequestTarget target) { } public FIELD getField() { return field; } /* * (non-Javadoc) * * @see org.apache.wicket.Component#onConfigure() */ @Override protected void onInitialize() { super.onInitialize(); if ((field instanceof RadioGroup) || (field instanceof CheckGroup)) { getAjaxFormChoiceComponentUpdatingBehavior(); } else { getAjaxFormComponentUpdatingBehavior(); } viewModeField = new Label("viewModeField", new ViewModeConverterModel<TYPE>(getModel())); viewModeField.setEscapeModelStrings(false); viewModeField.setVisibilityAllowed(ComponentUtil.isViewMode()); border.add(viewModeField); tooltipLabel.setConfigWithTrigger(configWithTrigger); } /** * @return the border */ public FormGroup getBorder() { return border; } public TooltipConfig.OpenTrigger getConfigWithTrigger() { return configWithTrigger; } public void setConfigWithTrigger(final TooltipConfig.OpenTrigger configWithTrigger) { this.configWithTrigger = configWithTrigger; } }
apache-2.0
Cangol/GBF
app/src/com/azhuoinfo/gbf/api/ApiPage.java
971
package com.azhuoinfo.gbf.api; public class ApiPage { private int pageSize; private int curPage; private long totalCount; private long totalPageCount; public ApiPage() { super(); } public ApiPage(int pageSize, int curPage, long totalCount, long totalPageCount) { super(); this.pageSize = pageSize; this.curPage = curPage; this.totalCount = totalCount; this.totalPageCount = totalPageCount; } public long getTotalCount() { return totalCount; } public void setTotalCount(long totalCount) { this.totalCount = totalCount; } public long getTotalPageCount() { return totalPageCount; } public void setTotalPageCount(long totalPageCount) { this.totalPageCount = totalPageCount; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getCurPage() { return curPage; } public void setCurPage(int curPage) { this.curPage = curPage; } }
apache-2.0
robsoncardosoti/flowable-engine
modules/flowable-idm-engine/src/main/java/org/flowable/idm/engine/impl/cmd/SetUserPictureCmd.java
1919
/* 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. */ package org.flowable.idm.engine.impl.cmd; import java.io.Serializable; import org.flowable.engine.common.api.FlowableIllegalArgumentException; import org.flowable.engine.common.api.FlowableObjectNotFoundException; import org.flowable.idm.api.Picture; import org.flowable.idm.api.User; import org.flowable.idm.engine.impl.interceptor.Command; import org.flowable.idm.engine.impl.interceptor.CommandContext; /** * @author Tom Baeyens */ public class SetUserPictureCmd implements Command<Object>, Serializable { private static final long serialVersionUID = 1L; protected String userId; protected Picture picture; public SetUserPictureCmd(String userId, Picture picture) { this.userId = userId; this.picture = picture; } public Object execute(CommandContext commandContext) { if (userId == null) { throw new FlowableIllegalArgumentException("userId is null"); } User user = commandContext.getIdmEngineConfiguration().getIdmIdentityService() .createUserQuery().userId(userId) .singleResult(); if (user == null) { throw new FlowableObjectNotFoundException("user " + userId + " doesn't exist", User.class); } commandContext.getUserEntityManager().setUserPicture(user, picture); return null; } }
apache-2.0
NottyCode/ci.maven
liberty-maven-plugin/src/it/tests/ear-project-it/SampleWLP/src/test/java/net/wasdev/wlp/maven/test/it/LooseConfigTestIT.java
4404
/******************************************************************************* * (c) Copyright IBM Corporation 2017. * * 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. *******************************************************************************/ package net.wasdev.wlp.maven.test.it; import java.io.File; import java.io.FileInputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Document; import static junit.framework.Assert.*; public class LooseConfigTestIT { public final String LOOSE_APP = "target/liberty/wlp/usr/servers/test/apps/SampleEAR.ear.xml"; @Test public void testLooseApplicationFileExist() throws Exception { File f = new File(LOOSE_APP); assertTrue(f.getCanonicalFile() + " doesn't exist", f.exists()); } @Test public void testLooseApplicationFileContent() throws Exception { File f = new File(LOOSE_APP); FileInputStream input = new FileInputStream(f); // get input XML Document DocumentBuilderFactory inputBuilderFactory = DocumentBuilderFactory.newInstance(); inputBuilderFactory.setIgnoringComments(true); inputBuilderFactory.setCoalescing(true); inputBuilderFactory.setIgnoringElementContentWhitespace(true); inputBuilderFactory.setValidating(false); DocumentBuilder inputBuilder = inputBuilderFactory.newDocumentBuilder(); Document inputDoc=inputBuilder.parse(input); // parse input XML Document XPath xPath = XPathFactory.newInstance().newXPath(); String expression = "/archive/file"; NodeList nodes = (NodeList) xPath.compile(expression).evaluate(inputDoc, XPathConstants.NODESET); assertEquals("Number of <file/> element ==>", 2, nodes.getLength()); assertEquals("file targetInArchive attribute value", "/META-INF/application.xml", nodes.item(0).getAttributes().getNamedItem("targetInArchive").getNodeValue()); assertEquals("file targetInArchive attribute value", "/META-INF/MANIFEST.MF", nodes.item(1).getAttributes().getNamedItem("targetInArchive").getNodeValue()); expression = "/archive/dir"; nodes = (NodeList) xPath.compile(expression).evaluate(inputDoc, XPathConstants.NODESET); assertEquals("Number of <dir/> element ==>", 1, nodes.getLength()); expression = "/archive/archive"; nodes = (NodeList) xPath.compile(expression).evaluate(inputDoc, XPathConstants.NODESET); assertEquals("Number of <archive/> element ==>", 3, nodes.getLength()); assertEquals("archive targetInArchive attribute value", "/SampleEJB.jar", nodes.item(0).getAttributes().getNamedItem("targetInArchive").getNodeValue()); assertEquals("archive targetInArchive attribute value", "/modules/web.war", nodes.item(1).getAttributes().getNamedItem("targetInArchive").getNodeValue()); assertEquals("archive targetInArchive attribute value", "/SampleWAR2.war", nodes.item(2).getAttributes().getNamedItem("targetInArchive").getNodeValue()); expression = "/archive/archive/file"; nodes = (NodeList) xPath.compile(expression).evaluate(inputDoc, XPathConstants.NODESET); assertEquals("Number of <archive/> element ==>", 5, nodes.getLength()); // test runtime scope dependency to be incldued in the ?WEB-INF/lib assertEquals("file targetInArchive attribute value", "/WEB-INF/lib/log4j-1.2.17.jar", nodes.item(2).getAttributes().getNamedItem("targetInArchive").getNodeValue()); } }
apache-2.0
max2me/collect
collect_app/src/main/java/org/odk/collect/android/activities/GeoTraceOsmMapActivity.java
31634
/* * Copyright (C) 2015 GeoODK * * 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. */ package org.odk.collect.android.activities; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.Paint; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.preference.PreferenceManager; import android.provider.Settings; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Spinner; import org.odk.collect.android.R; import org.odk.collect.android.spatial.MapHelper; import org.odk.collect.android.widgets.GeoTraceWidget; import org.osmdroid.DefaultResourceProxyImpl; import org.osmdroid.bonuspack.overlays.Marker; import org.osmdroid.bonuspack.overlays.Marker.OnMarkerClickListener; import org.osmdroid.bonuspack.overlays.Marker.OnMarkerDragListener; import org.osmdroid.tileprovider.IRegisterReceiver; import org.osmdroid.util.BoundingBoxE6; import org.osmdroid.util.GeoPoint; import org.osmdroid.views.MapView; import org.osmdroid.views.overlay.PathOverlay; import org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; public class GeoTraceOsmMapActivity extends Activity implements IRegisterReceiver, LocationListener { private ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); private ScheduledFuture schedulerHandler; public int zoom_level = 3; public Boolean gpsStatus = true; private Boolean play_check = false; private MapView mapView; private SharedPreferences sharedPreferences; public DefaultResourceProxyImpl resource_proxy; public MyLocationNewOverlay mMyLocationOverlay; private Button mLocationButton; private Button mPlayButton; private Button mSaveButton; public Button mLayersButton; public Button mClearButton; private Button mManualCaptureButton; private Button mPauseButton; public AlertDialog.Builder builder; public AlertDialog.Builder p_builder; public LayoutInflater inflater; private AlertDialog alert; private AlertDialog p_alert; private View traceSettingsView; private View polygonPolylineView; private PathOverlay pathOverlay; private ArrayList<Marker> map_markers = new ArrayList<Marker>(); private String final_return_string; private Integer TRACE_MODE; // 0 manual, 1 is automatic private Boolean inital_location_found = false; private Spinner time_units; private Spinner time_delay; private Button mPolygonSaveButton; private Button mPolylineSaveButton; private Boolean beenPaused; private MapHelper mHelper; private AlertDialog zoomDialog; private View zoomDialogView; private LocationManager mLocationManager; private Button zoomPointButton; private Button zoomLocationButton; private Boolean mode_active = false; private Boolean mGPSOn = false; private Boolean mNetworkOn = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.geotrace_osm_layout); setTitle(getString(R.string.geotrace_title)); // Setting title of the action sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); resource_proxy = new DefaultResourceProxyImpl(getApplicationContext()); mapView = (MapView) findViewById(R.id.geotrace_mapview); mHelper = new MapHelper(this, mapView, GeoTraceOsmMapActivity.this); mapView.setMultiTouchControls(true); mapView.setBuiltInZoomControls(true); mapView.getController().setZoom(zoom_level); mMyLocationOverlay = new MyLocationNewOverlay(this, mapView); inflater = this.getLayoutInflater(); traceSettingsView = inflater.inflate(R.layout.geotrace_dialog, null); polygonPolylineView = inflater.inflate(R.layout.polygon_polyline_dialog, null); time_delay = (Spinner) traceSettingsView.findViewById(R.id.trace_delay); time_delay.setSelection(3); time_units = (Spinner) traceSettingsView.findViewById(R.id.trace_scale); mLayersButton = (Button) findViewById(R.id.layers); mLayersButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mHelper.showLayersDialog(); } }); mLocationButton = (Button) findViewById(R.id.show_location); mLocationButton.setEnabled(false); mLocationButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { reset_trace_settings(); showZoomDialog(); } }); mClearButton = (Button) findViewById(R.id.clear); mClearButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showClearDialog(); } }); mSaveButton = (Button) findViewById(R.id.geotrace_save); mSaveButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (map_markers.size() != 0) { p_alert.show(); } else { saveGeoTrace(); } } }); if (map_markers == null || map_markers.size() == 0) { mClearButton.setEnabled(false); } mManualCaptureButton = (Button) findViewById(R.id.manual_button); mManualCaptureButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addLocationMarker(); } }); mPauseButton = (Button) findViewById(R.id.pause); mPlayButton = (Button) findViewById(R.id.play); mPlayButton.setEnabled(false); beenPaused = false; TRACE_MODE = 1; mPlayButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { if (!play_check) { if (!beenPaused) { alert.show(); } else { RadioGroup rb = (RadioGroup) traceSettingsView.findViewById( R.id.radio_group); int radioButtonID = rb.getCheckedRadioButtonId(); View radioButton = rb.findViewById(radioButtonID); int idx = rb.indexOfChild(radioButton); TRACE_MODE = idx; if (TRACE_MODE == 0) { setupManualMode(); } else if (TRACE_MODE == 1) { setupAutomaticMode(); } else { reset_trace_settings(); } } play_check = true; } else { play_check = false; startGeoTrace(); } } }); mPauseButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { mPlayButton.setVisibility(View.VISIBLE); if (map_markers != null && map_markers.size() > 0) { mClearButton.setEnabled(true); } mPauseButton.setVisibility(View.GONE); mManualCaptureButton.setVisibility(View.GONE); play_check = true; mode_active = false; mMyLocationOverlay.disableFollowLocation(); try { schedulerHandler.cancel(true); } catch (Exception e) { // Do nothing } } }); overlayMapLayerListner(); buildDialogs(); Intent intent = getIntent(); if (intent != null && intent.getExtras() != null) { if (intent.hasExtra(GeoTraceWidget.TRACE_LOCATION)) { String s = intent.getStringExtra(GeoTraceWidget.TRACE_LOCATION); mPlayButton.setEnabled(false); mClearButton.setEnabled(true); overlayIntentTrace(s); mLocationButton.setEnabled(true); //zoomToCentroid(); zoomtoBounds(); } } else { mMyLocationOverlay.runOnFirstFix(centerAroundFix); } mPolygonSaveButton = (Button) polygonPolylineView.findViewById(R.id.polygon_save); mPolygonSaveButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (map_markers.size() > 2) { createPolygon(); p_alert.dismiss(); saveGeoTrace(); } else { p_alert.dismiss(); showPolyonErrorDialog(); } } }); mPolylineSaveButton = (Button) polygonPolylineView.findViewById(R.id.polyline_save); mPolylineSaveButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { p_alert.dismiss(); saveGeoTrace(); } }); zoomDialogView = getLayoutInflater().inflate(R.layout.geoshape_zoom_dialog, null); zoomLocationButton = (Button) zoomDialogView.findViewById(R.id.zoom_location); zoomLocationButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { zoomToMyLocation(); mapView.invalidate(); zoomDialog.dismiss(); } }); zoomPointButton = (Button) zoomDialogView.findViewById(R.id.zoom_shape); zoomPointButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //zoomToCentroid(); zoomtoBounds(); mapView.invalidate(); zoomDialog.dismiss(); } }); mapView.invalidate(); mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); List<String> providers = mLocationManager.getProviders(true); for (String provider : providers) { if (provider.equalsIgnoreCase(LocationManager.GPS_PROVIDER)) { mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); mGPSOn = true; } if (provider.equalsIgnoreCase(LocationManager.NETWORK_PROVIDER)) { mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); mNetworkOn = true; } } if (mGPSOn) { mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); } if (mNetworkOn) { mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this); } } @Override protected void onStart() { super.onStart(); } @Override protected void onRestart() { super.onRestart(); } @Override protected void onResume() { super.onResume(); mHelper.setBasemap(); upMyLocationOverlayLayers(); } @Override protected void onPause() { super.onPause(); mMyLocationOverlay.enableMyLocation(); // if(mMyLocationOverlay.getMyLocation()!= null){ // mMyLocationOverlay.runOnFirstFix(centerAroundFix); // } } @Override protected void onStop() { super.onStop(); disableMyLocation(); } @Override public void finish() { ViewGroup view = (ViewGroup) getWindow().getDecorView(); view.removeAllViews(); super.finish(); } @Override protected void onDestroy() { super.onDestroy(); } public void setGeoTraceScheuler(long delay, TimeUnit units) { schedulerHandler = scheduler.scheduleAtFixedRate(new Runnable() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { addLocationMarker(); } }); } }, delay, delay, units); } public void overlayIntentTrace(String str) { String s = str.replace("; ", ";"); String[] sa = s.split(";"); for (int i = 0; i < (sa.length); i++) { String[] sp = sa[i].split(" "); double gp[] = new double[4]; String lat = sp[0].replace(" ", ""); String lng = sp[1].replace(" ", ""); String altStr = sp[2].replace(" ", ""); String acu = sp[3].replace(" ", ""); gp[0] = Double.parseDouble(lat); gp[1] = Double.parseDouble(lng); Double alt = Double.parseDouble(altStr); Marker marker = new Marker(mapView); marker.setSubDescription(acu); GeoPoint point = new GeoPoint(gp[0], gp[1]); point.setAltitude(alt.intValue()); marker.setPosition(point); marker.setOnMarkerClickListener(nullmarkerlistner); marker.setDraggable(true); marker.setOnMarkerDragListener(draglistner); marker.setIcon(getResources().getDrawable(R.drawable.ic_place_black_36dp)); marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM); map_markers.add(marker); pathOverlay.addPoint(marker.getPosition()); mapView.getOverlays().add(marker); } mapView.invalidate(); } private void disableMyLocation() { LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); if (locationManager.isProviderEnabled(locationManager.GPS_PROVIDER)) { mMyLocationOverlay.setEnabled(false); mMyLocationOverlay.disableFollowLocation(); mMyLocationOverlay.disableMyLocation(); gpsStatus = false; } } private void upMyLocationOverlayLayers() { LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); if (locationManager.isProviderEnabled(locationManager.GPS_PROVIDER)) { overlayMyLocationLayers(); } else { showGPSDisabledAlertToUser(); } } private void overlayMapLayerListner() { pathOverlay = new PathOverlay(Color.RED, this); Paint pPaint = pathOverlay.getPaint(); pPaint.setStrokeWidth(5); mapView.getOverlays().add(pathOverlay); mapView.invalidate(); } private void overlayMyLocationLayers() { // mMyLocationOverlay.runOnFirstFix(centerAroundFix); // if(mMyLocationOverlay.getMyLocation()!= null){ // mMyLocationOverlay.runOnFirstFix(centerAroundFix); // } mapView.getOverlays().add(mMyLocationOverlay); mMyLocationOverlay.setEnabled(true); mMyLocationOverlay.enableMyLocation(); } private Handler mHandler = new Handler(Looper.getMainLooper()); private Runnable centerAroundFix = new Runnable() { public void run() { mHandler.post(new Runnable() { public void run() { mLocationButton.setEnabled(true); mPlayButton.setEnabled(true); showZoomDialog(); } }); } }; private void zoomToMyLocation() { if (mMyLocationOverlay.getMyLocation() != null) { inital_location_found = true; if (zoom_level == 3) { mapView.getController().setZoom(15); } else { mapView.getController().setZoom(zoom_level); } mapView.getController().setCenter(mMyLocationOverlay.getMyLocation()); } else { mapView.getController().setZoom(zoom_level); } } private void showGPSDisabledAlertToUser() { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setMessage(getString(R.string.enable_gps_message)) .setCancelable(false) .setPositiveButton(getString(R.string.enable_gps), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { startActivityForResult( new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0); } }); alertDialogBuilder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = alertDialogBuilder.create(); alert.show(); } //This happens on click of the play button public void setGeoTraceMode(View view) { boolean checked = ((RadioButton) view).isChecked(); switch (view.getId()) { case R.id.trace_manual: if (checked) { TRACE_MODE = 0; time_units.setVisibility(View.GONE); time_delay.setVisibility(View.GONE); time_delay.invalidate(); time_units.invalidate(); } break; case R.id.trace_automatic: if (checked) { TRACE_MODE = 1; time_units.setVisibility(View.VISIBLE); time_delay.setVisibility(View.VISIBLE); time_delay.invalidate(); time_units.invalidate(); } break; } } private void buildDialogs() { builder = new AlertDialog.Builder(this); builder.setTitle(getString(R.string.select_geotrace_mode)); builder.setView(null); builder.setView(traceSettingsView) // Add action buttons .setPositiveButton(getString(R.string.start), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { startGeoTrace(); dialog.cancel(); alert.dismiss(); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); alert.dismiss(); reset_trace_settings(); } }) .setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { reset_trace_settings(); } }); alert = builder.create(); p_builder = new AlertDialog.Builder(this); p_builder.setTitle(getString(R.string.polyline_polygon_text)); p_builder.setView(polygonPolylineView) // Add action buttons .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }) .setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { dialog.cancel(); alert.dismiss(); } }); p_alert = p_builder.create(); } private void reset_trace_settings() { play_check = false; } private void startGeoTrace() { RadioGroup rb = (RadioGroup) traceSettingsView.findViewById(R.id.radio_group); int radioButtonID = rb.getCheckedRadioButtonId(); View radioButton = rb.findViewById(radioButtonID); int idx = rb.indexOfChild(radioButton); beenPaused = true; TRACE_MODE = idx; if (TRACE_MODE == 0) { setupManualMode(); } else if (TRACE_MODE == 1) { setupAutomaticMode(); } else { reset_trace_settings(); } mPlayButton.setVisibility(View.GONE); mClearButton.setEnabled(false); mPauseButton.setVisibility(View.VISIBLE); } private void setupManualMode() { mManualCaptureButton.setVisibility(View.VISIBLE); mode_active = true; } private void setupAutomaticMode() { mManualCaptureButton.setVisibility(View.VISIBLE); String delay = time_delay.getSelectedItem().toString(); String units = time_units.getSelectedItem().toString(); Long time_delay; TimeUnit time_units_value; if (units == getString(R.string.minutes)) { time_delay = Long.parseLong(delay) * (60); //Convert minutes to seconds time_units_value = TimeUnit.SECONDS; } else { //in Seconds time_delay = Long.parseLong(delay); time_units_value = TimeUnit.SECONDS; } setGeoTraceScheuler(time_delay, time_units_value); mode_active = true; } private void addLocationMarker() { Marker marker = new Marker(mapView); marker.setPosition(mMyLocationOverlay.getMyLocation()); Float last_know_acuracy = mMyLocationOverlay.getMyLocationProvider().getLastKnownLocation().getAccuracy(); mMyLocationOverlay.getMyLocationProvider().getLastKnownLocation().getAccuracy(); marker.setIcon(getResources().getDrawable(R.drawable.ic_place_black_36dp)); marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM); marker.setDraggable(true); marker.setOnMarkerDragListener(draglistner); marker.setSubDescription(Float.toString(last_know_acuracy)); map_markers.add(marker); marker.setOnMarkerClickListener(nullmarkerlistner); mapView.getOverlays().add(marker); pathOverlay.addPoint(marker.getPosition()); mapView.invalidate(); } private void saveGeoTrace() { returnLocation(); finish(); } private void showPolyonErrorDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(getString(R.string.polygon_validator)) .setPositiveButton(getString(R.string.dialog_continue), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // FIRE ZE MISSILES! } }).show(); } private String generateReturnString() { String temp_string = ""; for (int i = 0; i < map_markers.size(); i++) { String lat = Double.toString(map_markers.get(i).getPosition().getLatitude()); String lng = Double.toString(map_markers.get(i).getPosition().getLongitude()); String alt = Integer.toString(map_markers.get(i).getPosition().getAltitude()); String acu = map_markers.get(i).getSubDescription(); temp_string = temp_string + lat + " " + lng + " " + alt + " " + acu + ";"; } return temp_string; } private void returnLocation() { final_return_string = generateReturnString(); Intent i = new Intent(); i.putExtra( FormEntryActivity.GEOTRACE_RESULTS, final_return_string); setResult(RESULT_OK, i); finish(); } private OnMarkerClickListener nullmarkerlistner = new Marker.OnMarkerClickListener() { @Override public boolean onMarkerClick(Marker arg0, MapView arg1) { return false; } }; private void createPolygon() { map_markers.add(map_markers.get(0)); pathOverlay.addPoint(map_markers.get(0).getPosition()); mapView.invalidate(); } private void update_polygon() { pathOverlay.clearPath(); for (int i = 0; i < map_markers.size(); i++) { pathOverlay.addPoint(map_markers.get(i).getPosition()); } mapView.invalidate(); } private OnMarkerDragListener draglistner = new Marker.OnMarkerDragListener() { @Override public void onMarkerDragStart(Marker marker) { } @Override public void onMarkerDragEnd(Marker arg0) { update_polygon(); } @Override public void onMarkerDrag(Marker marker) { update_polygon(); } }; private void showClearDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(getString(R.string.geo_clear_warning)) .setPositiveButton(getString(R.string.clear), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { clearFeatures(); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }).show(); } private void clearFeatures() { map_markers.clear(); pathOverlay.clearPath(); mapView.getOverlays().clear(); mClearButton.setEnabled(false); overlayMyLocationLayers(); overlayMapLayerListner(); mapView.invalidate(); mPlayButton.setEnabled(true); mode_active = false; } private void zoomtoBounds() { mapView.getController().setZoom(4); mapView.invalidate(); Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { int minLat = Integer.MAX_VALUE; int maxLat = Integer.MIN_VALUE; int minLong = Integer.MAX_VALUE; int maxLong = Integer.MIN_VALUE; Integer size = map_markers.size(); for (int i = 0; i < size; i++) { GeoPoint temp_marker = map_markers.get(i).getPosition(); if (temp_marker.getLatitudeE6() < minLat) { minLat = temp_marker.getLatitudeE6(); } if (temp_marker.getLatitudeE6() > maxLat) { maxLat = temp_marker.getLatitudeE6(); } if (temp_marker.getLongitudeE6() < minLong) { minLong = temp_marker.getLongitudeE6(); } if (temp_marker.getLongitudeE6() > maxLong) { maxLong = temp_marker.getLongitudeE6(); } } BoundingBoxE6 boundingBox = new BoundingBoxE6(maxLat, maxLong, minLat, minLong); mapView.zoomToBoundingBox(boundingBox); mapView.invalidate(); } }, 100); mapView.invalidate(); } public void showZoomDialog() { if (zoomDialog == null) { AlertDialog.Builder p_builder = new AlertDialog.Builder(this); p_builder.setTitle(getString(R.string.zoom_to_where)); p_builder.setView(zoomDialogView) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }) .setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { dialog.cancel(); zoomDialog.dismiss(); } }); zoomDialog = p_builder.create(); } if (mMyLocationOverlay.getMyLocation() != null) { zoomLocationButton.setEnabled(true); zoomLocationButton.setBackgroundColor(Color.parseColor("#50cccccc")); zoomLocationButton.setTextColor(Color.parseColor("#ff333333")); } else { zoomLocationButton.setEnabled(false); zoomLocationButton.setBackgroundColor(Color.parseColor("#50e2e2e2")); zoomLocationButton.setTextColor(Color.parseColor("#FF979797")); } //If feature enable zoom to button else disable if (map_markers.size() != 0) { zoomPointButton.setEnabled(true); zoomPointButton.setBackgroundColor(Color.parseColor("#50cccccc")); zoomPointButton.setTextColor(Color.parseColor("#ff333333")); } else { zoomPointButton.setEnabled(false); zoomPointButton.setBackgroundColor(Color.parseColor("#50e2e2e2")); zoomPointButton.setTextColor(Color.parseColor("#FF979797")); } zoomDialog.show(); } @Override public void onLocationChanged(Location location) { if (mode_active) { mapView.getController().setCenter(mMyLocationOverlay.getMyLocation()); } } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } }
apache-2.0
geekboxzone/mmallow_external_jetty
src/java/org/eclipse/jetty/server/AbstractConnector.java
37910
// // ======================================================================== // Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // // You may elect to redistribute this code under either of these licenses. // ======================================================================== // package org.eclipse.jetty.server; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.util.concurrent.atomic.AtomicLong; import javax.servlet.ServletRequest; import org.eclipse.jetty.http.HttpBuffers; import org.eclipse.jetty.http.HttpBuffersImpl; import org.eclipse.jetty.http.HttpFields; import org.eclipse.jetty.http.HttpHeaders; import org.eclipse.jetty.http.HttpSchemes; import org.eclipse.jetty.io.Buffers; import org.eclipse.jetty.io.Buffers.Type; import org.eclipse.jetty.io.Connection; import org.eclipse.jetty.io.EndPoint; import org.eclipse.jetty.io.EofException; import org.eclipse.jetty.util.component.AggregateLifeCycle; import org.eclipse.jetty.util.component.Dumpable; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.statistic.CounterStatistic; import org.eclipse.jetty.util.statistic.SampleStatistic; import org.eclipse.jetty.util.thread.ThreadPool; /** * Abstract Connector implementation. This abstract implementation of the Connector interface provides: * <ul> * <li>AbstractLifeCycle implementation</li> * <li>Implementations for connector getters and setters</li> * <li>Buffer management</li> * <li>Socket configuration</li> * <li>Base acceptor thread</li> * <li>Optional reverse proxy headers checking</li> * </ul> */ public abstract class AbstractConnector extends AggregateLifeCycle implements HttpBuffers, Connector, Dumpable { private static final Logger LOG = Log.getLogger(AbstractConnector.class); private String _name; private Server _server; private ThreadPool _threadPool; private String _host; private int _port = 0; private String _integralScheme = HttpSchemes.HTTPS; private int _integralPort = 0; private String _confidentialScheme = HttpSchemes.HTTPS; private int _confidentialPort = 0; private int _acceptQueueSize = 0; private int _acceptors = 1; private int _acceptorPriorityOffset = 0; private boolean _useDNS; private boolean _forwarded; private String _hostHeader; private String _forwardedHostHeader = HttpHeaders.X_FORWARDED_HOST; private String _forwardedServerHeader = HttpHeaders.X_FORWARDED_SERVER; private String _forwardedForHeader = HttpHeaders.X_FORWARDED_FOR; private String _forwardedProtoHeader = HttpHeaders.X_FORWARDED_PROTO; private String _forwardedCipherSuiteHeader; private String _forwardedSslSessionIdHeader; private boolean _reuseAddress = true; protected int _maxIdleTime = 200000; protected int _lowResourceMaxIdleTime = -1; protected int _soLingerTime = -1; private transient Thread[] _acceptorThreads; private final AtomicLong _statsStartedAt = new AtomicLong(-1L); /** connections to server */ private final CounterStatistic _connectionStats = new CounterStatistic(); /** requests per connection */ private final SampleStatistic _requestStats = new SampleStatistic(); /** duration of a connection */ private final SampleStatistic _connectionDurationStats = new SampleStatistic(); protected final HttpBuffersImpl _buffers = new HttpBuffersImpl(); /* ------------------------------------------------------------ */ /** */ public AbstractConnector() { addBean(_buffers); } /* ------------------------------------------------------------ */ /* */ public Server getServer() { return _server; } /* ------------------------------------------------------------ */ public void setServer(Server server) { _server = server; } /* ------------------------------------------------------------ */ public ThreadPool getThreadPool() { return _threadPool; } /* ------------------------------------------------------------ */ /** Set the ThreadPool. * The threadpool passed is added via {@link #addBean(Object)} so that * it's lifecycle may be managed as a {@link AggregateLifeCycle}. * @param pool the threadPool to set */ public void setThreadPool(ThreadPool pool) { removeBean(_threadPool); _threadPool = pool; addBean(_threadPool); } /* ------------------------------------------------------------ */ /** */ public void setHost(String host) { _host = host; } /* ------------------------------------------------------------ */ /* */ public String getHost() { return _host; } /* ------------------------------------------------------------ */ public void setPort(int port) { _port = port; } /* ------------------------------------------------------------ */ public int getPort() { return _port; } /* ------------------------------------------------------------ */ /** * @return Returns the maxIdleTime. */ public int getMaxIdleTime() { return _maxIdleTime; } /* ------------------------------------------------------------ */ /** * Set the maximum Idle time for a connection, which roughly translates to the {@link Socket#setSoTimeout(int)} call, although with NIO implementations * other mechanisms may be used to implement the timeout. The max idle time is applied: * <ul> * <li>When waiting for a new request to be received on a connection</li> * <li>When reading the headers and content of a request</li> * <li>When writing the headers and content of a response</li> * </ul> * Jetty interprets this value as the maximum time between some progress being made on the connection. So if a single byte is read or written, then the * timeout (if implemented by jetty) is reset. However, in many instances, the reading/writing is delegated to the JVM, and the semantic is more strictly * enforced as the maximum time a single read/write operation can take. Note, that as Jetty supports writes of memory mapped file buffers, then a write may * take many 10s of seconds for large content written to a slow device. * <p> * Previously, Jetty supported separate idle timeouts and IO operation timeouts, however the expense of changing the value of soTimeout was significant, so * these timeouts were merged. With the advent of NIO, it may be possible to again differentiate these values (if there is demand). * * @param maxIdleTime * The maxIdleTime to set. */ public void setMaxIdleTime(int maxIdleTime) { _maxIdleTime = maxIdleTime; } /* ------------------------------------------------------------ */ /** * @return Returns the maxIdleTime when resources are low. */ public int getLowResourcesMaxIdleTime() { return _lowResourceMaxIdleTime; } /* ------------------------------------------------------------ */ /** * @param maxIdleTime * The maxIdleTime to set when resources are low. */ public void setLowResourcesMaxIdleTime(int maxIdleTime) { _lowResourceMaxIdleTime = maxIdleTime; } /* ------------------------------------------------------------ */ /** * @return Returns the maxIdleTime when resources are low. * @deprecated */ @Deprecated public final int getLowResourceMaxIdleTime() { return getLowResourcesMaxIdleTime(); } /* ------------------------------------------------------------ */ /** * @param maxIdleTime * The maxIdleTime to set when resources are low. * @deprecated */ @Deprecated public final void setLowResourceMaxIdleTime(int maxIdleTime) { setLowResourcesMaxIdleTime(maxIdleTime); } /* ------------------------------------------------------------ */ /** * @return Returns the soLingerTime. */ public int getSoLingerTime() { return _soLingerTime; } /* ------------------------------------------------------------ */ /** * @return Returns the acceptQueueSize. */ public int getAcceptQueueSize() { return _acceptQueueSize; } /* ------------------------------------------------------------ */ /** * @param acceptQueueSize * The acceptQueueSize to set. */ public void setAcceptQueueSize(int acceptQueueSize) { _acceptQueueSize = acceptQueueSize; } /* ------------------------------------------------------------ */ /** * @return Returns the number of acceptor threads. */ public int getAcceptors() { return _acceptors; } /* ------------------------------------------------------------ */ /** * @param acceptors * The number of acceptor threads to set. */ public void setAcceptors(int acceptors) { if (acceptors > 2 * Runtime.getRuntime().availableProcessors()) LOG.warn("Acceptors should be <=2*availableProcessors: " + this); _acceptors = acceptors; } /* ------------------------------------------------------------ */ /** * @param soLingerTime * The soLingerTime to set or -1 to disable. */ public void setSoLingerTime(int soLingerTime) { _soLingerTime = soLingerTime; } /* ------------------------------------------------------------ */ @Override protected void doStart() throws Exception { if (_server == null) throw new IllegalStateException("No server"); // open listener port open(); if (_threadPool == null) { _threadPool = _server.getThreadPool(); addBean(_threadPool,false); } super.doStart(); // Start selector thread synchronized (this) { _acceptorThreads = new Thread[getAcceptors()]; for (int i = 0; i < _acceptorThreads.length; i++) if (!_threadPool.dispatch(new Acceptor(i))) throw new IllegalStateException("!accepting"); if (_threadPool.isLowOnThreads()) LOG.warn("insufficient threads configured for {}",this); } LOG.info("Started {}",this); } /* ------------------------------------------------------------ */ @Override protected void doStop() throws Exception { try { close(); } catch (IOException e) { LOG.warn(e); } super.doStop(); Thread[] acceptors; synchronized (this) { acceptors = _acceptorThreads; _acceptorThreads = null; } if (acceptors != null) { for (Thread thread : acceptors) { if (thread != null) thread.interrupt(); } } } /* ------------------------------------------------------------ */ public void join() throws InterruptedException { Thread[] threads; synchronized(this) { threads=_acceptorThreads; } if (threads != null) for (Thread thread : threads) if (thread != null) thread.join(); } /* ------------------------------------------------------------ */ protected void configure(Socket socket) throws IOException { try { socket.setTcpNoDelay(true); if (_soLingerTime >= 0) socket.setSoLinger(true,_soLingerTime / 1000); else socket.setSoLinger(false,0); } catch (Exception e) { LOG.ignore(e); } } /* ------------------------------------------------------------ */ public void customize(EndPoint endpoint, Request request) throws IOException { if (isForwarded()) checkForwardedHeaders(endpoint,request); } /* ------------------------------------------------------------ */ protected void checkForwardedHeaders(EndPoint endpoint, Request request) throws IOException { HttpFields httpFields = request.getConnection().getRequestFields(); // Do SSL first if (getForwardedCipherSuiteHeader()!=null) { String cipher_suite=httpFields.getStringField(getForwardedCipherSuiteHeader()); if (cipher_suite!=null) request.setAttribute("javax.servlet.request.cipher_suite",cipher_suite); } if (getForwardedSslSessionIdHeader()!=null) { String ssl_session_id=httpFields.getStringField(getForwardedSslSessionIdHeader()); if(ssl_session_id!=null) { request.setAttribute("javax.servlet.request.ssl_session_id", ssl_session_id); request.setScheme(HttpSchemes.HTTPS); } } // Retrieving headers from the request String forwardedHost = getLeftMostFieldValue(httpFields,getForwardedHostHeader()); String forwardedServer = getLeftMostFieldValue(httpFields,getForwardedServerHeader()); String forwardedFor = getLeftMostFieldValue(httpFields,getForwardedForHeader()); String forwardedProto = getLeftMostFieldValue(httpFields,getForwardedProtoHeader()); if (_hostHeader != null) { // Update host header httpFields.put(HttpHeaders.HOST_BUFFER,_hostHeader); request.setServerName(null); request.setServerPort(-1); request.getServerName(); } else if (forwardedHost != null) { // Update host header httpFields.put(HttpHeaders.HOST_BUFFER,forwardedHost); request.setServerName(null); request.setServerPort(-1); request.getServerName(); } else if (forwardedServer != null) { // Use provided server name request.setServerName(forwardedServer); } if (forwardedFor != null) { request.setRemoteAddr(forwardedFor); InetAddress inetAddress = null; if (_useDNS) { try { inetAddress = InetAddress.getByName(forwardedFor); } catch (UnknownHostException e) { LOG.ignore(e); } } request.setRemoteHost(inetAddress == null?forwardedFor:inetAddress.getHostName()); } if (forwardedProto != null) { request.setScheme(forwardedProto); } } /* ------------------------------------------------------------ */ protected String getLeftMostFieldValue(HttpFields fields, String header) { if (header == null) return null; String headerValue = fields.getStringField(header); if (headerValue == null) return null; int commaIndex = headerValue.indexOf(','); if (commaIndex == -1) { // Single value return headerValue; } // The left-most value is the farthest downstream client return headerValue.substring(0,commaIndex); } /* ------------------------------------------------------------ */ public void persist(EndPoint endpoint) throws IOException { } /* ------------------------------------------------------------ */ /* * @see org.eclipse.jetty.server.Connector#getConfidentialPort() */ public int getConfidentialPort() { return _confidentialPort; } /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ /* * @see org.eclipse.jetty.server.Connector#getConfidentialScheme() */ public String getConfidentialScheme() { return _confidentialScheme; } /* ------------------------------------------------------------ */ /* * @see org.eclipse.jetty.server.Connector#isConfidential(org.eclipse.jetty.server .Request) */ public boolean isIntegral(Request request) { return false; } /* ------------------------------------------------------------ */ /* * @see org.eclipse.jetty.server.Connector#getConfidentialPort() */ public int getIntegralPort() { return _integralPort; } /* ------------------------------------------------------------ */ /* * @see org.eclipse.jetty.server.Connector#getIntegralScheme() */ public String getIntegralScheme() { return _integralScheme; } /* ------------------------------------------------------------ */ /* * @see org.eclipse.jetty.server.Connector#isConfidential(org.eclipse.jetty.server.Request) */ public boolean isConfidential(Request request) { return _forwarded && request.getScheme().equalsIgnoreCase(HttpSchemes.HTTPS); } /* ------------------------------------------------------------ */ /** * @param confidentialPort * The confidentialPort to set. */ public void setConfidentialPort(int confidentialPort) { _confidentialPort = confidentialPort; } /* ------------------------------------------------------------ */ /** * @param confidentialScheme * The confidentialScheme to set. */ public void setConfidentialScheme(String confidentialScheme) { _confidentialScheme = confidentialScheme; } /* ------------------------------------------------------------ */ /** * @param integralPort * The integralPort to set. */ public void setIntegralPort(int integralPort) { _integralPort = integralPort; } /* ------------------------------------------------------------ */ /** * @param integralScheme * The integralScheme to set. */ public void setIntegralScheme(String integralScheme) { _integralScheme = integralScheme; } /* ------------------------------------------------------------ */ protected abstract void accept(int acceptorID) throws IOException, InterruptedException; /* ------------------------------------------------------------ */ public void stopAccept(int acceptorID) throws Exception { } /* ------------------------------------------------------------ */ public boolean getResolveNames() { return _useDNS; } /* ------------------------------------------------------------ */ public void setResolveNames(boolean resolve) { _useDNS = resolve; } /* ------------------------------------------------------------ */ /** * Is reverse proxy handling on? * * @return true if this connector is checking the x-forwarded-for/host/server headers */ public boolean isForwarded() { return _forwarded; } /* ------------------------------------------------------------ */ /** * Set reverse proxy handling. If set to true, then the X-Forwarded headers (or the headers set in their place) are looked for to set the request protocol, * host, server and client ip. * * @param check * true if this connector is checking the x-forwarded-for/host/server headers * @see #setForwardedForHeader(String) * @see #setForwardedHostHeader(String) * @see #setForwardedProtoHeader(String) * @see #setForwardedServerHeader(String) */ public void setForwarded(boolean check) { if (check) LOG.debug("{} is forwarded",this); _forwarded = check; } /* ------------------------------------------------------------ */ public String getHostHeader() { return _hostHeader; } /* ------------------------------------------------------------ */ /** * Set a forced valued for the host header to control what is returned by {@link ServletRequest#getServerName()} and {@link ServletRequest#getServerPort()}. * This value is only used if {@link #isForwarded()} is true. * * @param hostHeader * The value of the host header to force. */ public void setHostHeader(String hostHeader) { _hostHeader = hostHeader; } /* ------------------------------------------------------------ */ /* * * @see #setForwarded(boolean) */ public String getForwardedHostHeader() { return _forwardedHostHeader; } /* ------------------------------------------------------------ */ /** * @param forwardedHostHeader * The header name for forwarded hosts (default x-forwarded-host) * @see #setForwarded(boolean) */ public void setForwardedHostHeader(String forwardedHostHeader) { _forwardedHostHeader = forwardedHostHeader; } /* ------------------------------------------------------------ */ /** * @return the header name for forwarded server. * @see #setForwarded(boolean) */ public String getForwardedServerHeader() { return _forwardedServerHeader; } /* ------------------------------------------------------------ */ /** * @param forwardedServerHeader * The header name for forwarded server (default x-forwarded-server) * @see #setForwarded(boolean) */ public void setForwardedServerHeader(String forwardedServerHeader) { _forwardedServerHeader = forwardedServerHeader; } /* ------------------------------------------------------------ */ /** * @see #setForwarded(boolean) */ public String getForwardedForHeader() { return _forwardedForHeader; } /* ------------------------------------------------------------ */ /** * @param forwardedRemoteAddressHeader * The header name for forwarded for (default x-forwarded-for) * @see #setForwarded(boolean) */ public void setForwardedForHeader(String forwardedRemoteAddressHeader) { _forwardedForHeader = forwardedRemoteAddressHeader; } /* ------------------------------------------------------------ */ /** * Get the forwardedProtoHeader. * * @return the forwardedProtoHeader (default X-Forwarded-For) * @see #setForwarded(boolean) */ public String getForwardedProtoHeader() { return _forwardedProtoHeader; } /* ------------------------------------------------------------ */ /** * Set the forwardedProtoHeader. * * @param forwardedProtoHeader * the forwardedProtoHeader to set (default X-Forwarded-For) * @see #setForwarded(boolean) */ public void setForwardedProtoHeader(String forwardedProtoHeader) { _forwardedProtoHeader = forwardedProtoHeader; } /* ------------------------------------------------------------ */ /** * @return The header name holding a forwarded cipher suite (default null) */ public String getForwardedCipherSuiteHeader() { return _forwardedCipherSuiteHeader; } /* ------------------------------------------------------------ */ /** * @param forwardedCipherSuite * The header name holding a forwarded cipher suite (default null) */ public void setForwardedCipherSuiteHeader(String forwardedCipherSuite) { _forwardedCipherSuiteHeader = forwardedCipherSuite; } /* ------------------------------------------------------------ */ /** * @return The header name holding a forwarded SSL Session ID (default null) */ public String getForwardedSslSessionIdHeader() { return _forwardedSslSessionIdHeader; } /* ------------------------------------------------------------ */ /** * @param forwardedSslSessionId * The header name holding a forwarded SSL Session ID (default null) */ public void setForwardedSslSessionIdHeader(String forwardedSslSessionId) { _forwardedSslSessionIdHeader = forwardedSslSessionId; } public int getRequestBufferSize() { return _buffers.getRequestBufferSize(); } public void setRequestBufferSize(int requestBufferSize) { _buffers.setRequestBufferSize(requestBufferSize); } public int getRequestHeaderSize() { return _buffers.getRequestHeaderSize(); } public void setRequestHeaderSize(int requestHeaderSize) { _buffers.setRequestHeaderSize(requestHeaderSize); } public int getResponseBufferSize() { return _buffers.getResponseBufferSize(); } public void setResponseBufferSize(int responseBufferSize) { _buffers.setResponseBufferSize(responseBufferSize); } public int getResponseHeaderSize() { return _buffers.getResponseHeaderSize(); } public void setResponseHeaderSize(int responseHeaderSize) { _buffers.setResponseHeaderSize(responseHeaderSize); } public Type getRequestBufferType() { return _buffers.getRequestBufferType(); } public Type getRequestHeaderType() { return _buffers.getRequestHeaderType(); } public Type getResponseBufferType() { return _buffers.getResponseBufferType(); } public Type getResponseHeaderType() { return _buffers.getResponseHeaderType(); } public void setRequestBuffers(Buffers requestBuffers) { _buffers.setRequestBuffers(requestBuffers); } public void setResponseBuffers(Buffers responseBuffers) { _buffers.setResponseBuffers(responseBuffers); } public Buffers getRequestBuffers() { return _buffers.getRequestBuffers(); } public Buffers getResponseBuffers() { return _buffers.getResponseBuffers(); } public void setMaxBuffers(int maxBuffers) { _buffers.setMaxBuffers(maxBuffers); } public int getMaxBuffers() { return _buffers.getMaxBuffers(); } /* ------------------------------------------------------------ */ @Override public String toString() { return String.format("%s@%s:%d", getClass().getSimpleName(), getHost()==null?"0.0.0.0":getHost(), getLocalPort()<=0?getPort():getLocalPort()); } /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ private class Acceptor implements Runnable { int _acceptor = 0; Acceptor(int id) { _acceptor = id; } /* ------------------------------------------------------------ */ public void run() { Thread current = Thread.currentThread(); String name; synchronized (AbstractConnector.this) { if (_acceptorThreads == null) return; _acceptorThreads[_acceptor] = current; name = _acceptorThreads[_acceptor].getName(); current.setName(name + " Acceptor" + _acceptor + " " + AbstractConnector.this); } int old_priority = current.getPriority(); try { current.setPriority(old_priority - _acceptorPriorityOffset); while (isRunning() && getConnection() != null) { try { accept(_acceptor); } catch (EofException e) { LOG.ignore(e); } catch (IOException e) { LOG.ignore(e); } catch (InterruptedException x) { // Connector has been stopped LOG.ignore(x); } catch (Throwable e) { LOG.warn(e); } } } finally { current.setPriority(old_priority); current.setName(name); synchronized (AbstractConnector.this) { if (_acceptorThreads != null) _acceptorThreads[_acceptor] = null; } } } } /* ------------------------------------------------------------ */ public String getName() { if (_name == null) _name = (getHost() == null?"0.0.0.0":getHost()) + ":" + (getLocalPort() <= 0?getPort():getLocalPort()); return _name; } /* ------------------------------------------------------------ */ public void setName(String name) { _name = name; } /* ------------------------------------------------------------ */ /** * @return Get the number of requests handled by this connector since last call of statsReset(). If setStatsOn(false) then this is undefined. */ public int getRequests() { return (int)_requestStats.getTotal(); } /* ------------------------------------------------------------ */ /** * @return Returns the connectionsDurationTotal. */ public long getConnectionsDurationTotal() { return _connectionDurationStats.getTotal(); } /* ------------------------------------------------------------ */ /** * @return Number of connections accepted by the server since statsReset() called. Undefined if setStatsOn(false). */ public int getConnections() { return (int)_connectionStats.getTotal(); } /* ------------------------------------------------------------ */ /** * @return Number of connections currently open that were opened since statsReset() called. Undefined if setStatsOn(false). */ public int getConnectionsOpen() { return (int)_connectionStats.getCurrent(); } /* ------------------------------------------------------------ */ /** * @return Maximum number of connections opened simultaneously since statsReset() called. Undefined if setStatsOn(false). */ public int getConnectionsOpenMax() { return (int)_connectionStats.getMax(); } /* ------------------------------------------------------------ */ /** * @return Mean duration in milliseconds of open connections since statsReset() called. Undefined if setStatsOn(false). */ public double getConnectionsDurationMean() { return _connectionDurationStats.getMean(); } /* ------------------------------------------------------------ */ /** * @return Maximum duration in milliseconds of an open connection since statsReset() called. Undefined if setStatsOn(false). */ public long getConnectionsDurationMax() { return _connectionDurationStats.getMax(); } /* ------------------------------------------------------------ */ /** * @return Standard deviation of duration in milliseconds of open connections since statsReset() called. Undefined if setStatsOn(false). */ public double getConnectionsDurationStdDev() { return _connectionDurationStats.getStdDev(); } /* ------------------------------------------------------------ */ /** * @return Mean number of requests per connection since statsReset() called. Undefined if setStatsOn(false). */ public double getConnectionsRequestsMean() { return _requestStats.getMean(); } /* ------------------------------------------------------------ */ /** * @return Maximum number of requests per connection since statsReset() called. Undefined if setStatsOn(false). */ public int getConnectionsRequestsMax() { return (int)_requestStats.getMax(); } /* ------------------------------------------------------------ */ /** * @return Standard deviation of number of requests per connection since statsReset() called. Undefined if setStatsOn(false). */ public double getConnectionsRequestsStdDev() { return _requestStats.getStdDev(); } /* ------------------------------------------------------------ */ /** * Reset statistics. */ public void statsReset() { updateNotEqual(_statsStartedAt,-1,System.currentTimeMillis()); _requestStats.reset(); _connectionStats.reset(); _connectionDurationStats.reset(); } /* ------------------------------------------------------------ */ public void setStatsOn(boolean on) { if (on && _statsStartedAt.get() != -1) return; if (LOG.isDebugEnabled()) LOG.debug("Statistics on = " + on + " for " + this); statsReset(); _statsStartedAt.set(on?System.currentTimeMillis():-1); } /* ------------------------------------------------------------ */ /** * @return True if statistics collection is turned on. */ public boolean getStatsOn() { return _statsStartedAt.get() != -1; } /* ------------------------------------------------------------ */ /** * @return Timestamp stats were started at. */ public long getStatsOnMs() { long start = _statsStartedAt.get(); return (start != -1)?(System.currentTimeMillis() - start):0; } /* ------------------------------------------------------------ */ protected void connectionOpened(Connection connection) { if (_statsStartedAt.get() == -1) return; _connectionStats.increment(); } /* ------------------------------------------------------------ */ protected void connectionUpgraded(Connection oldConnection, Connection newConnection) { _requestStats.set((oldConnection instanceof AbstractHttpConnection)?((AbstractHttpConnection)oldConnection).getRequests():0); } /* ------------------------------------------------------------ */ protected void connectionClosed(Connection connection) { connection.onClose(); if (_statsStartedAt.get() == -1) return; long duration = System.currentTimeMillis() - connection.getTimeStamp(); int requests = (connection instanceof AbstractHttpConnection)?((AbstractHttpConnection)connection).getRequests():0; _requestStats.set(requests); _connectionStats.decrement(); _connectionDurationStats.set(duration); } /* ------------------------------------------------------------ */ /** * @return the acceptorPriority */ public int getAcceptorPriorityOffset() { return _acceptorPriorityOffset; } /* ------------------------------------------------------------ */ /** * Set the priority offset of the acceptor threads. The priority is adjusted by this amount (default 0) to either favour the acceptance of new threads and * newly active connections or to favour the handling of already dispatched connections. * * @param offset * the amount to alter the priority of the acceptor threads. */ public void setAcceptorPriorityOffset(int offset) { _acceptorPriorityOffset = offset; } /* ------------------------------------------------------------ */ /** * @return True if the the server socket will be opened in SO_REUSEADDR mode. */ public boolean getReuseAddress() { return _reuseAddress; } /* ------------------------------------------------------------ */ /** * @param reuseAddress * True if the the server socket will be opened in SO_REUSEADDR mode. */ public void setReuseAddress(boolean reuseAddress) { _reuseAddress = reuseAddress; } /* ------------------------------------------------------------ */ public boolean isLowResources() { if (_threadPool != null) return _threadPool.isLowOnThreads(); return _server.getThreadPool().isLowOnThreads(); } /* ------------------------------------------------------------ */ private void updateNotEqual(AtomicLong valueHolder, long compare, long value) { long oldValue = valueHolder.get(); while (compare != oldValue) { if (valueHolder.compareAndSet(oldValue,value)) break; oldValue = valueHolder.get(); } } }
apache-2.0
pdxrunner/geode
geode-dunit/src/main/java/hydra/MethExecutorResult.java
5304
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You 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. */ package hydra; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.PrintWriter; import java.io.Serializable; import java.io.StringWriter; /** * * The result of a MethExecutor execute method. * */ public class MethExecutorResult implements Serializable { /** * A "result" object that indicates that an exception occurred while invoking the method */ public static final Serializable EXCEPTION_OCCURRED = new Serializable() { public boolean equals(Object o) { // Allows instances to be compared across VMs return o != null && this.getClass().equals(o.getClass()); } public String toString() { return "EXCEPTION_OCCURRED"; } }; /** * A "exception" object that indicates that an exception could not be serialized. */ public static final Throwable NONSERIALIZABLE_EXCEPTION = new Throwable() { public boolean equals(Object o) { // Allows instances to be compared across VMs return o != null && this.getClass().equals(o.getClass()); } public String toString() { return "NONSERIALIZABLE_EXCEPTION"; } }; //////////////////// Instance Methods /////////////////////////// /** The result of execution (may be an exception or error type) */ private Object result; /** The exception that resulted from invoking the method */ private Throwable exception; /** Type of the exception (if applicable) */ private String exceptionClassName; /** Message of the exception (if applicable) */ private String exceptionMessage; /** Stack trace information (if applicable) */ private String stackTrace; public MethExecutorResult() { this.result = null; } public MethExecutorResult(Object result) { this.result = result; } /** * This constructor is invoked when invoking a method resulted in an exception being thrown. The * "result" is set to {@link #EXCEPTION_OCCURRED}. If the exception could not be serialized, * {@link #getException()} will return IOException with the exception stack as the message. */ public MethExecutorResult(Throwable thr) { this.result = EXCEPTION_OCCURRED; this.exceptionClassName = thr.getClass().getName(); this.exceptionMessage = thr.getMessage(); StringWriter sw = new StringWriter(); thr.printStackTrace(new PrintWriter(sw, true)); this.stackTrace = sw.toString(); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(thr); this.exception = thr; } catch (IOException ex) { sw = new StringWriter(); ex.printStackTrace(new PrintWriter(sw, true)); this.exception = new IOException(sw.toString()); } } public String toString() { StringBuffer s = new StringBuffer(); s.append(this.getResult()); s.append("\n"); if (this.getStackTrace() != null) { s.append(this.getStackTrace()); } return s.toString(); } /** * Returns the result of the method call. If an exception was thrown during the method call, * {@link #EXCEPTION_OCCURRED} is returned. * * @see #exceptionOccurred() */ public Object getResult() { return this.result; } /** * Returns the name of the exception class of the exception that was thrown while invoking a * method. If no exception was thrown, <code>null</code> is returned. */ public String getExceptionClassName() { return this.exceptionClassName; } /** * Returns the message of the exception that was thrown while invoking a method. If no exception * was thrown, <code>null</code> is returned. */ public String getExceptionMessage() { return this.exceptionMessage; } /** * Returns the stack trace of the exception that was thrown while invoking a method. If no * exception was thrown, <code>null</code> is returned. */ public String getStackTrace() { return this.stackTrace; } /** * Returns the exception that was thrown while invoking a method. If the exception could not be * serialized, then {@link #NONSERIALIZABLE_EXCEPTION} is returned. If no exception was thrown, * <code>null</code> is returned. */ public Throwable getException() { return this.exception; } /** * Returns whether or not an exception occurred while invoking the method */ public boolean exceptionOccurred() { return EXCEPTION_OCCURRED.equals(this.result); } }
apache-2.0
lingochamp/presto
presto-main/src/main/java/com/facebook/presto/connector/informationSchema/InformationSchemaMetadata.java
8741
/* * 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. */ package com.facebook.presto.connector.informationSchema; import com.facebook.presto.spi.ColumnHandle; import com.facebook.presto.spi.ColumnMetadata; import com.facebook.presto.spi.ConnectorSession; import com.facebook.presto.spi.ConnectorTableHandle; import com.facebook.presto.spi.ConnectorTableMetadata; import com.facebook.presto.spi.SchemaTableName; import com.facebook.presto.spi.SchemaTablePrefix; import com.facebook.presto.spi.connector.ConnectorMetadata; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import static com.facebook.presto.connector.informationSchema.InformationSchemaColumnHandle.toInformationSchemaColumnHandles; import static com.facebook.presto.metadata.MetadataUtil.SchemaMetadataBuilder.schemaMetadataBuilder; import static com.facebook.presto.metadata.MetadataUtil.TableMetadataBuilder.tableMetadataBuilder; import static com.facebook.presto.metadata.MetadataUtil.findColumnMetadata; import static com.facebook.presto.spi.type.BigintType.BIGINT; import static com.facebook.presto.spi.type.VarcharType.VARCHAR; import static com.facebook.presto.util.Types.checkType; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Predicates.compose; import static com.google.common.base.Predicates.equalTo; import static com.google.common.collect.Iterables.filter; import static java.util.Objects.requireNonNull; public class InformationSchemaMetadata implements ConnectorMetadata { public static final String INFORMATION_SCHEMA = "information_schema"; public static final SchemaTableName TABLE_COLUMNS = new SchemaTableName(INFORMATION_SCHEMA, "columns"); public static final SchemaTableName TABLE_TABLES = new SchemaTableName(INFORMATION_SCHEMA, "tables"); public static final SchemaTableName TABLE_VIEWS = new SchemaTableName(INFORMATION_SCHEMA, "views"); public static final SchemaTableName TABLE_SCHEMATA = new SchemaTableName(INFORMATION_SCHEMA, "schemata"); public static final SchemaTableName TABLE_INTERNAL_PARTITIONS = new SchemaTableName(INFORMATION_SCHEMA, "__internal_partitions__"); public static final Map<SchemaTableName, ConnectorTableMetadata> TABLES = schemaMetadataBuilder() .table(tableMetadataBuilder(TABLE_COLUMNS) .column("table_catalog", VARCHAR) .column("table_schema", VARCHAR) .column("table_name", VARCHAR) .column("column_name", VARCHAR) .column("ordinal_position", BIGINT) .column("column_default", VARCHAR) .column("is_nullable", VARCHAR) .column("data_type", VARCHAR) .column("is_partition_key", VARCHAR) .column("comment", VARCHAR) .build()) .table(tableMetadataBuilder(TABLE_TABLES) .column("table_catalog", VARCHAR) .column("table_schema", VARCHAR) .column("table_name", VARCHAR) .column("table_type", VARCHAR) .build()) .table(tableMetadataBuilder(TABLE_VIEWS) .column("table_catalog", VARCHAR) .column("table_schema", VARCHAR) .column("table_name", VARCHAR) .column("view_definition", VARCHAR) .build()) .table(tableMetadataBuilder(TABLE_SCHEMATA) .column("catalog_name", VARCHAR) .column("schema_name", VARCHAR) .build()) .table(tableMetadataBuilder(TABLE_INTERNAL_PARTITIONS) .column("table_catalog", VARCHAR) .column("table_schema", VARCHAR) .column("table_name", VARCHAR) .column("partition_number", BIGINT) .column("partition_key", VARCHAR) .column("partition_value", VARCHAR) .build()) .build(); private final String connectorId; private final String catalogName; public InformationSchemaMetadata(String connectorId, String catalogName) { this.connectorId = requireNonNull(connectorId, "connectorId is null"); this.catalogName = requireNonNull(catalogName, "catalogName is null"); } private InformationSchemaTableHandle checkTableHandle(ConnectorTableHandle tableHandle) { InformationSchemaTableHandle handle = checkType(tableHandle, InformationSchemaTableHandle.class, "tableHandle"); checkArgument(handle.getCatalogName().equals(catalogName), "invalid table handle: expected catalog %s but got %s", catalogName, handle.getCatalogName()); checkArgument(TABLES.containsKey(handle.getSchemaTableName()), "table %s does not exist", handle.getSchemaTableName()); return handle; } @Override public List<String> listSchemaNames(ConnectorSession session) { return ImmutableList.of(INFORMATION_SCHEMA); } @Override public ConnectorTableHandle getTableHandle(ConnectorSession connectorSession, SchemaTableName tableName) { if (!TABLES.containsKey(tableName)) { return null; } return new InformationSchemaTableHandle(connectorId, catalogName, tableName.getSchemaName(), tableName.getTableName()); } @Override public ConnectorTableMetadata getTableMetadata(ConnectorSession session, ConnectorTableHandle tableHandle) { InformationSchemaTableHandle informationSchemaTableHandle = checkTableHandle(tableHandle); return TABLES.get(informationSchemaTableHandle.getSchemaTableName()); } @Override public List<SchemaTableName> listTables(ConnectorSession session, String schemaNameOrNull) { if (schemaNameOrNull == null) { return ImmutableList.copyOf(TABLES.keySet()); } return ImmutableList.copyOf(filter(TABLES.keySet(), compose(equalTo(schemaNameOrNull), SchemaTableName::getSchemaName))); } @Override public ColumnMetadata getColumnMetadata(ConnectorSession session, ConnectorTableHandle tableHandle, ColumnHandle columnHandle) { InformationSchemaTableHandle informationSchemaTableHandle = checkTableHandle(tableHandle); ConnectorTableMetadata tableMetadata = TABLES.get(informationSchemaTableHandle.getSchemaTableName()); String columnName = checkType(columnHandle, InformationSchemaColumnHandle.class, "columnHandle").getColumnName(); ColumnMetadata columnMetadata = findColumnMetadata(tableMetadata, columnName); checkArgument(columnMetadata != null, "Column %s on table %s does not exist", columnName, tableMetadata.getTable()); return columnMetadata; } @Override public Map<String, ColumnHandle> getColumnHandles(ConnectorSession session, ConnectorTableHandle tableHandle) { InformationSchemaTableHandle informationSchemaTableHandle = checkTableHandle(tableHandle); ConnectorTableMetadata tableMetadata = TABLES.get(informationSchemaTableHandle.getSchemaTableName()); return toInformationSchemaColumnHandles(connectorId, tableMetadata); } @Override public Map<SchemaTableName, List<ColumnMetadata>> listTableColumns(ConnectorSession session, SchemaTablePrefix prefix) { requireNonNull(prefix, "prefix is null"); ImmutableMap.Builder<SchemaTableName, List<ColumnMetadata>> builder = ImmutableMap.builder(); for (Entry<SchemaTableName, ConnectorTableMetadata> entry : TABLES.entrySet()) { if (prefix.matches(entry.getKey())) { builder.put(entry.getKey(), entry.getValue().getColumns()); } } return builder.build(); } static List<ColumnMetadata> informationSchemaTableColumns(SchemaTableName tableName) { checkArgument(TABLES.containsKey(tableName), "table does not exist: %s", tableName); return TABLES.get(tableName).getColumns(); } }
apache-2.0