repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
taciano-perez/JamVM-PH | src/classpath/javax/swing/JWindow.java | 8145 | /* JWindow.java --
Copyright (C) 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package javax.swing;
import java.awt.AWTEvent;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.LayoutManager;
import java.awt.Window;
import java.awt.event.KeyEvent;
import javax.accessibility.Accessible;
import javax.accessibility.AccessibleContext;
/**
* Unlike JComponent derivatives, JWindow inherits from
* java.awt.Window. But also lets a look-and-feel component to its work.
*
* @author Ronald Veldema (rveldema@cs.vu.nl)
*/
public class JWindow extends Window implements Accessible, RootPaneContainer
{
/**
* Provides accessibility support for <code>JWindow</code>.
*/
protected class AccessibleJWindow extends Window.AccessibleAWTWindow
{
/**
* Creates a new instance of <code>AccessibleJWindow</code>.
*/
protected AccessibleJWindow()
{
super();
// Nothing to do here.
}
}
private static final long serialVersionUID = 5420698392125238833L;
protected JRootPane rootPane;
/**
* @specnote rootPaneCheckingEnabled is false to comply with J2SE 5.0
*/
protected boolean rootPaneCheckingEnabled = false;
protected AccessibleContext accessibleContext;
/**
* Creates a new <code>JWindow</code> that has a shared invisible owner frame
* as its parent.
*/
public JWindow()
{
super(SwingUtilities.getOwnerFrame(null));
windowInit();
}
/**
* Creates a new <code>JWindow</code> that uses the specified graphics
* environment. This can be used to open a window on a different screen for
* example.
*
* @param gc the graphics environment to use
*/
public JWindow(GraphicsConfiguration gc)
{
super(SwingUtilities.getOwnerFrame(null), gc);
windowInit();
}
/**
* Creates a new <code>JWindow</code> that has the specified
* <code>owner</code> frame. If <code>owner</code> is <code>null</code>, then
* an invisible shared owner frame is installed as owner frame.
*
* @param owner the owner frame of this window; if <code>null</code> a shared
* invisible owner frame is used
*/
public JWindow(Frame owner)
{
super(SwingUtilities.getOwnerFrame(owner));
windowInit();
}
/**
* Creates a new <code>JWindow</code> that has the specified
* <code>owner</code> window. If <code>owner</code> is <code>null</code>,
* then an invisible shared owner frame is installed as owner frame.
*
* @param owner the owner window of this window; if <code>null</code> a
* shared invisible owner frame is used
*/
public JWindow(Window owner)
{
super(SwingUtilities.getOwnerFrame(owner));
windowInit();
}
/**
* Creates a new <code>JWindow</code> for the given graphics configuration
* and that has the specified <code>owner</code> window. If
* <code>owner</code> is <code>null</code>, then an invisible shared owner
* frame is installed as owner frame.
*
* The <code>gc</code> parameter can be used to open the window on a
* different screen for example.
*
* @param owner the owner window of this window; if <code>null</code> a
* shared invisible owner frame is used
* @param gc the graphics configuration to use
*/
public JWindow(Window owner, GraphicsConfiguration gc)
{
super(SwingUtilities.getOwnerFrame(owner), gc);
windowInit();
}
protected void windowInit()
{
// We need to explicitly enable events here so that our processKeyEvent()
// and processWindowEvent() gets called.
enableEvents(AWTEvent.KEY_EVENT_MASK);
super.setLayout(new BorderLayout(1, 1));
getRootPane(); // will do set/create
// Now we're done init stage, adds and layouts go to content pane.
setRootPaneCheckingEnabled(true);
}
public Dimension getPreferredSize()
{
return super.getPreferredSize();
}
public void setLayout(LayoutManager manager)
{
// Check if we're in initialization stage. If so, call super.setLayout
// otherwise, valid calls go to the content pane.
if (isRootPaneCheckingEnabled())
getContentPane().setLayout(manager);
else
super.setLayout(manager);
}
public void setLayeredPane(JLayeredPane layeredPane)
{
getRootPane().setLayeredPane(layeredPane);
}
public JLayeredPane getLayeredPane()
{
return getRootPane().getLayeredPane();
}
public JRootPane getRootPane()
{
if (rootPane == null)
setRootPane(createRootPane());
return rootPane;
}
protected void setRootPane(JRootPane root)
{
if (rootPane != null)
remove(rootPane);
rootPane = root;
add(rootPane, BorderLayout.CENTER);
}
protected JRootPane createRootPane()
{
return new JRootPane();
}
public Container getContentPane()
{
return getRootPane().getContentPane();
}
public void setContentPane(Container contentPane)
{
getRootPane().setContentPane(contentPane);
}
public Component getGlassPane()
{
return getRootPane().getGlassPane();
}
public void setGlassPane(Component glassPane)
{
getRootPane().setGlassPane(glassPane);
}
protected void addImpl(Component comp, Object constraints, int index)
{
// If we're adding in the initialization stage use super.add.
// otherwise pass the add onto the content pane.
if (isRootPaneCheckingEnabled())
getContentPane().add(comp, constraints, index);
else
super.addImpl(comp, constraints, index);
}
public void remove(Component comp)
{
// If we're removing the root pane, use super.remove. Otherwise
// pass it on to the content pane instead.
if (comp == rootPane)
super.remove(rootPane);
else
getContentPane().remove(comp);
}
protected boolean isRootPaneCheckingEnabled()
{
return rootPaneCheckingEnabled;
}
protected void setRootPaneCheckingEnabled(boolean enabled)
{
rootPaneCheckingEnabled = enabled;
}
public void update(Graphics g)
{
paint(g);
}
protected void processKeyEvent(KeyEvent e)
{
super.processKeyEvent(e);
}
public AccessibleContext getAccessibleContext()
{
if (accessibleContext == null)
accessibleContext = new AccessibleJWindow();
return accessibleContext;
}
protected String paramString()
{
return "JWindow";
}
}
| gpl-2.0 |
Lekanich/intellij-community | java/idea-ui/src/com/intellij/projectImport/ProjectFormatPanel.java | 2323 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* 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.
*/
/*
* User: anna
* Date: 09-Feb-2009
*/
package com.intellij.projectImport;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.ide.util.projectWizard.WizardContext;
import com.intellij.openapi.components.StorageScheme;
import com.intellij.openapi.project.Project;
import javax.swing.*;
public class ProjectFormatPanel {
private static final String STORAGE_FORMAT_PROPERTY = "default.storage.format";
public static final String DIR_BASED = Project.DIRECTORY_STORE_FOLDER + " (directory based)";
private static final String FILE_BASED = ".ipr (file based)";
private JComboBox myStorageFormatCombo;
private JPanel myWholePanel;
public ProjectFormatPanel() {
myStorageFormatCombo.insertItemAt(DIR_BASED, 0);
myStorageFormatCombo.insertItemAt(FILE_BASED, 1);
myStorageFormatCombo.setSelectedItem(PropertiesComponent.getInstance().getOrInit(STORAGE_FORMAT_PROPERTY, DIR_BASED));
}
public JPanel getPanel() {
return myWholePanel;
}
public JComboBox getStorageFormatComboBox() {
return myStorageFormatCombo;
}
public void updateData(WizardContext context) {
StorageScheme format =
FILE_BASED.equals(myStorageFormatCombo.getSelectedItem()) ? StorageScheme.DEFAULT : StorageScheme.DIRECTORY_BASED;
context.setProjectStorageFormat(format);
setDefaultFormat(isDefault());
}
public static void setDefaultFormat(boolean aDefault) {
PropertiesComponent.getInstance().setValue(STORAGE_FORMAT_PROPERTY, aDefault ? FILE_BASED : DIR_BASED);
}
public void setVisible(boolean visible) {
myWholePanel.setVisible(visible);
}
public boolean isDefault() {
return FILE_BASED.equals(myStorageFormatCombo.getSelectedItem());
}
} | apache-2.0 |
Drifftr/devstudio-tooling-bps | plugins/org.eclipse.bpel.common.ui/src/org/eclipse/bpel/common/ui/assist/FieldAssistAdapter.java | 2503 | /*******************************************************************************
* Copyright (c) 2006 Oracle Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Oracle Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.bpel.common.ui.assist;
import org.eclipse.jface.fieldassist.IContentProposalProvider;
import org.eclipse.jface.fieldassist.IControlContentAdapter;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Control;
import org.eclipse.ui.fieldassist.ContentAssistCommandAdapter;
/**
* This is a field assist adapter which extends the core SWT content
* assist adapter and allows programmatic opening of the assist dialog
* as well as automatic width sizing.
*
* @author Michal Chmielewski (michal.chmielewski@oracle.com)
* @date Aug 9, 2006
*
*/
public class FieldAssistAdapter extends ContentAssistCommandAdapter {
/**
* @param control
* @param controlContentAdapter
* @param proposalProvider
* @param commandId
* @param autoActivationCharacters
*/
public FieldAssistAdapter(Control control, IControlContentAdapter controlContentAdapter, IContentProposalProvider proposalProvider, String commandId, char[] autoActivationCharacters) {
super(control, controlContentAdapter, proposalProvider, commandId,
autoActivationCharacters);
}
/**
* @param control
* @param controlContentAdapter
* @param proposalProvider
* @param commandId
* @param autoActivationCharacters
* @param installDecoration
*/
public FieldAssistAdapter(Control control, IControlContentAdapter controlContentAdapter, IContentProposalProvider proposalProvider, String commandId, char[] autoActivationCharacters, boolean installDecoration) {
super(control, controlContentAdapter, proposalProvider, commandId,
autoActivationCharacters, installDecoration);
}
public void openProposals () {
openProposalPopup();
getControl().setFocus();
}
@Override
protected void openProposalPopup () {
Point popupSize = getPopupSize();
popupSize.x = getProposalWidth();
super.openProposalPopup();
}
public int getProposalWidth () {
Point size = getControl().getSize();
return size.x + 20;
}
}
| apache-2.0 |
sdgdsffdsfff/nutz | test/org/nutz/dao/test/meta/SimplePOJO.java | 818 | package org.nutz.dao.test.meta;
import org.nutz.dao.entity.annotation.Column;
import org.nutz.dao.entity.annotation.Id;
import org.nutz.dao.entity.annotation.Readonly;
import org.nutz.dao.entity.annotation.Table;
@Table("t_simple_pojo")
public class SimplePOJO {
@Id
private long id;
@Column
@Readonly
private String name;
@Column
private String sex;
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| apache-2.0 |
jandppw/ppwcode-recovered-from-google-code | java/vernacular/semantics/trunk/src/test/java/org/ppwcode/vernacular/semantics_VI/bean/stubs/StubRousseauBeanB.java | 995 | /*<license>
Copyright 2004 - $Date$ by PeopleWare n.v..
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.
</license>*/
package org.ppwcode.vernacular.semantics_VI.bean.stubs;
public class StubRousseauBeanB extends StubRousseauBean {
private StubRousseauBeanA $property8;
public final StubRousseauBeanA getProperty8() {
return $property8;
}
public final void setProperty8(StubRousseauBeanA property8) {
$property8 = property8;
}
@Override
public int nrOfProperties() {
return 6;
}
}
| apache-2.0 |
0xkasun/zaproxy | src/org/parosproxy/paros/extension/manualrequest/ExtensionManualRequestEditor.java | 6249 | /*
*
* Paros and its related class files.
*
* Paros is an HTTP/HTTPS proxy for assessing web application security.
* Copyright (C) 2003-2004 Chinotec Technologies Company
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the Clarified Artistic License
* as published by the Free Software Foundation.
*
* 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
* Clarified Artistic License for more details.
*
* You should have received a copy of the Clarified Artistic License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// ZAP: 2011/08/04 Changed for cleanup
// ZAP: 2011/11/20 Set order
// ZAP: 2012/03/15 Changed to reset the message of the ManualRequestEditorDialog
// when a new session is created. Added the key configuration to the
// ManualRequestEditorDialog.
// ZAP: 2012/03/17 Issue 282 Added getAuthor()
// ZAP: 2012/04/25 Added @Override annotation to all appropriate methods.
// ZAP: 2012/07/02 ManualRequestEditorDialog changed to receive Message instead
// of HttpMessage. Changed logger to static.
// ZAP: 2012/07/29 Issue 43: added sessionScopeChanged event
// ZAP: 2012/08/01 Issue 332: added support for Modes
// ZAP: 2012/11/21 Heavily refactored extension to support non-HTTP messages.
// ZAP: 2013/01/25 Added method removeManualSendEditor().
// ZAP: 2013/02/06 Issue 499: NullPointerException while uninstalling an add-on
// with a manual request editor
// ZAP: 2014/03/23 Issue 1094: Change ExtensionManualRequestEditor to only add view components if in GUI mode
// ZAP: 2014/08/14 Issue 1292: NullPointerException while attempting to remove an unregistered ManualRequestEditorDialog
// ZAP: 2014/12/12 Issue 1449: Added help button
// ZAP: 2015/03/16 Issue 1525: Further database independence changes
package org.parosproxy.paros.extension.manualrequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.control.Control;
import org.parosproxy.paros.control.Control.Mode;
import org.parosproxy.paros.extension.ExtensionAdaptor;
import org.parosproxy.paros.extension.ExtensionHook;
import org.parosproxy.paros.extension.ExtensionLoader;
import org.parosproxy.paros.extension.SessionChangedListener;
import org.parosproxy.paros.extension.ViewDelegate;
import org.parosproxy.paros.extension.manualrequest.http.impl.ManualHttpRequestEditorDialog;
import org.parosproxy.paros.model.Session;
import org.zaproxy.zap.extension.httppanel.Message;
public class ExtensionManualRequestEditor extends ExtensionAdaptor implements SessionChangedListener {
private Map<Class<? extends Message>, ManualRequestEditorDialog> dialogues = new HashMap<>();
/**
* Name of this extension.
*/
public static final String NAME = "ExtensionManualRequest";
public ExtensionManualRequestEditor() {
super();
initialize();
}
public ExtensionManualRequestEditor(String name) {
super(name);
}
private void initialize() {
this.setName(NAME);
this.setOrder(36);
}
@Override
public void initView(ViewDelegate view) {
super.initView(view);
// add default manual request editor
ManualRequestEditorDialog httpSendEditorDialog = new ManualHttpRequestEditorDialog(true, "manual", "ui.dialogs.manreq");
httpSendEditorDialog.setTitle(Constant.messages.getString("manReq.dialog.title"));
addManualSendEditor(httpSendEditorDialog);
}
/**
* Should be called before extension is initialized via its
* {@link #hook(ExtensionHook)} method.
*
* @param dialogue
*/
public void addManualSendEditor(ManualRequestEditorDialog dialogue) {
dialogues.put(dialogue.getMessageType(), dialogue);
}
public void removeManualSendEditor(Class<? extends Message> messageType) {
// remove from list
ManualRequestEditorDialog dialogue = dialogues.remove(messageType);
if (dialogue != null) {
// remove from GUI
dialogue.clear();
dialogue.dispose();
if (getView() != null) {
// unload menu items
ExtensionLoader extLoader = Control.getSingleton().getExtensionLoader();
extLoader.removeToolsMenuItem(dialogue.getMenuItem());
}
}
}
/**
* Get special manual send editor to add listeners, etc.
*
* @param type
* @return
*/
public ManualRequestEditorDialog getManualSendEditor(Class<? extends Message> type) {
return dialogues.get(type);
}
@Override
public void hook(ExtensionHook extensionHook) {
super.hook(extensionHook);
if (getView() != null) {
for (Entry<Class<? extends Message>, ManualRequestEditorDialog> dialogue : dialogues.entrySet()) {
extensionHook.getHookMenu().addToolsMenuItem(dialogue.getValue().getMenuItem());
}
extensionHook.addSessionListener(this);
}
}
@Override
public String getAuthor() {
return Constant.PAROS_TEAM;
}
@Override
public void sessionChanged(Session session) {
for (Entry<Class<? extends Message>, ManualRequestEditorDialog> dialogue : dialogues.entrySet()) {
dialogue.getValue().clear();
dialogue.getValue().setDefaultMessage();
}
}
@Override
public void sessionAboutToChange(Session session) {
}
@Override
public void sessionScopeChanged(Session session) {
}
@Override
public void sessionModeChanged(Mode mode) {
Boolean isEnabled = null;
switch (mode) {
case safe:
isEnabled = false;
break;
case protect:
case standard:
case attack:
isEnabled = true;
break;
}
if (isEnabled != null) {
for (Entry<Class<? extends Message>, ManualRequestEditorDialog> dialog : dialogues.entrySet()) {
dialog.getValue().setEnabled(isEnabled);
}
}
}
/**
* No database tables used, so all supported
*/
@Override
public boolean supportsDb(String type) {
return true;
}
} | apache-2.0 |
kleopatra999/solutions-mobile-backend-starter-java | src/com/google/cloud/backend/spi/SubscriptionUtility.java | 5854 | /*
* Copyright (c) 2013 Google 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.google.cloud.backend.spi;
import com.google.appengine.api.prospectivesearch.ProspectiveSearchService;
import com.google.appengine.api.prospectivesearch.ProspectiveSearchServiceFactory;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.cloud.backend.config.StringUtility;
import com.google.gson.Gson;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
/**
* Utility class with helper functions to decode subscription information and handle
* Prospective Search API.
*/
public class SubscriptionUtility {
protected static final String IOS_DEVICE_PREFIX = "ios_";
protected static final String GCM_KEY_SUBID = "subId";
protected static final String REQUEST_TYPE_DEVICE_SUB = "deviceSubscriptionRequest";
protected static final String REQUEST_TYPE_PSI_SUB = "PSISubscriptionRequest";
/**
* A key word to indicate "query" type in Prospective Search API subscription id.
*/
public static final String GCM_TYPEID_QUERY = "query";
private static final ProspectiveSearchService prosSearch = ProspectiveSearchServiceFactory
.getProspectiveSearchService();
private static final Logger log = Logger.getLogger(SubscriptionUtility.class.getName());
/**
* An enumeration of supported mobile device type.
*/
public enum MobileType {
ANDROID,
IOS
}
/**
* Gets the mobile type based on the subscription id provided by client.
*
* Subscription id is in format of <device token>:GCM_TYPEID_QUERY:<topic>. Clients prefix
* device token with "ios_" if the mobile type is "iOS", while Android device
* token does not have any prefix.
*
* @param subId Subscription ID sent by client during query subscription
* @return Mobile type
*/
public static MobileType getMobileType(String subId) {
return (subId.startsWith(IOS_DEVICE_PREFIX)) ? MobileType.IOS :
MobileType.ANDROID;
}
/**
* Extracts device registration id from subscription id.
*
* @param subId Subscription id sent by client during query subscription
* @return Device registration id
*/
public static String extractRegId(String subId) {
if (StringUtility.isNullOrEmpty(subId)) {
throw new IllegalArgumentException("subId cannot be null or empty");
}
String[] tokens = subId.split(":");
return tokens[0].replaceFirst(IOS_DEVICE_PREFIX, "");
}
/**
* Extracts device registration id from subscription id.
*
* @param subId Subscription id sent by client during query subscription
* @return Device registration id as List
*/
public static List<String> extractRegIdAsList(String subId) {
return Arrays.asList(extractRegId(subId));
}
/**
* Constructs subscription id based on registration id and query id.
*
* @param regId Registration id provided by the client
* @param queryId Query id provided by the client
* @return
*/
public static String constructSubId(String regId, String queryId) {
if (StringUtility.isNullOrEmpty(regId) || StringUtility.isNullOrEmpty(queryId)) {
throw new IllegalArgumentException("regId and queryId cannot be null or empty");
}
// ProsSearch subId = <regId>:query:<clientSubId>
return regId + ":" + GCM_TYPEID_QUERY + ":" + queryId;
}
/**
* Clears Prospective Search API subscription and device subscription entity for listed devices.
*
* @param deviceIds A list of device ids for which subscriptions are to be removed
*/
public static void clearSubscriptionAndDeviceEntity(List<String> deviceIds) {
DeviceSubscription deviceSubscription = new DeviceSubscription();
for (String deviceId : deviceIds) {
Set<String> subIds = deviceSubscription.getSubscriptionIds(deviceId);
// Delete all subscriptions for the device from Prospective Search API
for (String subId : subIds) {
try {
prosSearch.unsubscribe(QueryOperations.PROS_SEARCH_DEFAULT_TOPIC, subId);
} catch (IllegalArgumentException e) {
log.warning("Unsubscribe " + subId + " from PSI encounters error, " + e.getMessage());
}
}
// Remove device from datastore
deviceSubscription.delete(deviceId);
}
}
/**
* Clears Prospective Search API subscription and removes device entity for all devices.
*/
public static void clearAllSubscriptionAndDeviceEntity() {
// Remove all device subscription and psi subscription
DeviceSubscription deviceSubscription = new DeviceSubscription();
deviceSubscription.enqueueDeleteDeviceSubscription();
}
/**
* Enqueues subscription ids in task queue for deletion.
*
* @param subIds Psi subscription ids to be deleted
*/
protected static void enqueueDeletePsiSubscription(String[] subIds) {
Queue deviceTokenCleanupQueue = QueueFactory.getQueue("subscription-removal");
deviceTokenCleanupQueue.add(TaskOptions.Builder.withMethod(TaskOptions.Method.POST)
.url("/admin/push/devicesubscription/delete")
.param("subIds", new Gson().toJson(subIds, String[].class))
.param("type", SubscriptionUtility.REQUEST_TYPE_PSI_SUB));
}
}
| apache-2.0 |
FauxFaux/jdk9-jdk | test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/ResourceManager.java | 2603 | /*
* Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.swingset3.demos;
import java.net.URL;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
/**
* @author Pavel Porvatov
*/
public class ResourceManager {
private static final Logger logger = Logger.getLogger(ResourceManager.class.getName());
private final Class<?> demoClass;
// Resource bundle for internationalized and accessible text
private ResourceBundle bundle = null;
public ResourceManager(Class<?> demoClass) {
this.demoClass = demoClass;
String bundleName = demoClass.getPackage().getName() + ".resources." + demoClass.getSimpleName();
try {
bundle = ResourceBundle.getBundle(bundleName);
} catch (MissingResourceException e) {
logger.log(Level.SEVERE, "Couldn't load bundle: " + bundleName);
}
}
public String getString(String key) {
return bundle != null ? bundle.getString(key) : key;
}
public char getMnemonic(String key) {
return (getString(key)).charAt(0);
}
public ImageIcon createImageIcon(String filename, String description) {
String path = "resources/images/" + filename;
URL imageURL = demoClass.getResource(path);
if (imageURL == null) {
logger.log(Level.SEVERE, "unable to access image file: " + path);
return null;
} else {
return new ImageIcon(imageURL, description);
}
}
}
| gpl-2.0 |
trfiladelfo/jd-gui | services/src/main/java/org/jd/gui/service/type/ClassFileTypeFactoryProvider.java | 13565 | /*
* Copyright (c) 2008-2015 Emmanuel Dupuy
* This program is made available under the terms of the GPLv3 License.
*/
package org.jd.gui.service.type;
import groovyjarjarasm.asm.ClassReader;
import groovyjarjarasm.asm.Opcodes;
import groovyjarjarasm.asm.tree.ClassNode;
import groovyjarjarasm.asm.tree.FieldNode;
import groovyjarjarasm.asm.tree.InnerClassNode;
import groovyjarjarasm.asm.tree.MethodNode;
import org.jd.gui.api.API;
import org.jd.gui.api.model.Container;
import org.jd.gui.api.model.Type;
import javax.swing.*;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.*;
public class ClassFileTypeFactoryProvider extends AbstractTypeFactoryProvider {
static {
// Early class loading
JavaType.class.getName();
}
// Create cache
protected Cache<URI, JavaType> cache = new Cache();
/**
* @return local + optional external selectors
*/
public String[] getSelectors() {
List<String> externalSelectors = getExternalSelectors();
if (externalSelectors == null) {
return new String[] { "*:file:*.class" };
} else {
int size = externalSelectors.size();
String[] selectors = new String[size+1];
externalSelectors.toArray(selectors);
selectors[size] = "*:file:*.class";
return selectors;
}
}
public Collection<Type> make(API api, Container.Entry entry) {
return Collections.singletonList(make(api, entry, null));
}
public Type make(API api, Container.Entry entry, String fragment) {
URI key = entry.getUri();
if (cache.containsKey(key)) {
return cache.get(key);
} else {
JavaType type;
try (InputStream is = entry.getInputStream()) {
ClassReader classReader = new ClassReader(is);
if ((fragment != null) && (fragment.length() > 0)) {
// Search type name in fragment. URI format : see jd.gui.api.feature.UriOpener
int index = fragment.indexOf('-');
if (index != -1) {
// Keep type name only
fragment = fragment.substring(0, index);
}
if (!classReader.getClassName().equals(fragment)) {
// Search entry for type name
String entryTypePath = classReader.getClassName() + ".class";
String fragmentTypePath = fragment + ".class";
while (true) {
if (entry.getPath().endsWith(entryTypePath)) {
// Entry path ends with the internal class name
String pathToFound = entry.getPath().substring(0, entry.getPath().length() - entryTypePath.length()) + fragmentTypePath;
Container.Entry entryFound = null;
for (Container.Entry e : entry.getParent().getChildren()) {
if (e.getPath().equals(pathToFound)) {
entryFound = e;
break;
}
}
if (entryFound == null)
return null;
entry = entryFound;
try (InputStream is2 = entry.getInputStream()) {
classReader = new ClassReader(is2);
} catch (IOException ignore) {
return null;
}
break;
}
// Truncated path ? Cut first package name and retry
int firstPackageSeparatorIndex = entryTypePath.indexOf('/');
if (firstPackageSeparatorIndex == -1) {
// Nothing to cut -> Stop
return null;
}
entryTypePath = entryTypePath.substring(firstPackageSeparatorIndex + 1);
fragmentTypePath = fragmentTypePath.substring(fragmentTypePath.indexOf('/') + 1);
}
}
}
type = new JavaType(entry, classReader, -1);
} catch (IOException ignore) {
type = null;
}
cache.put(key, type);
return type;
}
}
static class JavaType implements Type {
protected ClassNode classNode;
protected Container.Entry entry;
protected int access;
protected String name;
protected String superName;
protected String outerName;
protected String displayTypeName;
protected String displayInnerTypeName;
protected String displayPackageName;
protected List<Type> innerTypes = null;
protected List<Type.Field> fields = null;
protected List<Type.Method> methods = null;
@SuppressWarnings("unchecked")
protected JavaType(Container.Entry entry, ClassReader classReader, int outerAccess) {
this.classNode = new ClassNode();
this.entry = entry;
classReader.accept(classNode, ClassReader.SKIP_CODE|ClassReader.SKIP_DEBUG|ClassReader.SKIP_FRAMES);
this.access = (outerAccess == -1) ? classNode.access : outerAccess;
this.name = classNode.name;
this.superName = ((access & Opcodes.ACC_INTERFACE) != 0) && "java/lang/Object".equals(classNode.superName) ? null : classNode.superName;
this.outerName = null;
this.displayInnerTypeName = null;
int indexDollar = name.lastIndexOf('$');
if (indexDollar != -1) {
int indexSeparator = name.lastIndexOf('/');
if (indexDollar > indexSeparator) {
for (final InnerClassNode innerClassNode : (List<InnerClassNode>)classNode.innerClasses) {
if (name.equals(innerClassNode.name)) {
// Inner class path found
if (innerClassNode.outerName != null) {
this.outerName = innerClassNode.outerName;
this.displayInnerTypeName = this.name.substring(this.outerName.length() + 1);
}
}
}
}
}
int lastPackageSeparatorIndex = name.lastIndexOf('/');
if (lastPackageSeparatorIndex == -1) {
this.displayPackageName = "";
this.displayTypeName = (this.outerName == null) ? this.name : null;
} else {
this.displayPackageName = this.name.substring(0, lastPackageSeparatorIndex).replace('/', '.');
this.displayTypeName = (this.outerName == null) ? this.name.substring(lastPackageSeparatorIndex+1) : null;
}
}
public int getFlags() { return access; }
public String getName() { return name; }
public String getSuperName() { return superName; }
public String getOuterName() { return outerName; }
public String getDisplayPackageName() { return displayPackageName; }
public String getDisplayTypeName() {
if (displayTypeName == null) {
displayTypeName = getDisplayTypeName(outerName, displayPackageName.length()) + '.' + displayInnerTypeName;
}
return displayTypeName;
}
@SuppressWarnings("unchecked")
protected String getDisplayTypeName(String name, int packageLength) {
int indexDollar = name.lastIndexOf('$');
if (indexDollar > packageLength) {
Container.Entry outerEntry = getEntry(name);
if (outerEntry != null) {
try (InputStream is = outerEntry.getInputStream()) {
ClassReader classReader = new ClassReader(is);
ClassNode classNode = new ClassNode();
classReader.accept(classNode, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
for (final InnerClassNode innerClassNode : (List<InnerClassNode>)classNode.innerClasses) {
if (name.equals(innerClassNode.name)) {
// Inner class path found => Recursive call
return getDisplayTypeName(innerClassNode.outerName, packageLength) + '.' + innerClassNode.innerName;
}
}
} catch (IOException ignore) {
}
}
}
return packageLength > 0 ? name.substring(packageLength+1) : name;
}
public String getDisplayInnerTypeName() { return displayInnerTypeName; }
public Icon getIcon() { return getTypeIcon(access); }
@SuppressWarnings("unchecked")
public List<Type> getInnerTypes() {
if (innerTypes == null) {
innerTypes = new ArrayList<>(classNode.innerClasses.size());
for (final InnerClassNode innerClassNode : (List<InnerClassNode>)classNode.innerClasses) {
if (((innerClassNode.access & (Opcodes.ACC_SYNTHETIC|Opcodes.ACC_BRIDGE)) == 0) && this.name.equals(innerClassNode.outerName)) {
Container.Entry innerEntry = getEntry(innerClassNode.name);
if (innerEntry != null) {
try (InputStream is = innerEntry.getInputStream()) {
ClassReader classReader = new ClassReader(is);
innerTypes.add(new JavaType(innerEntry, classReader, innerClassNode.access));
} catch (IOException ignore) {
}
}
}
}
}
return innerTypes;
}
protected Container.Entry getEntry(String typeName) {
String pathToFound = typeName + ".class";
for (Container.Entry e : entry.getParent().getChildren()) {
if (e.getPath().equals(pathToFound)) {
return e;
}
}
return null;
}
@SuppressWarnings("unchecked")
public List<Type.Field> getFields() {
if (fields == null) {
fields = new ArrayList<>(classNode.fields.size());
for (final FieldNode fieldNode : (List<FieldNode>)classNode.fields) {
if ((fieldNode.access & (Opcodes.ACC_SYNTHETIC|Opcodes.ACC_ENUM)) == 0) {
fields.add(new Type.Field() {
public int getFlags() { return fieldNode.access; }
public String getName() { return fieldNode.name; }
public String getDescriptor() { return fieldNode.desc; }
public Icon getIcon() { return getFieldIcon(fieldNode.access); }
public String getDisplayName() {
StringBuffer sb = new StringBuffer();
sb.append(fieldNode.name).append(" : ");
writeSignature(sb, fieldNode.desc, fieldNode.desc.length(), 0, false);
return sb.toString();
}
});
}
}
}
return fields;
}
@SuppressWarnings("unchecked")
public List<Type.Method> getMethods() {
if (methods == null) {
methods = new ArrayList<>(classNode.methods.size());
for (final MethodNode methodNode : (List<MethodNode>)classNode.methods) {
if ((methodNode.access & (Opcodes.ACC_SYNTHETIC|Opcodes.ACC_ENUM|Opcodes.ACC_BRIDGE)) == 0) {
methods.add(new Type.Method() {
public int getFlags() { return methodNode.access; }
public String getName() { return methodNode.name; }
public String getDescriptor() { return methodNode.desc; }
public Icon getIcon() { return getMethodIcon(methodNode.access); }
public String getDisplayName() {
String constructorName = displayInnerTypeName;
boolean isInnerClass = (constructorName != null);
if (constructorName == null)
constructorName = getDisplayTypeName();
StringBuffer sb = new StringBuffer();
writeMethodSignature(sb, access, methodNode.access, isInnerClass, constructorName, methodNode.name, methodNode.desc);
return sb.toString();
}
});
}
}
}
return methods;
}
}
}
| gpl-3.0 |
sabre1041/camel | components/camel-netty4/src/main/java/org/apache/camel/component/netty4/NettyEndpoint.java | 6630 | /**
* 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.netty4;
import java.math.BigInteger;
import java.security.Principal;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import javax.security.cert.X509Certificate;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.ssl.SslHandler;
import org.apache.camel.AsyncEndpoint;
import org.apache.camel.Consumer;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.impl.DefaultEndpoint;
import org.apache.camel.impl.SynchronousDelegateProducer;
import org.apache.camel.spi.UriEndpoint;
import org.apache.camel.spi.UriParam;
import org.apache.camel.util.ObjectHelper;
/**
* Socket level networking using TCP or UDP with the Netty 4.x library.
*/
@UriEndpoint(scheme = "netty4", title = "Netty4", syntax = "netty4:protocol:host:port", consumerClass = NettyConsumer.class, label = "networking,tcp,udp")
public class NettyEndpoint extends DefaultEndpoint implements AsyncEndpoint {
@UriParam
private NettyConfiguration configuration;
@UriParam(label = "advanced", javaType = "org.apache.camel.component.netty4.NettyServerBootstrapConfiguration",
description = "To use a custom configured NettyServerBootstrapConfiguration for configuring this endpoint.")
private Object bootstrapConfiguration; // to include in component docs as NettyServerBootstrapConfiguration is a @UriParams class
public NettyEndpoint(String endpointUri, NettyComponent component, NettyConfiguration configuration) {
super(endpointUri, component);
this.configuration = configuration;
}
public Consumer createConsumer(Processor processor) throws Exception {
Consumer answer = new NettyConsumer(this, processor, configuration);
configureConsumer(answer);
return answer;
}
public Producer createProducer() throws Exception {
Producer answer = new NettyProducer(this, configuration);
if (isSynchronous()) {
return new SynchronousDelegateProducer(answer);
} else {
return answer;
}
}
public Exchange createExchange(ChannelHandlerContext ctx, Object message) throws Exception {
Exchange exchange = createExchange();
updateMessageHeader(exchange.getIn(), ctx);
NettyPayloadHelper.setIn(exchange, message);
return exchange;
}
public boolean isSingleton() {
return true;
}
@Override
public NettyComponent getComponent() {
return (NettyComponent) super.getComponent();
}
public NettyConfiguration getConfiguration() {
return configuration;
}
public void setConfiguration(NettyConfiguration configuration) {
this.configuration = configuration;
}
@Override
protected String createEndpointUri() {
ObjectHelper.notNull(configuration, "configuration");
return "netty4:" + getConfiguration().getProtocol() + "://" + getConfiguration().getHost() + ":" + getConfiguration().getPort();
}
protected SSLSession getSSLSession(ChannelHandlerContext ctx) {
final SslHandler sslHandler = ctx.pipeline().get(SslHandler.class);
SSLSession sslSession = null;
if (sslHandler != null) {
sslSession = sslHandler.engine().getSession();
}
return sslSession;
}
protected void updateMessageHeader(Message in, ChannelHandlerContext ctx) {
in.setHeader(NettyConstants.NETTY_CHANNEL_HANDLER_CONTEXT, ctx);
in.setHeader(NettyConstants.NETTY_REMOTE_ADDRESS, ctx.channel().remoteAddress());
in.setHeader(NettyConstants.NETTY_LOCAL_ADDRESS, ctx.channel().localAddress());
if (configuration.isSsl()) {
// setup the SslSession header
SSLSession sslSession = getSSLSession(ctx);
in.setHeader(NettyConstants.NETTY_SSL_SESSION, sslSession);
// enrich headers with details from the client certificate if option is enabled
if (configuration.isSslClientCertHeaders()) {
enrichWithClientCertInformation(sslSession, in);
}
}
}
/**
* Enriches the message with client certificate details such as subject name, serial number etc.
* <p/>
* If the certificate is unverified then the headers is not enriched.
*
* @param sslSession the SSL session
* @param message the message to enrich
*/
protected void enrichWithClientCertInformation(SSLSession sslSession, Message message) {
try {
X509Certificate[] certificates = sslSession.getPeerCertificateChain();
if (certificates != null && certificates.length > 0) {
X509Certificate cert = certificates[0];
Principal subject = cert.getSubjectDN();
if (subject != null) {
message.setHeader(NettyConstants.NETTY_SSL_CLIENT_CERT_SUBJECT_NAME, subject.getName());
}
Principal issuer = cert.getIssuerDN();
if (issuer != null) {
message.setHeader(NettyConstants.NETTY_SSL_CLIENT_CERT_ISSUER_NAME, issuer.getName());
}
BigInteger serial = cert.getSerialNumber();
if (serial != null) {
message.setHeader(NettyConstants.NETTY_SSL_CLIENT_CERT_SERIAL_NO, serial.toString());
}
message.setHeader(NettyConstants.NETTY_SSL_CLIENT_CERT_NOT_BEFORE, cert.getNotBefore());
message.setHeader(NettyConstants.NETTY_SSL_CLIENT_CERT_NOT_AFTER, cert.getNotAfter());
}
} catch (SSLPeerUnverifiedException e) {
// ignore
}
}
} | apache-2.0 |
profjrr/zaproxy | src/org/zaproxy/zap/extension/script/OptionsScriptTableModel.java | 2653 | /*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* 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.zaproxy.zap.extension.script;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.parosproxy.paros.Constant;
import org.zaproxy.zap.view.AbstractMultipleOptionsBaseTableModel;
public class OptionsScriptTableModel extends AbstractMultipleOptionsBaseTableModel<File> {
private static final long serialVersionUID = 1L;
private static final String[] COLUMN_NAMES = {
Constant.messages.getString("options.script.table.header.dir")};
private static final int COLUMN_COUNT = COLUMN_NAMES.length;
private List<File> tokens = new ArrayList<>(0);
/**
*
*/
public OptionsScriptTableModel() {
super();
}
@Override
public List<File> getElements() {
return tokens;
}
/**
* @param tokens The tokens to set.
*/
public void setTokens(List<File> files) {
this.tokens = new ArrayList<>(tokens.size());
for (File file : files) {
this.tokens.add(file);
}
fireTableDataChanged();
}
@Override
public String getColumnName(int col) {
return COLUMN_NAMES[col];
}
@Override
public int getColumnCount() {
return COLUMN_COUNT;
}
@Override
public Class<?> getColumnClass(int c) {
return String.class;
}
@Override
public int getRowCount() {
return tokens.size();
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
switch(columnIndex) {
case 0:
return getElement(rowIndex).getAbsolutePath();
}
return null;
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
}
}
| apache-2.0 |
wtanaka/beam | runners/core-construction-java/src/test/java/org/apache/beam/runners/core/construction/TriggerTranslationTest.java | 4942 | /*
* 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.beam.runners.core.construction;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import org.apache.beam.sdk.transforms.windowing.AfterAll;
import org.apache.beam.sdk.transforms.windowing.AfterEach;
import org.apache.beam.sdk.transforms.windowing.AfterFirst;
import org.apache.beam.sdk.transforms.windowing.AfterPane;
import org.apache.beam.sdk.transforms.windowing.AfterProcessingTime;
import org.apache.beam.sdk.transforms.windowing.AfterSynchronizedProcessingTime;
import org.apache.beam.sdk.transforms.windowing.AfterWatermark;
import org.apache.beam.sdk.transforms.windowing.DefaultTrigger;
import org.apache.beam.sdk.transforms.windowing.Never;
import org.apache.beam.sdk.transforms.windowing.Repeatedly;
import org.apache.beam.sdk.transforms.windowing.Trigger;
import org.joda.time.Duration;
import org.joda.time.Instant;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
/** Tests for utilities in {@link TriggerTranslation}. */
@RunWith(Parameterized.class)
public class TriggerTranslationTest {
@AutoValue
abstract static class ToProtoAndBackSpec {
abstract Trigger getTrigger();
}
private static ToProtoAndBackSpec toProtoAndBackSpec(Trigger trigger) {
return new AutoValue_TriggerTranslationTest_ToProtoAndBackSpec(trigger);
}
@Parameters(name = "{index}: {0}")
public static Iterable<ToProtoAndBackSpec> data() {
return ImmutableList.of(
// Atomic triggers
toProtoAndBackSpec(AfterWatermark.pastEndOfWindow()),
toProtoAndBackSpec(AfterPane.elementCountAtLeast(73)),
toProtoAndBackSpec(AfterSynchronizedProcessingTime.ofFirstElement()),
toProtoAndBackSpec(Never.ever()),
toProtoAndBackSpec(DefaultTrigger.of()),
toProtoAndBackSpec(AfterProcessingTime.pastFirstElementInPane()),
toProtoAndBackSpec(
AfterProcessingTime.pastFirstElementInPane().plusDelayOf(Duration.millis(23))),
toProtoAndBackSpec(
AfterProcessingTime.pastFirstElementInPane()
.alignedTo(Duration.millis(5), new Instant(27))),
toProtoAndBackSpec(
AfterProcessingTime.pastFirstElementInPane()
.plusDelayOf(Duration.standardSeconds(3))
.alignedTo(Duration.millis(5), new Instant(27))
.plusDelayOf(Duration.millis(13))),
// Composite triggers
toProtoAndBackSpec(
AfterAll.of(AfterPane.elementCountAtLeast(79), AfterWatermark.pastEndOfWindow())),
toProtoAndBackSpec(
AfterEach.inOrder(AfterPane.elementCountAtLeast(79), AfterPane.elementCountAtLeast(3))),
toProtoAndBackSpec(
AfterFirst.of(AfterWatermark.pastEndOfWindow(), AfterPane.elementCountAtLeast(3))),
toProtoAndBackSpec(
AfterWatermark.pastEndOfWindow().withEarlyFirings(AfterPane.elementCountAtLeast(3))),
toProtoAndBackSpec(
AfterWatermark.pastEndOfWindow().withLateFirings(AfterPane.elementCountAtLeast(3))),
toProtoAndBackSpec(
AfterWatermark.pastEndOfWindow()
.withEarlyFirings(
AfterProcessingTime.pastFirstElementInPane().plusDelayOf(Duration.millis(42)))
.withLateFirings(AfterPane.elementCountAtLeast(3))),
toProtoAndBackSpec(Repeatedly.forever(AfterWatermark.pastEndOfWindow())),
toProtoAndBackSpec(
Repeatedly.forever(AfterPane.elementCountAtLeast(1))
.orFinally(AfterWatermark.pastEndOfWindow())));
}
@Parameter(0)
public ToProtoAndBackSpec toProtoAndBackSpec;
@Test
public void testToProtoAndBack() throws Exception {
Trigger trigger = toProtoAndBackSpec.getTrigger();
Trigger toProtoAndBackTrigger =
TriggerTranslation.fromProto(TriggerTranslation.toProto(trigger));
assertThat(toProtoAndBackTrigger, equalTo(trigger));
}
}
| apache-2.0 |
ZanyLeonic/Balloons | src/main/java/ic2/api/event/LaserEvent.java | 4508 | package ic2.api.event;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import cpw.mods.fml.common.eventhandler.Cancelable;
import net.minecraftforge.event.world.WorldEvent;
/**
* A bunch of Events to handle the power of the Mining Laser.
*/
@Cancelable
public class LaserEvent extends WorldEvent {
// the Laser Entity
public final Entity lasershot;
// the following variables can be changed and the Laser will adjust to them
// the Player firing the Laser. If the Laser gets "reflected" the Player could change.
public EntityLivingBase owner;
// Range of the Laser Shot. Determine the amount of broken blocks, as well, as each broken block will subtract ~1F from range.
public float range, power;
public int blockBreaks;
// Determines whether the laser will explode upon hitting something
public boolean explosive, smelt;
public LaserEvent(World world1, Entity lasershot1, EntityLivingBase owner1, float range1, float power1, int blockBreaks1, boolean explosive1, boolean smelt1) {
super(world1);
this.lasershot = lasershot1;
this.owner = owner1;
this.range = range1;
this.power = power1;
this.blockBreaks = blockBreaks1;
this.explosive = explosive1;
this.smelt = smelt1;
}
/**
* Event when the Laser is getting shot by a Player.
*
* The Item is the Laser Gun which the "Player" has shot
*/
public static class LaserShootEvent extends LaserEvent {
ItemStack laseritem;
public LaserShootEvent(World world1, Entity lasershot1, EntityLivingBase owner1, float range1, float power1, int blockBreaks1, boolean explosive1, boolean smelt1, ItemStack laseritem1) {
super(world1, lasershot1, owner1, range1, power1, blockBreaks1, explosive1, smelt1);
this.laseritem = laseritem1;
}
}
/**
* Event when the Laser is exploding for some Reason.
*
* The Laser will no longer exist after this Event is posted as it either Explodes or despawns after the Event is fired.
*/
public static class LaserExplodesEvent extends LaserEvent {
// explosion strength, even that can be changed!
public float explosionpower, explosiondroprate, explosionentitydamage;
public LaserExplodesEvent(World world1, Entity lasershot1, EntityLivingBase owner1, float range1, float power1, int blockBreaks1, boolean explosive1, boolean smelt1, float explosionpower1, float explosiondroprate1, float explosionentitydamage1) {
super(world1, lasershot1, owner1, range1, power1, blockBreaks1, explosive1, smelt1);
this.explosionpower = explosionpower1;
this.explosiondroprate = explosiondroprate1;
this.explosionentitydamage = explosionentitydamage1;
}
}
/**
* Event when the Laser is hitting a Block
* x, y and z are the Coords of the Block.
*
* Canceling this Event stops the Laser from attempting to break the Block, what is very useful for Glass.
* Use lasershot.setDead() to remove the Shot entirely.
*/
public static class LaserHitsBlockEvent extends LaserEvent {
// targeted block, even that can be changed!
public int x, y, z;
public int side;
// removeBlock determines if the Block will be removed. dropBlock determines if the Block should drop something.
public boolean removeBlock, dropBlock;
public float dropChance;
public LaserHitsBlockEvent(World world1, Entity lasershot1, EntityLivingBase owner1, float range1, float power1, int blockBreaks1, boolean explosive1, boolean smelt1, int x1, int y1, int z1, int side1, float dropChance1, boolean removeBlock1, boolean dropBlock1) {
super(world1, lasershot1, owner1, range1, power1, blockBreaks1, explosive1, smelt1);
this.x = x1;
this.y = y1;
this.z = z1;
this.side = side1;
this.removeBlock = removeBlock1;
this.dropBlock = dropBlock1;
this.dropChance = dropChance1;
}
}
/**
* Event when the Laser is getting at a Living Entity
*
* Canceling this Event ignores the Entity
* Use lasershot.setDead() to remove the Shot entirely.
*/
public static class LaserHitsEntityEvent extends LaserEvent {
// the Entity which the Laser has shot at, even the target can be changed!
public Entity hitentity;
public LaserHitsEntityEvent(World world1, Entity lasershot1, EntityLivingBase owner1, float range1, float power1, int blockBreaks1, boolean explosive1, boolean smelt1, Entity hitentity1) {
super(world1, lasershot1, owner1, range1, power1, blockBreaks1, explosive1, smelt1);
this.hitentity = hitentity1;
}
}
}
| mit |
rokn/Count_Words_2015 | testing/openjdk/jdk/src/share/classes/sun/rmi/transport/tcp/ConnectionMultiplexer.java | 16501 | /*
* Copyright (c) 1996, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.rmi.transport.tcp;
import java.io.*;
import java.util.*;
import java.rmi.server.LogStream;
import sun.rmi.runtime.Log;
/**
* ConnectionMultiplexer manages the transparent multiplexing of
* multiple virtual connections from one endpoint to another through
* one given real connection to that endpoint. The input and output
* streams for the the underlying real connection must be supplied.
* A callback object is also supplied to be informed of new virtual
* connections opened by the remote endpoint. After creation, the
* run() method must be called in a thread created for demultiplexing
* the connections. The openConnection() method is called to
* initiate a virtual connection from this endpoint.
*
* @author Peter Jones
*/
final class ConnectionMultiplexer {
/** "multiplex" log level */
static int logLevel = LogStream.parseLevel(getLogLevel());
private static String getLogLevel() {
return java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("sun.rmi.transport.tcp.multiplex.logLevel"));
}
/* multiplex system log */
static final Log multiplexLog =
Log.getLog("sun.rmi.transport.tcp.multiplex",
"multiplex", ConnectionMultiplexer.logLevel);
/** multiplexing protocol operation codes */
private final static int OPEN = 0xE1;
private final static int CLOSE = 0xE2;
private final static int CLOSEACK = 0xE3;
private final static int REQUEST = 0xE4;
private final static int TRANSMIT = 0xE5;
/** object to notify for new connections from remote endpoint */
private TCPChannel channel;
/** input stream for underlying single connection */
private InputStream in;
/** output stream for underlying single connection */
private OutputStream out;
/** true if underlying connection originated from this endpoint
(used for generating unique connection IDs) */
private boolean orig;
/** layered stream for reading formatted data from underlying connection */
private DataInputStream dataIn;
/** layered stream for writing formatted data to underlying connection */
private DataOutputStream dataOut;
/** table holding currently open connection IDs and related info */
private Hashtable connectionTable = new Hashtable(7);
/** number of currently open connections */
private int numConnections = 0;
/** maximum allowed open connections */
private final static int maxConnections = 256;
/** ID of last connection opened */
private int lastID = 0x1001;
/** true if this mechanism is still alive */
private boolean alive = true;
/**
* Create a new ConnectionMultiplexer using the given underlying
* input/output stream pair. The run method must be called
* (possibly on a new thread) to handle the demultiplexing.
* @param channel object to notify when new connection is received
* @param in input stream of underlying connection
* @param out output stream of underlying connection
* @param orig true if this endpoint intiated the underlying
* connection (needs to be set differently at both ends)
*/
public ConnectionMultiplexer(
TCPChannel channel,
InputStream in,
OutputStream out,
boolean orig)
{
this.channel = channel;
this.in = in;
this.out = out;
this.orig = orig;
dataIn = new DataInputStream(in);
dataOut = new DataOutputStream(out);
}
/**
* Process multiplexing protocol received from underlying connection.
*/
public void run() throws IOException
{
try {
int op, id, length;
Integer idObj;
MultiplexConnectionInfo info;
while (true) {
// read next op code from remote endpoint
op = dataIn.readUnsignedByte();
switch (op) {
// remote endpoint initiating new connection
case OPEN:
id = dataIn.readUnsignedShort();
if (multiplexLog.isLoggable(Log.VERBOSE)) {
multiplexLog.log(Log.VERBOSE, "operation OPEN " + id);
}
idObj = new Integer(id);
info =
(MultiplexConnectionInfo) connectionTable.get(idObj);
if (info != null)
throw new IOException(
"OPEN: Connection ID already exists");
info = new MultiplexConnectionInfo(id);
info.in = new MultiplexInputStream(this, info, 2048);
info.out = new MultiplexOutputStream(this, info, 2048);
synchronized (connectionTable) {
connectionTable.put(idObj, info);
++ numConnections;
}
sun.rmi.transport.Connection conn;
conn = new TCPConnection(channel, info.in, info.out);
channel.acceptMultiplexConnection(conn);
break;
// remote endpoint closing connection
case CLOSE:
id = dataIn.readUnsignedShort();
if (multiplexLog.isLoggable(Log.VERBOSE)) {
multiplexLog.log(Log.VERBOSE, "operation CLOSE " + id);
}
idObj = new Integer(id);
info =
(MultiplexConnectionInfo) connectionTable.get(idObj);
if (info == null)
throw new IOException(
"CLOSE: Invalid connection ID");
info.in.disconnect();
info.out.disconnect();
if (!info.closed)
sendCloseAck(info);
synchronized (connectionTable) {
connectionTable.remove(idObj);
-- numConnections;
}
break;
// remote endpoint acknowledging close of connection
case CLOSEACK:
id = dataIn.readUnsignedShort();
if (multiplexLog.isLoggable(Log.VERBOSE)) {
multiplexLog.log(Log.VERBOSE,
"operation CLOSEACK " + id);
}
idObj = new Integer(id);
info =
(MultiplexConnectionInfo) connectionTable.get(idObj);
if (info == null)
throw new IOException(
"CLOSEACK: Invalid connection ID");
if (!info.closed)
throw new IOException(
"CLOSEACK: Connection not closed");
info.in.disconnect();
info.out.disconnect();
synchronized (connectionTable) {
connectionTable.remove(idObj);
-- numConnections;
}
break;
// remote endpoint declaring additional bytes receivable
case REQUEST:
id = dataIn.readUnsignedShort();
idObj = new Integer(id);
info =
(MultiplexConnectionInfo) connectionTable.get(idObj);
if (info == null)
throw new IOException(
"REQUEST: Invalid connection ID");
length = dataIn.readInt();
if (multiplexLog.isLoggable(Log.VERBOSE)) {
multiplexLog.log(Log.VERBOSE,
"operation REQUEST " + id + ": " + length);
}
info.out.request(length);
break;
// remote endpoint transmitting data packet
case TRANSMIT:
id = dataIn.readUnsignedShort();
idObj = new Integer(id);
info =
(MultiplexConnectionInfo) connectionTable.get(idObj);
if (info == null)
throw new IOException("SEND: Invalid connection ID");
length = dataIn.readInt();
if (multiplexLog.isLoggable(Log.VERBOSE)) {
multiplexLog.log(Log.VERBOSE,
"operation TRANSMIT " + id + ": " + length);
}
info.in.receive(length, dataIn);
break;
default:
throw new IOException("Invalid operation: " +
Integer.toHexString(op));
}
}
} finally {
shutDown();
}
}
/**
* Initiate a new multiplexed connection through the underlying
* connection.
*/
public synchronized TCPConnection openConnection() throws IOException
{
// generate ID that should not be already used
// If all possible 32768 IDs are used,
// this method will block searching for a new ID forever.
int id;
Integer idObj;
do {
lastID = (++ lastID) & 0x7FFF;
id = lastID;
// The orig flag (copied to the high bit of the ID) is used
// to have two distinct ranges to choose IDs from for the
// two endpoints.
if (orig)
id |= 0x8000;
idObj = new Integer(id);
} while (connectionTable.get(idObj) != null);
// create multiplexing streams and bookkeeping information
MultiplexConnectionInfo info = new MultiplexConnectionInfo(id);
info.in = new MultiplexInputStream(this, info, 2048);
info.out = new MultiplexOutputStream(this, info, 2048);
// add to connection table if multiplexer has not died
synchronized (connectionTable) {
if (!alive)
throw new IOException("Multiplexer connection dead");
if (numConnections >= maxConnections)
throw new IOException("Cannot exceed " + maxConnections +
" simultaneous multiplexed connections");
connectionTable.put(idObj, info);
++ numConnections;
}
// inform remote endpoint of new connection
synchronized (dataOut) {
try {
dataOut.writeByte(OPEN);
dataOut.writeShort(id);
dataOut.flush();
} catch (IOException e) {
multiplexLog.log(Log.BRIEF, "exception: ", e);
shutDown();
throw e;
}
}
return new TCPConnection(channel, info.in, info.out);
}
/**
* Shut down all connections and clean up.
*/
public void shutDown()
{
// inform all associated streams
synchronized (connectionTable) {
// return if multiplexer already officially dead
if (!alive)
return;
alive = false;
Enumeration enum_ = connectionTable.elements();
while (enum_.hasMoreElements()) {
MultiplexConnectionInfo info =
(MultiplexConnectionInfo) enum_.nextElement();
info.in.disconnect();
info.out.disconnect();
}
connectionTable.clear();
numConnections = 0;
}
// close underlying connection, if possible (and not already done)
try {
in.close();
} catch (IOException e) {
}
try {
out.close();
} catch (IOException e) {
}
}
/**
* Send request for more data on connection to remote endpoint.
* @param info connection information structure
* @param len number of more bytes that can be received
*/
void sendRequest(MultiplexConnectionInfo info, int len) throws IOException
{
synchronized (dataOut) {
if (alive && !info.closed)
try {
dataOut.writeByte(REQUEST);
dataOut.writeShort(info.id);
dataOut.writeInt(len);
dataOut.flush();
} catch (IOException e) {
multiplexLog.log(Log.BRIEF, "exception: ", e);
shutDown();
throw e;
}
}
}
/**
* Send packet of requested data on connection to remote endpoint.
* @param info connection information structure
* @param buf array containg bytes to send
* @param off offset of first array index of packet
* @param len number of bytes in packet to send
*/
void sendTransmit(MultiplexConnectionInfo info,
byte buf[], int off, int len) throws IOException
{
synchronized (dataOut) {
if (alive && !info.closed)
try {
dataOut.writeByte(TRANSMIT);
dataOut.writeShort(info.id);
dataOut.writeInt(len);
dataOut.write(buf, off, len);
dataOut.flush();
} catch (IOException e) {
multiplexLog.log(Log.BRIEF, "exception: ", e);
shutDown();
throw e;
}
}
}
/**
* Inform remote endpoint that connection has been closed.
* @param info connection information structure
*/
void sendClose(MultiplexConnectionInfo info) throws IOException
{
info.out.disconnect();
synchronized (dataOut) {
if (alive && !info.closed)
try {
dataOut.writeByte(CLOSE);
dataOut.writeShort(info.id);
dataOut.flush();
info.closed = true;
} catch (IOException e) {
multiplexLog.log(Log.BRIEF, "exception: ", e);
shutDown();
throw e;
}
}
}
/**
* Acknowledge remote endpoint's closing of connection.
* @param info connection information structure
*/
void sendCloseAck(MultiplexConnectionInfo info) throws IOException
{
synchronized (dataOut) {
if (alive && !info.closed)
try {
dataOut.writeByte(CLOSEACK);
dataOut.writeShort(info.id);
dataOut.flush();
info.closed = true;
} catch (IOException e) {
multiplexLog.log(Log.BRIEF, "exception: ", e);
shutDown();
throw e;
}
}
}
/**
* Shut down connection upon finalization.
*/
protected void finalize() throws Throwable
{
super.finalize();
shutDown();
}
}
| mit |
evansj/openhab | bundles/binding/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/connection/ConnectionSettings.java | 6850 | /**
* Copyright (c) 2010-2016, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.lcn.connection;
import java.util.Dictionary;
import org.openhab.binding.lcn.common.LcnDefs;
/**
* Settings for a connection to LCN-PCHK.
*
* @author Tobias Jüttner
*/
public class ConnectionSettings {
/** Unique identifier for this connection. */
private final String id;
/** The user name for authentication. */
private final String username;
/** The password for authentication. */
private final String password;
/** The TCP/IP address or IP of the connection. */
private final String address;
/** The TCP/IP port of the connection. */
private final int port;
/** The dimming mode to use. */
private final LcnDefs.OutputPortDimMode dimMode;
/** The status-messages mode to use. */
private final LcnDefs.OutputPortStatusMode statusMode;
/** The default timeout to use for requests. Worst case: Requesting threshold 4-4 takes at least 1.8s */
private static final long DEFAULT_TIMEOUT_MSEC = 3500;
/** Timeout for requests. */
private final long timeoutMSec;
/**
* Constructor.
*
* @param id the connnection's unique identifier
* @param address the connection's TCP/IP address or IP
* @param port the connection's TCP/IP port
* @param username the user name for authentication
* @param password the password for authentication
* @param dimMode the dimming mode
* @param statusMode the status-messages mode
* @param timeout the request timeout
*/
private ConnectionSettings(String id, String address, int port, String username, String password,
LcnDefs.OutputPortDimMode dimMode, LcnDefs.OutputPortStatusMode statusMode, int timeout) {
this.id = id;
this.address = address;
this.port = port;
this.username = username;
this.password = password;
this.dimMode = dimMode;
this.statusMode = statusMode;
this.timeoutMSec = timeout;
}
/**
* Gets the unique identifier for the connection.
*
* @return the unique identifier
*/
public String getId() {
return this.id;
}
/**
* Gets the user name used for authentication.
*
* @return the user name
*/
public String getUsername() {
return this.username;
}
/**
* Gets the password used for authentication.
*
* @return the password
*/
public String getPassword() {
return this.password;
}
/**
* Gets the TCP/IP address or IP of the connection.
*
* @return the address or IP
*/
public String getAddress() {
return this.address;
}
/**
* Gets the TCP/IP port of the connection.
*
* @return the port
*/
public int getPort() {
return this.port;
}
/**
* Gets the dimming mode to use for the connection.
*
* @return the dimming mode
*/
public LcnDefs.OutputPortDimMode getDimMode() {
return this.dimMode;
}
/**
* Gets the status-messages mode to use for the connection.
*
* @return the status-messages mode
*/
public LcnDefs.OutputPortStatusMode getStatusMode() {
return this.statusMode;
}
/**
* Gets the request timeout.
*
* @return the timeout in milliseconds
*/
public long getTimeout() {
return this.timeoutMSec;
}
/**
* Tries to parse LCN-PCHK connection settings from the given openHAB configuration.
*
* @param config the binding's configuration
* @param counter 0..x (1..x+1 in actual configuration file)
* @return the connection settings on success or null
*/
public static ConnectionSettings tryParse(Dictionary<String, ?> config, int counter) {
if (config == null) {
return null;
}
String id = (String) config.get("id" + (counter + 1));
id = id == null ? "" : id.trim();
String addressWithOptPort = (String) config.get("address" + (counter + 1));
addressWithOptPort = addressWithOptPort == null ? "" : addressWithOptPort.trim();
String username = (String) config.get("username" + (counter + 1));
username = username == null ? "" : username.trim();
String password = (String) config.get("password" + (counter + 1));
password = password == null ? "" : password.trim();
String mode = (String) config.get("mode" + (counter + 1));
mode = mode == null ? "" : mode.trim();
if (id.isEmpty() || addressWithOptPort.isEmpty() || username.isEmpty() || password.isEmpty()
|| mode.isEmpty()) {
return null;
}
String dataRequestTimeout = (String) config.get("timeout" + (counter + 1));
dataRequestTimeout = dataRequestTimeout == null ? Long.valueOf(DEFAULT_TIMEOUT_MSEC).toString()
: dataRequestTimeout.trim();
try {
String address = addressWithOptPort.contains(":") ? addressWithOptPort.split(":")[0] : addressWithOptPort;
int port = addressWithOptPort.contains(":") ? Integer.parseInt(addressWithOptPort.split(":")[1]) : 4114;
LcnDefs.OutputPortDimMode dimMode = mode.equalsIgnoreCase("percent200")
|| mode.equalsIgnoreCase("native200") ? LcnDefs.OutputPortDimMode.STEPS200
: LcnDefs.OutputPortDimMode.STEPS50;
LcnDefs.OutputPortStatusMode statusMode = mode.equalsIgnoreCase("percent50")
|| mode.equalsIgnoreCase("percent200") ? LcnDefs.OutputPortStatusMode.PERCENT
: LcnDefs.OutputPortStatusMode.NATIVE;
int timeout = Integer.parseInt(dataRequestTimeout);
return new ConnectionSettings(id, address, port, username, password, dimMode, statusMode, timeout);
} catch (NumberFormatException ex) {
}
return null;
}
/** {@inheritDoc} */
@Override
public boolean equals(Object o) {
if (!(o instanceof ConnectionSettings)) {
return false;
}
ConnectionSettings other = (ConnectionSettings) o;
return this.id.equals(other.id) && this.address.equals(other.address) && this.port == other.port
&& this.username.equals(other.username) && this.password.equals(other.password)
&& this.dimMode == other.dimMode && this.statusMode == other.statusMode
&& this.timeoutMSec == other.timeoutMSec;
}
}
| epl-1.0 |
sanyaade-g2g-repos/orientdb | core/src/main/java/com/orientechnologies/orient/core/sql/method/misc/OSQLMethodJavaType.java | 1305 | /*
* Copyright 2013 Orient Technologies.
* Copyright 2013 Geomatys.
*
* 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.orientechnologies.orient.core.sql.method.misc;
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
/**
* Returns the value's Java type.
*
* @author Luca Garulli
*/
public class OSQLMethodJavaType extends OAbstractSQLMethod {
public static final String NAME = "javatype";
public OSQLMethodJavaType() {
super(NAME);
}
@Override
public Object execute(Object iThis, OIdentifiable iCurrentRecord, OCommandContext iContext, Object ioResult, Object[] iParams) {
if (ioResult == null) {
return null;
}
return ioResult.getClass().getName();
}
}
| apache-2.0 |
fengshao0907/titan | titan-test/src/test/java/com/thinkaurelius/titan/graphdb/serializer/NoDefaultConstructor.java | 243 | package com.thinkaurelius.titan.graphdb.serializer;
/**
* @author Matthias Broecheler (me@matthiasb.com)
*/
public class NoDefaultConstructor {
private final int i;
public NoDefaultConstructor(int i) {
this.i=i;
}
}
| apache-2.0 |
KatharineYe/ews-java-api | src/main/java/microsoft/exchange/webservices/data/sync/Change.java | 3475 | /*
* The MIT License
* Copyright (c) 2012 Microsoft Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package microsoft.exchange.webservices.data.sync;
import microsoft.exchange.webservices.data.attribute.EditorBrowsable;
import microsoft.exchange.webservices.data.core.service.ServiceObject;
import microsoft.exchange.webservices.data.core.enumeration.sync.ChangeType;
import microsoft.exchange.webservices.data.core.enumeration.attribute.EditorBrowsableState;
import microsoft.exchange.webservices.data.core.exception.service.local.ServiceLocalException;
import microsoft.exchange.webservices.data.property.complex.ServiceId;
/**
* Represents a change as returned by a synchronization operation.
*/
@EditorBrowsable(state = EditorBrowsableState.Never)
public abstract class Change {
/**
* The type of change.
*/
private ChangeType changeType;
/**
* The service object the change applies to.
*/
private ServiceObject serviceObject;
/**
* The Id of the service object the change applies to.
*/
private ServiceId id;
/**
* Initializes a new instance of Change.
*/
protected Change() {
}
/**
* Initializes a new instance of Change.
*
* @return the service id
*/
public abstract ServiceId createId();
/**
* Gets the type of the change.
*
* @return the change type
*/
public ChangeType getChangeType() {
return this.changeType;
}
/**
* sets the type of the change.
*
* @param changeType the new change type
*/
public void setChangeType(ChangeType changeType) {
this.changeType = changeType;
}
/**
* Gets the service object the change applies to.
*
* @return the service object
*/
public ServiceObject getServiceObject() {
return this.serviceObject;
}
/**
* Sets the service object.
*
* @param serviceObject the new service object
*/
public void setServiceObject(ServiceObject serviceObject) {
this.serviceObject = serviceObject;
}
/**
* Gets the Id of the service object the change applies to.
*
* @return the id
* @throws ServiceLocalException the service local exception
*/
public ServiceId getId() throws ServiceLocalException {
return this.getServiceObject() != null ? this.getServiceObject()
.getId() : this.id;
}
/**
* Sets the id.
*
* @param id the new id
*/
public void setId(ServiceId id) {
this.id = id;
}
}
| mit |
tiarebalbi/spring-boot | spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/liquibase/LiquibaseEndpointAutoConfigurationTests.java | 4067 | /*
* Copyright 2012-2019 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
*
* https://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.springframework.boot.actuate.autoconfigure.liquibase;
import liquibase.integration.spring.SpringLiquibase;
import org.junit.jupiter.api.Test;
import org.springframework.boot.actuate.liquibase.LiquibaseEndpoint;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.liquibase.DataSourceClosingSpringLiquibase;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link LiquibaseEndpointAutoConfiguration}.
*
* @author Phillip Webb
*/
class LiquibaseEndpointAutoConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(LiquibaseEndpointAutoConfiguration.class));
@Test
void runShouldHaveEndpointBean() {
this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=liquibase")
.withBean(SpringLiquibase.class, () -> mock(SpringLiquibase.class))
.run((context) -> assertThat(context).hasSingleBean(LiquibaseEndpoint.class));
}
@Test
void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() {
this.contextRunner.withBean(SpringLiquibase.class, () -> mock(SpringLiquibase.class))
.withPropertyValues("management.endpoint.liquibase.enabled:false")
.run((context) -> assertThat(context).doesNotHaveBean(LiquibaseEndpoint.class));
}
@Test
void runWhenNotExposedShouldNotHaveEndpointBean() {
this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(LiquibaseEndpoint.class));
}
@Test
void disablesCloseOfDataSourceWhenEndpointIsEnabled() {
this.contextRunner.withUserConfiguration(DataSourceClosingLiquibaseConfiguration.class)
.withPropertyValues("management.endpoints.web.exposure.include=liquibase").run((context) -> {
assertThat(context).hasSingleBean(LiquibaseEndpoint.class);
assertThat(context.getBean(DataSourceClosingSpringLiquibase.class))
.hasFieldOrPropertyWithValue("closeDataSourceOnceMigrated", false);
});
}
@Test
void doesNotDisableCloseOfDataSourceWhenEndpointIsDisabled() {
this.contextRunner.withUserConfiguration(DataSourceClosingLiquibaseConfiguration.class)
.withPropertyValues("management.endpoint.liquibase.enabled:false").run((context) -> {
assertThat(context).doesNotHaveBean(LiquibaseEndpoint.class);
DataSourceClosingSpringLiquibase bean = context.getBean(DataSourceClosingSpringLiquibase.class);
assertThat(bean).hasFieldOrPropertyWithValue("closeDataSourceOnceMigrated", true);
});
}
@Configuration(proxyBeanMethods = false)
static class DataSourceClosingLiquibaseConfiguration {
@Bean
SpringLiquibase liquibase() {
return new DataSourceClosingSpringLiquibase() {
private boolean propertiesSet = false;
@Override
public void setCloseDataSourceOnceMigrated(boolean closeDataSourceOnceMigrated) {
if (this.propertiesSet) {
throw new IllegalStateException(
"setCloseDataSourceOnceMigrated invoked after afterPropertiesSet");
}
super.setCloseDataSourceOnceMigrated(closeDataSourceOnceMigrated);
}
@Override
public void afterPropertiesSet() {
this.propertiesSet = true;
}
};
}
}
}
| apache-2.0 |
s2oBCN/testng | src/test/java/test/verify/VerifyTest.java | 1103 | package test.verify;
import org.testng.Assert;
import org.testng.TestListenerAdapter;
import org.testng.TestNG;
import org.testng.annotations.Test;
import test.SimpleBaseTest;
public class VerifyTest extends SimpleBaseTest {
private void runTest(Class<?> cls, int expected) {
TestNG tng = create(cls);
TestListenerAdapter tla = new TestListenerAdapter();
tng.addListener(tla);
tng.run();
Assert.assertEquals(tla.getPassedTests().size(), expected);
}
@Test
public void verifyWithAnnotation() {
runTest(VerifySampleTest.class, 4);
}
@Test
public void verifyWithoutAnnotation() {
runTest(VerifyNoListenersSampleTest.class, 3);
}
@Test
public void verifyTestListener() {
TestNG tng = create(Verify2SampleTest.class);
VerifyTestListener.m_count = 0;
tng.run();
Assert.assertEquals(VerifyTestListener.m_count, 1);
}
@Test
public void verifyBaseClassTestListener() {
TestNG tng = create(Verify3SampleTest.class);
VerifyTestListener.m_count = 0;
tng.run();
Assert.assertEquals(VerifyTestListener.m_count, 1);
}
}
| apache-2.0 |
idea4bsd/idea4bsd | platform/lang-api/src/com/intellij/refactoring/RefactoringBundle.java | 2776 | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* 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.intellij.refactoring;
import com.intellij.CommonBundle;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.PropertyKey;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.util.ResourceBundle;
/**
* @author ven
*/
public class RefactoringBundle {
public static String message(@NotNull @PropertyKey(resourceBundle = BUNDLE) String key, @NotNull Object... params) {
return CommonBundle.message(getBundle(), key, params);
}
private static Reference<ResourceBundle> ourBundle;
@NonNls private static final String BUNDLE = "messages.RefactoringBundle";
private RefactoringBundle() {
}
public static String getSearchInCommentsAndStringsText() {
return message("search.in.comments.and.strings");
}
public static String getSearchForTextOccurrencesText() {
return message("search.for.text.occurrences");
}
public static String getVisibilityPackageLocal() {
return message("visibility.package.local");
}
public static String getVisibilityPrivate() {
return message("visibility.private");
}
public static String getVisibilityProtected() {
return message("visibility.protected");
}
public static String getVisibilityPublic() {
return message("visibility.public");
}
public static String getVisibilityAsIs() {
return message("visibility.as.is");
}
public static String getEscalateVisibility() {
return message("visibility.escalate");
}
public static String getCannotRefactorMessage(@Nullable final String message) {
return message("cannot.perform.refactoring") + (message == null ? "" : "\n" + message);
}
public static String message(@PropertyKey(resourceBundle = BUNDLE) String key) {
return CommonBundle.message(getBundle(), key);
}
private static ResourceBundle getBundle() {
ResourceBundle bundle = com.intellij.reference.SoftReference.dereference(ourBundle);
if (bundle == null) {
bundle = ResourceBundle.getBundle(BUNDLE);
ourBundle = new SoftReference<>(bundle);
}
return bundle;
}
}
| apache-2.0 |
sheofir/aws-sdk-java | aws-java-sdk-elasticbeanstalk/src/main/java/com/amazonaws/services/elasticbeanstalk/model/ApplicationVersionDescription.java | 12433 | /*
* Copyright 2010-2015 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.elasticbeanstalk.model;
import java.io.Serializable;
/**
* <p>
* Describes the properties of an application version.
* </p>
*/
public class ApplicationVersionDescription implements Serializable, Cloneable {
/**
* <p>
* The name of the application associated with this release.
* </p>
*/
private String applicationName;
/**
* <p>
* The description of this application version.
* </p>
*/
private String description;
/**
* <p>
* A label uniquely identifying the version for the associated application.
* </p>
*/
private String versionLabel;
/**
* <p>
* The location where the source bundle is located for this version.
* </p>
*/
private S3Location sourceBundle;
/**
* <p>
* The creation date of the application version.
* </p>
*/
private java.util.Date dateCreated;
/**
* <p>
* The last modified date of the application version.
* </p>
*/
private java.util.Date dateUpdated;
/**
* <p>
* The name of the application associated with this release.
* </p>
*
* @param applicationName
* The name of the application associated with this release.
*/
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
/**
* <p>
* The name of the application associated with this release.
* </p>
*
* @return The name of the application associated with this release.
*/
public String getApplicationName() {
return this.applicationName;
}
/**
* <p>
* The name of the application associated with this release.
* </p>
*
* @param applicationName
* The name of the application associated with this release.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ApplicationVersionDescription withApplicationName(
String applicationName) {
setApplicationName(applicationName);
return this;
}
/**
* <p>
* The description of this application version.
* </p>
*
* @param description
* The description of this application version.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* <p>
* The description of this application version.
* </p>
*
* @return The description of this application version.
*/
public String getDescription() {
return this.description;
}
/**
* <p>
* The description of this application version.
* </p>
*
* @param description
* The description of this application version.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ApplicationVersionDescription withDescription(String description) {
setDescription(description);
return this;
}
/**
* <p>
* A label uniquely identifying the version for the associated application.
* </p>
*
* @param versionLabel
* A label uniquely identifying the version for the associated
* application.
*/
public void setVersionLabel(String versionLabel) {
this.versionLabel = versionLabel;
}
/**
* <p>
* A label uniquely identifying the version for the associated application.
* </p>
*
* @return A label uniquely identifying the version for the associated
* application.
*/
public String getVersionLabel() {
return this.versionLabel;
}
/**
* <p>
* A label uniquely identifying the version for the associated application.
* </p>
*
* @param versionLabel
* A label uniquely identifying the version for the associated
* application.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ApplicationVersionDescription withVersionLabel(String versionLabel) {
setVersionLabel(versionLabel);
return this;
}
/**
* <p>
* The location where the source bundle is located for this version.
* </p>
*
* @param sourceBundle
* The location where the source bundle is located for this version.
*/
public void setSourceBundle(S3Location sourceBundle) {
this.sourceBundle = sourceBundle;
}
/**
* <p>
* The location where the source bundle is located for this version.
* </p>
*
* @return The location where the source bundle is located for this version.
*/
public S3Location getSourceBundle() {
return this.sourceBundle;
}
/**
* <p>
* The location where the source bundle is located for this version.
* </p>
*
* @param sourceBundle
* The location where the source bundle is located for this version.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ApplicationVersionDescription withSourceBundle(
S3Location sourceBundle) {
setSourceBundle(sourceBundle);
return this;
}
/**
* <p>
* The creation date of the application version.
* </p>
*
* @param dateCreated
* The creation date of the application version.
*/
public void setDateCreated(java.util.Date dateCreated) {
this.dateCreated = dateCreated;
}
/**
* <p>
* The creation date of the application version.
* </p>
*
* @return The creation date of the application version.
*/
public java.util.Date getDateCreated() {
return this.dateCreated;
}
/**
* <p>
* The creation date of the application version.
* </p>
*
* @param dateCreated
* The creation date of the application version.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ApplicationVersionDescription withDateCreated(
java.util.Date dateCreated) {
setDateCreated(dateCreated);
return this;
}
/**
* <p>
* The last modified date of the application version.
* </p>
*
* @param dateUpdated
* The last modified date of the application version.
*/
public void setDateUpdated(java.util.Date dateUpdated) {
this.dateUpdated = dateUpdated;
}
/**
* <p>
* The last modified date of the application version.
* </p>
*
* @return The last modified date of the application version.
*/
public java.util.Date getDateUpdated() {
return this.dateUpdated;
}
/**
* <p>
* The last modified date of the application version.
* </p>
*
* @param dateUpdated
* The last modified date of the application version.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ApplicationVersionDescription withDateUpdated(
java.util.Date dateUpdated) {
setDateUpdated(dateUpdated);
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 (getApplicationName() != null)
sb.append("ApplicationName: " + getApplicationName() + ",");
if (getDescription() != null)
sb.append("Description: " + getDescription() + ",");
if (getVersionLabel() != null)
sb.append("VersionLabel: " + getVersionLabel() + ",");
if (getSourceBundle() != null)
sb.append("SourceBundle: " + getSourceBundle() + ",");
if (getDateCreated() != null)
sb.append("DateCreated: " + getDateCreated() + ",");
if (getDateUpdated() != null)
sb.append("DateUpdated: " + getDateUpdated());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ApplicationVersionDescription == false)
return false;
ApplicationVersionDescription other = (ApplicationVersionDescription) obj;
if (other.getApplicationName() == null
^ this.getApplicationName() == null)
return false;
if (other.getApplicationName() != null
&& other.getApplicationName().equals(this.getApplicationName()) == false)
return false;
if (other.getDescription() == null ^ this.getDescription() == null)
return false;
if (other.getDescription() != null
&& other.getDescription().equals(this.getDescription()) == false)
return false;
if (other.getVersionLabel() == null ^ this.getVersionLabel() == null)
return false;
if (other.getVersionLabel() != null
&& other.getVersionLabel().equals(this.getVersionLabel()) == false)
return false;
if (other.getSourceBundle() == null ^ this.getSourceBundle() == null)
return false;
if (other.getSourceBundle() != null
&& other.getSourceBundle().equals(this.getSourceBundle()) == false)
return false;
if (other.getDateCreated() == null ^ this.getDateCreated() == null)
return false;
if (other.getDateCreated() != null
&& other.getDateCreated().equals(this.getDateCreated()) == false)
return false;
if (other.getDateUpdated() == null ^ this.getDateUpdated() == null)
return false;
if (other.getDateUpdated() != null
&& other.getDateUpdated().equals(this.getDateUpdated()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime
* hashCode
+ ((getApplicationName() == null) ? 0 : getApplicationName()
.hashCode());
hashCode = prime
* hashCode
+ ((getDescription() == null) ? 0 : getDescription().hashCode());
hashCode = prime
* hashCode
+ ((getVersionLabel() == null) ? 0 : getVersionLabel()
.hashCode());
hashCode = prime
* hashCode
+ ((getSourceBundle() == null) ? 0 : getSourceBundle()
.hashCode());
hashCode = prime
* hashCode
+ ((getDateCreated() == null) ? 0 : getDateCreated().hashCode());
hashCode = prime
* hashCode
+ ((getDateUpdated() == null) ? 0 : getDateUpdated().hashCode());
return hashCode;
}
@Override
public ApplicationVersionDescription clone() {
try {
return (ApplicationVersionDescription) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(
"Got a CloneNotSupportedException from Object.clone() "
+ "even though we're Cloneable!", e);
}
}
} | apache-2.0 |
qtekfun/htcDesire820Kernel | external/chromium_org/content/shell/android/linker_test_apk/src/org/chromium/content_linker_test_apk/LinkerTests.java | 2419 | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.content_linker_test_apk;
import android.util.Log;
import org.chromium.base.JNINamespace;
import org.chromium.content.app.Linker;
// A class that is only used in linker test APK to perform runtime checks
// in the current process.
@JNINamespace("content")
public class LinkerTests implements Linker.TestRunner {
private static final String TAG = "LinkerTests";
public LinkerTests() {}
public boolean runChecks(int memoryDeviceConfig,
boolean isBrowserProcess) {
boolean checkSharedRelro;
if (isBrowserProcess) {
switch (Linker.BROWSER_SHARED_RELRO_CONFIG) {
case Linker.BROWSER_SHARED_RELRO_CONFIG_NEVER:
checkSharedRelro = false;
break;
case Linker.BROWSER_SHARED_RELRO_CONFIG_LOW_RAM_ONLY:
// A shared RELRO should only be used on low-end devices.
checkSharedRelro =
(memoryDeviceConfig == Linker.MEMORY_DEVICE_CONFIG_LOW);
break;
case Linker.BROWSER_SHARED_RELRO_CONFIG_ALWAYS:
// Always check for a shared RELRO.
checkSharedRelro = true;
break;
default:
Log.e(TAG, "Invalid shared RELRO linker configuration: " +
Linker.BROWSER_SHARED_RELRO_CONFIG);
return false;
}
} else {
// Service processes should always use a shared RELRO section.
checkSharedRelro = true;
}
if (checkSharedRelro)
return nativeCheckForSharedRelros(isBrowserProcess);
else
return nativeCheckForNoSharedRelros(isBrowserProcess);
}
// Check that there are shared RELRO sections in the current process,
// and that they are properly mapped read-only. Returns true on success.
private static native boolean nativeCheckForSharedRelros(boolean isBrowserProcess);
// Check that there are no shared RELRO sections in the current process,
// return true on success.
private static native boolean nativeCheckForNoSharedRelros(boolean isBrowserProcess);
}
| gpl-2.0 |
md-5/jdk10 | test/jdk/java/lang/Math/HyperbolicTests.java | 58838 | /*
* Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4851625 4900189 4939441
* @summary Tests for {Math, StrictMath}.{sinh, cosh, tanh}
* @author Joseph D. Darcy
*/
public class HyperbolicTests {
private HyperbolicTests(){}
static final double NaNd = Double.NaN;
/**
* Test accuracy of {Math, StrictMath}.sinh. The specified
* accuracy is 2.5 ulps.
*
* The defintion of sinh(x) is
*
* (e^x - e^(-x))/2
*
* The series expansion of sinh(x) =
*
* x + x^3/3! + x^5/5! + x^7/7! +...
*
* Therefore,
*
* 1. For large values of x sinh(x) ~= signum(x)*exp(|x|)/2
*
* 2. For small values of x, sinh(x) ~= x.
*
* Additionally, sinh is an odd function; sinh(-x) = -sinh(x).
*
*/
static int testSinh() {
int failures = 0;
/*
* Array elements below generated using a quad sinh
* implementation. Rounded to a double, the quad result
* *should* be correctly rounded, unless we are quite unlucky.
* Assuming the quad value is a correctly rounded double, the
* allowed error is 3.0 ulps instead of 2.5 since the quad
* value rounded to double can have its own 1/2 ulp error.
*/
double [][] testCases = {
// x sinh(x)
{0.0625, 0.06254069805219182172183988501029229},
{0.1250, 0.12532577524111545698205754229137154},
{0.1875, 0.18860056562029018382047025055167585},
{0.2500, 0.25261231680816830791412515054205787},
{0.3125, 0.31761115611357728583959867611490292},
{0.3750, 0.38385106791361456875429567642050245},
{0.4375, 0.45159088610312053032509815226723017},
{0.5000, 0.52109530549374736162242562641149155},
{0.5625, 0.59263591611468777373870867338492247},
{0.6250, 0.66649226445661608227260655608302908},
{0.6875, 0.74295294580567543571442036910465007},
{0.7500, 0.82231673193582998070366163444691386},
{0.8125, 0.90489373856606433650504536421491368},
{0.8750, 0.99100663714429475605317427568995231},
{0.9375, 1.08099191569306394011007867453992548},
{1.0000, 1.17520119364380145688238185059560082},
{1.0625, 1.27400259579739321279181130344911907},
{1.1250, 1.37778219077984075760379987065228373},
{1.1875, 1.48694549961380717221109202361777593},
{1.2500, 1.60191908030082563790283030151221415},
{1.3125, 1.72315219460596010219069206464391528},
{1.3750, 1.85111856355791532419998548438506416},
{1.4375, 1.98631821852425112898943304217629457},
{1.5000, 2.12927945509481749683438749467763195},
{1.5625, 2.28056089740825247058075476705718764},
{1.6250, 2.44075368098794353221372986997161132},
{1.6875, 2.61048376261693140366028569794027603},
{1.7500, 2.79041436627764265509289122308816092},
{1.8125, 2.98124857471401377943765253243875520},
{1.8750, 3.18373207674259205101326780071803724},
{1.9375, 3.39865608104779099764440244167531810},
{2.0000, 3.62686040784701876766821398280126192},
{2.0625, 3.86923677050642806693938384073620450},
{2.1250, 4.12673225993027252260441410537905269},
{2.1875, 4.40035304533919660406976249684469164},
{2.2500, 4.69116830589833069188357567763552003},
{2.3125, 5.00031440855811351554075363240262157},
{2.3750, 5.32899934843284576394645856548481489},
{2.4375, 5.67850746906785056212578751630266858},
{2.5000, 6.05020448103978732145032363835040319},
{2.5625, 6.44554279850040875063706020260185553},
{2.6250, 6.86606721451642172826145238779845813},
{2.6875, 7.31342093738196587585692115636603571},
{2.7500, 7.78935201149073201875513401029935330},
{2.8125, 8.29572014785741787167717932988491961},
{2.8750, 8.83450399097893197351853322827892144},
{2.9375, 9.40780885043076394429977972921690859},
{3.0000, 10.01787492740990189897459361946582867},
{3.0625, 10.66708606836969224165124519209968368},
{3.1250, 11.35797907995166028304704128775698426},
{3.1875, 12.09325364161259019614431093344260209},
{3.2500, 12.87578285468067003959660391705481220},
{3.3125, 13.70862446906136798063935858393686525},
{3.3750, 14.59503283146163690015482636921657975},
{3.4375, 15.53847160182039311025096666980558478},
{3.5000, 16.54262728763499762495673152901249743},
{3.5625, 17.61142364906941482858466494889121694},
{3.6250, 18.74903703113232171399165788088277979},
{3.6875, 19.95991268283598684128844120984214675},
{3.7500, 21.24878212710338697364101071825171163},
{3.8125, 22.62068164929685091969259499078125023},
{3.8750, 24.08097197661255803883403419733891573},
{3.9375, 25.63535922523855307175060244757748997},
{4.0000, 27.28991719712775244890827159079382096},
{4.0625, 29.05111111351106713777825462100160185},
{4.1250, 30.92582287788986031725487699744107092},
{4.1875, 32.92137796722343190618721270937061472},
{4.2500, 35.04557405638942942322929652461901154},
{4.3125, 37.30671148776788628118833357170042385},
{4.3750, 39.71362570500944929025069048612806024},
{4.4375, 42.27572177772344954814418332587050658},
{4.5000, 45.00301115199178562180965680564371424},
{4.5625, 47.90615077031205065685078058248081891},
{4.6250, 50.99648471383193131253995134526177467},
{4.6875, 54.28608852959281437757368957713936555},
{4.7500, 57.78781641599226874961859781628591635},
{4.8125, 61.51535145084362283008545918273109379},
{4.8750, 65.48325905829987165560146562921543361},
{4.9375, 69.70704392356508084094318094283346381},
{5.0000, 74.20321057778875897700947199606456364},
{5.0625, 78.98932788987998983462810080907521151},
{5.1250, 84.08409771724448958901392613147384951},
{5.1875, 89.50742798369883598816307922895346849},
{5.2500, 95.28051047011540739630959111303975956},
{5.3125, 101.42590362176666730633859252034238987},
{5.3750, 107.96762069594029162704530843962700133},
{5.4375, 114.93122359426386042048760580590182604},
{5.5000, 122.34392274639096192409774240457730721},
{5.5625, 130.23468343534638291488502321709913206},
{5.6250, 138.63433897999898233879574111119546728},
{5.6875, 147.57571121692522056519568264304815790},
{5.7500, 157.09373875244884423880085377625986165},
{5.8125, 167.22561348600435888568183143777868662},
{5.8750, 178.01092593829229887752609866133883987},
{5.9375, 189.49181995209921964640216682906501778},
{6.0000, 201.71315737027922812498206768797872263},
{6.0625, 214.72269333437984291483666459592578915},
{6.1250, 228.57126288889537420461281285729970085},
{6.1875, 243.31297962030799867970551767086092471},
{6.2500, 259.00544710710289911522315435345489966},
{6.3125, 275.70998400700299790136562219920451185},
{6.3750, 293.49186366095654566861661249898332253},
{6.4375, 312.42056915013535342987623229485223434},
{6.5000, 332.57006480258443156075705566965111346},
{6.5625, 354.01908521044116928437570109827956007},
{6.6250, 376.85144288706511933454985188849781703},
{6.6875, 401.15635576625530823119100750634165252},
{6.7500, 427.02879582326538080306830640235938517},
{6.8125, 454.56986017986077163530945733572724452},
{6.8750, 483.88716614351897894746751705315210621},
{6.9375, 515.09527172439720070161654727225752288},
{7.0000, 548.31612327324652237375611757601851598},
{7.0625, 583.67953198942753384680988096024373270},
{7.1250, 621.32368116099280160364794462812762880},
{7.1875, 661.39566611888784148449430491465857519},
{7.2500, 704.05206901515336623551137120663358760},
{7.3125, 749.45957067108712382864538206200700256},
{7.3750, 797.79560188617531521347351754559776282},
{7.4375, 849.24903675279739482863565789325699416},
{7.5000, 904.02093068584652953510919038935849651},
{7.5625, 962.32530605113249628368993221570636328},
{7.6250, 1024.38998846242707559349318193113614698},
{7.6875, 1090.45749701500081956792547346904792325},
{7.7500, 1160.78599193425808533255719118417856088},
{7.8125, 1235.65028334242796895820912936318532502},
{7.8750, 1315.34290508508890654067255740428824014},
{7.9375, 1400.17525781352742299995139486063802583},
{8.0000, 1490.47882578955018611587663903188144796},
{8.0625, 1586.60647216744061169450001100145859236},
{8.1250, 1688.93381781440241350635231605477507900},
{8.1875, 1797.86070905726094477721128358866360644},
{8.2500, 1913.81278009067446281883262689250118009},
{8.3125, 2037.24311615199935553277163192983440062},
{8.3750, 2168.63402396170125867037749369723761636},
{8.4375, 2308.49891634734644432370720900969004306},
{8.5000, 2457.38431841538268239359965370719928775},
{8.5625, 2615.87200310986940554256648824234335262},
{8.6250, 2784.58126450289932429469130598902487336},
{8.6875, 2964.17133769964321637973459949999057146},
{8.7500, 3155.34397481384944060352507473513108710},
{8.8125, 3358.84618707947841898217318996045550438},
{8.8750, 3575.47316381333288862617411467285480067},
{8.9375, 3806.07137963459383403903729660349293583},
{9.0000, 4051.54190208278996051522359589803425598},
{9.0625, 4312.84391255878980330955246931164633615},
{9.1250, 4590.99845434696991399363282718106006883},
{9.1875, 4887.09242236403719571363798584676797558},
{9.2500, 5202.28281022453561319352901552085348309},
{9.3125, 5537.80123121853803935727335892054791265},
{9.3750, 5894.95873086734181634245918412592155656},
{9.4375, 6275.15090986233399457103055108344546942},
{9.5000, 6679.86337740502119410058225086262108741},
{9.5625, 7110.67755625726876329967852256934334025},
{9.6250, 7569.27686218510919585241049433331592115},
{9.6875, 8057.45328194243077504648484392156371121},
{9.7500, 8577.11437549816065709098061006273039092},
{9.8125, 9130.29072986829727910801024120918114778},
{9.8750, 9719.14389367880274015504995181862860062},
{9.9375, 10345.97482346383208590278839409938269134},
{10.0000, 11013.23287470339337723652455484636420303},
};
for(int i = 0; i < testCases.length; i++) {
double [] testCase = testCases[i];
failures += testSinhCaseWithUlpDiff(testCase[0],
testCase[1],
3.0);
}
double [][] specialTestCases = {
{0.0, 0.0},
{NaNd, NaNd},
{Double.longBitsToDouble(0x7FF0000000000001L), NaNd},
{Double.longBitsToDouble(0xFFF0000000000001L), NaNd},
{Double.longBitsToDouble(0x7FF8555555555555L), NaNd},
{Double.longBitsToDouble(0xFFF8555555555555L), NaNd},
{Double.longBitsToDouble(0x7FFFFFFFFFFFFFFFL), NaNd},
{Double.longBitsToDouble(0xFFFFFFFFFFFFFFFFL), NaNd},
{Double.longBitsToDouble(0x7FFDeadBeef00000L), NaNd},
{Double.longBitsToDouble(0xFFFDeadBeef00000L), NaNd},
{Double.longBitsToDouble(0x7FFCafeBabe00000L), NaNd},
{Double.longBitsToDouble(0xFFFCafeBabe00000L), NaNd},
{Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY}
};
for(int i = 0; i < specialTestCases.length; i++) {
failures += testSinhCaseWithUlpDiff(specialTestCases[i][0],
specialTestCases[i][1],
0.0);
}
// For powers of 2 less than 2^(-27), the second and
// subsequent terms of the Taylor series expansion will get
// rounded away since |n-n^3| > 53, the binary precision of a
// double significand.
for(int i = DoubleConsts.MIN_SUB_EXPONENT; i < -27; i++) {
double d = Math.scalb(2.0, i);
// Result and expected are the same.
failures += testSinhCaseWithUlpDiff(d, d, 2.5);
}
// For values of x larger than 22, the e^(-x) term is
// insignificant to the floating-point result. Util exp(x)
// overflows around 709.8, sinh(x) ~= exp(x)/2; will will test
// 10000 values in this range.
long trans22 = Double.doubleToLongBits(22.0);
// (approximately) largest value such that exp shouldn't
// overflow
long transExpOvfl = Double.doubleToLongBits(Math.nextDown(709.7827128933841));
for(long i = trans22;
i < transExpOvfl;
i +=(transExpOvfl-trans22)/10000) {
double d = Double.longBitsToDouble(i);
// Allow 3.5 ulps of error to deal with error in exp.
failures += testSinhCaseWithUlpDiff(d, StrictMath.exp(d)*0.5, 3.5);
}
// (approximately) largest value such that sinh shouldn't
// overflow.
long transSinhOvfl = Double.doubleToLongBits(710.4758600739439);
// Make sure sinh(x) doesn't overflow as soon as exp(x)
// overflows.
/*
* For large values of x, sinh(x) ~= 0.5*(e^x). Therefore,
*
* sinh(x) ~= e^(ln 0.5) * e^x = e^(x + ln 0.5)
*
* So, we can calculate the approximate expected result as
* exp(x + -0.693147186). However, this sum suffers from
* roundoff, limiting the accuracy of the approximation. The
* accuracy can be improved by recovering the rounded-off
* information. Since x is larger than ln(0.5), the trailing
* bits of ln(0.5) get rounded away when the two values are
* added. However, high-order bits of ln(0.5) that
* contribute to the sum can be found:
*
* offset = log(0.5);
* effective_offset = (x + offset) - x; // exact subtraction
* rounded_away_offset = offset - effective_offset; // exact subtraction
*
* Therefore, the product
*
* exp(x + offset)*exp(rounded_away_offset)
*
* will be a better approximation to the exact value of
*
* e^(x + offset)
*
* than exp(x+offset) alone. (The expected result cannot be
* computed as exp(x)*exp(offset) since exp(x) by itself would
* overflow to infinity.)
*/
double offset = StrictMath.log(0.5);
for(long i = transExpOvfl+1; i < transSinhOvfl;
i += (transSinhOvfl-transExpOvfl)/1000 ) {
double input = Double.longBitsToDouble(i);
double expected =
StrictMath.exp(input + offset) *
StrictMath.exp( offset - ((input + offset) - input) );
failures += testSinhCaseWithUlpDiff(input, expected, 4.0);
}
// sinh(x) overflows for values greater than 710; in
// particular, it overflows for all 2^i, i > 10.
for(int i = 10; i <= Double.MAX_EXPONENT; i++) {
double d = Math.scalb(2.0, i);
// Result and expected are the same.
failures += testSinhCaseWithUlpDiff(d,
Double.POSITIVE_INFINITY, 0.0);
}
return failures;
}
public static int testSinhCaseWithTolerance(double input,
double expected,
double tolerance) {
int failures = 0;
failures += Tests.testTolerance("Math.sinh(double)",
input, Math.sinh(input),
expected, tolerance);
failures += Tests.testTolerance("Math.sinh(double)",
-input, Math.sinh(-input),
-expected, tolerance);
failures += Tests.testTolerance("StrictMath.sinh(double)",
input, StrictMath.sinh(input),
expected, tolerance);
failures += Tests.testTolerance("StrictMath.sinh(double)",
-input, StrictMath.sinh(-input),
-expected, tolerance);
return failures;
}
public static int testSinhCaseWithUlpDiff(double input,
double expected,
double ulps) {
int failures = 0;
failures += Tests.testUlpDiff("Math.sinh(double)",
input, Math.sinh(input),
expected, ulps);
failures += Tests.testUlpDiff("Math.sinh(double)",
-input, Math.sinh(-input),
-expected, ulps);
failures += Tests.testUlpDiff("StrictMath.sinh(double)",
input, StrictMath.sinh(input),
expected, ulps);
failures += Tests.testUlpDiff("StrictMath.sinh(double)",
-input, StrictMath.sinh(-input),
-expected, ulps);
return failures;
}
/**
* Test accuracy of {Math, StrictMath}.cosh. The specified
* accuracy is 2.5 ulps.
*
* The defintion of cosh(x) is
*
* (e^x + e^(-x))/2
*
* The series expansion of cosh(x) =
*
* 1 + x^2/2! + x^4/4! + x^6/6! +...
*
* Therefore,
*
* 1. For large values of x cosh(x) ~= exp(|x|)/2
*
* 2. For small values of x, cosh(x) ~= 1.
*
* Additionally, cosh is an even function; cosh(-x) = cosh(x).
*
*/
static int testCosh() {
int failures = 0;
/*
* Array elements below generated using a quad cosh
* implementation. Rounded to a double, the quad result
* *should* be correctly rounded, unless we are quite unlucky.
* Assuming the quad value is a correctly rounded double, the
* allowed error is 3.0 ulps instead of 2.5 since the quad
* value rounded to double can have its own 1/2 ulp error.
*/
double [][] testCases = {
// x cosh(x)
{0.0625, 1.001953760865667607841550709632597376},
{0.1250, 1.007822677825710859846949685520422223},
{0.1875, 1.017629683800690526835115759894757615},
{0.2500, 1.031413099879573176159295417520378622},
{0.3125, 1.049226785060219076999158096606305793},
{0.3750, 1.071140346704586767299498015567016002},
{0.4375, 1.097239412531012567673453832328262160},
{0.5000, 1.127625965206380785226225161402672030},
{0.5625, 1.162418740845610783505338363214045218},
{0.6250, 1.201753692975606324229229064105075301},
{0.6875, 1.245784523776616395403056980542275175},
{0.7500, 1.294683284676844687841708185390181730},
{0.8125, 1.348641048647144208352285714214372703},
{0.8750, 1.407868656822803158638471458026344506},
{0.9375, 1.472597542369862933336886403008640891},
{1.0000, 1.543080634815243778477905620757061497},
{1.0625, 1.619593348374367728682469968448090763},
{1.1250, 1.702434658138190487400868008124755757},
{1.1875, 1.791928268324866464246665745956119612},
{1.2500, 1.888423877161015738227715728160051696},
{1.3125, 1.992298543335143985091891077551921106},
{1.3750, 2.103958159362661802010972984204389619},
{1.4375, 2.223839037619709260803023946704272699},
{1.5000, 2.352409615243247325767667965441644201},
{1.5625, 2.490172284559350293104864895029231913},
{1.6250, 2.637665356192137582275019088061812951},
{1.6875, 2.795465162524235691253423614360562624},
{1.7500, 2.964188309728087781773608481754531801},
{1.8125, 3.144494087167972176411236052303565201},
{1.8750, 3.337087043587520514308832278928116525},
{1.9375, 3.542719740149244276729383650503145346},
{2.0000, 3.762195691083631459562213477773746099},
{2.0625, 3.996372503438463642260225717607554880},
{2.1250, 4.246165228196992140600291052990934410},
{2.1875, 4.512549935859540340856119781585096760},
{2.2500, 4.796567530460195028666793366876218854},
{2.3125, 5.099327816921939817643745917141739051},
{2.3750, 5.422013837643509250646323138888569746},
{2.4375, 5.765886495263270945949271410819116399},
{2.5000, 6.132289479663686116619852312817562517},
{2.5625, 6.522654518468725462969589397439224177},
{2.6250, 6.938506971550673190999796241172117288},
{2.6875, 7.381471791406976069645686221095397137},
{2.7500, 7.853279872697439591457564035857305647},
{2.8125, 8.355774815752725814638234943192709129},
{2.8750, 8.890920130482709321824793617157134961},
{2.9375, 9.460806908834119747071078865866737196},
{3.0000, 10.067661995777765841953936035115890343},
{3.0625, 10.713856690753651225304006562698007312},
{3.1250, 11.401916013575067700373788969458446177},
{3.1875, 12.134528570998387744547733730974713055},
{3.2500, 12.914557062512392049483503752322408761},
{3.3125, 13.745049466398732213877084541992751273},
{3.3750, 14.629250949773302934853381428660210721},
{3.4375, 15.570616549147269180921654324879141947},
{3.5000, 16.572824671057316125696517821376119469},
{3.5625, 17.639791465519127930722105721028711044},
{3.6250, 18.775686128468677200079039891415789429},
{3.6875, 19.984947192985946987799359614758598457},
{3.7500, 21.272299872959396081877161903352144126},
{3.8125, 22.642774526961913363958587775566619798},
{3.8750, 24.101726314486257781049388094955970560},
{3.9375, 25.654856121347151067170940701379544221},
{4.0000, 27.308232836016486629201989612067059978},
{4.0625, 29.068317063936918520135334110824828950},
{4.1250, 30.941986372478026192360480044849306606},
{4.1875, 32.936562165180269851350626768308756303},
{4.2500, 35.059838290298428678502583470475012235},
{4.3125, 37.320111495433027109832850313172338419},
{4.3750, 39.726213847251883288518263854094284091},
{4.4375, 42.287547242982546165696077854963452084},
{4.5000, 45.014120148530027928305799939930642658},
{4.5625, 47.916586706774825161786212701923307169},
{4.6250, 51.006288368867753140854830589583165950},
{4.6875, 54.295298211196782516984520211780624960},
{4.7500, 57.796468111195389383795669320243166117},
{4.8125, 61.523478966332915041549750463563672435},
{4.8750, 65.490894152518731617237739112888213645},
{4.9375, 69.714216430810089539924900313140922323},
{5.0000, 74.209948524787844444106108044487704798},
{5.0625, 78.995657605307475581204965926043112946},
{5.1250, 84.090043934600961683400343038519519678},
{5.1875, 89.513013937957834087706670952561002466},
{5.2500, 95.285757988514588780586084642381131013},
{5.3125, 101.430833209098212357990123684449846912},
{5.3750, 107.972251614673824873137995865940755392},
{5.4375, 114.935573939814969189535554289886848550},
{5.5000, 122.348009517829425991091207107262038316},
{5.5625, 130.238522601820409078244923165746295574},
{5.6250, 138.637945543134998069351279801575968875},
{5.6875, 147.579099269447055276899288971207106581},
{5.7500, 157.096921533245353905868840194264636395},
{5.8125, 167.228603431860671946045256541679445836},
{5.8750, 178.013734732486824390148614309727161925},
{5.9375, 189.494458570056311567917444025807275896},
{6.0000, 201.715636122455894483405112855409538488},
{6.0625, 214.725021906554080628430756558271312513},
{6.1250, 228.573450380013557089736092321068279231},
{6.1875, 243.315034578039208138752165587134488645},
{6.2500, 259.007377561239126824465367865430519592},
{6.3125, 275.711797500835732516530131577254654076},
{6.3750, 293.493567280752348242602902925987643443},
{6.4375, 312.422169552825597994104814531010579387},
{6.5000, 332.571568241777409133204438572983297292},
{6.5625, 354.020497560858198165985214519757890505},
{6.6250, 376.852769667496146326030849450983914197},
{6.6875, 401.157602161123700280816957271992998156},
{6.7500, 427.029966702886171977469256622451185850},
{6.8125, 454.570960119471524953536004647195906721},
{6.8750, 483.888199441157626584508920036981010995},
{6.9375, 515.096242417696720610477570797503766179},
{7.0000, 548.317035155212076889964120712102928484},
{7.0625, 583.680388623257719787307547662358502345},
{7.1250, 621.324485894002926216918634755431456031},
{7.1875, 661.396422095589629755266517362992812037},
{7.2500, 704.052779189542208784574955807004218856},
{7.3125, 749.460237818184878095966335081928645934},
{7.3750, 797.796228612873763671070863694973560629},
{7.4375, 849.249625508044731271830060572510241864},
{7.5000, 904.021483770216677368692292389446994987},
{7.5625, 962.325825625814651122171697031114091993},
{7.6250, 1024.390476557670599008492465853663578558},
{7.6875, 1090.457955538048482588540574008226583335},
{7.7500, 1160.786422676798661020094043586456606003},
{7.8125, 1235.650687987597295222707689125107720568},
{7.8750, 1315.343285214046776004329388551335841550},
{7.9375, 1400.175614911635999247504386054087931958},
{8.0000, 1490.479161252178088627715460421007179728},
{8.0625, 1586.606787305415349050508956232945539108},
{8.1250, 1688.934113859132470361718199038326340668},
{8.1875, 1797.860987165547537276364148450577336075},
{8.2500, 1913.813041349231764486365114317586148767},
{8.3125, 2037.243361581700856522236313401822532385},
{8.3750, 2168.634254521568851112005905503069409349},
{8.4375, 2308.499132938297821208734949028296170563},
{8.5000, 2457.384521883751693037774022640629666294},
{8.5625, 2615.872194250713123494312356053193077854},
{8.6250, 2784.581444063104750127653362960649823247},
{8.6875, 2964.171506380845754878370650565756538203},
{8.7500, 3155.344133275174556354775488913749659006},
{8.8125, 3358.846335940117183452010789979584950102},
{8.8750, 3575.473303654961482727206202358956274888},
{8.9375, 3806.071511003646460448021740303914939059},
{9.0000, 4051.542025492594047194773093534725371440},
{9.0625, 4312.844028491571841588188869958240355518},
{9.1250, 4590.998563255739769060078863130940205710},
{9.1875, 4887.092524674358252509551443117048351290},
{9.2500, 5202.282906336187674588222835339193136030},
{9.3125, 5537.801321507079474415176386655744387251},
{9.3750, 5894.958815685577062811620236195525504885},
{9.4375, 6275.150989541692149890530417987358096221},
{9.5000, 6679.863452256851081801173722051940058824},
{9.5625, 7110.677626574055535297758456126491707647},
{9.6250, 7569.276928241617224537226019600213961572},
{9.6875, 8057.453343996777301036241026375049070162},
{9.7500, 8577.114433792824387959788368429252257664},
{9.8125, 9130.290784631065880205118262838330689429},
{9.8750, 9719.143945123662919857326995631317996715},
{9.9375, 10345.974871791805753327922796701684092861},
{10.0000, 11013.232920103323139721376090437880844591},
};
for(int i = 0; i < testCases.length; i++) {
double [] testCase = testCases[i];
failures += testCoshCaseWithUlpDiff(testCase[0],
testCase[1],
3.0);
}
double [][] specialTestCases = {
{0.0, 1.0},
{NaNd, NaNd},
{Double.longBitsToDouble(0x7FF0000000000001L), NaNd},
{Double.longBitsToDouble(0xFFF0000000000001L), NaNd},
{Double.longBitsToDouble(0x7FF8555555555555L), NaNd},
{Double.longBitsToDouble(0xFFF8555555555555L), NaNd},
{Double.longBitsToDouble(0x7FFFFFFFFFFFFFFFL), NaNd},
{Double.longBitsToDouble(0xFFFFFFFFFFFFFFFFL), NaNd},
{Double.longBitsToDouble(0x7FFDeadBeef00000L), NaNd},
{Double.longBitsToDouble(0xFFFDeadBeef00000L), NaNd},
{Double.longBitsToDouble(0x7FFCafeBabe00000L), NaNd},
{Double.longBitsToDouble(0xFFFCafeBabe00000L), NaNd},
{Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY}
};
for(int i = 0; i < specialTestCases.length; i++ ) {
failures += testCoshCaseWithUlpDiff(specialTestCases[i][0],
specialTestCases[i][1],
0.0);
}
// For powers of 2 less than 2^(-27), the second and
// subsequent terms of the Taylor series expansion will get
// rounded.
for(int i = DoubleConsts.MIN_SUB_EXPONENT; i < -27; i++) {
double d = Math.scalb(2.0, i);
// Result and expected are the same.
failures += testCoshCaseWithUlpDiff(d, 1.0, 2.5);
}
// For values of x larger than 22, the e^(-x) term is
// insignificant to the floating-point result. Util exp(x)
// overflows around 709.8, cosh(x) ~= exp(x)/2; will will test
// 10000 values in this range.
long trans22 = Double.doubleToLongBits(22.0);
// (approximately) largest value such that exp shouldn't
// overflow
long transExpOvfl = Double.doubleToLongBits(Math.nextDown(709.7827128933841));
for(long i = trans22;
i < transExpOvfl;
i +=(transExpOvfl-trans22)/10000) {
double d = Double.longBitsToDouble(i);
// Allow 3.5 ulps of error to deal with error in exp.
failures += testCoshCaseWithUlpDiff(d, StrictMath.exp(d)*0.5, 3.5);
}
// (approximately) largest value such that cosh shouldn't
// overflow.
long transCoshOvfl = Double.doubleToLongBits(710.4758600739439);
// Make sure sinh(x) doesn't overflow as soon as exp(x)
// overflows.
/*
* For large values of x, cosh(x) ~= 0.5*(e^x). Therefore,
*
* cosh(x) ~= e^(ln 0.5) * e^x = e^(x + ln 0.5)
*
* So, we can calculate the approximate expected result as
* exp(x + -0.693147186). However, this sum suffers from
* roundoff, limiting the accuracy of the approximation. The
* accuracy can be improved by recovering the rounded-off
* information. Since x is larger than ln(0.5), the trailing
* bits of ln(0.5) get rounded away when the two values are
* added. However, high-order bits of ln(0.5) that
* contribute to the sum can be found:
*
* offset = log(0.5);
* effective_offset = (x + offset) - x; // exact subtraction
* rounded_away_offset = offset - effective_offset; // exact subtraction
*
* Therefore, the product
*
* exp(x + offset)*exp(rounded_away_offset)
*
* will be a better approximation to the exact value of
*
* e^(x + offset)
*
* than exp(x+offset) alone. (The expected result cannot be
* computed as exp(x)*exp(offset) since exp(x) by itself would
* overflow to infinity.)
*/
double offset = StrictMath.log(0.5);
for(long i = transExpOvfl+1; i < transCoshOvfl;
i += (transCoshOvfl-transExpOvfl)/1000 ) {
double input = Double.longBitsToDouble(i);
double expected =
StrictMath.exp(input + offset) *
StrictMath.exp( offset - ((input + offset) - input) );
failures += testCoshCaseWithUlpDiff(input, expected, 4.0);
}
// cosh(x) overflows for values greater than 710; in
// particular, it overflows for all 2^i, i > 10.
for(int i = 10; i <= Double.MAX_EXPONENT; i++) {
double d = Math.scalb(2.0, i);
// Result and expected are the same.
failures += testCoshCaseWithUlpDiff(d,
Double.POSITIVE_INFINITY, 0.0);
}
return failures;
}
public static int testCoshCaseWithTolerance(double input,
double expected,
double tolerance) {
int failures = 0;
failures += Tests.testTolerance("Math.cosh(double)",
input, Math.cosh(input),
expected, tolerance);
failures += Tests.testTolerance("Math.cosh(double)",
-input, Math.cosh(-input),
expected, tolerance);
failures += Tests.testTolerance("StrictMath.cosh(double)",
input, StrictMath.cosh(input),
expected, tolerance);
failures += Tests.testTolerance("StrictMath.cosh(double)",
-input, StrictMath.cosh(-input),
expected, tolerance);
return failures;
}
public static int testCoshCaseWithUlpDiff(double input,
double expected,
double ulps) {
int failures = 0;
failures += Tests.testUlpDiff("Math.cosh(double)",
input, Math.cosh(input),
expected, ulps);
failures += Tests.testUlpDiff("Math.cosh(double)",
-input, Math.cosh(-input),
expected, ulps);
failures += Tests.testUlpDiff("StrictMath.cosh(double)",
input, StrictMath.cosh(input),
expected, ulps);
failures += Tests.testUlpDiff("StrictMath.cosh(double)",
-input, StrictMath.cosh(-input),
expected, ulps);
return failures;
}
/**
* Test accuracy of {Math, StrictMath}.tanh. The specified
* accuracy is 2.5 ulps.
*
* The defintion of tanh(x) is
*
* (e^x - e^(-x))/(e^x + e^(-x))
*
* The series expansion of tanh(x) =
*
* x - x^3/3 + 2x^5/15 - 17x^7/315 + ...
*
* Therefore,
*
* 1. For large values of x tanh(x) ~= signum(x)
*
* 2. For small values of x, tanh(x) ~= x.
*
* Additionally, tanh is an odd function; tanh(-x) = -tanh(x).
*
*/
static int testTanh() {
int failures = 0;
/*
* Array elements below generated using a quad sinh
* implementation. Rounded to a double, the quad result
* *should* be correctly rounded, unless we are quite unlucky.
* Assuming the quad value is a correctly rounded double, the
* allowed error is 3.0 ulps instead of 2.5 since the quad
* value rounded to double can have its own 1/2 ulp error.
*/
double [][] testCases = {
// x tanh(x)
{0.0625, 0.06241874674751251449014289119421133},
{0.1250, 0.12435300177159620805464727580589271},
{0.1875, 0.18533319990813951753211997502482787},
{0.2500, 0.24491866240370912927780113149101697},
{0.3125, 0.30270972933210848724239738970991712},
{0.3750, 0.35835739835078594631936023155315807},
{0.4375, 0.41157005567402245143207555859415687},
{0.5000, 0.46211715726000975850231848364367256},
{0.5625, 0.50982997373525658248931213507053130},
{0.6250, 0.55459972234938229399903909532308371},
{0.6875, 0.59637355547924233984437303950726939},
{0.7500, 0.63514895238728731921443435731249638},
{0.8125, 0.67096707420687367394810954721913358},
{0.8750, 0.70390560393662106058763026963135371},
{0.9375, 0.73407151960434149263991588052503660},
{1.0000, 0.76159415595576488811945828260479366},
{1.0625, 0.78661881210869761781941794647736081},
{1.1250, 0.80930107020178101206077047354332696},
{1.1875, 0.82980190998595952708572559629034476},
{1.2500, 0.84828363995751289761338764670750445},
{1.3125, 0.86490661772074179125443141102709751},
{1.3750, 0.87982669965198475596055310881018259},
{1.4375, 0.89319334040035153149249598745889365},
{1.5000, 0.90514825364486643824230369645649557},
{1.5625, 0.91582454416876231820084311814416443},
{1.6250, 0.92534622531174107960457166792300374},
{1.6875, 0.93382804322259173763570528576138652},
{1.7500, 0.94137553849728736226942088377163687},
{1.8125, 0.94808528560440629971240651310180052},
{1.8750, 0.95404526017994877009219222661968285},
{1.9375, 0.95933529331468249183399461756952555},
{2.0000, 0.96402758007581688394641372410092317},
{2.0625, 0.96818721657637057702714316097855370},
{2.1250, 0.97187274591350905151254495374870401},
{2.1875, 0.97513669829362836159665586901156483},
{2.2500, 0.97802611473881363992272924300618321},
{2.3125, 0.98058304703705186541999427134482061},
{2.3750, 0.98284502917257603002353801620158861},
{2.4375, 0.98484551746427837912703608465407824},
{2.5000, 0.98661429815143028888127603923734964},
{2.5625, 0.98817786228751240824802592958012269},
{2.6250, 0.98955974861288320579361709496051109},
{2.6875, 0.99078085564125158320311117560719312},
{2.7500, 0.99185972456820774534967078914285035},
{2.8125, 0.99281279483715982021711715899682324},
{2.8750, 0.99365463431502962099607366282699651},
{2.9375, 0.99439814606575805343721743822723671},
{3.0000, 0.99505475368673045133188018525548849},
{3.0625, 0.99563456710930963835715538507891736},
{3.1250, 0.99614653067334504917102591131792951},
{3.1875, 0.99659855517712942451966113109487039},
{3.2500, 0.99699763548652601693227592643957226},
{3.3125, 0.99734995516557367804571991063376923},
{3.3750, 0.99766097946988897037219469409451602},
{3.4375, 0.99793553792649036103161966894686844},
{3.5000, 0.99817789761119870928427335245061171},
{3.5625, 0.99839182812874152902001617480606320},
{3.6250, 0.99858065920179882368897879066418294},
{3.6875, 0.99874733168378115962760304582965538},
{3.7500, 0.99889444272615280096784208280487888},
{3.8125, 0.99902428575443546808677966295308778},
{3.8750, 0.99913888583735077016137617231569011},
{3.9375, 0.99924003097049627100651907919688313},
{4.0000, 0.99932929973906704379224334434172499},
{4.0625, 0.99940808577297384603818654530731215},
{4.1250, 0.99947761936180856115470576756499454},
{4.1875, 0.99953898655601372055527046497863955},
{4.2500, 0.99959314604388958696521068958989891},
{4.3125, 0.99964094406130644525586201091350343},
{4.3750, 0.99968312756179494813069349082306235},
{4.4375, 0.99972035584870534179601447812936151},
{4.5000, 0.99975321084802753654050617379050162},
{4.5625, 0.99978220617994689112771768489030236},
{4.6250, 0.99980779516900105210240981251048167},
{4.6875, 0.99983037791655283849546303868853396},
{4.7500, 0.99985030754497877753787358852000255},
{4.8125, 0.99986789571029070417475400133989992},
{4.8750, 0.99988341746867772271011794614780441},
{4.9375, 0.99989711557251558205051185882773206},
{5.0000, 0.99990920426259513121099044753447306},
{5.0625, 0.99991987261554158551063867262784721},
{5.1250, 0.99992928749851651137225712249720606},
{5.1875, 0.99993759617721206697530526661105307},
{5.2500, 0.99994492861777083305830639416802036},
{5.3125, 0.99995139951851344080105352145538345},
{5.3750, 0.99995711010315817210152906092289064},
{5.4375, 0.99996214970350792531554669737676253},
{5.5000, 0.99996659715630380963848952941756868},
{5.5625, 0.99997052203605101013786592945475432},
{5.6250, 0.99997398574306704793434088941484766},
{5.6875, 0.99997704246374583929961850444364696},
{5.7500, 0.99997974001803825215761760428815437},
{5.8125, 0.99998212060739040166557477723121777},
{5.8750, 0.99998422147482750993344503195672517},
{5.9375, 0.99998607548749972326220227464612338},
{6.0000, 0.99998771165079557056434885235523206},
{6.0625, 0.99998915556205996764518917496149338},
{6.1250, 0.99999042981101021976277974520745310},
{6.1875, 0.99999155433311068015449574811497719},
{6.2500, 0.99999254672143162687722782398104276},
{6.3125, 0.99999342250186907900400800240980139},
{6.3750, 0.99999419537602957780612639767025158},
{6.4375, 0.99999487743557848265406225515388994},
{6.5000, 0.99999547935140419285107893831698753},
{6.5625, 0.99999601054055694588617385671796346},
{6.6250, 0.99999647931357331502887600387959900},
{6.6875, 0.99999689300449080997594368612277442},
{6.7500, 0.99999725808558628431084200832778748},
{6.8125, 0.99999758026863294516387464046135924},
{6.8750, 0.99999786459425991170635407313276785},
{6.9375, 0.99999811551081218572759991597586905},
{7.0000, 0.99999833694394467173571641595066708},
{7.0625, 0.99999853235803894918375164252059190},
{7.1250, 0.99999870481040359014665019356422927},
{7.1875, 0.99999885699910593255108365463415411},
{7.2500, 0.99999899130518359709674536482047025},
{7.3125, 0.99999910982989611769943303422227663},
{7.3750, 0.99999921442759946591163427422888252},
{7.4375, 0.99999930673475777603853435094943258},
{7.5000, 0.99999938819554614875054970643513124},
{7.5625, 0.99999946008444508183970109263856958},
{7.6250, 0.99999952352618001331402589096040117},
{7.6875, 0.99999957951331792817413683491979752},
{7.7500, 0.99999962892179632633374697389145081},
{7.8125, 0.99999967252462750190604116210421169},
{7.8750, 0.99999971100399253750324718031574484},
{7.9375, 0.99999974496191422474977283863588658},
{8.0000, 0.99999977492967588981001883295636840},
{8.0625, 0.99999980137613348259726597081723424},
{8.1250, 0.99999982471505097353529823063673263},
{8.1875, 0.99999984531157382142423402736529911},
{8.2500, 0.99999986348794179107425910499030547},
{8.3125, 0.99999987952853049895833839645847571},
{8.3750, 0.99999989368430056302584289932834041},
{8.4375, 0.99999990617672396471542088609051728},
{8.5000, 0.99999991720124905211338798152800748},
{8.5625, 0.99999992693035839516545287745322387},
{8.6250, 0.99999993551626733394129009365703767},
{8.6875, 0.99999994309330543951799157347876934},
{8.7500, 0.99999994978001814614368429416607424},
{8.8125, 0.99999995568102143535399207289008504},
{8.8750, 0.99999996088863858914831986187674522},
{8.9375, 0.99999996548434461974481685677429908},
{9.0000, 0.99999996954004097447930211118358244},
{9.0625, 0.99999997311918045901919121395899372},
{9.1250, 0.99999997627775997868467948564005257},
{9.1875, 0.99999997906519662964368381583648379},
{9.2500, 0.99999998152510084671976114264303159},
{9.3125, 0.99999998369595870397054673668361266},
{9.3750, 0.99999998561173404286033236040150950},
{9.4375, 0.99999998730239984852716512979473289},
{9.5000, 0.99999998879440718770812040917618843},
{9.5625, 0.99999999011109904501789298212541698},
{9.6250, 0.99999999127307553219220251303121960},
{9.6875, 0.99999999229851618412119275358396363},
{9.7500, 0.99999999320346438410630581726217930},
{9.8125, 0.99999999400207836827291739324060736},
{9.8750, 0.99999999470685273619047001387577653},
{9.9375, 0.99999999532881393331131526966058758},
{10.0000, 0.99999999587769276361959283713827574},
};
for(int i = 0; i < testCases.length; i++) {
double [] testCase = testCases[i];
failures += testTanhCaseWithUlpDiff(testCase[0],
testCase[1],
3.0);
}
double [][] specialTestCases = {
{0.0, 0.0},
{NaNd, NaNd},
{Double.longBitsToDouble(0x7FF0000000000001L), NaNd},
{Double.longBitsToDouble(0xFFF0000000000001L), NaNd},
{Double.longBitsToDouble(0x7FF8555555555555L), NaNd},
{Double.longBitsToDouble(0xFFF8555555555555L), NaNd},
{Double.longBitsToDouble(0x7FFFFFFFFFFFFFFFL), NaNd},
{Double.longBitsToDouble(0xFFFFFFFFFFFFFFFFL), NaNd},
{Double.longBitsToDouble(0x7FFDeadBeef00000L), NaNd},
{Double.longBitsToDouble(0xFFFDeadBeef00000L), NaNd},
{Double.longBitsToDouble(0x7FFCafeBabe00000L), NaNd},
{Double.longBitsToDouble(0xFFFCafeBabe00000L), NaNd},
{Double.POSITIVE_INFINITY, 1.0}
};
for(int i = 0; i < specialTestCases.length; i++) {
failures += testTanhCaseWithUlpDiff(specialTestCases[i][0],
specialTestCases[i][1],
0.0);
}
// For powers of 2 less than 2^(-27), the second and
// subsequent terms of the Taylor series expansion will get
// rounded away since |n-n^3| > 53, the binary precision of a
// double significand.
for(int i = DoubleConsts.MIN_SUB_EXPONENT; i < -27; i++) {
double d = Math.scalb(2.0, i);
// Result and expected are the same.
failures += testTanhCaseWithUlpDiff(d, d, 2.5);
}
// For values of x larger than 22, tanh(x) is 1.0 in double
// floating-point arithmetic.
for(int i = 22; i < 32; i++) {
failures += testTanhCaseWithUlpDiff(i, 1.0, 2.5);
}
for(int i = 5; i <= Double.MAX_EXPONENT; i++) {
double d = Math.scalb(2.0, i);
failures += testTanhCaseWithUlpDiff(d, 1.0, 2.5);
}
return failures;
}
public static int testTanhCaseWithTolerance(double input,
double expected,
double tolerance) {
int failures = 0;
failures += Tests.testTolerance("Math.tanh(double",
input, Math.tanh(input),
expected, tolerance);
failures += Tests.testTolerance("Math.tanh(double",
-input, Math.tanh(-input),
-expected, tolerance);
failures += Tests.testTolerance("StrictMath.tanh(double",
input, StrictMath.tanh(input),
expected, tolerance);
failures += Tests.testTolerance("StrictMath.tanh(double",
-input, StrictMath.tanh(-input),
-expected, tolerance);
return failures;
}
public static int testTanhCaseWithUlpDiff(double input,
double expected,
double ulps) {
int failures = 0;
failures += Tests.testUlpDiffWithAbsBound("Math.tanh(double)",
input, Math.tanh(input),
expected, ulps, 1.0);
failures += Tests.testUlpDiffWithAbsBound("Math.tanh(double)",
-input, Math.tanh(-input),
-expected, ulps, 1.0);
failures += Tests.testUlpDiffWithAbsBound("StrictMath.tanh(double)",
input, StrictMath.tanh(input),
expected, ulps, 1.0);
failures += Tests.testUlpDiffWithAbsBound("StrictMath.tanh(double)",
-input, StrictMath.tanh(-input),
-expected, ulps, 1.0);
return failures;
}
public static void main(String argv[]) {
int failures = 0;
failures += testSinh();
failures += testCosh();
failures += testTanh();
if (failures > 0) {
System.err.println("Testing the hyperbolic functions incurred "
+ failures + " failures.");
throw new RuntimeException();
}
}
}
| gpl-2.0 |
saivarunr/zemoso-training | whatsapp_project/whatsapp/test/IntegrationTest.java | 644 | import org.junit.*;
import play.mvc.*;
import play.test.*;
import static play.test.Helpers.*;
import static org.junit.Assert.*;
import static org.fluentlenium.core.filter.FilterConstructor.*;
public class IntegrationTest {
/**
* add your integration test here
* in this example we just check if the welcome page is being shown
*/
@Test
public void test() {
running(testServer(3333, fakeApplication(inMemoryDatabase())), HTMLUNIT, browser -> {
browser.goTo("http://localhost:3333");
assertTrue(browser.pageSource().contains("Your new application is ready."));
});
}
}
| apache-2.0 |
wangcy6/storm_app | frame/kafka-0.11.0/kafka-0.11.0.1-src/clients/src/main/java/org/apache/kafka/common/errors/ReplicaNotAvailableException.java | 1252 | /*
* 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.kafka.common.errors;
public class ReplicaNotAvailableException extends ApiException {
private static final long serialVersionUID = 1L;
public ReplicaNotAvailableException(String message) {
super(message);
}
public ReplicaNotAvailableException(String message, Throwable cause) {
super(message, cause);
}
public ReplicaNotAvailableException(Throwable cause) {
super(cause);
}
}
| apache-2.0 |
thejeshgn/sl4a | android/QuickAction/src/net/londatiga/android/ActionItem.java | 1583 | package net.londatiga.android;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.View.OnClickListener;
/**
* Action item, displayed as menu with icon and text.
*
* @author Lorensius. W. L. T
*
*/
public class ActionItem {
private Drawable icon;
private String title;
private OnClickListener listener;
/**
* Constructor
*/
public ActionItem() {
}
/**
* Constructor
*
* @param icon {@link Drawable} action icon
*/
public ActionItem(Drawable icon) {
this.icon = icon;
}
/**
* Set action title
*
* @param title action title
*/
public void setTitle(String title) {
this.title = title;
}
/**
* Get action title
*
* @return action title
*/
public String getTitle() {
return this.title;
}
/**
* Set action icon
*
* @param icon {@link Drawable} action icon
*/
public void setIcon(Drawable icon) {
this.icon = icon;
}
/**
* Get action icon
*
* @return {@link Drawable} action icon
*/
public Drawable getIcon() {
return this.icon;
}
/**
* Set on click listener
*
* @param listener on click listener {@link View.OnClickListener}
*/
public void setOnClickListener(OnClickListener listener) {
this.listener = listener;
}
/**
* Get on click listener
*
* @return on click listener {@link View.OnClickListener}
*/
public OnClickListener getListener() {
return this.listener;
}
}
| apache-2.0 |
aakashysharma/opengse | engines/minigse/java/com/google/opengse/parser/Chset.java | 15420 | // Copyright 2007 Google Inc. 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.
package com.google.opengse.parser;
import java.util.ArrayList;
import java.util.BitSet;
/**
* The {@code Chset} (character set) parser matches the current character
* in the parse buffer against an arbitrary character set. The character set is
* represented as a sorted array of ranges for which a match should be
* successful. Matching takes O(log nranges) time. There are predefined
* character sets for matching any character ({@code ANYCHAR}), no
* characters ({@code NOTHING}) and some standard 7-bit ASCII ranges
* ({@code ALNUM}, {@code ALPHA}, {@code DIGIT},
* {@code XDIGIT}, {@code LOWER}, {@code UPPER},
* {@code WHITESPACE}), and {@code ASCII}.
*
* Note that the character set parser only matches a single character of the
* parse buffer. The {@code Sequence} or }Repeat} parsers need
* to be used to match more than one character.
*
* The following matches vowels and digits:
* <pre> {@code
* Parser p = new Chset("uoiea0-9");
* p.parse("a") -> matches "a"
* p.parse("3") -> matches "3"
* p.parse("b") -> no match
* } </pre>
*
* @see Parser
* @author Peter Mattis
*/
public final class Chset extends Parser<Object> implements Cloneable {
protected static final char MIN_CHAR = 0;
protected static final char MAX_CHAR = 65535;
private static final char MAX_ASCII_CHAR = 127;
public static final Chset ANYCHAR = new Chset(MIN_CHAR, MAX_CHAR);
public static final Chset NOTHING = new Chset();
public static final Chset ALNUM = new Chset("a-zA-Z0-9");
public static final Chset ALPHA = new Chset("a-zA-Z");
public static final Chset DIGIT = new Chset("0-9");
public static final Chset XDIGIT = new Chset("0-9a-fA-F");
public static final Chset LOWER = new Chset("a-z");
public static final Chset UPPER = new Chset("A-Z");
public static final Chset WHITESPACE = new Chset(" \t\r\n\f");
public static final Chset ASCII = new Chset(MIN_CHAR, MAX_ASCII_CHAR);
private final ArrayList<Range> ranges = new ArrayList<Range>();
/**
* A secondary representation for ASCII members of the character set.
* Maintaining this bitmap allows us to check ASCII characters for set
* membership quickly.
*/
private final BitSet asciiSet = new BitSet(MAX_ASCII_CHAR + 1);
/**
* Class constructor for an empty character set.
*/
public Chset() {
super();
}
/**
* Class constructor for a character literal.
*
* @param ch The character literal for this character set to match against.
*/
public Chset(char ch) {
this(ch, ch);
}
/**
* Class constructor for a single character range. The range is inclusive:
* all character including {@code min} and {@code max} match.
*
* @param min The beginning of the character range.
* @param max The end of the character range.
*/
public Chset(char min, char max) {
super();
ranges.add(new Range(min, max));
refreshAsciiSet();
}
/**
* Class constructor that initializes a {@code Chset} from a string
* specification.
*
* @param spec The string specification to initialize the {@code Chset}
* from.
*/
public Chset(String spec) {
for (int i = 0; i < spec.length();) {
final char s = spec.charAt(i);
if ((i + 1) < spec.length()) {
final char n = spec.charAt(i + 1);
if (n == '-') {
if ((i + 2) < spec.length()) {
final char e = spec.charAt(i + 2);
set(new Range(s, e));
i += 3;
continue;
} else {
set(new Range(s, s));
set(new Range('-', '-'));
break;
}
}
}
set(new Range(s, s));
i += 1;
}
}
/**
* Returns a clone character set of {@code this}.
*/
@Override
public Chset clone() {
Chset n = new Chset();
for (Range r : ranges) {
n.ranges.add(new Range(r.first, r.last));
}
return n;
}
/**
* Matches {@code buf[start]} against the character set.
*
* @see Parser#parse
*/
@Override
public int parse(char[] buf, int start, int end, Object data) {
if ((start < end) && checkInCharacterSet(buf[start])) {
return 1;
}
return NO_MATCH;
}
/**
* Tests to see if a single character matches the character set.
*
* @param ch The character to test.
*/
public boolean checkInCharacterSet(char ch) {
if (ch <= MAX_ASCII_CHAR) {
return asciiSet.get(ch);
}
return checkInRanges(ch);
}
/**
* Tests to see if a single character matches the character set, but only
* looks at the ranges representation.
*
* @param ch The character to test.
*/
protected boolean checkInRanges(char ch) {
int rangeSize = ranges.size();
if (rangeSize == 0) {
return false;
} else if (rangeSize == 1) {
// Optimization for a common simple case -- we don't need to do a find().
return ranges.get(0).includes(ch);
} else {
int pos = find(ch);
// We need to test both the range at the position the character would be
// inserted at and the preceding range due to the semantics of find().
// For example, if the Chset contains a single range of [10-19], then
// find() will return 1 for the range [11-11] and we'll want to test
// against 'pos - 1'.
if ((pos != rangeSize) && ranges.get(pos).includes(ch)) {
return true;
}
if ((pos != 0) && ranges.get(pos - 1).includes(ch)) {
return true;
}
return false;
}
}
/**
* @see #set(Range)
*/
protected void set(char min, char max) {
set(new Range(min, max));
}
/**
* Sets the specified range of characters in the character set so that
* subsequent calls to {@code test} for characters within the range will
* return {@code true}.
*
* @see #union
*/
private void set(Range r) {
if (ranges.isEmpty()) {
ranges.add(r);
refreshAsciiSet();
return;
}
int pos = find(r.first);
if (((pos != ranges.size()) && ranges.get(pos).includes(r)) ||
((pos != 0) && ranges.get(pos - 1).includes(r))) {
return;
}
if ((pos != 0) && ranges.get(pos - 1).mergeable(r)) {
merge(pos - 1, r);
} else if ((pos != ranges.size()) && ranges.get(pos).mergeable(r)) {
merge(pos, r);
} else {
ranges.add(pos, r);
}
refreshAsciiSet();
}
/**
* @see #clear(Range)
*/
protected void clear(char min, char max) {
clear(new Range(min, max));
}
/**
* Clears the specified range of characters from the character set so that
* subsequent calls to {@code test} for characters within the range will
* return {@code false}.
*
* @see #difference(Chset, Chset)
*/
private void clear(Range r) {
if (ranges.isEmpty()) {
return;
}
int pos = find(r.first);
if (pos > 0) {
Range prev = ranges.get(pos - 1);
if (prev.includes(r.first)) {
if (prev.last > r.last) {
Range n = new Range(r.last + 1, prev.last);
prev.last = r.first - 1;
ranges.add(pos, n);
refreshAsciiSet();
return;
} else {
prev.last = r.first - 1;
}
}
}
while ((pos < ranges.size()) && r.includes(ranges.get(pos))) {
ranges.remove(pos);
}
if ((pos < ranges.size()) && ranges.get(pos).includes(r.last)) {
ranges.get(pos).first = r.last + 1;
}
refreshAsciiSet();
}
/**
* Reconstructs the BitSet representation of the ASCII characters in the
* set, so that it matches what's stored in ranges.
*/
private void refreshAsciiSet() {
asciiSet.clear();
for (char ch = MIN_CHAR; ch <= MAX_ASCII_CHAR; ch++) {
if (checkInRanges(ch)) {
asciiSet.set(ch);
}
}
}
/**
* Returns the size of the range array.
*/
protected int size() {
return ranges.size();
}
/**
* Find the position in the range array for which the beginning of the
* specified range is greater than or equal to the range at that position. In
* other words, it returns the insertion point for the specified range.
*
* @param first The start of the range to find the insertion point for.
*
* @see #checkInCharacterSet(char)
* @see #set(char, char)
* @see #clear(char, char)
* @see java.util.Arrays#binarySearch(char[], char)
*/
private int find(int first) {
int s = 0;
int e = ranges.size() - 1;
while (s <= e) {
int m = (s + e) / 2; // equivalent to: m = s + (e - s) / 2;
Range r = ranges.get(m);
if (r.first < first) {
s = m + 1;
} else if (r.first > first) {
e = m - 1;
} else {
return m;
}
}
return s;
}
/**
* Merge the specified range with the range at the specified position in the
* range array. After performing the merge operation, we iterate down the
* range array and continue merging any newly mergeable ranges. The specified
* range and the range at the specified position in the range array must be
* mergeable.
*
* @see #set(Range)
* @see #clear(Range)
*/
private void merge(int pos, Range r) {
Range t = ranges.get(pos);
t.merge(r);
pos += 1;
while ((pos < ranges.size()) && t.mergeable(ranges.get(pos))) {
t.merge(ranges.get(pos));
ranges.remove(pos);
}
}
/**
* Creates a new character set which matches a character if that character
* does not match the {@code subject} character set. This operation is
* implemented by taking the difference of the {@code ANYCHAR} character
* set and the {@code subject} character set.
* <pre>
* ~subject --> anychar - subject
* </pre>
*
* @param subject The source character set.
*/
public static Chset not(Chset subject) {
return difference(ANYCHAR, subject);
}
/**
* Creates a new character set which matches a character if that character
* matches either the {@code left} or {@code right} character sets.
*
* left | right
*
*
* @param left The left source character set.
*
* @param right The right source character set.
*/
public static Chset union(Chset left, Chset right) {
Chset n = left.clone();
for (Range r : right.ranges) {
n.set(r);
}
return n;
}
/**
* Creates a new character set which matches a character if that character
* matches the {@code left} character set but does not match the
* {@code right} character set.
*
* left - right
*
* @param left The left source character set.
*
* @param right The right source character set.
*/
public static Chset difference(Chset left, Chset right) {
Chset n = left.clone();
for (Range r : right.ranges) {
n.clear(r);
}
return n;
}
/**
* Creates a new character set which matches a character if that character
* matches both the {@code left} and {@code right} character sets.
*
* left & right --> left - ~right
*
* @param left The left source character set.
*
* @param right The right source character set.
*/
public static Chset intersection(Chset left, Chset right) {
return difference(left, not(right));
}
/**
* Creates a new character set which matches a character if that character
* matches the {@code left} character set or the {@code right}
* character set, but not both.
*
* left ^ right --> (left - right) | (right - left)
*
* @param left The left source character set.
*
* @param right The right source character set.
*/
public static Chset xor(Chset left, Chset right) {
return union(difference(left, right), difference(right, left));
}
@Override
public String toString() {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < ranges.size(); i++) {
Range r = ranges.get(i);
if (i > 0) {
buf.append(" ");
}
buf.append(r.first);
buf.append("-");
buf.append(r.last);
}
return buf.toString();
}
/**
* The {@code Range} class represents a range from
* {@code [first,last]}. It is used by the {@code Chset} class to
* implement character sets for large alphabets where a bitmap based approach
* would be too expensive in terms of memory. The {@code first} and
* {@code last} member variables are specified as integers to avoid
* casting that would be necessary if they were specified as characters due to
* java's type promotion rules.
*
* @author Peter Mattis
*/
static class Range {
int first;
int last;
/**
* Class constructor.
*
* @param first The beginning of the range.
*
* @param last The end of the range.
*/
Range(int first, int last) {
if (first > last) {
throw new IllegalArgumentException("descending ranges not supported: " +
first + "-" + last);
}
this.first = first;
this.last = last;
}
/**
* Tests whether the specified character lies within the target range.
*
* @param ch The character to test for inclusion.
*
* @see #checkInCharacterSet(char)
* @see #set(char, char)
* @see #clear(char, char)
*/
boolean includes(int ch) {
return (first <= ch) && (ch <= last);
}
/**
* Tests whether the specified range lies entirely within the target range.
*
* @param r The range to test for inclusion.
*
* @see #set(Range)
* @see #clear(char, char)
*/
boolean includes(Range r) {
return (first <= r.first) && (r.last <= last);
}
/**
* Tests whether the specified range is mergeable with the target range. Two
* ranges are mergeable if they can be replaced with a single range that
* spans exactly the same range of values.
*
* @param r The range to test for mergeability with.
*
* @see #set(Range)
*/
boolean mergeable(Range r) {
/*
* A range is mergeable if there are no gaps between the ranges. If
* there is a gap, then it will be obvious as the difference in the
* extremes will be greater than the sum of the ranges.
*/
return (1 + Math.max(last, r.last) - Math.min(first, r.first)) <=
((1 + r.last - r.first) + (1 + last - first));
}
/**
* Merges the specified range with the target range. This function is simple
* minded and will produce unexpected results if the ranges being merged are
* not {@link #mergeable(Range)}.
*
* @param r The range to merge with.
*
* @see #set(char, char)
* @see #merge(int, Range)
*/
void merge(Range r) {
first = Math.min(first, r.first);
last = Math.max(last, r.last);
}
}
}
| apache-2.0 |
sheofir/aws-sdk-java | aws-java-sdk-route53/src/main/java/com/amazonaws/services/route53domains/model/transform/UpdateDomainContactResultJsonUnmarshaller.java | 2748 | /*
* Copyright 2010-2015 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.route53domains.model.transform;
import java.util.Map;
import java.util.Map.Entry;
import com.amazonaws.services.route53domains.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* Update Domain Contact Result JSON Unmarshaller
*/
public class UpdateDomainContactResultJsonUnmarshaller implements Unmarshaller<UpdateDomainContactResult, JsonUnmarshallerContext> {
public UpdateDomainContactResult unmarshall(JsonUnmarshallerContext context) throws Exception {
UpdateDomainContactResult updateDomainContactResult = new UpdateDomainContactResult();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null) token = context.nextToken();
if (token == VALUE_NULL) return null;
while (true) {
if (token == null) break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("OperationId", targetDepth)) {
context.nextToken();
updateDomainContactResult.setOperationId(StringJsonUnmarshaller.getInstance().unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth) break;
}
}
token = context.nextToken();
}
return updateDomainContactResult;
}
private static UpdateDomainContactResultJsonUnmarshaller instance;
public static UpdateDomainContactResultJsonUnmarshaller getInstance() {
if (instance == null) instance = new UpdateDomainContactResultJsonUnmarshaller();
return instance;
}
}
| apache-2.0 |
ipros-team/presto | presto-main/src/main/java/com/facebook/presto/operator/aggregation/state/HyperLogLogStateFactory.java | 2985 | /*
* 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.aggregation.state;
import com.facebook.presto.util.array.ObjectBigArray;
import io.airlift.stats.cardinality.HyperLogLog;
import static java.util.Objects.requireNonNull;
public class HyperLogLogStateFactory
implements AccumulatorStateFactory<HyperLogLogState>
{
@Override
public HyperLogLogState createSingleState()
{
return new SingleHyperLogLogState();
}
@Override
public Class<? extends HyperLogLogState> getSingleStateClass()
{
return SingleHyperLogLogState.class;
}
@Override
public HyperLogLogState createGroupedState()
{
return new GroupedHyperLogLogState();
}
@Override
public Class<? extends HyperLogLogState> getGroupedStateClass()
{
return GroupedHyperLogLogState.class;
}
public static class GroupedHyperLogLogState
extends AbstractGroupedAccumulatorState
implements HyperLogLogState
{
private final ObjectBigArray<HyperLogLog> hlls = new ObjectBigArray<>();
private long size;
@Override
public void ensureCapacity(long size)
{
hlls.ensureCapacity(size);
}
@Override
public HyperLogLog getHyperLogLog()
{
return hlls.get(getGroupId());
}
@Override
public void setHyperLogLog(HyperLogLog value)
{
requireNonNull(value, "value is null");
hlls.set(getGroupId(), value);
}
@Override
public void addMemoryUsage(int value)
{
size += value;
}
@Override
public long getEstimatedSize()
{
return size + hlls.sizeOf();
}
}
public static class SingleHyperLogLogState
implements HyperLogLogState
{
private HyperLogLog hll;
@Override
public HyperLogLog getHyperLogLog()
{
return hll;
}
@Override
public void setHyperLogLog(HyperLogLog value)
{
hll = value;
}
@Override
public void addMemoryUsage(int value)
{
// noop
}
@Override
public long getEstimatedSize()
{
if (hll == null) {
return 0;
}
return hll.estimatedInMemorySize();
}
}
}
| apache-2.0 |
caoanhhao/AndEngine | src/org/andengine/util/level/simple/SimpleLevelLoaderResult.java | 1539 | package org.andengine.util.level.simple;
import org.andengine.entity.scene.Scene;
import org.andengine.util.level.ILevelLoaderResult;
/**
* (c) 2012 Zynga Inc.
*
* @author Nicolas Gramlich <ngramlich@zynga.com>
* @since 16:13:38 - 19.04.2012
*/
public class SimpleLevelLoaderResult implements ILevelLoaderResult {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final Scene mScene;
// ===========================================================
// Constructors
// ===========================================================
public SimpleLevelLoaderResult(final Scene pScene) {
this.mScene = pScene;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public Scene getScene() {
return this.mScene;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| apache-2.0 |
suthat/signal | vendor/mysql-connector-java-5.1.26/src/com/mysql/jdbc/V1toV2StatementInterceptorAdapter.java | 2175 | /*
Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved., Inc. All rights reserved.
U.S. Government Rights - Commercial software. Government users are subject
to the Sun Microsystems, Inc. standard license agreement and applicable
provisions of the FAR and its supplements. Use is subject to license terms.
This distribution may include materials developed by third parties.Sun,
Sun Microsystems, the Sun logo and MySQL Enterprise Monitor are
trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S.
and other countries.
Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved., Inc. Tous droits réservés.
L'utilisation est soumise aux termes du contrat de licence.Cette
distribution peut comprendre des composants développés par des tierces
parties.Sun, Sun Microsystems, le logo Sun et MySQL Enterprise Monitor sont
des marques de fabrique ou des marques déposées de Sun Microsystems, Inc.
aux Etats-Unis et dans du'autres pays.
*/
package com.mysql.jdbc;
import java.sql.SQLException;
import java.util.Properties;
public class V1toV2StatementInterceptorAdapter implements StatementInterceptorV2 {
private final StatementInterceptor toProxy;
public V1toV2StatementInterceptorAdapter(StatementInterceptor toProxy) {
this.toProxy = toProxy;
}
public ResultSetInternalMethods postProcess(String sql,
Statement interceptedStatement,
ResultSetInternalMethods originalResultSet, Connection connection,
int warningCount, boolean noIndexUsed, boolean noGoodIndexUsed,
SQLException statementException) throws SQLException {
return toProxy.postProcess(sql, interceptedStatement, originalResultSet, connection);
}
public void destroy() {
toProxy.destroy();
}
public boolean executeTopLevelOnly() {
return toProxy.executeTopLevelOnly();
}
public void init(Connection conn, Properties props) throws SQLException {
toProxy.init(conn, props);
}
public ResultSetInternalMethods preProcess(String sql,
Statement interceptedStatement, Connection connection)
throws SQLException {
return toProxy.preProcess(sql, interceptedStatement, connection);
}
}
| apache-2.0 |
pombredanne/brisk-hadoop-common | src/test/org/apache/hadoop/hdfs/server/namenode/TestSecurityTokenEditLog.java | 5772 | /**
* 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.hdfs.server.namenode;
import junit.framework.TestCase;
import java.io.*;
import java.net.URI;
import java.util.Iterator;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier;
import org.apache.hadoop.hdfs.server.common.Storage.StorageDirectory;
import org.apache.hadoop.hdfs.server.namenode.FSImage.NameNodeDirType;
import org.apache.hadoop.hdfs.server.namenode.FSImage.NameNodeFile;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.hdfs.server.namenode.FSEditLog.EditLogFileInputStream;
import org.mortbay.log.Log;
/**
* This class tests the creation and validation of a checkpoint.
*/
public class TestSecurityTokenEditLog extends TestCase {
static final int NUM_DATA_NODES = 1;
// This test creates NUM_THREADS threads and each thread does
// 2 * NUM_TRANSACTIONS Transactions concurrently.
static final int NUM_TRANSACTIONS = 100;
static final int NUM_THREADS = 100;
static final int opsPerTrans = 3;
//
// an object that does a bunch of transactions
//
static class Transactions implements Runnable {
FSNamesystem namesystem;
int numTransactions;
short replication = 3;
long blockSize = 64;
Transactions(FSNamesystem ns, int num) {
namesystem = ns;
numTransactions = num;
}
// add a bunch of transactions.
public void run() {
FSEditLog editLog = namesystem.getEditLog();
for (int i = 0; i < numTransactions; i++) {
try {
String renewer = UserGroupInformation.getLoginUser().getUserName();
Token<DelegationTokenIdentifier> token = namesystem
.getDelegationToken(new Text(renewer));
namesystem.renewDelegationToken(token);
namesystem.cancelDelegationToken(token);
editLog.logSync();
} catch (IOException e) {
System.out.println("Transaction " + i + " encountered exception " +
e);
}
}
}
}
/**
* Tests transaction logging in dfs.
*/
public void testEditLog() throws IOException {
// start a cluster
Configuration conf = new Configuration();
MiniDFSCluster cluster = null;
FileSystem fileSys = null;
try {
cluster = new MiniDFSCluster(conf, NUM_DATA_NODES, true, null);
cluster.waitActive();
fileSys = cluster.getFileSystem();
final FSNamesystem namesystem = cluster.getNameNode().getNamesystem();
for (Iterator<File> it = cluster.getNameDirs().iterator(); it.hasNext(); ) {
File dir = new File(it.next().getPath());
System.out.println(dir);
}
FSImage fsimage = namesystem.getFSImage();
FSEditLog editLog = fsimage.getEditLog();
// set small size of flush buffer
editLog.setBufferCapacity(2048);
editLog.close();
editLog.open();
namesystem.getDelegationTokenSecretManager().startThreads();
// Create threads and make them run transactions concurrently.
Thread threadId[] = new Thread[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++) {
Transactions trans = new Transactions(namesystem, NUM_TRANSACTIONS);
threadId[i] = new Thread(trans, "TransactionThread-" + i);
threadId[i].start();
}
// wait for all transactions to get over
for (int i = 0; i < NUM_THREADS; i++) {
try {
threadId[i].join();
} catch (InterruptedException e) {
i--; // retry
}
}
editLog.close();
// Verify that we can read in all the transactions that we have written.
// If there were any corruptions, it is likely that the reading in
// of these transactions will throw an exception.
//
namesystem.getDelegationTokenSecretManager().stopThreads();
int numKeys = namesystem.getDelegationTokenSecretManager().getNumberOfKeys();
for (Iterator<StorageDirectory> it =
fsimage.dirIterator(NameNodeDirType.EDITS); it.hasNext();) {
File editFile = FSImage.getImageFile(it.next(), NameNodeFile.EDITS);
System.out.println("Verifying file: " + editFile);
int numEdits = FSEditLog.loadFSEdits(
new EditLogFileInputStream(editFile));
assertTrue("Verification for " + editFile + " failed. " +
"Expected " + (NUM_THREADS * opsPerTrans * NUM_TRANSACTIONS + numKeys) + " transactions. "+
"Found " + numEdits + " transactions.",
numEdits == NUM_THREADS * opsPerTrans * NUM_TRANSACTIONS +numKeys);
}
} finally {
if(fileSys != null) fileSys.close();
if(cluster != null) cluster.shutdown();
}
}
}
| apache-2.0 |
hurricup/intellij-community | java/debugger/impl/src/com/intellij/debugger/impl/DebuggerStateManager.java | 1818 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* 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.intellij.debugger.impl;
import com.intellij.util.EventDispatcher;
import org.jetbrains.annotations.NotNull;
/**
* Created by IntelliJ IDEA.
* User: lex
* Date: Jun 4, 2003
* Time: 12:45:56 PM
* To change this template use Options | File Templates.
*/
public abstract class DebuggerStateManager {
private final EventDispatcher<DebuggerContextListener> myEventDispatcher = EventDispatcher.create(DebuggerContextListener.class);
@NotNull
public abstract DebuggerContextImpl getContext();
public abstract void setState(@NotNull DebuggerContextImpl context, DebuggerSession.State state, DebuggerSession.Event event, String description);
//we allow add listeners inside DebuggerContextListener.changeEvent
public void addListener(DebuggerContextListener listener){
myEventDispatcher.addListener(listener);
}
//we allow remove listeners inside DebuggerContextListener.changeEvent
public void removeListener(DebuggerContextListener listener){
myEventDispatcher.removeListener(listener);
}
protected void fireStateChanged(@NotNull DebuggerContextImpl newContext, DebuggerSession.Event event) {
myEventDispatcher.getMulticaster().changeEvent(newContext, event);
}
}
| apache-2.0 |
isaacl/openjdk-jdk | src/share/classes/javax/swing/Scrollable.java | 5605 | /*
* Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.Dimension;
import java.awt.Rectangle;
/**
* An interface that provides information to a scrolling container
* like JScrollPane. A complex component that's likely to be used
* as a viewing a JScrollPane viewport (or other scrolling container)
* should implement this interface.
*
* @see JViewport
* @see JScrollPane
* @see JScrollBar
* @author Hans Muller
* @since 1.2
*/
public interface Scrollable
{
/**
* Returns the preferred size of the viewport for a view component.
* For example, the preferred size of a <code>JList</code> component
* is the size required to accommodate all of the cells in its list.
* However, the value of <code>preferredScrollableViewportSize</code>
* is the size required for <code>JList.getVisibleRowCount</code> rows.
* A component without any properties that would affect the viewport
* size should just return <code>getPreferredSize</code> here.
*
* @return the preferredSize of a <code>JViewport</code> whose view
* is this <code>Scrollable</code>
* @see JViewport#getPreferredSize
*/
Dimension getPreferredScrollableViewportSize();
/**
* Components that display logical rows or columns should compute
* the scroll increment that will completely expose one new row
* or column, depending on the value of orientation. Ideally,
* components should handle a partially exposed row or column by
* returning the distance required to completely expose the item.
* <p>
* Scrolling containers, like JScrollPane, will use this method
* each time the user requests a unit scroll.
*
* @param visibleRect The view area visible within the viewport
* @param orientation Either SwingConstants.VERTICAL or SwingConstants.HORIZONTAL.
* @param direction Less than zero to scroll up/left, greater than zero for down/right.
* @return The "unit" increment for scrolling in the specified direction.
* This value should always be positive.
* @see JScrollBar#setUnitIncrement
*/
int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction);
/**
* Components that display logical rows or columns should compute
* the scroll increment that will completely expose one block
* of rows or columns, depending on the value of orientation.
* <p>
* Scrolling containers, like JScrollPane, will use this method
* each time the user requests a block scroll.
*
* @param visibleRect The view area visible within the viewport
* @param orientation Either SwingConstants.VERTICAL or SwingConstants.HORIZONTAL.
* @param direction Less than zero to scroll up/left, greater than zero for down/right.
* @return The "block" increment for scrolling in the specified direction.
* This value should always be positive.
* @see JScrollBar#setBlockIncrement
*/
int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction);
/**
* Return true if a viewport should always force the width of this
* <code>Scrollable</code> to match the width of the viewport.
* For example a normal
* text view that supported line wrapping would return true here, since it
* would be undesirable for wrapped lines to disappear beyond the right
* edge of the viewport. Note that returning true for a Scrollable
* whose ancestor is a JScrollPane effectively disables horizontal
* scrolling.
* <p>
* Scrolling containers, like JViewport, will use this method each
* time they are validated.
*
* @return True if a viewport should force the Scrollables width to match its own.
*/
boolean getScrollableTracksViewportWidth();
/**
* Return true if a viewport should always force the height of this
* Scrollable to match the height of the viewport. For example a
* columnar text view that flowed text in left to right columns
* could effectively disable vertical scrolling by returning
* true here.
* <p>
* Scrolling containers, like JViewport, will use this method each
* time they are validated.
*
* @return True if a viewport should force the Scrollables height to match its own.
*/
boolean getScrollableTracksViewportHeight();
}
| gpl-2.0 |
anchela/jackrabbit-oak | oak-jcr/src/test/java/org/apache/jackrabbit/oak/jcr/tck/RetentionIT.java | 1195 | /*
* 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.jackrabbit.oak.jcr.tck;
import junit.framework.Test;
public class RetentionIT extends TCKBase {
public static Test suite() {
return new RetentionIT();
}
public RetentionIT() {
super("JCR retention tests");
}
@Override
protected void addTests() {
addTest(org.apache.jackrabbit.test.api.retention.TestAll.suite());
}
}
| apache-2.0 |
tempbottle/kafka | clients/src/main/java/org/apache/kafka/clients/consumer/ConsumerRebalanceCallback.java | 5998 | /**
* 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.kafka.clients.consumer;
import java.util.Collection;
import org.apache.kafka.common.TopicPartition;
/**
* A callback interface that the user can implement to trigger custom actions when the set of partitions assigned to the
* consumer changes.
* <p>
* This is applicable when the consumer is having Kafka auto-manage group membership, if the consumer's directly subscribe to partitions
* those partitions will never be reassigned and this callback is not applicable.
* <p>
* When Kafka is managing the group membership, a partition re-assignment will be triggered any time the members of the group changes or the subscription
* of the members changes. This can occur when processes die, new process instances are added or old instances come back to life after failure.
* <p>
* There are many uses for this functionality. One common use is saving offsets in a custom store. By saving offsets in
* the {@link #onPartitionsRevoked(Consumer, Collection)} call we can ensure that any time partition assignment changes
* the offset gets saved.
* <p>
* Another use is flushing out any kind of cache of intermediate results the consumer may be keeping. For example,
* consider a case where the consumer is subscribed to a topic containing user page views, and the goal is to count the
* number of page views per users for each five minute window. Let's say the topic is partitioned by the user id so that
* all events for a particular user will go to a single consumer instance. The consumer can keep in memory a running
* tally of actions per user and only flush these out to a remote data store when it's cache gets to big. However if a
* partition is reassigned it may want to automatically trigger a flush of this cache, before the new owner takes over
* consumption.
* <p>
* This callback will execute in the user thread as part of the {@link Consumer#poll(long) poll(long)} call whenever partition assignment changes.
* <p>
* It is guaranteed that all consumer processes will invoke {@link #onPartitionsRevoked(Consumer, Collection) onPartitionsRevoked} prior to
* any process invoking {@link #onPartitionsAssigned(Consumer, Collection) onPartitionsAssigned}. So if offsets or other state is saved in the
* {@link #onPartitionsRevoked(Consumer, Collection) onPartitionsRevoked} call it is guaranteed to be saved by the time the process taking over that
* partition has their {@link #onPartitionsAssigned(Consumer, Collection) onPartitionsAssigned} callback called to load the state.
* <p>
* Here is pseudo-code for a callback implementation for saving offsets:
* <pre>
* {@code
* public class SaveOffsetsOnRebalance implements ConsumerRebalanceCallback {
* public void onPartitionsAssigned(Consumer<?, ?> consumer, Collection<TopicPartition> partitions) {
* // read the offsets from an external store using some custom code not described here
* for(TopicPartition partition: partitions)
* consumer.position(partition, readOffsetFromExternalStore(partition));
* }
* public void onPartitionsRevoked(Consumer<?, ?> consumer, Collection<TopicPartition> partitions) {
* // save the offsets in an external store using some custom code not described here
* for(TopicPartition partition: partitions)
* saveOffsetInExternalStore(consumer.position(partition));
* }
* }
* }
* </pre>
*/
public interface ConsumerRebalanceCallback {
/**
* A callback method the user can implement to provide handling of customized offsets on completion of a successful
* partition re-assignement. This method will be called after an offset re-assignement completes and before the
* consumer starts fetching data.
* <p>
* It is guaranteed that all the processes in a consumer group will execute their
* {@link #onPartitionsRevoked(Consumer, Collection)} callback before any instance executes its
* {@link #onPartitionsAssigned(Consumer, Collection)} callback.
*
* @param consumer Reference to the consumer for convenience
* @param partitions The list of partitions that are now assigned to the consumer (may include partitions previously
* assigned to the consumer)
*/
public void onPartitionsAssigned(Consumer<?, ?> consumer, Collection<TopicPartition> partitions);
/**
* A callback method the user can implement to provide handling of offset commits to a customized store on the start
* of a rebalance operation. This method will be called before a rebalance operation starts and after the consumer
* stops fetching data. It is recommended that offsets should be committed in this callback to either Kafka or a
* custom offset store to prevent duplicate data
* <p>
* For examples on usage of this API, see Usage Examples section of {@link KafkaConsumer KafkaConsumer}
*
* @param consumer Reference to the consumer for convenience
* @param partitions The list of partitions that were assigned to the consumer on the last rebalance
*/
public void onPartitionsRevoked(Consumer<?, ?> consumer, Collection<TopicPartition> partitions);
}
| apache-2.0 |
Kleagleguo/druid | processing/src/main/java/io/druid/query/metadata/metadata/NoneColumnIncluderator.java | 937 | /*
* Druid - a distributed column store.
* Copyright 2012 - 2015 Metamarkets Group 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 io.druid.query.metadata.metadata;
/**
*/
public class NoneColumnIncluderator implements ColumnIncluderator
{
@Override
public boolean include(String columnName)
{
return false;
}
@Override
public byte[] getCacheKey()
{
return NONE_CACHE_PREFIX;
}
}
| apache-2.0 |
AndreasAbdi/jackrabbit-oak | oak-run/src/main/java/org/apache/jackrabbit/oak/fixture/RepositoryFixture.java | 2647 | /*
* 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.jackrabbit.oak.fixture;
import javax.jcr.Repository;
public interface RepositoryFixture {
/**
* Checks whether this fixture is currently available. For example
* a database-based fixture would only be available when the underlying
* database service is running.
*
* @param n size of the requested cluster
* @return {@code true} iff the fixture is available
*/
boolean isAvailable(int n);
/**
* Creates a new repository cluster with the given number of nodes.
* The initial state of the cluster consists of just the default
* repository content included by the implementation. The caller of
* this method should have exclusive access to the created cluster.
* The caller is also responsible for calling {@link #tearDownCluster()}
* when the test cluster is no longer needed.
*
* @param n size of the requested cluster
* @return nodes of the created cluster
* @throws Exception if the cluster could not be set up
*/
Repository[] setUpCluster(int n) throws Exception;
/**
* Ensures that all content changes seen by one of the given cluster
* nodes are seen also by all the other given nodes. Used to help
* testing features like eventual consistency where the normal APIs
* don't make strong enough guarantees to enable writing a test case
* without a potentially unbounded wait for changes to propagate
* across the cluster.
*
* @param nodes cluster nodes to be synchronized
*/
void syncRepositoryCluster(Repository... nodes);
/**
* Releases resources associated with the given repository cluster.
* The caller of {@link #setUpCluster(int)} shall call this
* method once the cluster is no longer needed.
*/
void tearDownCluster();
}
| apache-2.0 |
nmelnick/aws-sdk-java | aws-java-sdk-route53/src/main/java/com/amazonaws/services/route53/model/ChangeAction.java | 1692 | /*
* Copyright 2010-2015 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.route53.model;
/**
* Change Action
*/
public enum ChangeAction {
CREATE("CREATE"),
DELETE("DELETE"),
UPSERT("UPSERT");
private String value;
private ChangeAction(String value) {
this.value = value;
}
@Override
public String toString() {
return this.value;
}
/**
* Use this in place of valueOf.
*
* @param value
* real value
* @return ChangeAction corresponding to the value
*/
public static ChangeAction fromValue(String value) {
if (value == null || "".equals(value)) {
throw new IllegalArgumentException("Value cannot be null or empty!");
} else if ("CREATE".equals(value)) {
return ChangeAction.CREATE;
} else if ("DELETE".equals(value)) {
return ChangeAction.DELETE;
} else if ("UPSERT".equals(value)) {
return ChangeAction.UPSERT;
} else {
throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
}
}
}
| apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk2/jaxws/src/share/jaxws_classes/com/sun/tools/internal/xjc/reader/xmlschema/DefaultClassBinder.java | 21517 | /*
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.internal.xjc.reader.xmlschema;
import static com.sun.tools.internal.xjc.reader.xmlschema.BGMBuilder.getName;
import java.util.Set;
import javax.xml.namespace.QName;
import com.sun.codemodel.internal.JJavaName;
import com.sun.codemodel.internal.JPackage;
import com.sun.istack.internal.NotNull;
import com.sun.istack.internal.Nullable;
import com.sun.tools.internal.xjc.ErrorReceiver;
import com.sun.tools.internal.xjc.model.CClassInfo;
import com.sun.tools.internal.xjc.model.CClassInfoParent;
import com.sun.tools.internal.xjc.model.CClassRef;
import com.sun.tools.internal.xjc.model.CCustomizations;
import com.sun.tools.internal.xjc.model.CElement;
import com.sun.tools.internal.xjc.model.CElementInfo;
import com.sun.tools.internal.xjc.model.Model;
import com.sun.tools.internal.xjc.reader.Ring;
import com.sun.tools.internal.xjc.reader.xmlschema.bindinfo.BIClass;
import com.sun.tools.internal.xjc.reader.xmlschema.bindinfo.BIGlobalBinding;
import com.sun.tools.internal.xjc.reader.xmlschema.bindinfo.BISchemaBinding;
import com.sun.tools.internal.xjc.reader.xmlschema.bindinfo.BindInfo;
import com.sun.tools.internal.xjc.reader.xmlschema.bindinfo.BIXSubstitutable;
import com.sun.tools.internal.xjc.reader.xmlschema.ct.ComplexTypeFieldBuilder;
import com.sun.tools.internal.xjc.reader.xmlschema.ct.ComplexTypeBindingMode;
import com.sun.xml.internal.xsom.XSAnnotation;
import com.sun.xml.internal.xsom.XSAttGroupDecl;
import com.sun.xml.internal.xsom.XSAttributeDecl;
import com.sun.xml.internal.xsom.XSAttributeUse;
import com.sun.xml.internal.xsom.XSComplexType;
import com.sun.xml.internal.xsom.XSComponent;
import com.sun.xml.internal.xsom.XSContentType;
import com.sun.xml.internal.xsom.XSDeclaration;
import com.sun.xml.internal.xsom.XSElementDecl;
import com.sun.xml.internal.xsom.XSFacet;
import com.sun.xml.internal.xsom.XSIdentityConstraint;
import com.sun.xml.internal.xsom.XSModelGroup;
import com.sun.xml.internal.xsom.XSModelGroupDecl;
import com.sun.xml.internal.xsom.XSNotation;
import com.sun.xml.internal.xsom.XSParticle;
import com.sun.xml.internal.xsom.XSSchema;
import com.sun.xml.internal.xsom.XSSchemaSet;
import com.sun.xml.internal.xsom.XSSimpleType;
import com.sun.xml.internal.xsom.XSType;
import com.sun.xml.internal.xsom.XSWildcard;
import com.sun.xml.internal.xsom.XSXPath;
import org.xml.sax.Locator;
/**
* Default classBinder implementation. Honors <jaxb:class> customizations
* and default bindings.
*/
final class DefaultClassBinder implements ClassBinder
{
private final SimpleTypeBuilder stb = Ring.get(SimpleTypeBuilder.class);
private final Model model = Ring.get(Model.class);
protected final BGMBuilder builder = Ring.get(BGMBuilder.class);
protected final ClassSelector selector = Ring.get(ClassSelector.class);
protected final XSSchemaSet schemas = Ring.get(XSSchemaSet.class);
public CElement attGroupDecl(XSAttGroupDecl decl) {
return allow(decl,decl.getName());
}
public CElement attributeDecl(XSAttributeDecl decl) {
return allow(decl,decl.getName());
}
public CElement modelGroup(XSModelGroup mgroup) {
return never();
}
public CElement modelGroupDecl(XSModelGroupDecl decl) {
return never();
}
public CElement complexType(XSComplexType type) {
CElement ci = allow(type,type.getName());
if(ci!=null) return ci;
// no customization is given -- do as the default binding.
BindInfo bi = builder.getBindInfo(type);
if(type.isGlobal()) {
QName tagName = null;
String className = deriveName(type);
Locator loc = type.getLocator();
if(getGlobalBinding().isSimpleMode()) {
// in the simple mode, we may optimize it away
XSElementDecl referer = getSoleElementReferer(type);
if(referer!=null && isCollapsable(referer)) {
// if a global element contains
// a collpsable complex type, we bind this element to a named one
// and collapses element and complex type.
tagName = getName(referer);
className = deriveName(referer);
loc = referer.getLocator();
}
}
// by default, global ones get their own classes.
JPackage pkg = selector.getPackage(type.getTargetNamespace());
return new CClassInfo(model,pkg,className, loc,getTypeName(type),tagName,type,bi.toCustomizationList());
} else {
XSElementDecl element = type.getScope();
if( element.isGlobal() && isCollapsable(element)) {
if(builder.getBindInfo(element).get(BIClass.class)!=null)
// the parent element was bound to a class. Don't bind this again to
// cause unnecessary wrapping
return null;
// generate one class from element and complex type together.
// this needs to be done before selector.isBound to avoid infinite recursion.
// but avoid doing so when the element is mapped to a class,
// which creates unnecessary classes
return new CClassInfo( model, selector.getClassScope(),
deriveName(element), element.getLocator(), null,
getName(element), element, bi.toCustomizationList() );
}
CElement parentType = selector.isBound(element,type);
String className;
CClassInfoParent scope;
if( parentType!=null
&& parentType instanceof CElementInfo
&& ((CElementInfo)parentType).hasClass() ) {
// special case where we put a nested 'Type' element
scope = (CElementInfo)parentType;
className = "Type";
} else {
// since the parent element isn't bound to a type, merge the customizations associated to it, too.
// custs = CCustomizations.merge( custs, builder.getBindInfo(type.getScope()).toCustomizationList());
className = builder.getNameConverter().toClassName(element.getName());
BISchemaBinding sb = builder.getBindInfo(
type.getOwnerSchema() ).get(BISchemaBinding.class);
if(sb!=null) className = sb.mangleAnonymousTypeClassName(className);
scope = selector.getClassScope();
}
return new CClassInfo(model, scope, className, type.getLocator(), null, null, type, bi.toCustomizationList() );
}
}
private QName getTypeName(XSComplexType type) {
if(type.getRedefinedBy()!=null)
return null;
else
return getName(type);
}
/**
* Returns true if the complex type of the given element can be "optimized away"
* and unified with its parent element decl to form a single class.
*/
private boolean isCollapsable(XSElementDecl decl) {
XSType type = decl.getType();
if(!type.isComplexType())
return false; // not a complex type
if(decl.getSubstitutables().size()>1 || decl.getSubstAffiliation()!=null)
// because element substitution calls for a proper JAXBElement hierarchy
return false;
if(decl.isNillable())
// because nillable needs JAXBElement to represent correctly
return false;
BIXSubstitutable bixSubstitutable = builder.getBindInfo(decl).get(BIXSubstitutable.class);
if(bixSubstitutable !=null) {
// see https://jaxb.dev.java.net/issues/show_bug.cgi?id=289
// this customization forces non-collapsing behavior.
bixSubstitutable.markAsAcknowledged();
return false;
}
if( getGlobalBinding().isSimpleMode() && decl.isGlobal()) {
// in the simple mode, we do more aggressive optimization, and get rid of
// a complex type class if it's only used once from a global element
XSElementDecl referer = getSoleElementReferer(decl.getType());
if(referer!=null) {
assert referer==decl; // I must be the sole referer
return true;
}
}
if(!type.isLocal() || !type.isComplexType())
return false;
return true;
}
/**
* If only one global {@link XSElementDecl} is refering to {@link XSType},
* return that element, otherwise null.
*/
private @Nullable XSElementDecl getSoleElementReferer(@NotNull XSType t) {
Set<XSComponent> referer = builder.getReferer(t);
XSElementDecl sole = null;
for (XSComponent r : referer) {
if(r instanceof XSElementDecl) {
XSElementDecl x = (XSElementDecl) r;
if(!x.isGlobal())
// local element references can be ignored, as their names are either given
// by the property, or by the JAXBElement (for things like mixed contents)
continue;
if(sole==null) sole=x;
else return null; // more than one
} else {
// if another type refers to this type, that means
// this type has a sub-type, so type substitution is possible now.
return null;
}
}
return sole;
}
public CElement elementDecl(XSElementDecl decl) {
CElement r = allow(decl,decl.getName());
if(r==null) {
QName tagName = getName(decl);
CCustomizations custs = builder.getBindInfo(decl).toCustomizationList();
if(decl.isGlobal()) {
if(isCollapsable(decl)) {
// we want the returned type to be built as a complex type,
// so the binding cannot be delayed.
return selector.bindToType(decl.getType().asComplexType(),decl,true);
} else {
String className = null;
if(getGlobalBinding().isGenerateElementClass())
className = deriveName(decl);
// otherwise map global elements to JAXBElement
CElementInfo cei = new CElementInfo(
model, tagName, selector.getClassScope(), className, custs, decl.getLocator());
selector.boundElements.put(decl,cei);
stb.refererStack.push(decl); // referer is element
cei.initContentType( selector.bindToType(decl.getType(),decl), decl, decl.getDefaultValue() );
stb.refererStack.pop();
r = cei;
}
}
}
// have the substitution member derive from the substitution head
XSElementDecl top = decl.getSubstAffiliation();
if(top!=null) {
CElement topci = selector.bindToType(top,decl);
if(r instanceof CClassInfo && topci instanceof CClassInfo)
((CClassInfo)r).setBaseClass((CClassInfo)topci);
if (r instanceof CElementInfo && topci instanceof CElementInfo)
((CElementInfo)r).setSubstitutionHead((CElementInfo)topci);
}
return r;
}
public CClassInfo empty( XSContentType ct ) { return null; }
public CClassInfo identityConstraint(XSIdentityConstraint xsIdentityConstraint) {
return never();
}
public CClassInfo xpath(XSXPath xsxPath) {
return never();
}
public CClassInfo attributeUse(XSAttributeUse use) {
return never();
}
public CElement simpleType(XSSimpleType type) {
CElement c = allow(type,type.getName());
if(c!=null) return c;
if(getGlobalBinding().isSimpleTypeSubstitution() && type.isGlobal()) {
return new CClassInfo(model,selector.getClassScope(),
deriveName(type), type.getLocator(), getName(type), null, type, null );
}
return never();
}
public CClassInfo particle(XSParticle particle) {
return never();
}
public CClassInfo wildcard(XSWildcard wc) {
return never();
}
// these methods won't be used
public CClassInfo annotation(XSAnnotation annon) {
assert false;
return null;
}
public CClassInfo notation(XSNotation not) {
assert false;
return null;
}
public CClassInfo facet(XSFacet decl) {
assert false;
return null;
}
public CClassInfo schema(XSSchema schema) {
assert false;
return null;
}
/**
* Makes sure that the component doesn't carry a {@link BIClass}
* customization.
*
* @return
* return value is unused. Since most of the caller needs to
* return null, to make the code a little bit shorter, this
* method always return null (so that the caller can always
* say <code>return never(sc);</code>.
*/
private CClassInfo never() {
// all we need to do here is just not to acknowledge
// any class customization. Then this class customization
// will be reported as an error later when we check all
// unacknowledged customizations.
// BIDeclaration cust=owner.getBindInfo(component).get(BIClass.NAME);
// if(cust!=null) {
// // error
// owner.errorReporter.error(
// cust.getLocation(),
// "test {0}", NameGetter.get(component) );
// }
return null;
}
/**
* Checks if a component carries a customization to map it to a class.
* If so, make it a class.
*
* @param defaultBaseName
* The token which will be used as the basis of the class name
* if the class name is not specified in the customization.
* This is usually the name of an element declaration, and so on.
*
* This parameter can be null, in that case it would be an error
* if a name is not given by the customization.
*/
private CElement allow( XSComponent component, String defaultBaseName ) {
BIClass decl = null;
if(component instanceof XSComplexType) {
XSType complexType = (XSType)component;
BIClass lastFoundRecursiveBiClass = null;
if(complexType.getName() != null) {
while( ! schemas.getAnyType().equals(complexType)) {
BindInfo bindInfo = builder.getBindInfo(complexType);
BIClass biClass = bindInfo.get(BIClass.class);
if(biClass != null && "true".equals(biClass.getRecursive()))
lastFoundRecursiveBiClass = biClass;
complexType = complexType.getBaseType();
}
}
// use this as biclass for current component
decl = lastFoundRecursiveBiClass;
}
BindInfo bindInfo = builder.getBindInfo(component);
if(decl == null) {
decl = bindInfo.get(BIClass.class);
if(decl==null) return null;
}
decl.markAsAcknowledged();
// first consider binding to the class reference.
String ref = decl.getExistingClassRef();
if(ref!=null) {
if(!JJavaName.isFullyQualifiedClassName(ref)) {
Ring.get(ErrorReceiver.class).error( decl.getLocation(),
Messages.format(Messages.ERR_INCORRECT_CLASS_NAME,ref) );
// recover by ignoring @ref
} else {
if(component instanceof XSComplexType) {
// UGLY UGLY UGLY
// since we are not going to bind this complex type, we need to figure out
// its binding mode without actually binding it (and also expose this otherwise
// hidden mechanism into this part of the code.)
//
// this code is potentially dangerous as the base class might have been bound
// in different ways. To be correct, we need to figure out how the content type
// would have been bound, from the schema.
Ring.get(ComplexTypeFieldBuilder.class).recordBindingMode(
(XSComplexType)component, ComplexTypeBindingMode.NORMAL
);
}
return new CClassRef(model, component, decl, bindInfo.toCustomizationList() );
}
}
String clsName = decl.getClassName();
if(clsName==null) {
// if the customiztion doesn't give us a name, derive one
// from the current component.
if( defaultBaseName==null ) {
Ring.get(ErrorReceiver.class).error( decl.getLocation(),
Messages.format(Messages.ERR_CLASS_NAME_IS_REQUIRED) );
// recover by generating a pseudo-random name
defaultBaseName = "undefined"+component.hashCode();
}
clsName = builder.deriveName( defaultBaseName, component );
} else {
if( !JJavaName.isJavaIdentifier(clsName) ) {
// not a valid Java class name
Ring.get(ErrorReceiver.class).error( decl.getLocation(),
Messages.format( Messages.ERR_INCORRECT_CLASS_NAME, clsName ));
// recover by a dummy name
clsName = "Undefined"+component.hashCode();
}
}
QName typeName = null;
QName elementName = null;
if(component instanceof XSType) {
XSType t = (XSType) component;
typeName = getName(t);
}
if (component instanceof XSElementDecl) {
XSElementDecl e = (XSElementDecl) component;
elementName = getName(e);
}
if (component instanceof XSElementDecl && !isCollapsable((XSElementDecl)component)) {
XSElementDecl e = ((XSElementDecl)component);
CElementInfo cei = new CElementInfo(model, elementName,
selector.getClassScope(), clsName,
bindInfo.toCustomizationList(), decl.getLocation() );
selector.boundElements.put(e,cei);
stb.refererStack.push(component); // referer is element
cei.initContentType(
selector.bindToType(e.getType(),e),
e,e.getDefaultValue());
stb.refererStack.pop();
return cei;
// TODO: support javadoc and userSpecifiedImplClass
} else {
CClassInfo bt = new CClassInfo(model,selector.getClassScope(),
clsName, decl.getLocation(), typeName, elementName, component, bindInfo.toCustomizationList() );
// set javadoc class comment.
if(decl.getJavadoc()!=null )
bt.javadoc = decl.getJavadoc()+"\n\n";
// add extra blank lines so that the schema fragment
// and user-specified javadoc would be separated
// if the implClass is given, set it to ClassItem
String implClass = decl.getUserSpecifiedImplClass();
if( implClass!=null )
bt.setUserSpecifiedImplClass( implClass );
return bt;
}
}
private BIGlobalBinding getGlobalBinding() {
return builder.getGlobalBinding();
}
/**
* Derives a name from a schema component.
* Use the name of the schema component as the default name.
*/
private String deriveName( XSDeclaration comp ) {
return builder.deriveName( comp.getName(), comp );
}
/**
* Derives a name from a schema component.
* For complex types, we take redefinition into account when
* deriving a default name.
*/
private String deriveName( XSComplexType comp ) {
String seed = builder.deriveName( comp.getName(), comp );
int cnt = comp.getRedefinedCount();
for( ; cnt>0; cnt-- )
seed = "Original"+seed;
return seed;
}
}
| mit |
chiastic-security/phoenix-for-cloudera | phoenix-core/src/test/java/org/apache/phoenix/expression/LnLogFunctionTest.java | 8173 | /*
* 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.phoenix.expression;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.List;
import java.util.Random;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.phoenix.expression.function.LnFunction;
import org.apache.phoenix.expression.function.LogFunction;
import org.apache.phoenix.schema.SortOrder;
import org.apache.phoenix.schema.types.PDecimal;
import org.apache.phoenix.schema.types.PDouble;
import org.apache.phoenix.schema.types.PFloat;
import org.apache.phoenix.schema.types.PInteger;
import org.apache.phoenix.schema.types.PLong;
import org.apache.phoenix.schema.types.PNumericType;
import org.apache.phoenix.schema.types.PSmallint;
import org.apache.phoenix.schema.types.PTinyint;
import org.apache.phoenix.schema.types.PUnsignedDouble;
import org.apache.phoenix.schema.types.PUnsignedFloat;
import org.apache.phoenix.schema.types.PUnsignedInt;
import org.apache.phoenix.schema.types.PUnsignedLong;
import org.junit.Test;
import com.google.common.collect.Lists;
/**
* Unit tests for {@link LnFunction} and {@link LogFunction}
*/
public class LnLogFunctionTest {
private static final double ZERO = 1e-9;
private static final Expression THREE = LiteralExpression.newConstant(3);
private static final Expression DEFAULT_VALUE = LiteralExpression.newConstant(10.0);
private static boolean twoDoubleEquals(double a, double b) {
if (Double.isNaN(a) ^ Double.isNaN(b)) return false;
if (Double.isNaN(a)) return true;
if (Double.isInfinite(a) ^ Double.isInfinite(b)) return false;
if (Double.isInfinite(a)) {
if ((a > 0) ^ (b > 0)) return false;
else return true;
}
if (Math.abs(a - b) <= ZERO) {
return true;
} else {
return false;
}
}
private static boolean testExpression(LiteralExpression literal, LiteralExpression literal2,
LiteralExpression literal3, double exptForLn, double exptForLog10, double exptForLog3)
throws SQLException {
List<Expression> expressionsLn = Lists.newArrayList((Expression) literal);
List<Expression> expressionsLog10 = Lists.newArrayList(literal2, DEFAULT_VALUE);
List<Expression> expressionsLog3 = Lists.newArrayList(literal3, THREE);
ImmutableBytesWritable ptr = new ImmutableBytesWritable();
Expression lnFunction = new LnFunction(expressionsLn);
boolean retLn = lnFunction.evaluate(null, ptr);
if (retLn) {
Double result =
(Double) lnFunction.getDataType().toObject(ptr, lnFunction.getSortOrder());
assertTrue(twoDoubleEquals(result.doubleValue(), exptForLn));
}
Expression log10Function = new LogFunction(expressionsLog10);
boolean retLog10 = log10Function.evaluate(null, ptr);
if (retLog10) {
Double result =
(Double) log10Function.getDataType()
.toObject(ptr, log10Function.getSortOrder());
assertTrue(twoDoubleEquals(result.doubleValue(), exptForLog10));
}
assertEquals(retLn, retLog10);
Expression log3Function = new LogFunction(expressionsLog3);
boolean retLog3 = log3Function.evaluate(null, ptr);
if (retLog3) {
Double result =
(Double) log3Function.getDataType().toObject(ptr, log3Function.getSortOrder());
assertTrue(twoDoubleEquals(result.doubleValue(), exptForLog3));
}
assertEquals(retLn, retLog3);
return retLn;
}
private static void test(Number value, PNumericType dataType, double exptForLn,
double exptForLog10, double exptForLog3) throws SQLException {
LiteralExpression literal, literal2, literal3;
literal = LiteralExpression.newConstant(value, dataType, SortOrder.ASC);
literal2 = LiteralExpression.newConstant(value, dataType, SortOrder.ASC);
literal3 = LiteralExpression.newConstant(value, dataType, SortOrder.ASC);
boolean ret1 =
testExpression(literal, literal2, literal3, exptForLn, exptForLog10, exptForLog3);
literal = LiteralExpression.newConstant(value, dataType, SortOrder.DESC);
literal2 = LiteralExpression.newConstant(value, dataType, SortOrder.DESC);
literal3 = LiteralExpression.newConstant(value, dataType, SortOrder.DESC);
boolean ret2 =
testExpression(literal, literal2, literal3, exptForLn, exptForLog10, exptForLog3);
assertEquals(ret1, ret2);
}
private static void testBatch(Number[] value, PNumericType dataType) throws SQLException {
double[][] expected = new double[value.length][3];
for (int i = 0; i < expected.length; ++i) {
expected[i][0] = Math.log(value[i].doubleValue());
expected[i][1] = Math.log10(value[i].doubleValue());
expected[i][2] = Math.log10(value[i].doubleValue()) / Math.log10(3);
}
assertEquals(value.length, expected.length);
for (int i = 0; i < value.length; ++i) {
test(value[i], dataType, expected[i][0], expected[i][1], expected[i][2]);
}
}
@Test
public void testLnLogFunction() throws Exception {
Random random = new Random();
testBatch(
new BigDecimal[] { BigDecimal.valueOf(1.0), BigDecimal.valueOf(0.0),
BigDecimal.valueOf(-1.0), BigDecimal.valueOf(123.1234),
BigDecimal.valueOf(-123.1234), BigDecimal.valueOf(random.nextDouble()),
BigDecimal.valueOf(random.nextDouble()) }, PDecimal.INSTANCE);
testBatch(new Float[] { 1.0f, 0.0f, -1.0f, 123.1234f, -123.1234f, random.nextFloat(),
random.nextFloat() }, PFloat.INSTANCE);
testBatch(new Float[] { 1.0f, 0.0f, 123.1234f, }, PUnsignedFloat.INSTANCE);
testBatch(
new Double[] { 1.0, 0.0, -1.0, 123.1234, -123.1234, random.nextDouble(),
random.nextDouble() }, PDouble.INSTANCE);
testBatch(new Double[] { 1.0, 0.0, 123.1234, }, PUnsignedDouble.INSTANCE);
testBatch(
new Long[] { 1L, 0L, -1L, Long.MAX_VALUE, Long.MIN_VALUE, 123L, -123L,
random.nextLong(), random.nextLong() }, PLong.INSTANCE);
testBatch(new Long[] { 1L, 0L, Long.MAX_VALUE, 123L }, PUnsignedLong.INSTANCE);
testBatch(
new Integer[] { 1, 0, -1, Integer.MAX_VALUE, Integer.MIN_VALUE, 123, -123,
random.nextInt(), random.nextInt() }, PInteger.INSTANCE);
testBatch(new Integer[] { 1, 0, Integer.MAX_VALUE, 123 }, PUnsignedInt.INSTANCE);
testBatch(new Short[] { (short) 1, (short) 0, (short) -1, Short.MAX_VALUE, Short.MIN_VALUE,
(short) 123, (short) -123 }, PSmallint.INSTANCE);
testBatch(new Short[] { (short) 1, (short) 0, Short.MAX_VALUE, (short) 123 },
PSmallint.INSTANCE);
testBatch(new Byte[] { (byte) 1, (byte) 0, (byte) -1, Byte.MAX_VALUE, Byte.MIN_VALUE,
(byte) 123, (byte) -123 }, PTinyint.INSTANCE);
testBatch(new Byte[] { (byte) 1, (byte) 0, Byte.MAX_VALUE, (byte) 123 }, PTinyint.INSTANCE);
}
}
| apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk2/jdk/src/share/classes/sun/text/resources/is/JavaTimeSupplementary_is.java | 5763 | /*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COPYRIGHT AND PERMISSION NOTICE
*
* Copyright (C) 1991-2012 Unicode, Inc. All rights reserved. Distributed under
* the Terms of Use in http://www.unicode.org/copyright.html.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of the Unicode data files and any associated documentation (the "Data
* Files") or Unicode software and any associated documentation (the
* "Software") to deal in the Data Files or Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, and/or sell copies of the Data Files or Software, and
* to permit persons to whom the Data Files or Software are furnished to do so,
* provided that (a) the above copyright notice(s) and this permission notice
* appear with all copies of the Data Files or Software, (b) both the above
* copyright notice(s) and this permission notice appear in associated
* documentation, and (c) there is clear notice in each modified Data File or
* in the Software as well as in the documentation associated with the Data
* File(s) or Software that the data or software has been modified.
*
* THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
* KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
* THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
* INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR
* CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
* DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THE DATA FILES OR SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder shall not
* be used in advertising or otherwise to promote the sale, use or other
* dealings in these Data Files or Software without prior written authorization
* of the copyright holder.
*/
// Note: this file has been generated by a tool.
package sun.text.resources.is;
import sun.util.resources.OpenListResourceBundle;
public class JavaTimeSupplementary_is extends OpenListResourceBundle {
@Override
protected final Object[][] getContents() {
return new Object[][] {
{ "QuarterAbbreviations",
new String[] {
"F1",
"F2",
"F3",
"F4",
}
},
{ "QuarterNames",
new String[] {
"1st fj\u00f3r\u00f0ungur",
"2nd fj\u00f3r\u00f0ungur",
"3rd fj\u00f3r\u00f0ungur",
"4th fj\u00f3r\u00f0ungur",
}
},
{ "QuarterNarrows",
new String[] {
"1",
"2",
"3",
"4",
}
},
{ "calendarname.buddhist",
"B\u00fadd\u00edskt dagatal" },
{ "calendarname.gregorian",
"Gregor\u00edskt dagatal" },
{ "calendarname.gregory",
"Gregor\u00edskt dagatal" },
{ "calendarname.islamic",
"\u00cdslamskt dagatal" },
{ "calendarname.islamic-civil",
"\u00cdslamskt borgaradagatal" },
{ "calendarname.islamicc",
"\u00cdslamskt borgaradagatal" },
{ "calendarname.japanese",
"Japanskt dagatal" },
{ "calendarname.roc",
"k\u00ednverskt dagatal" },
{ "field.dayperiod",
"f.h./e.h." },
{ "field.era",
"t\u00edmabil" },
{ "field.hour",
"klukkustund" },
{ "field.minute",
"m\u00edn\u00fata" },
{ "field.month",
"m\u00e1nu\u00f0ur" },
{ "field.second",
"sek\u00fanda" },
{ "field.week",
"vika" },
{ "field.weekday",
"vikudagur" },
{ "field.year",
"\u00e1r" },
{ "field.zone",
"sv\u00e6\u00f0i" },
{ "java.time.short.Eras",
new String[] {
"fyrir Krist",
"eftir Krist",
}
},
};
}
}
| mit |
dahlstrom-g/intellij-community | platform/lang-api/src/com/intellij/execution/filters/OpenFileHyperlinkInfo.java | 1626 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* 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.intellij.execution.filters;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class OpenFileHyperlinkInfo extends FileHyperlinkInfoBase implements FileHyperlinkInfo {
private final VirtualFile myFile;
public OpenFileHyperlinkInfo(@NotNull OpenFileDescriptor descriptor) {
this(descriptor.getProject(), descriptor.getFile(), descriptor.getLine(), descriptor.getColumn());
}
public OpenFileHyperlinkInfo(@NotNull Project project, @NotNull VirtualFile file, int documentLine, int documentColumn) {
super(project, documentLine, documentColumn);
myFile = file;
}
public OpenFileHyperlinkInfo(@NotNull Project project, @NotNull final VirtualFile file, final int line) {
this(project, file, line, 0);
}
@Nullable
@Override
public VirtualFile getVirtualFile() {
return myFile;
}
}
| apache-2.0 |
WillCh/cs286A | dataMover/kafka/clients/src/test/java/org/apache/kafka/clients/ClientUtilsTest.java | 1447 | /**
* 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.kafka.clients;
import org.apache.kafka.common.config.ConfigException;
import org.junit.Test;
import java.util.Arrays;
public class ClientUtilsTest {
@Test
public void testParseAndValidateAddresses() {
check("127.0.0.1:8000");
check("mydomain.com:8080");
check("[::1]:8000");
check("[2001:db8:85a3:8d3:1319:8a2e:370:7348]:1234", "mydomain.com:10000");
}
@Test(expected = ConfigException.class)
public void testNoPort() {
check("127.0.0.1");
}
private void check(String... url) {
ClientUtils.parseAndValidateAddresses(Arrays.asList(url));
}
} | bsd-2-clause |
markwalkom/elasticsearch | modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/AppendProcessor.java | 3131 | /*
* 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.ingest.common;
import org.elasticsearch.ingest.AbstractProcessor;
import org.elasticsearch.ingest.ConfigurationUtils;
import org.elasticsearch.ingest.IngestDocument;
import org.elasticsearch.ingest.Processor;
import org.elasticsearch.ingest.ValueSource;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.TemplateScript;
import java.util.Map;
/**
* Processor that appends value or values to existing lists. If the field is not present a new list holding the
* provided values will be added. If the field is a scalar it will be converted to a single item list and the provided
* values will be added to the newly created list.
*/
public final class AppendProcessor extends AbstractProcessor {
public static final String TYPE = "append";
private final TemplateScript.Factory field;
private final ValueSource value;
AppendProcessor(String tag, TemplateScript.Factory field, ValueSource value) {
super(tag);
this.field = field;
this.value = value;
}
public TemplateScript.Factory getField() {
return field;
}
public ValueSource getValue() {
return value;
}
@Override
public void execute(IngestDocument ingestDocument) throws Exception {
ingestDocument.appendFieldValue(field, value);
}
@Override
public String getType() {
return TYPE;
}
public static final class Factory implements Processor.Factory {
private final ScriptService scriptService;
public Factory(ScriptService scriptService) {
this.scriptService = scriptService;
}
@Override
public AppendProcessor create(Map<String, Processor.Factory> registry, String processorTag,
Map<String, Object> config) throws Exception {
String field = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "field");
Object value = ConfigurationUtils.readObject(TYPE, processorTag, config, "value");
TemplateScript.Factory compiledTemplate = ConfigurationUtils.compileTemplate(TYPE, processorTag,
"field", field, scriptService);
return new AppendProcessor(processorTag, compiledTemplate, ValueSource.wrap(value, scriptService));
}
}
}
| apache-2.0 |
akosyakov/intellij-community | python/testSrc/com/jetbrains/python/refactoring/PyConvertPackageToModuleTest.java | 1324 | package com.jetbrains.python.refactoring;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiManager;
import com.intellij.testFramework.PlatformTestUtil;
import com.jetbrains.python.fixtures.PyTestCase;
import com.jetbrains.python.refactoring.convert.PyConvertPackageToModuleAction;
/**
* @author Mikhail Golubev
*/
public class PyConvertPackageToModuleTest extends PyTestCase {
// PY-4387
public void testSimple() throws Exception {
final String rootBeforePath = getTestName(true) + "/before";
final String rootAfterPath = getTestName(true) + "/after";
final VirtualFile copiedDirectory = myFixture.copyDirectoryToProject(rootBeforePath, "");
final VirtualFile directory = assertInstanceOf(myFixture.findFileInTempDir("a"), VirtualFile.class);
final PsiDirectory packageToConvert = PsiManager.getInstance(myFixture.getProject()).findDirectory(directory);
assertNotNull(packageToConvert);
new PyConvertPackageToModuleAction().createModuleFromPackage(packageToConvert);
PlatformTestUtil.assertDirectoriesEqual(copiedDirectory, getVirtualFileByName(getTestDataPath() +rootAfterPath));
}
@Override
protected String getTestDataPath() {
return super.getTestDataPath() + "/refactoring/convertPackageToModule/";
}
}
| apache-2.0 |
OpenCollabZA/sakai | edu-services/gradebook-service/impl/src/java/org/sakaiproject/tool/gradebook/facades/sections/AuthzSectionsImpl.java | 27307 | /**
* Copyright (c) 2003-2017 The Apereo Foundation
*
* Licensed under the Educational Community 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://opensource.org/licenses/ecl2
*
* 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.sakaiproject.tool.gradebook.facades.sections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.section.api.SectionAwareness;
import org.sakaiproject.section.api.coursemanagement.CourseSection;
import org.sakaiproject.section.api.coursemanagement.EnrollmentRecord;
import org.sakaiproject.section.api.facade.Role;
import org.sakaiproject.service.gradebook.shared.GradebookPermissionService;
import org.sakaiproject.service.gradebook.shared.GradebookService;
import org.sakaiproject.site.api.Group;
import org.sakaiproject.tool.gradebook.GradebookAssignment;
import org.sakaiproject.tool.gradebook.facades.Authn;
import org.sakaiproject.tool.gradebook.facades.Authz;
/**
* An implementation of Gradebook-specific authorization needs based
* on the shared Section Awareness API.
*/
@Slf4j
public class AuthzSectionsImpl implements Authz {
private Authn authn;
private SectionAwareness sectionAwareness;
private GradebookPermissionService gradebookPermissionService;
public boolean isUserAbleToGrade(String gradebookUid) {
String userUid = authn.getUserUid();
return isUserAbleToGrade(gradebookUid, userUid);
}
public boolean isUserAbleToGrade(String gradebookUid, String userUid) {
return (getSectionAwareness().isSiteMemberInRole(gradebookUid, userUid, Role.INSTRUCTOR) || getSectionAwareness().isSiteMemberInRole(gradebookUid, userUid, Role.TA));
}
public boolean isUserAbleToGradeAll(String gradebookUid) {
return isUserAbleToGradeAll(gradebookUid, authn.getUserUid());
}
public boolean isUserAbleToGradeAll(String gradebookUid, String userUid) {
return getSectionAwareness().isSiteMemberInRole(gradebookUid, userUid, Role.INSTRUCTOR);
}
public boolean isUserHasGraderPermissions(String gradebookUid) {
String userUid = authn.getUserUid();
List permissions = gradebookPermissionService.getGraderPermissionsForUser(gradebookUid, userUid);
return permissions != null && permissions.size() > 0;
}
public boolean isUserHasGraderPermissions(Long gradebookId) {
String userUid = authn.getUserUid();
List permissions = gradebookPermissionService.getGraderPermissionsForUser(gradebookId, userUid);
return permissions != null && permissions.size() > 0;
}
public boolean isUserHasGraderPermissions(String gradebookUid, String userUid) {
List permissions = gradebookPermissionService.getGraderPermissionsForUser(gradebookUid, userUid);
return permissions != null && permissions.size() > 0;
}
public boolean isUserHasGraderPermissions(Long gradebookId, String userUid) {
List permissions = gradebookPermissionService.getGraderPermissionsForUser(gradebookId, userUid);
return permissions != null && permissions.size() > 0;
}
/**
*
* @param sectionUid
* @return whether user is Role.TA in given section
*/
private boolean isUserTAinSection(String sectionUid) {
String userUid = authn.getUserUid();
return getSectionAwareness().isSectionMemberInRole(sectionUid, userUid, Role.TA);
}
private boolean isUserTAinSection(String sectionUid, String userUid) {
return getSectionAwareness().isSectionMemberInRole(sectionUid, userUid, Role.TA);
}
public boolean isUserAbleToEditAssessments(String gradebookUid) {
String userUid = authn.getUserUid();
return getSectionAwareness().isSiteMemberInRole(gradebookUid, userUid, Role.INSTRUCTOR);
}
public boolean isUserAbleToViewOwnGrades(String gradebookUid) {
String userUid = authn.getUserUid();
return getSectionAwareness().isSiteMemberInRole(gradebookUid, userUid, Role.STUDENT);
}
public boolean isUserAbleToViewStudentNumbers(String gradebookUid)
{
String userUid = authn.getUserUid();
return getSectionAwareness().isSiteMemberInRole(gradebookUid, userUid, Role.INSTRUCTOR);
}
public String getGradeViewFunctionForUserForStudentForItem(String gradebookUid, Long itemId, String studentUid) {
if (itemId == null || studentUid == null || gradebookUid == null) {
throw new IllegalArgumentException("Null parameter(s) in AuthzSectionsServiceImpl.isUserAbleToGradeItemForStudent");
}
if (isUserAbleToGradeAll(gradebookUid)) {
return GradebookService.gradePermission;
}
String userUid = authn.getUserUid();
List viewableSections = getViewableSections(gradebookUid);
List sectionIds = new ArrayList();
if (viewableSections != null && !viewableSections.isEmpty()) {
for (Iterator sectionIter = viewableSections.iterator(); sectionIter.hasNext();) {
CourseSection section = (CourseSection) sectionIter.next();
sectionIds.add(section.getUuid());
}
}
if (isUserHasGraderPermissions(gradebookUid, userUid)) {
// get the map of authorized item (assignment) ids to grade/view function
Map itemIdFunctionMap = gradebookPermissionService.getAvailableItemsForStudent(gradebookUid, userUid, studentUid, viewableSections);
if (itemIdFunctionMap == null || itemIdFunctionMap.isEmpty()) {
return null; // not authorized to grade/view any items for this student
}
String functionValueForItem = (String)itemIdFunctionMap.get(itemId);
String view = GradebookService.viewPermission;
String grade = GradebookService.gradePermission;
if (functionValueForItem != null) {
if (functionValueForItem.equalsIgnoreCase(grade))
return GradebookService.gradePermission;
if (functionValueForItem.equalsIgnoreCase(view))
return GradebookService.viewPermission;
}
return null;
} else {
// use OOTB permissions based upon TA section membership
for (Iterator iter = sectionIds.iterator(); iter.hasNext(); ) {
String sectionUuid = (String) iter.next();
if (isUserTAinSection(sectionUuid) && getSectionAwareness().isSectionMemberInRole(sectionUuid, studentUid, Role.STUDENT)) {
return GradebookService.gradePermission;
}
}
return null;
}
}
private boolean isUserAbleToGradeOrViewItemForStudent(String gradebookUid, Long itemId, String studentUid, String function) throws IllegalArgumentException {
if (itemId == null || studentUid == null || function == null) {
throw new IllegalArgumentException("Null parameter(s) in AuthzSectionsServiceImpl.isUserAbleToGradeItemForStudent");
}
if (isUserAbleToGradeAll(gradebookUid)) {
return true;
}
String userUid = authn.getUserUid();
List viewableSections = getViewableSections(gradebookUid);
List sectionIds = new ArrayList();
if (viewableSections != null && !viewableSections.isEmpty()) {
for (Iterator sectionIter = viewableSections.iterator(); sectionIter.hasNext();) {
CourseSection section = (CourseSection) sectionIter.next();
sectionIds.add(section.getUuid());
}
}
if (isUserHasGraderPermissions(gradebookUid, userUid)) {
// get the map of authorized item (assignment) ids to grade/view function
Map itemIdFunctionMap = gradebookPermissionService.getAvailableItemsForStudent(gradebookUid, userUid, studentUid, viewableSections);
if (itemIdFunctionMap == null || itemIdFunctionMap.isEmpty()) {
return false; // not authorized to grade/view any items for this student
}
String functionValueForItem = (String)itemIdFunctionMap.get(itemId);
String view = GradebookService.viewPermission;
String grade = GradebookService.gradePermission;
if (functionValueForItem != null) {
if (function.equalsIgnoreCase(grade) && functionValueForItem.equalsIgnoreCase(grade))
return true;
if (function.equalsIgnoreCase(view) && (functionValueForItem.equalsIgnoreCase(grade) || functionValueForItem.equalsIgnoreCase(view)))
return true;
}
return false;
} else {
// use OOTB permissions based upon TA section membership
for (Iterator iter = sectionIds.iterator(); iter.hasNext(); ) {
String sectionUuid = (String) iter.next();
if (isUserTAinSection(sectionUuid) && getSectionAwareness().isSectionMemberInRole(sectionUuid, studentUid, Role.STUDENT)) {
return true;
}
}
return false;
}
}
public boolean isUserAbleToGradeItemForStudent(String gradebookUid, Long itemId, String studentUid) throws IllegalArgumentException {
return isUserAbleToGradeOrViewItemForStudent(gradebookUid, itemId, studentUid, GradebookService.gradePermission);
}
public boolean isUserAbleToViewItemForStudent(String gradebookUid, Long itemId, String studentUid) throws IllegalArgumentException {
return isUserAbleToGradeOrViewItemForStudent(gradebookUid, itemId, studentUid, GradebookService.viewPermission);
}
public List getViewableSections(String gradebookUid) {
List viewableSections = new ArrayList();
List allSections = getAllSections(gradebookUid);
if (allSections == null || allSections.isEmpty()) {
return viewableSections;
}
if (isUserAbleToGradeAll(gradebookUid)) {
return allSections;
}
Map sectionIdCourseSectionMap = new HashMap();
for (Iterator sectionIter = allSections.iterator(); sectionIter.hasNext();) {
CourseSection section = (CourseSection) sectionIter.next();
sectionIdCourseSectionMap.put(section.getUuid(), section);
}
String userUid = authn.getUserUid();
if (isUserHasGraderPermissions(gradebookUid, userUid)) {
List viewableSectionIds = gradebookPermissionService.getViewableGroupsForUser(gradebookUid, userUid, new ArrayList(sectionIdCourseSectionMap.keySet()));
if (viewableSectionIds != null && !viewableSectionIds.isEmpty()) {
for (Iterator idIter = viewableSectionIds.iterator(); idIter.hasNext();) {
String sectionUuid = (String) idIter.next();
CourseSection viewableSection = (CourseSection)sectionIdCourseSectionMap.get(sectionUuid);
if (viewableSection != null)
viewableSections.add(viewableSection);
}
}
} else {
// return all sections that the current user is a TA for
for (Iterator<Map.Entry<String, CourseSection>> iter = sectionIdCourseSectionMap.entrySet().iterator(); iter.hasNext(); ) {
Map.Entry<String, CourseSection> entry = iter.next();
String sectionUuid = entry.getKey();
if (isUserTAinSection(sectionUuid)) {
CourseSection viewableSection = (CourseSection)sectionIdCourseSectionMap.get(sectionUuid);
if (viewableSection != null)
viewableSections.add(viewableSection);
}
}
}
Collections.sort(viewableSections);
return viewableSections;
}
public List getAllSections(String gradebookUid) {
SectionAwareness sectionAwareness = getSectionAwareness();
List sections = sectionAwareness.getSections(gradebookUid);
return sections;
}
private List getSectionEnrollmentsTrusted(String sectionUid) {
return getSectionAwareness().getSectionMembersInRole(sectionUid, Role.STUDENT);
}
public Map findMatchingEnrollmentsForItem(String gradebookUid, Long categoryId, int gbCategoryType, String optionalSearchString, String optionalSectionUid) {
String userUid = authn.getUserUid();
return findMatchingEnrollmentsForItemOrCourseGrade(userUid, gradebookUid, categoryId, gbCategoryType, optionalSearchString, optionalSectionUid, false);
}
public Map findMatchingEnrollmentsForItemForUser(String userUid, String gradebookUid, Long categoryId, int gbCategoryType, String optionalSearchString, String optionalSectionUid) {
return findMatchingEnrollmentsForItemOrCourseGrade(userUid, gradebookUid, categoryId, gbCategoryType, optionalSearchString, optionalSectionUid, false);
}
public Map findMatchingEnrollmentsForViewableCourseGrade(String gradebookUid, int gbCategoryType, String optionalSearchString, String optionalSectionUid) {
String userUid = authn.getUserUid();
return findMatchingEnrollmentsForItemOrCourseGrade(userUid, gradebookUid, null, gbCategoryType, optionalSearchString, optionalSectionUid, true);
}
public Map findMatchingEnrollmentsForViewableItems(String gradebookUid, List allGbItems, String optionalSearchString, String optionalSectionUid) {
Map enrollmentMap = new HashMap();
List<EnrollmentRecord> filteredEnrollments = null;
if (optionalSearchString != null)
filteredEnrollments = getSectionAwareness().findSiteMembersInRole(gradebookUid, Role.STUDENT, optionalSearchString);
else
filteredEnrollments = getSectionAwareness().getSiteMembersInRole(gradebookUid, Role.STUDENT);
if (filteredEnrollments == null || filteredEnrollments.isEmpty())
return enrollmentMap;
// get all the students in the filtered section, if appropriate
Map<String, EnrollmentRecord> studentsInSectionMap = new HashMap<String, EnrollmentRecord>();
if (optionalSectionUid != null) {
List<EnrollmentRecord> sectionMembers = getSectionEnrollmentsTrusted(optionalSectionUid);
if (!sectionMembers.isEmpty()) {
for(Iterator<EnrollmentRecord> memberIter = sectionMembers.iterator(); memberIter.hasNext();) {
EnrollmentRecord member = (EnrollmentRecord) memberIter.next();
studentsInSectionMap.put(member.getUser().getUserUid(), member);
}
}
}
Map<String, EnrollmentRecord> studentIdEnrRecMap = new HashMap<String, EnrollmentRecord>();
for (Iterator<EnrollmentRecord> enrIter = filteredEnrollments.iterator(); enrIter.hasNext();) {
EnrollmentRecord enr = (EnrollmentRecord) enrIter.next();
String studentId = enr.getUser().getUserUid();
if (optionalSectionUid != null) {
if (studentsInSectionMap.containsKey(studentId)) {
studentIdEnrRecMap.put(studentId, enr);
}
} else {
studentIdEnrRecMap.put(studentId, enr);
}
}
if (isUserAbleToGradeAll(gradebookUid)) {
List enrollments = new ArrayList(studentIdEnrRecMap.values());
HashMap assignFunctionMap = new HashMap();
if (allGbItems != null && !allGbItems.isEmpty()) {
for (Iterator assignIter = allGbItems.iterator(); assignIter.hasNext();) {
Object assign = assignIter.next();
Long assignId = null;
if (assign instanceof org.sakaiproject.service.gradebook.shared.Assignment) {
assignId = ((org.sakaiproject.service.gradebook.shared.Assignment)assign).getId();
} else if (assign instanceof GradebookAssignment) {
assignId = ((GradebookAssignment)assign).getId();
}
if (assignId != null)
assignFunctionMap.put(assignId, GradebookService.gradePermission);
}
}
for (Iterator enrIter = enrollments.iterator(); enrIter.hasNext();) {
EnrollmentRecord enr = (EnrollmentRecord) enrIter.next();
enrollmentMap.put(enr, assignFunctionMap);
}
} else {
String userId = authn.getUserUid();
Map sectionIdCourseSectionMap = new HashMap();
List viewableSections = getViewableSections(gradebookUid);
for (Iterator sectionIter = viewableSections.iterator(); sectionIter.hasNext();) {
CourseSection section = (CourseSection) sectionIter.next();
sectionIdCourseSectionMap.put(section.getUuid(), section);
}
if (isUserHasGraderPermissions(gradebookUid)) {
// user has special grader permissions that override default perms
List myStudentIds = new ArrayList(studentIdEnrRecMap.keySet());
List selSections = new ArrayList();
if (optionalSectionUid == null) {
// pass all sections
selSections = new ArrayList(sectionIdCourseSectionMap.values());
} else {
// only pass the selected section
CourseSection section = (CourseSection) sectionIdCourseSectionMap.get(optionalSectionUid);
if (section != null)
selSections.add(section);
}
// we need to get the viewable students, so first create section id --> student ids map
myStudentIds = getGradebookPermissionService().getViewableStudentsForUser(gradebookUid, userId, myStudentIds, selSections);
Map viewableStudentIdItemsMap = new HashMap();
if (allGbItems == null || allGbItems.isEmpty()) {
if (myStudentIds != null) {
for (Iterator stIter = myStudentIds.iterator(); stIter.hasNext();) {
String stId = (String) stIter.next();
if (stId != null)
viewableStudentIdItemsMap.put(stId, null);
}
}
} else {
viewableStudentIdItemsMap = gradebookPermissionService.getAvailableItemsForStudents(gradebookUid, userId, myStudentIds, selSections);
}
if (!viewableStudentIdItemsMap.isEmpty()) {
for (Iterator<Map.Entry<String, EnrollmentRecord>> enrIter = viewableStudentIdItemsMap.entrySet().iterator(); enrIter.hasNext();) {
Map.Entry<String, EnrollmentRecord> entry = enrIter.next();
String studentId = entry.getKey();
EnrollmentRecord enrRec = (EnrollmentRecord)studentIdEnrRecMap.get(studentId);
if (enrRec != null) {
Map itemIdFunctionMap = (Map)viewableStudentIdItemsMap.get(studentId);
//if (!itemIdFunctionMap.isEmpty()) {
enrollmentMap.put(enrRec, itemIdFunctionMap);
//}
}
}
}
} else {
// use default section-based permissions
// Determine the current user's section memberships
List availableSections = new ArrayList();
if (optionalSectionUid != null && isUserTAinSection(optionalSectionUid)) {
if (sectionIdCourseSectionMap.containsKey(optionalSectionUid))
availableSections.add(optionalSectionUid);
} else {
for (Iterator iter = sectionIdCourseSectionMap.keySet().iterator(); iter.hasNext(); ) {
String sectionUuid = (String)iter.next();
if (isUserTAinSection(sectionUuid)) {
availableSections.add(sectionUuid);
}
}
}
// Determine which enrollees are in these sections
Map uniqueEnrollees = new HashMap();
for (Iterator iter = availableSections.iterator(); iter.hasNext(); ) {
String sectionUuid = (String)iter.next();
List sectionEnrollments = getSectionEnrollmentsTrusted(sectionUuid);
for (Iterator eIter = sectionEnrollments.iterator(); eIter.hasNext(); ) {
EnrollmentRecord enr = (EnrollmentRecord)eIter.next();
uniqueEnrollees.put(enr.getUser().getUserUid(), enr);
}
}
// Filter out based upon the original filtered students
for (Iterator iter = studentIdEnrRecMap.keySet().iterator(); iter.hasNext(); ) {
String enrId = (String)iter.next();
if (uniqueEnrollees.containsKey(enrId)) {
// iterate through the assignments
Map itemFunctionMap = new HashMap();
if (allGbItems != null && !allGbItems.isEmpty()) {
for (Iterator itemIter = allGbItems.iterator(); itemIter.hasNext();) {
Object assign = itemIter.next();
Long assignId = null;
if (assign instanceof org.sakaiproject.service.gradebook.shared.Assignment) {
assignId = ((org.sakaiproject.service.gradebook.shared.Assignment)assign).getId();
} else if (assign instanceof GradebookAssignment) {
assignId = ((GradebookAssignment)assign).getId();
}
if (assignId != null) {
itemFunctionMap.put(assignId, GradebookService.gradePermission);
}
}
}
enrollmentMap.put(studentIdEnrRecMap.get(enrId), itemFunctionMap);
}
}
}
}
return enrollmentMap;
}
/**
* @param userUid
* @param gradebookUid
* @param categoryId
* @param optionalSearchString
* @param optionalSectionUid
* @param itemIsCourseGrade
* @return Map of EnrollmentRecord --> View or Grade
*/
private Map findMatchingEnrollmentsForItemOrCourseGrade(String userUid, String gradebookUid, Long categoryId, int gbCategoryType, String optionalSearchString, String optionalSectionUid, boolean itemIsCourseGrade) {
Map enrollmentMap = new HashMap();
List filteredEnrollments = new ArrayList();
if (optionalSearchString != null)
filteredEnrollments = getSectionAwareness().findSiteMembersInRole(gradebookUid, Role.STUDENT, optionalSearchString);
else
filteredEnrollments = getSectionAwareness().getSiteMembersInRole(gradebookUid, Role.STUDENT);
if (filteredEnrollments.isEmpty())
return enrollmentMap;
// get all the students in the filtered section, if appropriate
Map studentsInSectionMap = new HashMap();
if (optionalSectionUid != null) {
List sectionMembers = getSectionAwareness().getSectionMembersInRole(optionalSectionUid, Role.STUDENT);
if (!sectionMembers.isEmpty()) {
for(Iterator memberIter = sectionMembers.iterator(); memberIter.hasNext();) {
EnrollmentRecord member = (EnrollmentRecord) memberIter.next();
studentsInSectionMap.put(member.getUser().getUserUid(), member);
}
}
}
Map studentIdEnrRecMap = new HashMap();
for (Iterator enrIter = filteredEnrollments.iterator(); enrIter.hasNext();) {
EnrollmentRecord enr = (EnrollmentRecord) enrIter.next();
String studentId = enr.getUser().getUserUid();
if (optionalSectionUid != null) {
if (studentsInSectionMap.containsKey(studentId)) {
studentIdEnrRecMap.put(studentId, enr);
}
} else {
studentIdEnrRecMap.put(enr.getUser().getUserUid(), enr);
}
}
if (isUserAbleToGradeAll(gradebookUid, userUid)) {
List enrollments = new ArrayList(studentIdEnrRecMap.values());
for (Iterator enrIter = enrollments.iterator(); enrIter.hasNext();) {
EnrollmentRecord enr = (EnrollmentRecord) enrIter.next();
enrollmentMap.put(enr, GradebookService.gradePermission);
}
} else {
Map sectionIdCourseSectionMap = new HashMap();
List allSections = getAllSections(gradebookUid);
for (Iterator sectionIter = allSections.iterator(); sectionIter.hasNext();) {
CourseSection section = (CourseSection) sectionIter.next();
sectionIdCourseSectionMap.put(section.getUuid(), section);
}
if (isUserHasGraderPermissions(gradebookUid, userUid)) {
// user has special grader permissions that override default perms
List myStudentIds = new ArrayList(studentIdEnrRecMap.keySet());
List selSections = new ArrayList();
if (optionalSectionUid == null) {
// pass all sections
selSections = new ArrayList(sectionIdCourseSectionMap.values());
} else {
// only pass the selected section
CourseSection section = (CourseSection) sectionIdCourseSectionMap.get(optionalSectionUid);
if (section != null)
selSections.add(section);
}
Map viewableEnrollees = new HashMap();
if (itemIsCourseGrade) {
viewableEnrollees = gradebookPermissionService.getCourseGradePermission(gradebookUid, userUid, myStudentIds, selSections);
} else {
viewableEnrollees = gradebookPermissionService.getStudentsForItem(gradebookUid, userUid, myStudentIds, gbCategoryType, categoryId, selSections);
}
if (!viewableEnrollees.isEmpty()) {
for (Iterator<Map.Entry<String, EnrollmentRecord>> enrIter = viewableEnrollees.entrySet().iterator(); enrIter.hasNext();) {
Map.Entry<String, EnrollmentRecord> entry = enrIter.next();
String studentId = entry.getKey();
EnrollmentRecord enrRec = (EnrollmentRecord)studentIdEnrRecMap.get(studentId);
if (enrRec != null) {
enrollmentMap.put(enrRec, (String)viewableEnrollees.get(studentId));
}
}
}
} else {
// use default section-based permissions
enrollmentMap = getEnrollmentMapUsingDefaultPermissions(userUid, studentIdEnrRecMap, sectionIdCourseSectionMap, optionalSectionUid);
}
}
return enrollmentMap;
}
/**
*
* @param userUid
* @param studentIdEnrRecMap
* @param sectionIdCourseSectionMap
* @param optionalSectionUid
* @return Map of EnrollmentRecord to function view/grade using the default permissions (based on TA section membership)
*/
private Map getEnrollmentMapUsingDefaultPermissions(String userUid, Map studentIdEnrRecMap, Map sectionIdCourseSectionMap, String optionalSectionUid) {
// Determine the current user's section memberships
Map enrollmentMap = new HashMap();
List availableSections = new ArrayList();
if (optionalSectionUid != null && isUserTAinSection(optionalSectionUid, userUid)) {
if (sectionIdCourseSectionMap.containsKey(optionalSectionUid))
availableSections.add(optionalSectionUid);
} else {
for (Iterator iter = sectionIdCourseSectionMap.keySet().iterator(); iter.hasNext(); ) {
String sectionUuid = (String)iter.next();
if (isUserTAinSection(sectionUuid, userUid)) {
availableSections.add(sectionUuid);
}
}
}
// Determine which enrollees are in these sections
Map uniqueEnrollees = new HashMap();
for (Iterator iter = availableSections.iterator(); iter.hasNext(); ) {
String sectionUuid = (String)iter.next();
List sectionEnrollments = getSectionEnrollmentsTrusted(sectionUuid);
for (Iterator eIter = sectionEnrollments.iterator(); eIter.hasNext(); ) {
EnrollmentRecord enr = (EnrollmentRecord)eIter.next();
uniqueEnrollees.put(enr.getUser().getUserUid(), enr);
}
}
// Filter out based upon the original filtered students
for (Iterator iter = studentIdEnrRecMap.keySet().iterator(); iter.hasNext(); ) {
String enrId = (String)iter.next();
if (uniqueEnrollees.containsKey(enrId)) {
enrollmentMap.put(studentIdEnrRecMap.get(enrId), GradebookService.gradePermission);
}
}
return enrollmentMap;
}
public List findStudentSectionMemberships(String gradebookUid, String studentUid) {
List sectionMemberships = new ArrayList();
try {
sectionMemberships = (List)org.sakaiproject.site.cover.SiteService.getSite(gradebookUid).getGroupsWithMember(studentUid);
} catch (IdUnusedException e) {
log.error("No site with id = " + gradebookUid);
}
return sectionMemberships;
}
public List getStudentSectionMembershipNames(String gradebookUid, String studentUid) {
List sectionNames = new ArrayList();
List sections = findStudentSectionMemberships(gradebookUid, studentUid);
if (sections != null && !sections.isEmpty()) {
Iterator sectionIter = sections.iterator();
while (sectionIter.hasNext()) {
Group myGroup = (Group) sectionIter.next();
sectionNames.add(myGroup.getTitle());
}
}
return sectionNames;
}
public Authn getAuthn() {
return authn;
}
public void setAuthn(Authn authn) {
this.authn = authn;
}
public SectionAwareness getSectionAwareness() {
return sectionAwareness;
}
public void setSectionAwareness(SectionAwareness sectionAwareness) {
this.sectionAwareness = sectionAwareness;
}
public GradebookPermissionService getGradebookPermissionService() {
return gradebookPermissionService;
}
public void setGradebookPermissionService(GradebookPermissionService gradebookPermissionService) {
this.gradebookPermissionService = gradebookPermissionService;
}
}
| apache-2.0 |
gfyoung/elasticsearch | x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/notification/pagerduty/IncidentEventDefaultsTests.java | 4735 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.watcher.notification.pagerduty;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.test.ESTestCase;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.Matchers.is;
public class IncidentEventDefaultsTests extends ESTestCase {
public void testConstructor() throws Exception {
Settings settings = randomSettings();
IncidentEventDefaults defaults = new IncidentEventDefaults(settings);
assertThat(defaults.incidentKey, is(settings.get("incident_key", null)));
assertThat(defaults.description, is(settings.get("description", null)));
assertThat(defaults.clientUrl, is(settings.get("client_url", null)));
assertThat(defaults.client, is(settings.get("client", null)));
assertThat(defaults.eventType, is(settings.get("event_type", null)));
assertThat(defaults.attachPayload, is(settings.getAsBoolean("attach_payload", false)));
if (settings.getAsSettings("link").names().isEmpty()) {
IncidentEventDefaults.Context.LinkDefaults linkDefaults = new IncidentEventDefaults.Context.LinkDefaults(Settings.EMPTY);
assertThat(defaults.link, is(linkDefaults));
} else {
assertThat(defaults.link, notNullValue());
assertThat(defaults.link.href, is(settings.get("link.href", null)));
assertThat(defaults.link.text, is(settings.get("link.text", null)));
}
if (settings.getAsSettings("image").names().isEmpty()) {
IncidentEventDefaults.Context.ImageDefaults imageDefaults = new IncidentEventDefaults.Context.ImageDefaults(Settings.EMPTY);
assertThat(defaults.image, is(imageDefaults));
} else {
assertThat(defaults.image, notNullValue());
assertThat(defaults.image.href, is(settings.get("image.href", null)));
assertThat(defaults.image.alt, is(settings.get("image.alt", null)));
assertThat(defaults.image.src, is(settings.get("image.src", null)));
}
}
public static Settings randomSettings() {
Settings.Builder settings = Settings.builder();
if (randomBoolean()) {
settings.put("from", randomAlphaOfLength(10));
}
if (randomBoolean()) {
String[] to = new String[randomIntBetween(1, 3)];
for (int i = 0; i < to.length; i++) {
to[i] = randomAlphaOfLength(10);
}
settings.putList("to", to);
}
if (randomBoolean()) {
settings.put("text", randomAlphaOfLength(10));
}
if (randomBoolean()) {
settings.put("event_type", randomAlphaOfLength(10));
}
if (randomBoolean()) {
settings.put("icon", randomAlphaOfLength(10));
}
if (randomBoolean()) {
settings.put("attachment.fallback", randomAlphaOfLength(10));
}
if (randomBoolean()) {
settings.put("attachment.color", randomAlphaOfLength(10));
}
if (randomBoolean()) {
settings.put("attachment.pretext", randomAlphaOfLength(10));
}
if (randomBoolean()) {
settings.put("attachment.author_name", randomAlphaOfLength(10));
}
if (randomBoolean()) {
settings.put("attachment.author_link", randomAlphaOfLength(10));
}
if (randomBoolean()) {
settings.put("attachment.author_icon", randomAlphaOfLength(10));
}
if (randomBoolean()) {
settings.put("attachment.title", randomAlphaOfLength(10));
}
if (randomBoolean()) {
settings.put("attachment.title_link", randomAlphaOfLength(10));
}
if (randomBoolean()) {
settings.put("attachment.text", randomAlphaOfLength(10));
}
if (randomBoolean()) {
settings.put("attachment.image_url", randomAlphaOfLength(10));
}
if (randomBoolean()) {
settings.put("attachment.thumb_url", randomAlphaOfLength(10));
}
if (randomBoolean()) {
settings.put("attachment.field.title", randomAlphaOfLength(10));
}
if (randomBoolean()) {
settings.put("attachment.field.value", randomAlphaOfLength(10));
}
if (randomBoolean()) {
settings.put("attachment.field.short", randomBoolean());
}
return settings.build();
}
}
| apache-2.0 |
tianshouzhi/hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/protocolPB/ClientNamenodeProtocolTranslatorPB.java | 59555 | /**
* 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.hdfs.protocolPB;
import java.io.Closeable;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import com.google.common.collect.Lists;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.crypto.CryptoProtocolVersion;
import org.apache.hadoop.fs.BatchedRemoteIterator.BatchedEntries;
import org.apache.hadoop.fs.CacheFlag;
import org.apache.hadoop.fs.ContentSummary;
import org.apache.hadoop.fs.CreateFlag;
import org.apache.hadoop.fs.FileAlreadyExistsException;
import org.apache.hadoop.fs.FsServerDefaults;
import org.apache.hadoop.fs.Options.Rename;
import org.apache.hadoop.fs.ParentNotDirectoryException;
import org.apache.hadoop.fs.StorageType;
import org.apache.hadoop.fs.UnresolvedLinkException;
import org.apache.hadoop.fs.XAttr;
import org.apache.hadoop.fs.XAttrSetFlag;
import org.apache.hadoop.fs.permission.AclEntry;
import org.apache.hadoop.fs.permission.AclStatus;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hdfs.inotify.EventBatchList;
import org.apache.hadoop.hdfs.protocol.AlreadyBeingCreatedException;
import org.apache.hadoop.hdfs.protocol.BlockStoragePolicy;
import org.apache.hadoop.hdfs.protocol.CacheDirectiveEntry;
import org.apache.hadoop.hdfs.protocol.CacheDirectiveInfo;
import org.apache.hadoop.hdfs.protocol.CachePoolEntry;
import org.apache.hadoop.hdfs.protocol.CachePoolInfo;
import org.apache.hadoop.hdfs.protocol.ClientProtocol;
import org.apache.hadoop.hdfs.protocol.CorruptFileBlocks;
import org.apache.hadoop.hdfs.protocol.DSQuotaExceededException;
import org.apache.hadoop.hdfs.protocol.DatanodeID;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.DirectoryListing;
import org.apache.hadoop.hdfs.protocol.EncryptionZone;
import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
import org.apache.hadoop.hdfs.protocol.HdfsConstants.DatanodeReportType;
import org.apache.hadoop.hdfs.protocol.HdfsConstants.RollingUpgradeAction;
import org.apache.hadoop.hdfs.protocol.HdfsConstants.SafeModeAction;
import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
import org.apache.hadoop.hdfs.protocol.LastBlockWithStatus;
import org.apache.hadoop.hdfs.protocol.LocatedBlock;
import org.apache.hadoop.hdfs.protocol.LocatedBlocks;
import org.apache.hadoop.hdfs.protocol.NSQuotaExceededException;
import org.apache.hadoop.hdfs.protocol.RollingUpgradeInfo;
import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport;
import org.apache.hadoop.hdfs.protocol.SnapshottableDirectoryStatus;
import org.apache.hadoop.hdfs.protocol.proto.AclProtos.GetAclStatusRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.AclProtos.ModifyAclEntriesRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.AclProtos.RemoveAclEntriesRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.AclProtos.RemoveAclRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.AclProtos.RemoveDefaultAclRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.AclProtos.SetAclRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AbandonBlockRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AddBlockRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AddCacheDirectiveRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AddCachePoolRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AllowSnapshotRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AppendRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AppendResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CachePoolEntryProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CheckAccessRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CompleteRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ConcatRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CreateRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CreateResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CreateSnapshotRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CreateSymlinkRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.DeleteRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.DeleteSnapshotRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.DisallowSnapshotRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.FinalizeUpgradeRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.FsyncRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetAdditionalDatanodeRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetBlockLocationsRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetBlockLocationsResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetContentSummaryRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetCurrentEditLogTxidRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetDataEncryptionKeyRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetDataEncryptionKeyResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetDatanodeReportRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetDatanodeStorageReportRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetEditsFromTxidRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetFileInfoRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetFileInfoResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetFileLinkInfoRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetFileLinkInfoResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetFsStatusRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetLinkTargetRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetLinkTargetResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetListingRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetListingResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetPreferredBlockSizeRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetServerDefaultsRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetSnapshotDiffReportRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetSnapshotDiffReportResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetSnapshottableDirListingRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetSnapshottableDirListingResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetStoragePoliciesRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetStoragePoliciesResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetStoragePolicyRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.IsFileClosedRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ListCacheDirectivesRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ListCacheDirectivesResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ListCachePoolsRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ListCachePoolsResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ListCorruptFileBlocksRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.MetaSaveRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.MkdirsRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ModifyCacheDirectiveRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ModifyCachePoolRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RecoverLeaseRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RefreshNodesRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RemoveCacheDirectiveRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RemoveCachePoolRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.Rename2RequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RenameRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RenameSnapshotRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RenewLeaseRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ReportBadBlocksRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RestoreFailedStorageRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RollEditsRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RollEditsResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RollingUpgradeRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RollingUpgradeResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SaveNamespaceRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetBalancerBandwidthRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetOwnerRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetPermissionRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetQuotaRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetReplicationRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetSafeModeRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetTimesRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.TruncateRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.UpdateBlockForPipelineRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.UpdatePipelineRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetStoragePolicyRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.EncryptionZonesProtos;
import org.apache.hadoop.hdfs.protocol.proto.EncryptionZonesProtos.CreateEncryptionZoneRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.EncryptionZonesProtos.GetEZForPathRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.EncryptionZonesProtos.ListEncryptionZonesRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.XAttrProtos.GetXAttrsRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.XAttrProtos.ListXAttrsRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.XAttrProtos.RemoveXAttrRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.XAttrProtos.SetXAttrRequestProto;
import org.apache.hadoop.hdfs.security.token.block.DataEncryptionKey;
import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier;
import org.apache.hadoop.hdfs.server.namenode.NotReplicatedYetException;
import org.apache.hadoop.hdfs.server.namenode.SafeModeException;
import org.apache.hadoop.hdfs.server.protocol.DatanodeStorageReport;
import org.apache.hadoop.io.EnumSetWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.ipc.ProtobufHelper;
import org.apache.hadoop.ipc.ProtocolMetaInterface;
import org.apache.hadoop.ipc.ProtocolTranslator;
import org.apache.hadoop.ipc.RPC;
import org.apache.hadoop.ipc.RpcClientUtil;
import org.apache.hadoop.security.AccessControlException;
import org.apache.hadoop.security.proto.SecurityProtos.CancelDelegationTokenRequestProto;
import org.apache.hadoop.security.proto.SecurityProtos.GetDelegationTokenRequestProto;
import org.apache.hadoop.security.proto.SecurityProtos.GetDelegationTokenResponseProto;
import org.apache.hadoop.security.proto.SecurityProtos.RenewDelegationTokenRequestProto;
import org.apache.hadoop.security.token.Token;
import com.google.protobuf.ByteString;
import com.google.protobuf.ServiceException;
import static org.apache.hadoop.fs.BatchedRemoteIterator.BatchedListEntries;
import static org.apache.hadoop.hdfs.protocol.proto.EncryptionZonesProtos
.EncryptionZoneProto;
/**
* This class forwards NN's ClientProtocol calls as RPC calls to the NN server
* while translating from the parameter types used in ClientProtocol to the
* new PB types.
*/
@InterfaceAudience.Private
@InterfaceStability.Stable
public class ClientNamenodeProtocolTranslatorPB implements
ProtocolMetaInterface, ClientProtocol, Closeable, ProtocolTranslator {
final private ClientNamenodeProtocolPB rpcProxy;
static final GetServerDefaultsRequestProto VOID_GET_SERVER_DEFAULT_REQUEST =
GetServerDefaultsRequestProto.newBuilder().build();
private final static GetFsStatusRequestProto VOID_GET_FSSTATUS_REQUEST =
GetFsStatusRequestProto.newBuilder().build();
private final static SaveNamespaceRequestProto VOID_SAVE_NAMESPACE_REQUEST =
SaveNamespaceRequestProto.newBuilder().build();
private final static RollEditsRequestProto VOID_ROLLEDITS_REQUEST =
RollEditsRequestProto.getDefaultInstance();
private final static RefreshNodesRequestProto VOID_REFRESH_NODES_REQUEST =
RefreshNodesRequestProto.newBuilder().build();
private final static FinalizeUpgradeRequestProto
VOID_FINALIZE_UPGRADE_REQUEST =
FinalizeUpgradeRequestProto.newBuilder().build();
private final static GetDataEncryptionKeyRequestProto
VOID_GET_DATA_ENCRYPTIONKEY_REQUEST =
GetDataEncryptionKeyRequestProto.newBuilder().build();
private final static GetStoragePoliciesRequestProto
VOID_GET_STORAGE_POLICIES_REQUEST =
GetStoragePoliciesRequestProto.newBuilder().build();
public ClientNamenodeProtocolTranslatorPB(ClientNamenodeProtocolPB proxy) {
rpcProxy = proxy;
}
@Override
public void close() {
RPC.stopProxy(rpcProxy);
}
@Override
public LocatedBlocks getBlockLocations(String src, long offset, long length)
throws AccessControlException, FileNotFoundException,
UnresolvedLinkException, IOException {
GetBlockLocationsRequestProto req = GetBlockLocationsRequestProto
.newBuilder()
.setSrc(src)
.setOffset(offset)
.setLength(length)
.build();
try {
GetBlockLocationsResponseProto resp = rpcProxy.getBlockLocations(null,
req);
return resp.hasLocations() ?
PBHelper.convert(resp.getLocations()) : null;
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public FsServerDefaults getServerDefaults() throws IOException {
GetServerDefaultsRequestProto req = VOID_GET_SERVER_DEFAULT_REQUEST;
try {
return PBHelper
.convert(rpcProxy.getServerDefaults(null, req).getServerDefaults());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public HdfsFileStatus create(String src, FsPermission masked,
String clientName, EnumSetWritable<CreateFlag> flag,
boolean createParent, short replication, long blockSize,
CryptoProtocolVersion[] supportedVersions)
throws AccessControlException, AlreadyBeingCreatedException,
DSQuotaExceededException, FileAlreadyExistsException,
FileNotFoundException, NSQuotaExceededException,
ParentNotDirectoryException, SafeModeException, UnresolvedLinkException,
IOException {
CreateRequestProto.Builder builder = CreateRequestProto.newBuilder()
.setSrc(src)
.setMasked(PBHelper.convert(masked))
.setClientName(clientName)
.setCreateFlag(PBHelper.convertCreateFlag(flag))
.setCreateParent(createParent)
.setReplication(replication)
.setBlockSize(blockSize);
builder.addAllCryptoProtocolVersion(PBHelper.convert(supportedVersions));
CreateRequestProto req = builder.build();
try {
CreateResponseProto res = rpcProxy.create(null, req);
return res.hasFs() ? PBHelper.convert(res.getFs()) : null;
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public boolean truncate(String src, long newLength, String clientName)
throws IOException, UnresolvedLinkException {
TruncateRequestProto req = TruncateRequestProto.newBuilder()
.setSrc(src)
.setNewLength(newLength)
.setClientName(clientName)
.build();
try {
return rpcProxy.truncate(null, req).getResult();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public LastBlockWithStatus append(String src, String clientName,
EnumSetWritable<CreateFlag> flag) throws AccessControlException,
DSQuotaExceededException, FileNotFoundException, SafeModeException,
UnresolvedLinkException, IOException {
AppendRequestProto req = AppendRequestProto.newBuilder().setSrc(src)
.setClientName(clientName).setFlag(PBHelper.convertCreateFlag(flag))
.build();
try {
AppendResponseProto res = rpcProxy.append(null, req);
LocatedBlock lastBlock = res.hasBlock() ? PBHelper
.convert(res.getBlock()) : null;
HdfsFileStatus stat = (res.hasStat()) ? PBHelper.convert(res.getStat())
: null;
return new LastBlockWithStatus(lastBlock, stat);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public boolean setReplication(String src, short replication)
throws AccessControlException, DSQuotaExceededException,
FileNotFoundException, SafeModeException, UnresolvedLinkException,
IOException {
SetReplicationRequestProto req = SetReplicationRequestProto.newBuilder()
.setSrc(src)
.setReplication(replication)
.build();
try {
return rpcProxy.setReplication(null, req).getResult();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void setPermission(String src, FsPermission permission)
throws AccessControlException, FileNotFoundException, SafeModeException,
UnresolvedLinkException, IOException {
SetPermissionRequestProto req = SetPermissionRequestProto.newBuilder()
.setSrc(src)
.setPermission(PBHelper.convert(permission))
.build();
try {
rpcProxy.setPermission(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void setOwner(String src, String username, String groupname)
throws AccessControlException, FileNotFoundException, SafeModeException,
UnresolvedLinkException, IOException {
SetOwnerRequestProto.Builder req = SetOwnerRequestProto.newBuilder()
.setSrc(src);
if (username != null)
req.setUsername(username);
if (groupname != null)
req.setGroupname(groupname);
try {
rpcProxy.setOwner(null, req.build());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void abandonBlock(ExtendedBlock b, long fileId, String src,
String holder) throws AccessControlException, FileNotFoundException,
UnresolvedLinkException, IOException {
AbandonBlockRequestProto req = AbandonBlockRequestProto.newBuilder()
.setB(PBHelperClient.convert(b)).setSrc(src).setHolder(holder)
.setFileId(fileId).build();
try {
rpcProxy.abandonBlock(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public LocatedBlock addBlock(String src, String clientName,
ExtendedBlock previous, DatanodeInfo[] excludeNodes, long fileId,
String[] favoredNodes)
throws AccessControlException, FileNotFoundException,
NotReplicatedYetException, SafeModeException, UnresolvedLinkException,
IOException {
AddBlockRequestProto.Builder req = AddBlockRequestProto.newBuilder()
.setSrc(src).setClientName(clientName).setFileId(fileId);
if (previous != null)
req.setPrevious(PBHelperClient.convert(previous));
if (excludeNodes != null)
req.addAllExcludeNodes(PBHelperClient.convert(excludeNodes));
if (favoredNodes != null) {
req.addAllFavoredNodes(Arrays.asList(favoredNodes));
}
try {
return PBHelper.convert(rpcProxy.addBlock(null, req.build()).getBlock());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public LocatedBlock getAdditionalDatanode(String src, long fileId,
ExtendedBlock blk, DatanodeInfo[] existings, String[] existingStorageIDs,
DatanodeInfo[] excludes,
int numAdditionalNodes, String clientName) throws AccessControlException,
FileNotFoundException, SafeModeException, UnresolvedLinkException,
IOException {
GetAdditionalDatanodeRequestProto req = GetAdditionalDatanodeRequestProto
.newBuilder()
.setSrc(src)
.setFileId(fileId)
.setBlk(PBHelperClient.convert(blk))
.addAllExistings(PBHelperClient.convert(existings))
.addAllExistingStorageUuids(Arrays.asList(existingStorageIDs))
.addAllExcludes(PBHelperClient.convert(excludes))
.setNumAdditionalNodes(numAdditionalNodes)
.setClientName(clientName)
.build();
try {
return PBHelper.convert(rpcProxy.getAdditionalDatanode(null, req)
.getBlock());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public boolean complete(String src, String clientName,
ExtendedBlock last, long fileId)
throws AccessControlException, FileNotFoundException, SafeModeException,
UnresolvedLinkException, IOException {
CompleteRequestProto.Builder req = CompleteRequestProto.newBuilder()
.setSrc(src)
.setClientName(clientName)
.setFileId(fileId);
if (last != null)
req.setLast(PBHelperClient.convert(last));
try {
return rpcProxy.complete(null, req.build()).getResult();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void reportBadBlocks(LocatedBlock[] blocks) throws IOException {
ReportBadBlocksRequestProto req = ReportBadBlocksRequestProto.newBuilder()
.addAllBlocks(Arrays.asList(PBHelper.convertLocatedBlock(blocks)))
.build();
try {
rpcProxy.reportBadBlocks(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public boolean rename(String src, String dst) throws UnresolvedLinkException,
IOException {
RenameRequestProto req = RenameRequestProto.newBuilder()
.setSrc(src)
.setDst(dst).build();
try {
return rpcProxy.rename(null, req).getResult();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void rename2(String src, String dst, Rename... options)
throws AccessControlException, DSQuotaExceededException,
FileAlreadyExistsException, FileNotFoundException,
NSQuotaExceededException, ParentNotDirectoryException, SafeModeException,
UnresolvedLinkException, IOException {
boolean overwrite = false;
if (options != null) {
for (Rename option : options) {
if (option == Rename.OVERWRITE) {
overwrite = true;
}
}
}
Rename2RequestProto req = Rename2RequestProto.newBuilder().
setSrc(src).
setDst(dst).setOverwriteDest(overwrite).
build();
try {
rpcProxy.rename2(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void concat(String trg, String[] srcs) throws IOException,
UnresolvedLinkException {
ConcatRequestProto req = ConcatRequestProto.newBuilder().
setTrg(trg).
addAllSrcs(Arrays.asList(srcs)).build();
try {
rpcProxy.concat(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public boolean delete(String src, boolean recursive)
throws AccessControlException, FileNotFoundException, SafeModeException,
UnresolvedLinkException, IOException {
DeleteRequestProto req = DeleteRequestProto.newBuilder().setSrc(src).setRecursive(recursive).build();
try {
return rpcProxy.delete(null, req).getResult();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public boolean mkdirs(String src, FsPermission masked, boolean createParent)
throws AccessControlException, FileAlreadyExistsException,
FileNotFoundException, NSQuotaExceededException,
ParentNotDirectoryException, SafeModeException, UnresolvedLinkException,
IOException {
MkdirsRequestProto req = MkdirsRequestProto.newBuilder()
.setSrc(src)
.setMasked(PBHelper.convert(masked))
.setCreateParent(createParent).build();
try {
return rpcProxy.mkdirs(null, req).getResult();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public DirectoryListing getListing(String src, byte[] startAfter,
boolean needLocation) throws AccessControlException,
FileNotFoundException, UnresolvedLinkException, IOException {
GetListingRequestProto req = GetListingRequestProto.newBuilder()
.setSrc(src)
.setStartAfter(ByteString.copyFrom(startAfter))
.setNeedLocation(needLocation).build();
try {
GetListingResponseProto result = rpcProxy.getListing(null, req);
if (result.hasDirList()) {
return PBHelper.convert(result.getDirList());
}
return null;
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void renewLease(String clientName) throws AccessControlException,
IOException {
RenewLeaseRequestProto req = RenewLeaseRequestProto.newBuilder()
.setClientName(clientName).build();
try {
rpcProxy.renewLease(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public boolean recoverLease(String src, String clientName)
throws IOException {
RecoverLeaseRequestProto req = RecoverLeaseRequestProto.newBuilder()
.setSrc(src)
.setClientName(clientName).build();
try {
return rpcProxy.recoverLease(null, req).getResult();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public long[] getStats() throws IOException {
try {
return PBHelper.convert(rpcProxy.getFsStats(null,
VOID_GET_FSSTATUS_REQUEST));
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public DatanodeInfo[] getDatanodeReport(DatanodeReportType type)
throws IOException {
GetDatanodeReportRequestProto req = GetDatanodeReportRequestProto
.newBuilder()
.setType(PBHelper.convert(type)).build();
try {
return PBHelper.convert(
rpcProxy.getDatanodeReport(null, req).getDiList());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public DatanodeStorageReport[] getDatanodeStorageReport(DatanodeReportType type)
throws IOException {
final GetDatanodeStorageReportRequestProto req
= GetDatanodeStorageReportRequestProto.newBuilder()
.setType(PBHelper.convert(type)).build();
try {
return PBHelper.convertDatanodeStorageReports(
rpcProxy.getDatanodeStorageReport(null, req).getDatanodeStorageReportsList());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public long getPreferredBlockSize(String filename) throws IOException,
UnresolvedLinkException {
GetPreferredBlockSizeRequestProto req = GetPreferredBlockSizeRequestProto
.newBuilder()
.setFilename(filename)
.build();
try {
return rpcProxy.getPreferredBlockSize(null, req).getBsize();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public boolean setSafeMode(SafeModeAction action, boolean isChecked) throws IOException {
SetSafeModeRequestProto req = SetSafeModeRequestProto.newBuilder()
.setAction(PBHelper.convert(action)).setChecked(isChecked).build();
try {
return rpcProxy.setSafeMode(null, req).getResult();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public boolean saveNamespace(long timeWindow, long txGap) throws IOException {
try {
SaveNamespaceRequestProto req = SaveNamespaceRequestProto.newBuilder()
.setTimeWindow(timeWindow).setTxGap(txGap).build();
return rpcProxy.saveNamespace(null, req).getSaved();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public long rollEdits() throws AccessControlException, IOException {
try {
RollEditsResponseProto resp = rpcProxy.rollEdits(null,
VOID_ROLLEDITS_REQUEST);
return resp.getNewSegmentTxId();
} catch (ServiceException se) {
throw ProtobufHelper.getRemoteException(se);
}
}
@Override
public boolean restoreFailedStorage(String arg)
throws AccessControlException, IOException{
RestoreFailedStorageRequestProto req = RestoreFailedStorageRequestProto
.newBuilder()
.setArg(arg).build();
try {
return rpcProxy.restoreFailedStorage(null, req).getResult();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void refreshNodes() throws IOException {
try {
rpcProxy.refreshNodes(null, VOID_REFRESH_NODES_REQUEST);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void finalizeUpgrade() throws IOException {
try {
rpcProxy.finalizeUpgrade(null, VOID_FINALIZE_UPGRADE_REQUEST);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public RollingUpgradeInfo rollingUpgrade(RollingUpgradeAction action) throws IOException {
final RollingUpgradeRequestProto r = RollingUpgradeRequestProto.newBuilder()
.setAction(PBHelper.convert(action)).build();
try {
final RollingUpgradeResponseProto proto = rpcProxy.rollingUpgrade(null, r);
if (proto.hasRollingUpgradeInfo()) {
return PBHelper.convert(proto.getRollingUpgradeInfo());
}
return null;
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public CorruptFileBlocks listCorruptFileBlocks(String path, String cookie)
throws IOException {
ListCorruptFileBlocksRequestProto.Builder req =
ListCorruptFileBlocksRequestProto.newBuilder().setPath(path);
if (cookie != null)
req.setCookie(cookie);
try {
return PBHelper.convert(
rpcProxy.listCorruptFileBlocks(null, req.build()).getCorrupt());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void metaSave(String filename) throws IOException {
MetaSaveRequestProto req = MetaSaveRequestProto.newBuilder()
.setFilename(filename).build();
try {
rpcProxy.metaSave(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public HdfsFileStatus getFileInfo(String src) throws AccessControlException,
FileNotFoundException, UnresolvedLinkException, IOException {
GetFileInfoRequestProto req = GetFileInfoRequestProto.newBuilder()
.setSrc(src).build();
try {
GetFileInfoResponseProto res = rpcProxy.getFileInfo(null, req);
return res.hasFs() ? PBHelper.convert(res.getFs()) : null;
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public HdfsFileStatus getFileLinkInfo(String src)
throws AccessControlException, UnresolvedLinkException, IOException {
GetFileLinkInfoRequestProto req = GetFileLinkInfoRequestProto.newBuilder()
.setSrc(src).build();
try {
GetFileLinkInfoResponseProto result = rpcProxy.getFileLinkInfo(null, req);
return result.hasFs() ?
PBHelper.convert(rpcProxy.getFileLinkInfo(null, req).getFs()) : null;
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public ContentSummary getContentSummary(String path)
throws AccessControlException, FileNotFoundException,
UnresolvedLinkException, IOException {
GetContentSummaryRequestProto req = GetContentSummaryRequestProto
.newBuilder()
.setPath(path)
.build();
try {
return PBHelper.convert(rpcProxy.getContentSummary(null, req)
.getSummary());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void setQuota(String path, long namespaceQuota, long storagespaceQuota,
StorageType type)
throws AccessControlException, FileNotFoundException,
UnresolvedLinkException, IOException {
final SetQuotaRequestProto.Builder builder
= SetQuotaRequestProto.newBuilder()
.setPath(path)
.setNamespaceQuota(namespaceQuota)
.setStoragespaceQuota(storagespaceQuota);
if (type != null) {
builder.setStorageType(PBHelperClient.convertStorageType(type));
}
final SetQuotaRequestProto req = builder.build();
try {
rpcProxy.setQuota(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void fsync(String src, long fileId, String client,
long lastBlockLength)
throws AccessControlException, FileNotFoundException,
UnresolvedLinkException, IOException {
FsyncRequestProto req = FsyncRequestProto.newBuilder().setSrc(src)
.setClient(client).setLastBlockLength(lastBlockLength)
.setFileId(fileId).build();
try {
rpcProxy.fsync(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void setTimes(String src, long mtime, long atime)
throws AccessControlException, FileNotFoundException,
UnresolvedLinkException, IOException {
SetTimesRequestProto req = SetTimesRequestProto.newBuilder()
.setSrc(src)
.setMtime(mtime)
.setAtime(atime)
.build();
try {
rpcProxy.setTimes(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void createSymlink(String target, String link, FsPermission dirPerm,
boolean createParent) throws AccessControlException,
FileAlreadyExistsException, FileNotFoundException,
ParentNotDirectoryException, SafeModeException, UnresolvedLinkException,
IOException {
CreateSymlinkRequestProto req = CreateSymlinkRequestProto.newBuilder()
.setTarget(target)
.setLink(link)
.setDirPerm(PBHelper.convert(dirPerm))
.setCreateParent(createParent)
.build();
try {
rpcProxy.createSymlink(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public String getLinkTarget(String path) throws AccessControlException,
FileNotFoundException, IOException {
GetLinkTargetRequestProto req = GetLinkTargetRequestProto.newBuilder()
.setPath(path).build();
try {
GetLinkTargetResponseProto rsp = rpcProxy.getLinkTarget(null, req);
return rsp.hasTargetPath() ? rsp.getTargetPath() : null;
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public LocatedBlock updateBlockForPipeline(ExtendedBlock block,
String clientName) throws IOException {
UpdateBlockForPipelineRequestProto req = UpdateBlockForPipelineRequestProto
.newBuilder()
.setBlock(PBHelperClient.convert(block))
.setClientName(clientName)
.build();
try {
return PBHelper.convert(
rpcProxy.updateBlockForPipeline(null, req).getBlock());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void updatePipeline(String clientName, ExtendedBlock oldBlock,
ExtendedBlock newBlock, DatanodeID[] newNodes, String[] storageIDs) throws IOException {
UpdatePipelineRequestProto req = UpdatePipelineRequestProto.newBuilder()
.setClientName(clientName)
.setOldBlock(PBHelperClient.convert(oldBlock))
.setNewBlock(PBHelperClient.convert(newBlock))
.addAllNewNodes(Arrays.asList(PBHelper.convert(newNodes)))
.addAllStorageIDs(storageIDs == null ? null : Arrays.asList(storageIDs))
.build();
try {
rpcProxy.updatePipeline(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public Token<DelegationTokenIdentifier> getDelegationToken(Text renewer)
throws IOException {
GetDelegationTokenRequestProto req = GetDelegationTokenRequestProto
.newBuilder()
.setRenewer(renewer == null ? "" : renewer.toString())
.build();
try {
GetDelegationTokenResponseProto resp = rpcProxy.getDelegationToken(null, req);
return resp.hasToken() ? PBHelper.convertDelegationToken(resp.getToken())
: null;
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public long renewDelegationToken(Token<DelegationTokenIdentifier> token)
throws IOException {
RenewDelegationTokenRequestProto req = RenewDelegationTokenRequestProto.newBuilder().
setToken(PBHelperClient.convert(token)).
build();
try {
return rpcProxy.renewDelegationToken(null, req).getNewExpiryTime();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void cancelDelegationToken(Token<DelegationTokenIdentifier> token)
throws IOException {
CancelDelegationTokenRequestProto req = CancelDelegationTokenRequestProto
.newBuilder()
.setToken(PBHelperClient.convert(token))
.build();
try {
rpcProxy.cancelDelegationToken(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void setBalancerBandwidth(long bandwidth) throws IOException {
SetBalancerBandwidthRequestProto req = SetBalancerBandwidthRequestProto.newBuilder()
.setBandwidth(bandwidth)
.build();
try {
rpcProxy.setBalancerBandwidth(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public boolean isMethodSupported(String methodName) throws IOException {
return RpcClientUtil.isMethodSupported(rpcProxy,
ClientNamenodeProtocolPB.class, RPC.RpcKind.RPC_PROTOCOL_BUFFER,
RPC.getProtocolVersion(ClientNamenodeProtocolPB.class), methodName);
}
@Override
public DataEncryptionKey getDataEncryptionKey() throws IOException {
try {
GetDataEncryptionKeyResponseProto rsp = rpcProxy.getDataEncryptionKey(
null, VOID_GET_DATA_ENCRYPTIONKEY_REQUEST);
return rsp.hasDataEncryptionKey() ?
PBHelper.convert(rsp.getDataEncryptionKey()) : null;
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public boolean isFileClosed(String src) throws AccessControlException,
FileNotFoundException, UnresolvedLinkException, IOException {
IsFileClosedRequestProto req = IsFileClosedRequestProto.newBuilder()
.setSrc(src).build();
try {
return rpcProxy.isFileClosed(null, req).getResult();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public Object getUnderlyingProxyObject() {
return rpcProxy;
}
@Override
public String createSnapshot(String snapshotRoot, String snapshotName)
throws IOException {
final CreateSnapshotRequestProto.Builder builder
= CreateSnapshotRequestProto.newBuilder().setSnapshotRoot(snapshotRoot);
if (snapshotName != null) {
builder.setSnapshotName(snapshotName);
}
final CreateSnapshotRequestProto req = builder.build();
try {
return rpcProxy.createSnapshot(null, req).getSnapshotPath();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void deleteSnapshot(String snapshotRoot, String snapshotName)
throws IOException {
DeleteSnapshotRequestProto req = DeleteSnapshotRequestProto.newBuilder()
.setSnapshotRoot(snapshotRoot).setSnapshotName(snapshotName).build();
try {
rpcProxy.deleteSnapshot(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void allowSnapshot(String snapshotRoot) throws IOException {
AllowSnapshotRequestProto req = AllowSnapshotRequestProto.newBuilder()
.setSnapshotRoot(snapshotRoot).build();
try {
rpcProxy.allowSnapshot(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void disallowSnapshot(String snapshotRoot) throws IOException {
DisallowSnapshotRequestProto req = DisallowSnapshotRequestProto
.newBuilder().setSnapshotRoot(snapshotRoot).build();
try {
rpcProxy.disallowSnapshot(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void renameSnapshot(String snapshotRoot, String snapshotOldName,
String snapshotNewName) throws IOException {
RenameSnapshotRequestProto req = RenameSnapshotRequestProto.newBuilder()
.setSnapshotRoot(snapshotRoot).setSnapshotOldName(snapshotOldName)
.setSnapshotNewName(snapshotNewName).build();
try {
rpcProxy.renameSnapshot(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public SnapshottableDirectoryStatus[] getSnapshottableDirListing()
throws IOException {
GetSnapshottableDirListingRequestProto req =
GetSnapshottableDirListingRequestProto.newBuilder().build();
try {
GetSnapshottableDirListingResponseProto result = rpcProxy
.getSnapshottableDirListing(null, req);
if (result.hasSnapshottableDirList()) {
return PBHelper.convert(result.getSnapshottableDirList());
}
return null;
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public SnapshotDiffReport getSnapshotDiffReport(String snapshotRoot,
String fromSnapshot, String toSnapshot) throws IOException {
GetSnapshotDiffReportRequestProto req = GetSnapshotDiffReportRequestProto
.newBuilder().setSnapshotRoot(snapshotRoot)
.setFromSnapshot(fromSnapshot).setToSnapshot(toSnapshot).build();
try {
GetSnapshotDiffReportResponseProto result =
rpcProxy.getSnapshotDiffReport(null, req);
return PBHelper.convert(result.getDiffReport());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public long addCacheDirective(CacheDirectiveInfo directive,
EnumSet<CacheFlag> flags) throws IOException {
try {
AddCacheDirectiveRequestProto.Builder builder =
AddCacheDirectiveRequestProto.newBuilder().
setInfo(PBHelper.convert(directive));
if (!flags.isEmpty()) {
builder.setCacheFlags(PBHelper.convertCacheFlags(flags));
}
return rpcProxy.addCacheDirective(null, builder.build()).getId();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void modifyCacheDirective(CacheDirectiveInfo directive,
EnumSet<CacheFlag> flags) throws IOException {
try {
ModifyCacheDirectiveRequestProto.Builder builder =
ModifyCacheDirectiveRequestProto.newBuilder().
setInfo(PBHelper.convert(directive));
if (!flags.isEmpty()) {
builder.setCacheFlags(PBHelper.convertCacheFlags(flags));
}
rpcProxy.modifyCacheDirective(null, builder.build());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void removeCacheDirective(long id)
throws IOException {
try {
rpcProxy.removeCacheDirective(null,
RemoveCacheDirectiveRequestProto.newBuilder().
setId(id).build());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
private static class BatchedCacheEntries
implements BatchedEntries<CacheDirectiveEntry> {
private final ListCacheDirectivesResponseProto response;
BatchedCacheEntries(
ListCacheDirectivesResponseProto response) {
this.response = response;
}
@Override
public CacheDirectiveEntry get(int i) {
return PBHelper.convert(response.getElements(i));
}
@Override
public int size() {
return response.getElementsCount();
}
@Override
public boolean hasMore() {
return response.getHasMore();
}
}
@Override
public BatchedEntries<CacheDirectiveEntry>
listCacheDirectives(long prevId,
CacheDirectiveInfo filter) throws IOException {
if (filter == null) {
filter = new CacheDirectiveInfo.Builder().build();
}
try {
return new BatchedCacheEntries(
rpcProxy.listCacheDirectives(null,
ListCacheDirectivesRequestProto.newBuilder().
setPrevId(prevId).
setFilter(PBHelper.convert(filter)).
build()));
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void addCachePool(CachePoolInfo info) throws IOException {
AddCachePoolRequestProto.Builder builder =
AddCachePoolRequestProto.newBuilder();
builder.setInfo(PBHelper.convert(info));
try {
rpcProxy.addCachePool(null, builder.build());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void modifyCachePool(CachePoolInfo req) throws IOException {
ModifyCachePoolRequestProto.Builder builder =
ModifyCachePoolRequestProto.newBuilder();
builder.setInfo(PBHelper.convert(req));
try {
rpcProxy.modifyCachePool(null, builder.build());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void removeCachePool(String cachePoolName) throws IOException {
try {
rpcProxy.removeCachePool(null,
RemoveCachePoolRequestProto.newBuilder().
setPoolName(cachePoolName).build());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
private static class BatchedCachePoolEntries
implements BatchedEntries<CachePoolEntry> {
private final ListCachePoolsResponseProto proto;
public BatchedCachePoolEntries(ListCachePoolsResponseProto proto) {
this.proto = proto;
}
@Override
public CachePoolEntry get(int i) {
CachePoolEntryProto elem = proto.getEntries(i);
return PBHelper.convert(elem);
}
@Override
public int size() {
return proto.getEntriesCount();
}
@Override
public boolean hasMore() {
return proto.getHasMore();
}
}
@Override
public BatchedEntries<CachePoolEntry> listCachePools(String prevKey)
throws IOException {
try {
return new BatchedCachePoolEntries(
rpcProxy.listCachePools(null,
ListCachePoolsRequestProto.newBuilder().
setPrevPoolName(prevKey).build()));
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void modifyAclEntries(String src, List<AclEntry> aclSpec)
throws IOException {
ModifyAclEntriesRequestProto req = ModifyAclEntriesRequestProto
.newBuilder().setSrc(src)
.addAllAclSpec(PBHelper.convertAclEntryProto(aclSpec)).build();
try {
rpcProxy.modifyAclEntries(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void removeAclEntries(String src, List<AclEntry> aclSpec)
throws IOException {
RemoveAclEntriesRequestProto req = RemoveAclEntriesRequestProto
.newBuilder().setSrc(src)
.addAllAclSpec(PBHelper.convertAclEntryProto(aclSpec)).build();
try {
rpcProxy.removeAclEntries(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void removeDefaultAcl(String src) throws IOException {
RemoveDefaultAclRequestProto req = RemoveDefaultAclRequestProto
.newBuilder().setSrc(src).build();
try {
rpcProxy.removeDefaultAcl(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void removeAcl(String src) throws IOException {
RemoveAclRequestProto req = RemoveAclRequestProto.newBuilder()
.setSrc(src).build();
try {
rpcProxy.removeAcl(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void setAcl(String src, List<AclEntry> aclSpec) throws IOException {
SetAclRequestProto req = SetAclRequestProto.newBuilder()
.setSrc(src)
.addAllAclSpec(PBHelper.convertAclEntryProto(aclSpec))
.build();
try {
rpcProxy.setAcl(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public AclStatus getAclStatus(String src) throws IOException {
GetAclStatusRequestProto req = GetAclStatusRequestProto.newBuilder()
.setSrc(src).build();
try {
return PBHelper.convert(rpcProxy.getAclStatus(null, req));
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void createEncryptionZone(String src, String keyName)
throws IOException {
final CreateEncryptionZoneRequestProto.Builder builder =
CreateEncryptionZoneRequestProto.newBuilder();
builder.setSrc(src);
if (keyName != null && !keyName.isEmpty()) {
builder.setKeyName(keyName);
}
CreateEncryptionZoneRequestProto req = builder.build();
try {
rpcProxy.createEncryptionZone(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public EncryptionZone getEZForPath(String src)
throws IOException {
final GetEZForPathRequestProto.Builder builder =
GetEZForPathRequestProto.newBuilder();
builder.setSrc(src);
final GetEZForPathRequestProto req = builder.build();
try {
final EncryptionZonesProtos.GetEZForPathResponseProto response =
rpcProxy.getEZForPath(null, req);
if (response.hasZone()) {
return PBHelper.convert(response.getZone());
} else {
return null;
}
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public BatchedEntries<EncryptionZone> listEncryptionZones(long id)
throws IOException {
final ListEncryptionZonesRequestProto req =
ListEncryptionZonesRequestProto.newBuilder()
.setId(id)
.build();
try {
EncryptionZonesProtos.ListEncryptionZonesResponseProto response =
rpcProxy.listEncryptionZones(null, req);
List<EncryptionZone> elements =
Lists.newArrayListWithCapacity(response.getZonesCount());
for (EncryptionZoneProto p : response.getZonesList()) {
elements.add(PBHelper.convert(p));
}
return new BatchedListEntries<EncryptionZone>(elements,
response.getHasMore());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void setXAttr(String src, XAttr xAttr, EnumSet<XAttrSetFlag> flag)
throws IOException {
SetXAttrRequestProto req = SetXAttrRequestProto.newBuilder()
.setSrc(src)
.setXAttr(PBHelper.convertXAttrProto(xAttr))
.setFlag(PBHelper.convert(flag))
.build();
try {
rpcProxy.setXAttr(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public List<XAttr> getXAttrs(String src, List<XAttr> xAttrs)
throws IOException {
GetXAttrsRequestProto.Builder builder = GetXAttrsRequestProto.newBuilder();
builder.setSrc(src);
if (xAttrs != null) {
builder.addAllXAttrs(PBHelper.convertXAttrProto(xAttrs));
}
GetXAttrsRequestProto req = builder.build();
try {
return PBHelper.convert(rpcProxy.getXAttrs(null, req));
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public List<XAttr> listXAttrs(String src)
throws IOException {
ListXAttrsRequestProto.Builder builder = ListXAttrsRequestProto.newBuilder();
builder.setSrc(src);
ListXAttrsRequestProto req = builder.build();
try {
return PBHelper.convert(rpcProxy.listXAttrs(null, req));
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void removeXAttr(String src, XAttr xAttr) throws IOException {
RemoveXAttrRequestProto req = RemoveXAttrRequestProto
.newBuilder().setSrc(src)
.setXAttr(PBHelper.convertXAttrProto(xAttr)).build();
try {
rpcProxy.removeXAttr(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void checkAccess(String path, FsAction mode) throws IOException {
CheckAccessRequestProto req = CheckAccessRequestProto.newBuilder()
.setPath(path).setMode(PBHelper.convert(mode)).build();
try {
rpcProxy.checkAccess(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void setStoragePolicy(String src, String policyName)
throws IOException {
SetStoragePolicyRequestProto req = SetStoragePolicyRequestProto
.newBuilder().setSrc(src).setPolicyName(policyName).build();
try {
rpcProxy.setStoragePolicy(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public BlockStoragePolicy getStoragePolicy(String path) throws IOException {
GetStoragePolicyRequestProto request = GetStoragePolicyRequestProto
.newBuilder().setPath(path).build();
try {
return PBHelper.convert(rpcProxy.getStoragePolicy(null, request)
.getStoragePolicy());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public BlockStoragePolicy[] getStoragePolicies() throws IOException {
try {
GetStoragePoliciesResponseProto response = rpcProxy
.getStoragePolicies(null, VOID_GET_STORAGE_POLICIES_REQUEST);
return PBHelper.convertStoragePolicies(response.getPoliciesList());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
public long getCurrentEditLogTxid() throws IOException {
GetCurrentEditLogTxidRequestProto req = GetCurrentEditLogTxidRequestProto
.getDefaultInstance();
try {
return rpcProxy.getCurrentEditLogTxid(null, req).getTxid();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public EventBatchList getEditsFromTxid(long txid) throws IOException {
GetEditsFromTxidRequestProto req = GetEditsFromTxidRequestProto.newBuilder()
.setTxid(txid).build();
try {
return PBHelper.convert(rpcProxy.getEditsFromTxid(null, req));
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
}
| apache-2.0 |
MichaelNedzelsky/intellij-community | java/java-impl/src/com/intellij/refactoring/replaceConstructorWithFactory/ReplaceConstructorWithFactoryProcessor.java | 13420 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* 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.intellij.refactoring.replaceConstructorWithFactory;
import com.intellij.lang.findUsages.DescriptiveNameUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Ref;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.refactoring.BaseRefactoringProcessor;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.util.ConflictsUtil;
import com.intellij.refactoring.util.RefactoringUIUtil;
import com.intellij.usageView.UsageInfo;
import com.intellij.usageView.UsageViewDescriptor;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.VisibilityUtil;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
/**
* @author dsl
*/
public class ReplaceConstructorWithFactoryProcessor extends BaseRefactoringProcessor {
private static final Logger LOG = Logger.getInstance(
"#com.intellij.refactoring.replaceConstructorWithFactory.ReplaceConstructorWithFactoryProcessor");
private final PsiMethod myConstructor;
private final String myFactoryName;
private final PsiElementFactory myFactory;
private final PsiClass myOriginalClass;
private final PsiClass myTargetClass;
private final PsiManager myManager;
private final boolean myIsInner;
public ReplaceConstructorWithFactoryProcessor(Project project,
PsiMethod originalConstructor,
PsiClass originalClass,
PsiClass targetClass,
@NonNls String factoryName) {
super(project);
myOriginalClass = originalClass;
myConstructor = originalConstructor;
myTargetClass = targetClass;
myFactoryName = factoryName;
myManager = PsiManager.getInstance(project);
myFactory = JavaPsiFacade.getInstance(myManager.getProject()).getElementFactory();
myIsInner = isInner(myOriginalClass);
}
private boolean isInner(PsiClass originalClass) {
final boolean result = PsiUtil.isInnerClass(originalClass);
if (result) {
LOG.assertTrue(PsiTreeUtil.isAncestor(myTargetClass, originalClass, false));
}
return result;
}
@NotNull
protected UsageViewDescriptor createUsageViewDescriptor(@NotNull UsageInfo[] usages) {
if (myConstructor != null) {
return new ReplaceConstructorWithFactoryViewDescriptor(myConstructor);
}
else {
return new ReplaceConstructorWithFactoryViewDescriptor(myOriginalClass);
}
}
private List<PsiElement> myNonNewConstructorUsages;
@NotNull
protected UsageInfo[] findUsages() {
GlobalSearchScope projectScope = GlobalSearchScope.projectScope(myProject);
ArrayList<UsageInfo> usages = new ArrayList<UsageInfo>();
myNonNewConstructorUsages = new ArrayList<PsiElement>();
for (PsiReference reference : ReferencesSearch.search(myConstructor == null ? myOriginalClass : myConstructor, projectScope, false)) {
PsiElement element = reference.getElement();
if (element.getParent() instanceof PsiNewExpression) {
usages.add(new UsageInfo(element.getParent()));
}
else if ("super".equals(element.getText()) || "this".equals(element.getText())) {
myNonNewConstructorUsages.add(element);
}
else if (element instanceof PsiMethod && ((PsiMethod)element).isConstructor()) {
myNonNewConstructorUsages.add(element);
}
else if (element instanceof PsiClass) {
myNonNewConstructorUsages.add(element);
}
}
//if (myConstructor != null && myConstructor.getParameterList().getParametersCount() == 0) {
// RefactoringUtil.visitImplicitConstructorUsages(getConstructorContainingClass(), new RefactoringUtil.ImplicitConstructorUsageVisitor() {
// @Override public void visitConstructor(PsiMethod constructor, PsiMethod baseConstructor) {
// myNonNewConstructorUsages.add(constructor);
// }
//
// @Override public void visitClassWithoutConstructors(PsiClass aClass) {
// myNonNewConstructorUsages.add(aClass);
// }
// });
//}
return usages.toArray(new UsageInfo[usages.size()]);
}
protected boolean preprocessUsages(@NotNull Ref<UsageInfo[]> refUsages) {
UsageInfo[] usages = refUsages.get();
MultiMap<PsiElement, String> conflicts = new MultiMap<PsiElement, String>();
final PsiResolveHelper helper = JavaPsiFacade.getInstance(myProject).getResolveHelper();
final PsiClass constructorContainingClass = getConstructorContainingClass();
if (!helper.isAccessible(constructorContainingClass, myTargetClass, null)) {
String message = RefactoringBundle.message("class.0.is.not.accessible.from.target.1",
RefactoringUIUtil.getDescription(constructorContainingClass, true),
RefactoringUIUtil.getDescription(myTargetClass, true));
conflicts.putValue(constructorContainingClass, message);
}
HashSet<PsiElement> reportedContainers = new HashSet<PsiElement>();
final String targetClassDescription = RefactoringUIUtil.getDescription(myTargetClass, true);
for (UsageInfo usage : usages) {
final PsiElement container = ConflictsUtil.getContainer(usage.getElement());
if (!reportedContainers.contains(container)) {
reportedContainers.add(container);
if (!helper.isAccessible(myTargetClass, usage.getElement(), null)) {
String message = RefactoringBundle.message("target.0.is.not.accessible.from.1",
targetClassDescription,
RefactoringUIUtil.getDescription(container, true));
conflicts.putValue(myTargetClass, message);
}
}
}
if (myIsInner) {
for (UsageInfo usage : usages) {
final PsiField field = PsiTreeUtil.getParentOfType(usage.getElement(), PsiField.class);
if (field != null) {
final PsiClass containingClass = field.getContainingClass();
if (PsiTreeUtil.isAncestor(containingClass, myTargetClass, true)) {
String message = RefactoringBundle.message("constructor.being.refactored.is.used.in.initializer.of.0",
RefactoringUIUtil.getDescription(field, true), RefactoringUIUtil.getDescription(
constructorContainingClass, false));
conflicts.putValue(field, message);
}
}
}
}
return showConflicts(conflicts, usages);
}
private PsiClass getConstructorContainingClass() {
if (myConstructor != null) {
return myConstructor.getContainingClass();
}
else {
return myOriginalClass;
}
}
protected void performRefactoring(@NotNull UsageInfo[] usages) {
try {
PsiReferenceExpression classReferenceExpression =
myFactory.createReferenceExpression(myTargetClass);
PsiReferenceExpression qualifiedMethodReference =
(PsiReferenceExpression)myFactory.createExpressionFromText("A." + myFactoryName, null);
PsiMethod factoryMethod = (PsiMethod)myTargetClass.add(createFactoryMethod());
if (myConstructor != null) {
PsiUtil.setModifierProperty(myConstructor, PsiModifier.PRIVATE, true);
VisibilityUtil.escalateVisibility(myConstructor, factoryMethod);
for (PsiElement place : myNonNewConstructorUsages) {
VisibilityUtil.escalateVisibility(myConstructor, place);
}
}
if (myConstructor == null) {
PsiMethod constructor = myFactory.createConstructor();
PsiUtil.setModifierProperty(constructor, PsiModifier.PRIVATE, true);
constructor = (PsiMethod)getConstructorContainingClass().add(constructor);
VisibilityUtil.escalateVisibility(constructor, myTargetClass);
}
for (UsageInfo usage : usages) {
PsiNewExpression newExpression = (PsiNewExpression)usage.getElement();
if (newExpression == null) continue;
VisibilityUtil.escalateVisibility(factoryMethod, newExpression);
PsiMethodCallExpression factoryCall =
(PsiMethodCallExpression)myFactory.createExpressionFromText(myFactoryName + "()", newExpression);
factoryCall.getArgumentList().replace(newExpression.getArgumentList());
boolean replaceMethodQualifier = false;
PsiExpression newQualifier = newExpression.getQualifier();
PsiElement resolvedFactoryMethod = factoryCall.getMethodExpression().resolve();
if (resolvedFactoryMethod != factoryMethod || newQualifier != null) {
factoryCall.getMethodExpression().replace(qualifiedMethodReference);
replaceMethodQualifier = true;
}
if (replaceMethodQualifier) {
if (newQualifier == null) {
factoryCall.getMethodExpression().getQualifierExpression().replace(classReferenceExpression);
}
else {
factoryCall.getMethodExpression().getQualifierExpression().replace(newQualifier);
}
}
newExpression.replace(factoryCall);
}
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
private PsiMethod createFactoryMethod() throws IncorrectOperationException {
final PsiClass containingClass = getConstructorContainingClass();
PsiClassType type = myFactory.createType(containingClass, PsiSubstitutor.EMPTY);
final PsiMethod factoryMethod = myFactory.createMethod(myFactoryName, type);
if (myConstructor != null) {
factoryMethod.getParameterList().replace(myConstructor.getParameterList());
factoryMethod.getThrowsList().replace(myConstructor.getThrowsList());
}
Collection<String> names = new HashSet<String>();
for (PsiTypeParameter typeParameter : PsiUtil.typeParametersIterable(myConstructor != null ? myConstructor : containingClass)) {
if (!names.contains(typeParameter.getName())) { //Otherwise type parameter is hidden in the constructor
names.add(typeParameter.getName());
factoryMethod.getTypeParameterList().addAfter(typeParameter, null);
}
}
PsiReturnStatement returnStatement =
(PsiReturnStatement)myFactory.createStatementFromText("return new A();", null);
PsiNewExpression newExpression = (PsiNewExpression)returnStatement.getReturnValue();
PsiJavaCodeReferenceElement classRef = myFactory.createReferenceElementByType(type);
newExpression.getClassReference().replace(classRef);
final PsiExpressionList argumentList = newExpression.getArgumentList();
PsiParameter[] params = factoryMethod.getParameterList().getParameters();
for (PsiParameter parameter : params) {
PsiExpression paramRef = myFactory.createExpressionFromText(parameter.getName(), null);
argumentList.add(paramRef);
}
factoryMethod.getBody().add(returnStatement);
PsiUtil.setModifierProperty(factoryMethod, getDefaultFactoryVisibility(), true);
if (!myIsInner) {
PsiUtil.setModifierProperty(factoryMethod, PsiModifier.STATIC, true);
}
return (PsiMethod)CodeStyleManager.getInstance(myProject).reformat(factoryMethod);
}
@PsiModifier.ModifierConstant
private String getDefaultFactoryVisibility() {
final PsiModifierList modifierList;
if (myConstructor != null) {
modifierList = myConstructor.getModifierList();
}
else {
modifierList = myOriginalClass.getModifierList();
}
return VisibilityUtil.getVisibilityModifier(modifierList);
}
protected String getCommandName() {
if (myConstructor != null) {
return RefactoringBundle.message("replace.constructor.0.with.a.factory.method",
DescriptiveNameUtil.getDescriptiveName(myConstructor));
}
else {
return RefactoringBundle.message("replace.default.constructor.of.0.with.a.factory.method",
DescriptiveNameUtil.getDescriptiveName(myOriginalClass));
}
}
public PsiClass getOriginalClass() {
return getConstructorContainingClass();
}
public PsiClass getTargetClass() {
return myTargetClass;
}
public PsiMethod getConstructor() {
return myConstructor;
}
public String getFactoryName() {
return myFactoryName;
}
}
| apache-2.0 |
Guavus/hbase | hbase-hadoop-compat/src/main/java/org/apache/hadoop/hbase/metrics/MBeanSource.java | 1377 | /**
* 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.hbase.metrics;
import javax.management.ObjectName;
/**
* Object that will register an mbean with the underlying metrics implementation.
*/
public interface MBeanSource {
/**
* Register an mbean with the underlying metrics system
* @param serviceName Metrics service/system name
* @param metricsName name of the metrics object to expose
* @param theMbean the actual MBean
* @return ObjectName from jmx
*/
ObjectName register(String serviceName, String metricsName,
Object theMbean);
}
| apache-2.0 |
jayway/powermock | powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/SafeExceptionRethrower.java | 936 | /*
* Copyright 2010 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 org.powermock.api.support;
public class SafeExceptionRethrower {
public static void safeRethrow(Throwable t) {
SafeExceptionRethrower.<RuntimeException> safeRethrow0(t);
}
@SuppressWarnings("unchecked")
private static <T extends Throwable> void safeRethrow0(Throwable t) throws T {
throw (T) t;
}
}
| apache-2.0 |
ivan-fedorov/intellij-community | python/src/com/jetbrains/python/psi/impl/PyBaseElementImpl.java | 6862 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* 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.jetbrains.python.psi.impl;
import com.intellij.extapi.psi.StubBasedPsiElementBase;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.resolve.reference.impl.PsiMultiReference;
import com.intellij.psi.stubs.IStubElementType;
import com.intellij.psi.stubs.StubElement;
import com.intellij.psi.templateLanguages.OuterLanguageElement;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import com.jetbrains.python.PythonFileType;
import com.jetbrains.python.PythonLanguage;
import com.jetbrains.python.psi.PyElement;
import com.jetbrains.python.psi.PyElementVisitor;
import com.jetbrains.python.psi.PyReferenceOwner;
import com.jetbrains.python.psi.resolve.PyResolveContext;
import com.jetbrains.python.psi.types.TypeEvalContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* @author max
*/
public class PyBaseElementImpl<T extends StubElement> extends StubBasedPsiElementBase<T> implements PyElement {
public PyBaseElementImpl(final T stub, IStubElementType nodeType) {
super(stub, nodeType);
}
public PyBaseElementImpl(final ASTNode node) {
super(node);
}
@NotNull
@Override
public PythonLanguage getLanguage() {
return (PythonLanguage)PythonFileType.INSTANCE.getLanguage();
}
@Override
public String toString() {
String className = getClass().getName();
int pos = className.lastIndexOf('.');
if (pos >= 0) {
className = className.substring(pos + 1);
}
if (className.endsWith("Impl")) {
className = className.substring(0, className.length() - 4);
}
return className;
}
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof PyElementVisitor) {
acceptPyVisitor(((PyElementVisitor)visitor));
}
else {
super.accept(visitor);
}
}
protected void acceptPyVisitor(PyElementVisitor pyVisitor) {
pyVisitor.visitPyElement(this);
}
@NotNull
protected <T extends PyElement> T[] childrenToPsi(TokenSet filterSet, T[] array) {
final ASTNode[] nodes = getNode().getChildren(filterSet);
return PyPsiUtils.nodesToPsi(nodes, array);
}
@Nullable
protected <T extends PyElement> T childToPsi(TokenSet filterSet, int index) {
final ASTNode[] nodes = getNode().getChildren(filterSet);
if (nodes.length <= index) {
return null;
}
//noinspection unchecked
return (T)nodes[index].getPsi();
}
@Nullable
protected <T extends PyElement> T childToPsi(IElementType elType) {
final ASTNode node = getNode().findChildByType(elType);
if (node == null) {
return null;
}
//noinspection unchecked
return (T)node.getPsi();
}
@Nullable
protected <T extends PyElement> T childToPsi(@NotNull TokenSet elTypes) {
final ASTNode node = getNode().findChildByType(elTypes);
//noinspection unchecked
return node != null ? (T)node.getPsi() : null;
}
@NotNull
protected <T extends PyElement> T childToPsiNotNull(TokenSet filterSet, int index) {
final PyElement child = childToPsi(filterSet, index);
if (child == null) {
throw new RuntimeException("child must not be null: expression text " + getText());
}
//noinspection unchecked
return (T)child;
}
@NotNull
protected <T extends PyElement> T childToPsiNotNull(IElementType elType) {
final PyElement child = childToPsi(elType);
if (child == null) {
throw new RuntimeException("child must not be null; expression text " + getText());
}
//noinspection unchecked
return (T)child;
}
/**
* Overrides the findReferenceAt() logic in order to provide a resolve context with origin file for returned references.
* The findReferenceAt() is usually invoked from UI operations, and it helps to be able to do deeper analysis in the
* current file for such operations.
*
* @param offset the offset to find the reference at
* @return the reference or null.
*/
@Override
public PsiReference findReferenceAt(int offset) {
// copy/paste from SharedPsiElementImplUtil
PsiElement element = findElementAt(offset);
if (element == null || element instanceof OuterLanguageElement) return null;
offset = getTextRange().getStartOffset() + offset - element.getTextRange().getStartOffset();
List<PsiReference> referencesList = new ArrayList<PsiReference>();
final PsiFile file = element.getContainingFile();
final PyResolveContext resolveContext = file != null ?
PyResolveContext.defaultContext().withTypeEvalContext(TypeEvalContext.codeAnalysis(file.getProject(), file)) :
PyResolveContext.defaultContext();
while (element != null) {
addReferences(offset, element, referencesList, resolveContext);
offset = element.getStartOffsetInParent() + offset;
if (element instanceof PsiFile) break;
element = element.getParent();
}
if (referencesList.isEmpty()) return null;
if (referencesList.size() == 1) return referencesList.get(0);
return new PsiMultiReference(referencesList.toArray(new PsiReference[referencesList.size()]),
referencesList.get(referencesList.size() - 1).getElement());
}
private static void addReferences(int offset, PsiElement element, final Collection<PsiReference> outReferences,
PyResolveContext resolveContext) {
final PsiReference[] references;
if (element instanceof PyReferenceOwner) {
final PsiPolyVariantReference reference = ((PyReferenceOwner)element).getReference(resolveContext);
references = reference == null ? PsiReference.EMPTY_ARRAY : new PsiReference[] {reference};
}
else {
references = element.getReferences();
}
for (final PsiReference reference : references) {
for (TextRange range : ReferenceRange.getRanges(reference)) {
assert range != null : reference;
if (range.containsOffset(offset)) {
outReferences.add(reference);
}
}
}
}
}
| apache-2.0 |
danielkec/liquibase | liquibase-core/src/main/java/liquibase/util/SystemUtils.java | 52176 | /*
* 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 liquibase.util;
import java.io.File;
/**
* Code taken from <a href="http://commons.apache.org/lang">Commons lang utils</a>
* <p>Helpers for <code>java.lang.System</code>.</p>
*
* <p>If a system property cannot be read due to security restrictions,
* the corresponding field in this class will be set to <code>null</code>
* and a message will be written to <code>System.err</code>.</p>
*
* @author Apache Software Foundation
* @author Based on code from Avalon Excalibur
* @author Based on code from Lucene
* @author <a href="mailto:sdowney@panix.com">Steve Downey</a>
* @author Gary Gregory
* @author Michael Becke
* @author Tetsuya Kaneuchi
* @author Rafal Krupinski
* @author Jason Gritman
* @since 1.0
* @version $Id: SystemUtils.java 905707 2010-02-02 16:59:59Z niallp $
*/
public class SystemUtils {
/**
* The prefix String for all Windows OS.
*/
private static final String OS_NAME_WINDOWS_PREFIX = "Windows";
// System property constants
//-----------------------------------------------------------------------
// These MUST be declared first. Other constants depend on this.
/**
* The System property key for the user home directory.
*/
private static final String USER_HOME_KEY = "user.home";
/**
* The System property key for the user directory.
*/
private static final String USER_DIR_KEY = "user.dir";
/**
* The System property key for the Java IO temporary directory.
*/
private static final String JAVA_IO_TMPDIR_KEY = "java.io.tmpdir";
/**
* The System property key for the Java home directory.
*/
private static final String JAVA_HOME_KEY = "java.home";
/**
* <p>The <code>awt.toolkit</code> System Property.</p>
* <p>Holds a class name, on Windows XP this is <code>sun.awt.windows.WToolkit</code>.</p>
* <p><b>On platforms without a GUI, this value is <code>null</code>.</b></p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since 2.1
*/
public static final String AWT_TOOLKIT = getSystemProperty("awt.toolkit");
/**
* <p>The <code>file.encoding</code> System Property.</p>
* <p>File encoding, such as <code>Cp1252</code>.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since 2.0
* @since Java 1.2
*/
public static final String FILE_ENCODING = getSystemProperty("file.encoding");
/**
* <p>The <code>file.separator</code> System Property.
* File separator (<code>"/"</code> on UNIX).</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since Java 1.1
*/
public static final String FILE_SEPARATOR = getSystemProperty("file.separator");
/**
* <p>The <code>java.awt.fonts</code> System Property.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since 2.1
*/
public static final String JAVA_AWT_FONTS = getSystemProperty("java.awt.fonts");
/**
* <p>The <code>java.awt.graphicsenv</code> System Property.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since 2.1
*/
public static final String JAVA_AWT_GRAPHICSENV = getSystemProperty("java.awt.graphicsenv");
/**
* <p>
* The <code>java.awt.headless</code> System Property.
* The value of this property is the String <code>"true"</code> or <code>"false"</code>.
* </p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @see #isJavaAwtHeadless()
* @since 2.1
* @since Java 1.4
*/
public static final String JAVA_AWT_HEADLESS = getSystemProperty("java.awt.headless");
/**
* <p>The <code>java.awt.printerjob</code> System Property.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since 2.1
*/
public static final String JAVA_AWT_PRINTERJOB = getSystemProperty("java.awt.printerjob");
/**
* <p>The <code>java.class.path</code> System Property. Java class path.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since Java 1.1
*/
public static final String JAVA_CLASS_PATH = getSystemProperty("java.class.path");
/**
* <p>The <code>java.class.version</code> System Property.
* Java class format version number.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since Java 1.1
*/
public static final String JAVA_CLASS_VERSION = getSystemProperty("java.class.version");
/**
* <p>The <code>java.compiler</code> System Property. Name of JIT compiler to use.
* First in JDK version 1.2. Not used in Sun JDKs after 1.2.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since Java 1.2. Not used in Sun versions after 1.2.
*/
public static final String JAVA_COMPILER = getSystemProperty("java.compiler");
/**
* <p>The <code>java.endorsed.dirs</code> System Property. Path of endorsed directory
* or directories.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since Java 1.4
*/
public static final String JAVA_ENDORSED_DIRS = getSystemProperty("java.endorsed.dirs");
/**
* <p>The <code>java.ext.dirs</code> System Property. Path of extension directory
* or directories.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since Java 1.3
*/
public static final String JAVA_EXT_DIRS = getSystemProperty("java.ext.dirs");
/**
* <p>The <code>java.home</code> System Property. Java installation directory.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since Java 1.1
*/
public static final String JAVA_HOME = getSystemProperty(JAVA_HOME_KEY);
/**
* <p>The <code>java.io.tmpdir</code> System Property. Default temp file path.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since Java 1.2
*/
public static final String JAVA_IO_TMPDIR = getSystemProperty(JAVA_IO_TMPDIR_KEY);
/**
* <p>The <code>java.library.path</code> System Property. List of paths to search
* when loading libraries.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since Java 1.2
*/
public static final String JAVA_LIBRARY_PATH = getSystemProperty("java.library.path");
/**
* <p>The <code>java.runtime.name</code> System Property. Java Runtime Environment
* name.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since 2.0
* @since Java 1.3
*/
public static final String JAVA_RUNTIME_NAME = getSystemProperty("java.runtime.name");
/**
* <p>The <code>java.runtime.version</code> System Property. Java Runtime Environment
* version.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since 2.0
* @since Java 1.3
*/
public static final String JAVA_RUNTIME_VERSION = getSystemProperty("java.runtime.version");
/**
* <p>The <code>java.specification.name</code> System Property. Java Runtime Environment
* specification name.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since Java 1.2
*/
public static final String JAVA_SPECIFICATION_NAME = getSystemProperty("java.specification.name");
/**
* <p>The <code>java.specification.vendor</code> System Property. Java Runtime Environment
* specification vendor.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since Java 1.2
*/
public static final String JAVA_SPECIFICATION_VENDOR = getSystemProperty("java.specification.vendor");
/**
* <p>The <code>java.specification.version</code> System Property. Java Runtime Environment
* specification version.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since Java 1.3
*/
public static final String JAVA_SPECIFICATION_VERSION = getSystemProperty("java.specification.version");
/**
* <p>The <code>java.util.prefs.PreferencesFactory</code> System Property. A class name.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since 2.1
* @since Java 1.4
*/
public static final String JAVA_UTIL_PREFS_PREFERENCES_FACTORY =
getSystemProperty("java.util.prefs.PreferencesFactory");
/**
* <p>The <code>java.vendor</code> System Property. Java vendor-specific string.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since Java 1.1
*/
public static final String JAVA_VENDOR = getSystemProperty("java.vendor");
/**
* <p>The <code>java.vendor.url</code> System Property. Java vendor URL.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since Java 1.1
*/
public static final String JAVA_VENDOR_URL = getSystemProperty("java.vendor.url");
/**
* <p>The <code>java.version</code> System Property. Java version number.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since Java 1.1
*/
public static final String JAVA_VERSION = getSystemProperty("java.version");
/**
* <p>The <code>java.vm.info</code> System Property. Java Virtual Machine implementation
* info.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since 2.0
* @since Java 1.2
*/
public static final String JAVA_VM_INFO = getSystemProperty("java.vm.info");
/**
* <p>The <code>java.vm.name</code> System Property. Java Virtual Machine implementation
* name.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since Java 1.2
*/
public static final String JAVA_VM_NAME = getSystemProperty("java.vm.name");
/**
* <p>The <code>java.vm.specification.name</code> System Property. Java Virtual Machine
* specification name.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since Java 1.2
*/
public static final String JAVA_VM_SPECIFICATION_NAME = getSystemProperty("java.vm.specification.name");
/**
* <p>The <code>java.vm.specification.vendor</code> System Property. Java Virtual
* Machine specification vendor.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since Java 1.2
*/
public static final String JAVA_VM_SPECIFICATION_VENDOR = getSystemProperty("java.vm.specification.vendor");
/**
* <p>The <code>java.vm.specification.version</code> System Property. Java Virtual Machine
* specification version.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since Java 1.2
*/
public static final String JAVA_VM_SPECIFICATION_VERSION = getSystemProperty("java.vm.specification.version");
/**
* <p>The <code>java.vm.vendor</code> System Property. Java Virtual Machine implementation
* vendor.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since Java 1.2
*/
public static final String JAVA_VM_VENDOR = getSystemProperty("java.vm.vendor");
/**
* <p>The <code>java.vm.version</code> System Property. Java Virtual Machine
* implementation version.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since Java 1.2
*/
public static final String JAVA_VM_VERSION = getSystemProperty("java.vm.version");
/**
* <p>The <code>line.separator</code> System Property. Line separator
* (<code>"\n"</code> on UNIX).</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since Java 1.1
*/
public static final String LINE_SEPARATOR = getSystemProperty("line.separator");
/**
* <p>The <code>os.arch</code> System Property. Operating system architecture.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since Java 1.1
*/
public static final String OS_ARCH = getSystemProperty("os.arch");
/**
* <p>The <code>os.name</code> System Property. Operating system name.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since Java 1.1
*/
public static final String OS_NAME = getSystemProperty("os.name");
/**
* <p>The <code>os.version</code> System Property. Operating system version.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since Java 1.1
*/
public static final String OS_VERSION = getSystemProperty("os.version");
/**
* <p>The <code>path.separator</code> System Property. Path separator
* (<code>":"</code> on UNIX).</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since Java 1.1
*/
public static final String PATH_SEPARATOR = getSystemProperty("path.separator");
/**
* <p>The <code>user.country</code> or <code>user.region</code> System Property.
* User's country code, such as <code>GB</code>. First in JDK version 1.2 as
* <code>user.region</code>. Renamed to <code>user.country</code> in 1.4</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since 2.0
* @since Java 1.2
*/
public static final String USER_COUNTRY =
getSystemProperty("user.country") == null ?
getSystemProperty("user.region") : getSystemProperty("user.country");
/**
* <p>The <code>user.dir</code> System Property. User's current working
* directory.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since Java 1.1
*/
public static final String USER_DIR = getSystemProperty(USER_DIR_KEY);
/**
* <p>The <code>user.home</code> System Property. User's home directory.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since Java 1.1
*/
public static final String USER_HOME = getSystemProperty(USER_HOME_KEY);
/**
* <p>The <code>user.language</code> System Property. User's language code,
* such as <code>"en"</code>.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since 2.0
* @since Java 1.2
*/
public static final String USER_LANGUAGE = getSystemProperty("user.language");
/**
* <p>The <code>user.name</code> System Property. User's account name.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since Java 1.1
*/
public static final String USER_NAME = getSystemProperty("user.name");
/**
* <p>The <code>user.timezone</code> System Property.
* For example: <code>"America/Los_Angeles"</code>.</p>
*
* <p>Defaults to <code>null</code> if the runtime does not have
* security access to read this property or the property does not exist.</p>
*
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)}
* or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value
* will be out of sync with that System property.
* </p>
*
* @since 2.1
*/
public static final String USER_TIMEZONE = getSystemProperty("user.timezone");
// Java version
//-----------------------------------------------------------------------
// This MUST be declared after those above as it depends on the
// values being set up
/**
* <p>Gets the Java version as a <code>String</code> trimming leading letters.</p>
*
* <p>The field will return <code>null</code> if {@link #JAVA_VERSION} is <code>null</code>.</p>
*
* @since 2.1
*/
public static final String JAVA_VERSION_TRIMMED = getJavaVersionTrimmed();
// Java version values
//-----------------------------------------------------------------------
// These MUST be declared after the trim above as they depend on the
// value being set up
/**
* <p>Gets the Java version as a <code>float</code>.</p>
*
* <p>Example return values:</p>
* <ul>
* <li><code>1.2f</code> for JDK 1.2
* <li><code>1.31f</code> for JDK 1.3.1
* </ul>
*
* <p>The field will return zero if {@link #JAVA_VERSION} is <code>null</code>.</p>
*
* @since 2.0
*/
public static final float JAVA_VERSION_FLOAT = getJavaVersionAsFloat();
/**
* <p>Gets the Java version as an <code>int</code>.</p>
*
* <p>Example return values:</p>
* <ul>
* <li><code>120</code> for JDK 1.2
* <li><code>131</code> for JDK 1.3.1
* </ul>
*
* <p>The field will return zero if {@link #JAVA_VERSION} is <code>null</code>.</p>
*
* @since 2.0
*/
public static final int JAVA_VERSION_INT = getJavaVersionAsInt();
// Java version checks
//-----------------------------------------------------------------------
// These MUST be declared after those above as they depend on the
// values being set up
/**
* <p>Is <code>true</code> if this is Java version 1.1 (also 1.1.x versions).</p>
*
* <p>The field will return <code>false</code> if {@link #JAVA_VERSION} is
* <code>null</code>.</p>
*/
public static final boolean IS_JAVA_1_1 = getJavaVersionMatches("1.1");
/**
* <p>Is <code>true</code> if this is Java version 1.2 (also 1.2.x versions).</p>
*
* <p>The field will return <code>false</code> if {@link #JAVA_VERSION} is
* <code>null</code>.</p>
*/
public static final boolean IS_JAVA_1_2 = getJavaVersionMatches("1.2");
/**
* <p>Is <code>true</code> if this is Java version 1.3 (also 1.3.x versions).</p>
*
* <p>The field will return <code>false</code> if {@link #JAVA_VERSION} is
* <code>null</code>.</p>
*/
public static final boolean IS_JAVA_1_3 = getJavaVersionMatches("1.3");
/**
* <p>Is <code>true</code> if this is Java version 1.4 (also 1.4.x versions).</p>
*
* <p>The field will return <code>false</code> if {@link #JAVA_VERSION} is
* <code>null</code>.</p>
*/
public static final boolean IS_JAVA_1_4 = getJavaVersionMatches("1.4");
/**
* <p>Is <code>true</code> if this is Java version 1.5 (also 1.5.x versions).</p>
*
* <p>The field will return <code>false</code> if {@link #JAVA_VERSION} is
* <code>null</code>.</p>
*/
public static final boolean IS_JAVA_1_5 = getJavaVersionMatches("1.5");
/**
* <p>Is <code>true</code> if this is Java version 1.6 (also 1.6.x versions).</p>
*
* <p>The field will return <code>false</code> if {@link #JAVA_VERSION} is
* <code>null</code>.</p>
*/
public static final boolean IS_JAVA_1_6 = getJavaVersionMatches("1.6");
/**
* <p>Is <code>true</code> if this is Java version 1.7 (also 1.7.x versions).</p>
*
* <p>The field will return <code>false</code> if {@link #JAVA_VERSION} is
* <code>null</code>.</p>
*
* @since 2.5
*/
public static final boolean IS_JAVA_1_7 = getJavaVersionMatches("1.7");
// Operating system checks
//-----------------------------------------------------------------------
// These MUST be declared after those above as they depend on the
// values being set up
// OS names from http://www.vamphq.com/os.html
// Selected ones included - please advise dev@commons.apache.org
// if you want another added or a mistake corrected
/**
* <p>Is <code>true</code> if this is AIX.</p>
*
* <p>The field will return <code>false</code> if <code>OS_NAME</code> is
* <code>null</code>.</p>
*
* @since 2.0
*/
public static final boolean IS_OS_AIX = getOSMatches("AIX");
/**
* <p>Is <code>true</code> if this is HP-UX.</p>
*
* <p>The field will return <code>false</code> if <code>OS_NAME</code> is
* <code>null</code>.</p>
*
* @since 2.0
*/
public static final boolean IS_OS_HP_UX = getOSMatches("HP-UX");
/**
* <p>Is <code>true</code> if this is Irix.</p>
*
* <p>The field will return <code>false</code> if <code>OS_NAME</code> is
* <code>null</code>.</p>
*
* @since 2.0
*/
public static final boolean IS_OS_IRIX = getOSMatches("Irix");
/**
* <p>Is <code>true</code> if this is Linux.</p>
*
* <p>The field will return <code>false</code> if <code>OS_NAME</code> is
* <code>null</code>.</p>
*
* @since 2.0
*/
public static final boolean IS_OS_LINUX = getOSMatches("Linux") || getOSMatches("LINUX");
/**
* <p>Is <code>true</code> if this is Mac.</p>
*
* <p>The field will return <code>false</code> if <code>OS_NAME</code> is
* <code>null</code>.</p>
*
* @since 2.0
*/
public static final boolean IS_OS_MAC = getOSMatches("Mac");
/**
* <p>Is <code>true</code> if this is Mac.</p>
*
* <p>The field will return <code>false</code> if <code>OS_NAME</code> is
* <code>null</code>.</p>
*
* @since 2.0
*/
public static final boolean IS_OS_MAC_OSX = getOSMatches("Mac OS X");
/**
* <p>Is <code>true</code> if this is OS/2.</p>
*
* <p>The field will return <code>false</code> if <code>OS_NAME</code> is
* <code>null</code>.</p>
*
* @since 2.0
*/
public static final boolean IS_OS_OS2 = getOSMatches("OS/2");
/**
* <p>Is <code>true</code> if this is Solaris.</p>
*
* <p>The field will return <code>false</code> if <code>OS_NAME</code> is
* <code>null</code>.</p>
*
* @since 2.0
*/
public static final boolean IS_OS_SOLARIS = getOSMatches("Solaris");
/**
* <p>Is <code>true</code> if this is SunOS.</p>
*
* <p>The field will return <code>false</code> if <code>OS_NAME</code> is
* <code>null</code>.</p>
*
* @since 2.0
*/
public static final boolean IS_OS_SUN_OS = getOSMatches("SunOS");
/**
* <p>Is <code>true</code> if this is a POSIX compilant system,
* as in any of AIX, HP-UX, Irix, Linux, MacOSX, Solaris or SUN OS.</p>
*
* <p>The field will return <code>false</code> if <code>OS_NAME</code> is
* <code>null</code>.</p>
*
* @since 2.1
*/
public static final boolean IS_OS_UNIX =
IS_OS_AIX || IS_OS_HP_UX || IS_OS_IRIX || IS_OS_LINUX ||
IS_OS_MAC_OSX || IS_OS_SOLARIS || IS_OS_SUN_OS;
/**
* <p>Is <code>true</code> if this is Windows.</p>
*
* <p>The field will return <code>false</code> if <code>OS_NAME</code> is
* <code>null</code>.</p>
*
* @since 2.0
*/
public static final boolean IS_OS_WINDOWS = getOSMatches(OS_NAME_WINDOWS_PREFIX);
/**
* <p>Is <code>true</code> if this is Windows 2000.</p>
*
* <p>The field will return <code>false</code> if <code>OS_NAME</code> is
* <code>null</code>.</p>
*
* @since 2.0
*/
public static final boolean IS_OS_WINDOWS_2000 = getOSMatches(OS_NAME_WINDOWS_PREFIX, "5.0");
/**
* <p>Is <code>true</code> if this is Windows 95.</p>
*
* <p>The field will return <code>false</code> if <code>OS_NAME</code> is
* <code>null</code>.</p>
*
* @since 2.0
*/
public static final boolean IS_OS_WINDOWS_95 = getOSMatches(OS_NAME_WINDOWS_PREFIX + " 9", "4.0");
// JDK 1.2 running on Windows98 returns 'Windows 95', hence the above
/**
* <p>Is <code>true</code> if this is Windows 98.</p>
*
* <p>The field will return <code>false</code> if <code>OS_NAME</code> is
* <code>null</code>.</p>
*
* @since 2.0
*/
public static final boolean IS_OS_WINDOWS_98 = getOSMatches(OS_NAME_WINDOWS_PREFIX + " 9", "4.1");
// JDK 1.2 running on Windows98 returns 'Windows 95', hence the above
/**
* <p>Is <code>true</code> if this is Windows ME.</p>
*
* <p>The field will return <code>false</code> if <code>OS_NAME</code> is
* <code>null</code>.</p>
*
* @since 2.0
*/
public static final boolean IS_OS_WINDOWS_ME = getOSMatches(OS_NAME_WINDOWS_PREFIX, "4.9");
// JDK 1.2 running on WindowsME may return 'Windows 95', hence the above
/**
* <p>Is <code>true</code> if this is Windows NT.</p>
*
* <p>The field will return <code>false</code> if <code>OS_NAME</code> is
* <code>null</code>.</p>
*
* @since 2.0
*/
public static final boolean IS_OS_WINDOWS_NT = getOSMatches(OS_NAME_WINDOWS_PREFIX + " NT");
// Windows 2000 returns 'Windows 2000' but may suffer from same JDK1.2 problem
/**
* <p>Is <code>true</code> if this is Windows XP.</p>
*
* <p>The field will return <code>false</code> if <code>OS_NAME</code> is
* <code>null</code>.</p>
*
* @since 2.0
*/
public static final boolean IS_OS_WINDOWS_XP = getOSMatches(OS_NAME_WINDOWS_PREFIX, "5.1");
//-----------------------------------------------------------------------
/**
* <p>Is <code>true</code> if this is Windows Vista.</p>
*
* <p>The field will return <code>false</code> if <code>OS_NAME</code> is
* <code>null</code>.</p>
*
* @since 2.4
*/
public static final boolean IS_OS_WINDOWS_VISTA = getOSMatches(OS_NAME_WINDOWS_PREFIX, "6.0");
/**
* <p>Is <code>true</code> if this is Windows 7.</p>
*
* <p>The field will return <code>false</code> if <code>OS_NAME</code> is
* <code>null</code>.</p>
*
* @since 2.5
*/
public static final boolean IS_OS_WINDOWS_7 = getOSMatches(OS_NAME_WINDOWS_PREFIX, "6.1");
//-----------------------------------------------------------------------
/**
* <p>SystemUtils instances should NOT be constructed in standard
* programming. Instead, the class should be used as
* <code>SystemUtils.FILE_SEPARATOR</code>.</p>
*
* <p>This constructor is public to permit tools that require a JavaBean
* instance to operate.</p>
*/
public SystemUtils() {
super();
}
//-----------------------------------------------------------------------
/**
* <p>Gets the Java version number as a <code>float</code>.</p>
*
* <p>Example return values:</p>
* <ul>
* <li><code>1.2f</code> for JDK 1.2
* <li><code>1.31f</code> for JDK 1.3.1
* </ul>
*
* @return the version, for example 1.31f for JDK 1.3.1
* @deprecated Use {@link #JAVA_VERSION_FLOAT} instead.
* Method will be removed in Commons Lang 3.0.
*/
public static float getJavaVersion() {
return JAVA_VERSION_FLOAT;
}
/**
* <p>Gets the Java version number as a <code>float</code>.</p>
*
* <p>Example return values:</p>
* <ul>
* <li><code>1.2f</code> for JDK 1.2
* <li><code>1.31f</code> for JDK 1.3.1
* </ul>
*
* <p>Patch releases are not reported.
* Zero is returned if {@link #JAVA_VERSION_TRIMMED} is <code>null</code>.</p>
*
* @return the version, for example 1.31f for JDK 1.3.1
*/
private static float getJavaVersionAsFloat() {
if (JAVA_VERSION_TRIMMED == null) {
return 0f;
}
String str = JAVA_VERSION_TRIMMED.substring(0, 3);
if (JAVA_VERSION_TRIMMED.length() >= 5) {
str = str + JAVA_VERSION_TRIMMED.substring(4, 5);
}
try {
return Float.parseFloat(str);
} catch (Exception ex) {
return 0;
}
}
/**
* <p>Gets the Java version number as an <code>int</code>.</p>
*
* <p>Example return values:</p>
* <ul>
* <li><code>120</code> for JDK 1.2
* <li><code>131</code> for JDK 1.3.1
* </ul>
*
* <p>Patch releases are not reported.
* Zero is returned if {@link #JAVA_VERSION_TRIMMED} is <code>null</code>.</p>
*
* @return the version, for example 131 for JDK 1.3.1
*/
private static int getJavaVersionAsInt() {
if (JAVA_VERSION_TRIMMED == null) {
return 0;
}
String str = JAVA_VERSION_TRIMMED.substring(0, 1);
str = str + JAVA_VERSION_TRIMMED.substring(2, 3);
if (JAVA_VERSION_TRIMMED.length() >= 5) {
str = str + JAVA_VERSION_TRIMMED.substring(4, 5);
} else {
str = str + "0";
}
try {
return Integer.parseInt(str);
} catch (Exception ex) {
return 0;
}
}
/**
* Trims the text of the java version to start with numbers.
*
* @return the trimmed java version
*/
private static String getJavaVersionTrimmed() {
if (JAVA_VERSION != null) {
for (int i = 0; i < JAVA_VERSION.length(); i++) {
char ch = JAVA_VERSION.charAt(i);
if (ch >= '0' && ch <= '9') {
return JAVA_VERSION.substring(i);
}
}
}
return null;
}
/**
* <p>Decides if the java version matches.</p>
*
* @param versionPrefix the prefix for the java version
* @return true if matches, or false if not or can't determine
*/
private static boolean getJavaVersionMatches(String versionPrefix) {
if (JAVA_VERSION_TRIMMED == null) {
return false;
}
return JAVA_VERSION_TRIMMED.startsWith(versionPrefix);
}
/**
* <p>Decides if the operating system matches.</p>
*
* @param osNamePrefix the prefix for the os name
* @return true if matches, or false if not or can't determine
*/
private static boolean getOSMatches(String osNamePrefix) {
if (OS_NAME == null) {
return false;
}
return OS_NAME.startsWith(osNamePrefix);
}
/**
* <p>Decides if the operating system matches.</p>
*
* @param osNamePrefix the prefix for the os name
* @param osVersionPrefix the prefix for the version
* @return true if matches, or false if not or can't determine
*/
private static boolean getOSMatches(String osNamePrefix, String osVersionPrefix) {
if (OS_NAME == null || OS_VERSION == null) {
return false;
}
return OS_NAME.startsWith(osNamePrefix) && OS_VERSION.startsWith(osVersionPrefix);
}
//-----------------------------------------------------------------------
/**
* <p>Gets a System property, defaulting to <code>null</code> if the property
* cannot be read.</p>
*
* <p>If a <code>SecurityException</code> is caught, the return
* value is <code>null</code> and a message is written to <code>System.err</code>.</p>
*
* @param property the system property name
* @return the system property value or <code>null</code> if a security problem occurs
*/
private static String getSystemProperty(String property) {
try {
return System.getProperty(property);
} catch (SecurityException ex) {
// we are not allowed to look at this property
System.err.println(
"Caught a SecurityException reading the system property '" + property
+ "'; the SystemUtils property value will default to null."
);
return null;
}
}
/**
* <p>Is the Java version at least the requested version.</p>
*
* <p>Example input:</p>
* <ul>
* <li><code>1.2f</code> to test for JDK 1.2</li>
* <li><code>1.31f</code> to test for JDK 1.3.1</li>
* </ul>
*
* @param requiredVersion the required version, for example 1.31f
* @return <code>true</code> if the actual version is equal or greater
* than the required version
*/
public static boolean isJavaVersionAtLeast(float requiredVersion) {
return JAVA_VERSION_FLOAT >= requiredVersion;
}
/**
* <p>Is the Java version at least the requested version.</p>
*
* <p>Example input:</p>
* <ul>
* <li><code>120</code> to test for JDK 1.2 or greater</li>
* <li><code>131</code> to test for JDK 1.3.1 or greater</li>
* </ul>
*
* @param requiredVersion the required version, for example 131
* @return <code>true</code> if the actual version is equal or greater
* than the required version
* @since 2.0
*/
public static boolean isJavaVersionAtLeast(int requiredVersion) {
return JAVA_VERSION_INT >= requiredVersion;
}
/**
* Returns whether the {@link #JAVA_AWT_HEADLESS} value is <code>true</code>.
*
* @return <code>true</code> if <code>JAVA_AWT_HEADLESS</code> is <code>"true"</code>,
* <code>false</code> otherwise.
*
* @see #JAVA_AWT_HEADLESS
* @since 2.1
* @since Java 1.4
*/
public static boolean isJavaAwtHeadless() {
return JAVA_AWT_HEADLESS != null ? JAVA_AWT_HEADLESS.equals(Boolean.TRUE.toString()) : false;
}
/**
* <p>Gets the Java home directory as a <code>File</code>.</p>
*
* @return a directory
* @throws SecurityException if a security manager exists and its
* <code>checkPropertyAccess</code> method doesn't allow
* access to the specified system property.
* @see System#getProperty(String)
* @since 2.1
*/
public static File getJavaHome() {
return new File(System.getProperty(JAVA_HOME_KEY));
}
/**
* <p>Gets the Java IO temporary directory as a <code>File</code>.</p>
*
* @return a directory
* @throws SecurityException if a security manager exists and its
* <code>checkPropertyAccess</code> method doesn't allow
* access to the specified system property.
* @see System#getProperty(String)
* @since 2.1
*/
public static File getJavaIoTmpDir() {
return new File(System.getProperty(JAVA_IO_TMPDIR_KEY));
}
/**
* <p>Gets the user directory as a <code>File</code>.</p>
*
* @return a directory
* @throws SecurityException if a security manager exists and its
* <code>checkPropertyAccess</code> method doesn't allow
* access to the specified system property.
* @see System#getProperty(String)
* @since 2.1
*/
public static File getUserDir() {
return new File(System.getProperty(USER_DIR_KEY));
}
/**
* <p>Gets the user home directory as a <code>File</code>.</p>
*
* @return a directory
* @throws SecurityException if a security manager exists and its
* <code>checkPropertyAccess</code> method doesn't allow
* access to the specified system property.
* @see System#getProperty(String)
* @since 2.1
*/
public static File getUserHome() {
return new File(System.getProperty(USER_HOME_KEY));
}
public static boolean isWindows() {
return System.getProperty("os.name").startsWith("Windows ");
}
}
| apache-2.0 |
allancth/camel | tooling/camel-route-parser/src/test/java/org/apache/camel/parser/java/RoasterConcatFieldRouteBuilderConfigureTest.java | 2314 | /**
* 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.parser.java;
import java.io.File;
import java.util.List;
import org.apache.camel.parser.ParserResult;
import org.apache.camel.parser.helper.CamelJavaParserHelper;
import org.jboss.forge.roaster.Roaster;
import org.jboss.forge.roaster.model.source.JavaClassSource;
import org.jboss.forge.roaster.model.source.MethodSource;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RoasterConcatFieldRouteBuilderConfigureTest {
private static final Logger LOG = LoggerFactory.getLogger(RoasterConcatFieldRouteBuilderConfigureTest.class);
@Test
public void parse() throws Exception {
JavaClassSource clazz = (JavaClassSource) Roaster.parse(new File("src/test/java/org/apache/camel/parser/java/MyConcatFieldRouteBuilder.java"));
MethodSource<JavaClassSource> method = clazz.getMethod("configure");
List<ParserResult> list = CamelJavaParserHelper.parseCamelConsumerUris(method, true, true);
for (ParserResult result : list) {
LOG.info("Consumer: " + result.getElement());
}
Assert.assertEquals("ftp:localhost:{{ftpPort}}/myapp?password=admin&username=admin", list.get(0).getElement());
list = CamelJavaParserHelper.parseCamelProducerUris(method, true, true);
for (ParserResult result : list) {
LOG.info("Producer: " + result.getElement());
}
Assert.assertEquals("log:b", list.get(0).getElement());
}
}
| apache-2.0 |
W3SS/android-menudrawer | menudrawer/src/net/simonvt/menudrawer/ViewHelper.java | 1145 | package net.simonvt.menudrawer;
import android.os.Build;
import android.view.View;
final class ViewHelper {
private ViewHelper() {
}
public static int getLeft(View v) {
if (MenuDrawer.USE_TRANSLATIONS) {
return (int) (v.getLeft() + v.getTranslationX());
}
return v.getLeft();
}
public static int getTop(View v) {
if (MenuDrawer.USE_TRANSLATIONS) {
return (int) (v.getTop() + v.getTranslationY());
}
return v.getTop();
}
public static int getRight(View v) {
if (MenuDrawer.USE_TRANSLATIONS) {
return (int) (v.getRight() + v.getTranslationX());
}
return v.getRight();
}
public static int getBottom(View v) {
if (MenuDrawer.USE_TRANSLATIONS) {
return (int) (v.getBottom() + v.getTranslationY());
}
return v.getBottom();
}
public static int getLayoutDirection(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
return v.getLayoutDirection();
}
return View.LAYOUT_DIRECTION_LTR;
}
}
| apache-2.0 |
ivan-fedorov/intellij-community | platform/platform-impl/src/com/intellij/ui/plaf/beg/BegBorders.java | 8804 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* 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.intellij.ui.plaf.beg;
import com.intellij.util.ui.UIUtil;
import javax.swing.*;
import javax.swing.border.AbstractBorder;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.plaf.BorderUIResource;
import javax.swing.plaf.UIResource;
import javax.swing.plaf.basic.BasicBorders;
import javax.swing.plaf.metal.MetalLookAndFeel;
import javax.swing.text.JTextComponent;
import java.awt.*;
/**
* @author Eugene Belyaev
*/
public class BegBorders {
private static Border ourButtonBorder;
private static Border ourTextFieldBorder;
private static Border ourScrollPaneBorder;
public static Border getButtonBorder() {
if (ourButtonBorder == null) {
ourButtonBorder = new BorderUIResource.CompoundBorderUIResource(
new ButtonBorder(),
new BasicBorders.MarginBorder());
}
return ourButtonBorder;
}
public static Border getTextFieldBorder() {
if (ourTextFieldBorder == null) {
ourTextFieldBorder = new BorderUIResource.CompoundBorderUIResource(
new TextFieldBorder(),
//new FlatLineBorder(),
BorderFactory.createEmptyBorder(2, 2, 2, 2));
}
return ourTextFieldBorder;
}
public static Border getScrollPaneBorder() {
if (ourScrollPaneBorder == null) {
ourScrollPaneBorder = new BorderUIResource.LineBorderUIResource(MetalLookAndFeel.getControlDarkShadow());
//ourScrollPaneBorder = new FlatLineBorder();
}
return ourScrollPaneBorder;
}
public static class FlatLineBorder extends LineBorder implements UIResource {
public FlatLineBorder() {
super(new Color(127, 157, 185), 1, true);
}
}
public static class ButtonBorder extends AbstractBorder implements UIResource {
protected static Insets borderInsets = new Insets(3, 3, 3, 3);
public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) {
AbstractButton button = (AbstractButton) c;
ButtonModel model = button.getModel();
if (model.isEnabled()) {
boolean isPressed = model.isPressed() && model.isArmed();
boolean isDefault = (button instanceof JButton && ((JButton) button).isDefaultButton());
if (isPressed && isDefault) {
drawDefaultButtonPressedBorder(g, x, y, w, h);
} else if (isPressed) {
drawPressed3DBorder(g, x, y, w, h);
} else if (isDefault) {
drawDefaultButtonBorder(g, x, y, w, h, false);
} else {
drawButtonBorder(g, x, y, w, h, false);
}
} else { // disabled state
drawDisabledBorder(g, x, y, w - 1, h - 1);
}
}
public Insets getBorderInsets(Component c) {
return (Insets)borderInsets.clone();
}
public Insets getBorderInsets(Component c, Insets newInsets) {
newInsets.top = borderInsets.top;
newInsets.left = borderInsets.left;
newInsets.bottom = borderInsets.bottom;
newInsets.right = borderInsets.right;
return newInsets;
}
}
public static class ScrollPaneBorder extends AbstractBorder implements UIResource {
private static final Insets insets = new Insets(1, 1, 2, 2);
public void paintBorder(Component c, Graphics g, int x, int y,
int w, int h) {
JScrollPane scroll = (JScrollPane) c;
JComponent colHeader = scroll.getColumnHeader();
int colHeaderHeight = 0;
if (colHeader != null)
colHeaderHeight = colHeader.getHeight();
JComponent rowHeader = scroll.getRowHeader();
int rowHeaderWidth = 0;
if (rowHeader != null)
rowHeaderWidth = rowHeader.getWidth();
/*
g.translate(x, y);
g.setColor(MetalLookAndFeel.getControlDarkShadow());
g.drawRect(0, 0, w - 2, h - 2);
g.setColor(MetalLookAndFeel.getControlHighlight());
g.drawLine(w - 1, 1, w - 1, h - 1);
g.drawLine(1, h - 1, w - 1, h - 1);
g.setColor(MetalLookAndFeel.getControl());
if (colHeaderHeight > 0) {
g.drawLine(w - 2, 2 + colHeaderHeight, w - 2, 2 + colHeaderHeight);
}
if (rowHeaderWidth > 0) {
g.drawLine(1 + rowHeaderWidth, h - 2, 1 + rowHeaderWidth, h - 2);
}
g.translate(-x, -y);
*/
drawLineBorder(g, x, y, w, h);
}
public Insets getBorderInsets(Component c) {
return (Insets)insets.clone();
}
}
public static class TextFieldBorder /*extends MetalBorders.Flush3DBorder*/ extends LineBorder implements UIResource {
public TextFieldBorder() {
super(null, 1);
}
public boolean isBorderOpaque() {
return false;
}
public void paintBorder(Component c, Graphics g, int x, int y,
int w, int h) {
if (!(c instanceof JTextComponent)) {
// special case for non-text components (bug ID 4144840)
if (c.isEnabled()) {
drawFlush3DBorder(g, x, y, w, h);
} else {
drawDisabledBorder(g, x, y, w, h);
}
return;
}
if (c.isEnabled() && ((JTextComponent) c).isEditable()) {
drawLineBorder(g, x, y, w, h);
/*
g.translate(x, y);
g.setColor(MetalLookAndFeel.getControlDarkShadow());
g.drawLine(1, 0, w - 2, 0);
g.drawLine(0, 1, 0, h - 2);
g.drawLine(w - 1, 1, w - 1, h - 2);
g.drawLine(1, h - 1, w - 2, h - 1);
g.translate(-x, -y);
*/
} else {
drawDisabledBorder(g, x, y, w, h);
}
}
}
static void drawLineBorder(Graphics g, int x, int y, int w, int h) {
g.translate(x, y);
g.setColor(MetalLookAndFeel.getControlDarkShadow());
g.drawRect(0, 0, w - 1, h - 1);
g.translate(-x, -y);
}
static void drawFlush3DBorder(Graphics g, int x, int y, int w, int h) {
g.translate(x, y);
g.setColor(MetalLookAndFeel.getControlHighlight());
g.drawRect(1, 1, w - 2, h - 2);
g.setColor(MetalLookAndFeel.getControlDarkShadow());
g.drawRect(0, 0, w - 2, h - 2);
g.translate(-x, -y);
}
static void drawDisabledBorder(Graphics g, int x, int y, int w, int h) {
g.translate(x, y);
g.setColor(MetalLookAndFeel.getControlShadow());
g.drawRect(0, 0, w - 1, h - 1);
g.translate(-x, -y);
}
static void drawDefaultButtonPressedBorder(Graphics g, int x, int y, int w, int h) {
drawPressed3DBorder(g, x + 1, y + 1, w - 1, h - 1);
g.translate(x, y);
g.setColor(MetalLookAndFeel.getControlDarkShadow());
g.drawRect(0, 0, w - 3, h - 3);
UIUtil.drawLine(g, w - 2, 0, w - 2, 0);
UIUtil.drawLine(g, 0, h - 2, 0, h - 2);
g.translate(-x, -y);
}
static void drawPressed3DBorder(Graphics g, int x, int y, int w, int h) {
g.translate(x, y);
drawFlush3DBorder(g, 0, 0, w, h);
g.setColor(MetalLookAndFeel.getControlShadow());
UIUtil.drawLine(g, 1, 1, 1, h - 1);
UIUtil.drawLine(g, 1, 1, w - 1, 1);
g.translate(-x, -y);
}
static void drawDefaultButtonBorder(Graphics g, int x, int y, int w, int h, boolean active) {
drawButtonBorder(g, x + 1, y + 1, w - 1, h - 1, active);
g.translate(x, y);
g.setColor(MetalLookAndFeel.getControlDarkShadow());
g.drawRect(0, 0, w - 3, h - 3);
UIUtil.drawLine(g, w - 2, 0, w - 2, 0);
UIUtil.drawLine(g, 0, h - 2, 0, h - 2);
g.translate(-x, -y);
}
static void drawButtonBorder(Graphics g, int x, int y, int w, int h, boolean active) {
if (active) {
drawActiveButtonBorder(g, x, y, w, h);
} else {
drawFlush3DBorder(g, x, y, w, h);
/*
drawLineBorder(g, x, y, w - 1, h - 1);
g.setColor(MetalLookAndFeel.getControlHighlight());
g.drawLine(x + 1, y + h - 1, x + w - 1, y + h - 1);
g.drawLine(x + w - 1, y + 1, x + w - 1, y + h - 1);
*/
}
}
static void drawActiveButtonBorder(Graphics g, int x, int y, int w, int h) {
drawFlush3DBorder(g, x, y, w, h);
g.setColor(MetalLookAndFeel.getPrimaryControl());
UIUtil.drawLine(g, x + 1, y + 1, x + 1, h - 3);
UIUtil.drawLine(g, x + 1, y + 1, w - 3, x + 1);
g.setColor(MetalLookAndFeel.getPrimaryControlDarkShadow());
UIUtil.drawLine(g, x + 2, h - 2, w - 2, h - 2);
UIUtil.drawLine(g, w - 2, y + 2, w - 2, h - 2);
}
}
| apache-2.0 |
Guardiola31337/joda-time | src/main/java/org/joda/time/ReadablePartial.java | 6784 | /*
* Copyright 2001-2011 Stephen Colebourne
*
* 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.joda.time;
/**
* Defines a partial time that does not support every datetime field, and is
* thus a local time.
* <p>
* A {@code ReadablePartial} supports a subset of those fields on the chronology.
* It cannot be compared to a {@code ReadableInstant}, as it does not fully
* specify an instant in time. The time it does specify is a local time, and does
* not include a time zone.
* <p>
* A {@code ReadablePartial} can be converted to a {@code ReadableInstant}
* using the {@code toDateTime} method. This works by providing a full base
* instant that can be used to 'fill in the gaps' and specify a time zone.
* <p>
* {@code ReadablePartial} is {@code Comparable} from v2.0.
* The comparison is based on the fields, compared in order, from largest to smallest.
* The first field that is non-equal is used to determine the result.
*
* @author Stephen Colebourne
* @since 1.0
*/
public interface ReadablePartial extends Comparable<ReadablePartial> {
/**
* Gets the number of fields that this partial supports.
*
* @return the number of fields supported
*/
int size();
/**
* Gets the field type at the specified index.
*
* @param index the index to retrieve
* @return the field at the specified index
* @throws IndexOutOfBoundsException if the index is invalid
*/
DateTimeFieldType getFieldType(int index);
/**
* Gets the field at the specified index.
*
* @param index the index to retrieve
* @return the field at the specified index
* @throws IndexOutOfBoundsException if the index is invalid
*/
DateTimeField getField(int index);
/**
* Gets the value at the specified index.
*
* @param index the index to retrieve
* @return the value of the field at the specified index
* @throws IndexOutOfBoundsException if the index is invalid
*/
int getValue(int index);
/**
* Gets the chronology of the partial which is never null.
* <p>
* The {@link Chronology} is the calculation engine behind the partial and
* provides conversion and validation of the fields in a particular calendar system.
*
* @return the chronology, never null
*/
Chronology getChronology();
/**
* Gets the value of one of the fields.
* <p>
* The field type specified must be one of those that is supported by the partial.
*
* @param field a DateTimeFieldType instance that is supported by this partial
* @return the value of that field
* @throws IllegalArgumentException if the field is null or not supported
*/
int get(DateTimeFieldType field);
/**
* Checks whether the field type specified is supported by this partial.
*
* @param field the field to check, may be null which returns false
* @return true if the field is supported
*/
boolean isSupported(DateTimeFieldType field);
/**
* Converts this partial to a full datetime by resolving it against another
* datetime.
* <p>
* This method takes the specified datetime and sets the fields from this
* instant on top. The chronology from the base instant is used.
* <p>
* For example, if this partial represents a time, then the result of this
* method will be the datetime from the specified base instant plus the
* time from this partial.
*
* @param baseInstant the instant that provides the missing fields, null means now
* @return the combined datetime
*/
DateTime toDateTime(ReadableInstant baseInstant);
//-----------------------------------------------------------------------
/**
* Compares this partial with the specified object for equality based
* on the supported fields, chronology and values.
* <p>
* Two instances of ReadablePartial are equal if they have the same
* chronology, same field types (in same order) and same values.
*
* @param partial the object to compare to
* @return true if equal
*/
boolean equals(Object partial);
/**
* Gets a hash code for the partial that is compatible with the
* equals method.
* <p>
* The formula used must be:
* <pre>
* int total = 157;
* for (int i = 0; i < fields.length; i++) {
* total = 23 * total + values[i];
* total = 23 * total + fieldTypes[i].hashCode();
* }
* total += chronology.hashCode();
* return total;
* </pre>
*
* @return a suitable hash code
*/
int hashCode();
//-----------------------------------------------------------------------
// This is commented out to improve backwards compatibility
// /**
// * Compares this partial with another returning an integer
// * indicating the order.
// * <p>
// * The fields are compared in order, from largest to smallest.
// * The first field that is non-equal is used to determine the result.
// * Thus a year-hour partial will first be compared on the year, and then
// * on the hour.
// * <p>
// * The specified object must be a partial instance whose field types
// * match those of this partial. If the partial instance has different
// * fields then a {@code ClassCastException} is thrown.
// *
// * @param partial an object to check against
// * @return negative if this is less, zero if equal, positive if greater
// * @throws ClassCastException if the partial is the wrong class
// * or if it has field types that don't match
// * @throws NullPointerException if the partial is null
// * @since 2.0, previously on {@code AbstractPartial}
// */
// int compareTo(ReadablePartial partial);
//-----------------------------------------------------------------------
/**
* Get the value as a String in a recognisable ISO8601 format, only
* displaying supported fields.
* <p>
* The string output is in ISO8601 format to enable the String
* constructor to correctly parse it.
*
* @return the value as an ISO8601 string
*/
String toString();
}
| apache-2.0 |
akosyakov/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/ex/ToolWindowManagerEx.java | 2657 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* 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.intellij.openapi.wm.ex;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.wm.ToolWindowAnchor;
import com.intellij.openapi.wm.ToolWindowEP;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.openapi.wm.impl.DesktopLayout;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.List;
public abstract class ToolWindowManagerEx extends ToolWindowManager {
public abstract void initToolWindow(@NotNull ToolWindowEP bean);
public static ToolWindowManagerEx getInstanceEx(final Project project){
return (ToolWindowManagerEx)getInstance(project);
}
public abstract void addToolWindowManagerListener(@NotNull ToolWindowManagerListener l);
public abstract void addToolWindowManagerListener(@NotNull ToolWindowManagerListener l, @NotNull Disposable parentDisposable);
public abstract void removeToolWindowManagerListener(@NotNull ToolWindowManagerListener l);
/**
* @return <code>ID</code> of tool window that was activated last time.
*/
@Nullable
public abstract String getLastActiveToolWindowId();
/**
* @return <code>ID</code> of tool window which was last activated among tool windows satisfying the current condition
*/
@Nullable
public abstract String getLastActiveToolWindowId(@Nullable Condition<JComponent> condition);
/**
* @return layout of tool windows.
*/
public abstract DesktopLayout getLayout();
public abstract void setLayoutToRestoreLater(DesktopLayout layout);
public abstract DesktopLayout getLayoutToRestoreLater();
/**
* Copied <code>layout</code> into internal layout and rearranges tool windows.
*/
public abstract void setLayout(@NotNull DesktopLayout layout);
public abstract void clearSideStack();
public abstract void hideToolWindow(@NotNull String id, boolean hideSide);
public abstract List<String> getIdsOn(@NotNull ToolWindowAnchor anchor);
}
| apache-2.0 |
hardbitcn/HardbitSafetyCheck | src/com/google/bitcoin/core/InventoryMessage.java | 3091 | /**
* Copyright 2011 Google 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.google.bitcoin.core;
import static com.google.common.base.Preconditions.checkArgument;
/**
* <p>Represents the "inv" P2P network message. An inv contains a list of hashes of either blocks or transactions. It's
* a bandwidth optimization - on receiving some data, a (fully validating) peer sends every connected peer an inv
* containing the hash of what it saw. It'll only transmit the full thing if a peer asks for it with a
* {@link GetDataMessage}.</p>
*/
public class InventoryMessage extends ListMessage {
private static final long serialVersionUID = -7050246551646107066L;
public InventoryMessage(NetworkParameters params, byte[] bytes) throws ProtocolException {
super(params, bytes);
}
/**
* Deserializes an 'inv' message.
* @param params NetworkParameters object.
* @param msg Bitcoin protocol formatted byte array containing message content.
* @param parseLazy Whether to perform a full parse immediately or delay until a read is requested.
* @param parseRetain Whether to retain the backing byte array for quick reserialization.
* If true and the backing byte array is invalidated due to modification of a field then
* the cached bytes may be repopulated and retained if the message is serialized again in the future.
* @param length The length of message if known. Usually this is provided when deserializing of the wire
* as the length will be provided as part of the header. If unknown then set to Message.UNKNOWN_LENGTH
* @throws ProtocolException
*/
public InventoryMessage(NetworkParameters params, byte[] msg, boolean parseLazy, boolean parseRetain, int length)
throws ProtocolException {
super(params, msg, parseLazy, parseRetain, length);
}
public InventoryMessage(NetworkParameters params) {
super(params);
}
public void addBlock(Block block) {
addItem(new InventoryItem(InventoryItem.Type.Block, block.getHash()));
}
public void addTransaction(Transaction tx) {
addItem(new InventoryItem(InventoryItem.Type.Transaction, tx.getHash()));
}
/** Creates a new inv message for the given transactions. */
public static InventoryMessage with(Transaction... txns) {
checkArgument(txns.length > 0);
InventoryMessage result = new InventoryMessage(txns[0].getParams());
for (Transaction tx : txns)
result.addTransaction(tx);
return result;
}
}
| apache-2.0 |
punkhorn/camel-upstream | tests/camel-itest-spring-boot/src/test/java/org/apache/camel/itest/springboot/CamelUnivocityParsersTest.java | 1889 | /**
* 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.springboot;
import org.apache.camel.itest.springboot.util.ArquillianPackager;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(Arquillian.class)
public class CamelUnivocityParsersTest extends AbstractSpringBootTestSupport {
@Deployment
public static Archive<?> createSpringBootPackage() throws Exception {
return ArquillianPackager.springBootPackage(createTestConfig());
}
public static ITestConfig createTestConfig() {
return new ITestConfigBuilder()
.module(inferModuleName(CamelUnivocityParsersTest.class))
.build();
}
@Test
public void componentTests() throws Exception {
this.runDataformatTest(config, "univocity-csv");
this.runDataformatTest(config, "univocity-fixed");
this.runDataformatTest(config, "univocity-tsv");
this.runModuleUnitTestsIfEnabled(config);
}
}
| apache-2.0 |
bunnyblue/UltimateRecyclerView | UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/TestAdMob.java | 6829 | package com.marshalchen.ultimaterecyclerview.demo;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.marshalchen.ultimaterecyclerview.AdmobAdapter;
import com.marshalchen.ultimaterecyclerview.URLogs;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.demo.modules.FastBinding;
import com.marshalchen.ultimaterecyclerview.demo.modules.SampleDataboxset;
import com.marshalchen.ultimaterecyclerview.demo.modules.admobdfpadapter;
import java.util.ArrayList;
import java.util.List;
/**
* Created by hesk on 20/5/15.
*/
public class TestAdMob extends AppCompatActivity {
UltimateRecyclerView ultimateRecyclerView;
admobdfpadapter simpleRecyclerViewAdapter = null;
LinearLayoutManager linearLayoutManager;
int moreNum = 2;
private ActionMode actionMode;
Toolbar toolbar;
boolean isDrag = true;
private boolean admob_test_mode = false;
private AdView createadmob() {
AdView mAdView = new AdView(this);
mAdView.setAdSize(AdSize.MEDIUM_RECTANGLE);
mAdView.setAdUnitId("/1015938/Hypebeast_App_320x50");
mAdView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
// Create an ad request.
AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
if (admob_test_mode)
// Optionally populate the ad request builder.
adRequestBuilder.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
// Start loading the ad.
mAdView.loadAd(adRequestBuilder.build());
return mAdView;
}
private void enableSwipe() {
}
private void enableRefreshAndLoadMore() {
ultimateRecyclerView.setDefaultOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
simpleRecyclerViewAdapter.insert(moreNum++ + " Refresh things");
ultimateRecyclerView.setRefreshing(false);
// ultimateRecyclerView.scrollBy(0, -50);
linearLayoutManager.scrollToPosition(0);
// ultimateRecyclerView.setAdapter(simpleRecyclerViewAdapter);
// simpleRecyclerViewAdapter.notifyDataSetChanged();
}
}, 1000);
}
});
ultimateRecyclerView.setOnLoadMoreListener(new UltimateRecyclerView.OnLoadMoreListener() {
@Override
public void loadMore(int itemsCount, final int maxLastVisiblePosition) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
Log.d("loadmore", maxLastVisiblePosition + " position");
SampleDataboxset.insertMore(simpleRecyclerViewAdapter, 1);
// linearLayoutManager.scrollToPosition(linearLayoutManager.getChildCount() - 1);
}
}, 5000);
}
});
simpleRecyclerViewAdapter.setCustomLoadMoreView(LayoutInflater.from(this).inflate(R.layout.custom_bottom_progressbar, null));
ultimateRecyclerView.enableLoadmore();
}
private void enableClick() {
}
private void impleAddDrop() {
findViewById(R.id.add).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SampleDataboxset.insertMore(simpleRecyclerViewAdapter, 1);
}
});
findViewById(R.id.del).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
simpleRecyclerViewAdapter.remove(3);
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
ultimateRecyclerView = (UltimateRecyclerView) findViewById(R.id.ultimate_recycler_view);
ultimateRecyclerView.setHasFixedSize(false);
/**
* wokring example 1 implementation of Admob banner with static Adview
*/
// simpleRecyclerViewAdapter = new admobdfpadapter(createadmob(), 5, stringList);
/**
* working example 2 with multiple called Adviews
*/
simpleRecyclerViewAdapter = new admobdfpadapter(createadmob(), 3, SampleDataboxset.newListFromGen(), new AdmobAdapter.AdviewListener() {
@Override
public AdView onGenerateAdview() {
return createadmob();
}
});
linearLayoutManager = new LinearLayoutManager(this);
ultimateRecyclerView.setLayoutManager(linearLayoutManager);
ultimateRecyclerView.setAdapter(simpleRecyclerViewAdapter);
ultimateRecyclerView.setRecylerViewBackgroundColor(Color.parseColor("#ffffff"));
enableRefreshAndLoadMore();
enableClick();
impleAddDrop();
}
private void toggleSelection(int position) {
simpleRecyclerViewAdapter.toggleSelection(position);
actionMode.setTitle("Selected " + "1");
}
@Override
protected void onDestroy() {
super.onDestroy();
}
public int getScreenHeight() {
return findViewById(android.R.id.content).getHeight();
}
//
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
FastBinding.startactivity(this, item.getItemId());
return super.onOptionsItemSelected(item);
}
}
| apache-2.0 |
shuvigoss/dubbox | dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/fst/FstObjectOutput.java | 2448 | /**
* Copyright 1999-2014 dangdang.com.
*
* 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.alibaba.dubbo.common.serialize.support.fst;
import com.alibaba.dubbo.common.serialize.ObjectOutput;
import de.ruedigermoeller.serialization.FSTObjectOutput;
import java.io.IOException;
import java.io.OutputStream;
/**
* @author lishen
*/
public class FstObjectOutput implements ObjectOutput {
private FSTObjectOutput output;
public FstObjectOutput(OutputStream outputStream) {
output = FstFactory.getDefaultFactory().getObjectOutput(outputStream);
}
public void writeBool(boolean v) throws IOException {
output.writeBoolean(v);
}
public void writeByte(byte v) throws IOException {
output.writeByte(v);
}
public void writeShort(short v) throws IOException {
output.writeShort(v);
}
public void writeInt(int v) throws IOException {
output.writeInt(v);
}
public void writeLong(long v) throws IOException {
output.writeLong(v);
}
public void writeFloat(float v) throws IOException {
output.writeFloat(v);
}
public void writeDouble(double v) throws IOException {
output.writeDouble(v);
}
public void writeBytes(byte[] v) throws IOException {
if (v == null) {
output.writeInt(-1);
} else {
writeBytes(v, 0, v.length);
}
}
public void writeBytes(byte[] v, int off, int len) throws IOException {
if (v == null) {
output.writeInt(-1);
} else {
output.writeInt(len);
output.write(v, off, len);
}
}
public void writeUTF(String v) throws IOException {
output.writeUTF(v);
}
public void writeObject(Object v) throws IOException {
output.writeObject(v);
}
public void flushBuffer() throws IOException {
output.flush();
}
} | apache-2.0 |
kuzemchik/presto | presto-main/src/main/java/com/facebook/presto/operator/aggregation/RegressionAggregation.java | 3161 | /*
* 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.aggregation;
import com.facebook.presto.operator.aggregation.state.RegressionState;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.type.StandardTypes;
import com.facebook.presto.type.SqlType;
import static com.facebook.presto.operator.aggregation.AggregationUtils.mergeRegressionState;
import static com.facebook.presto.operator.aggregation.AggregationUtils.updateRegressionState;
import static com.facebook.presto.spi.type.DoubleType.DOUBLE;
@AggregationFunction("") // Names are on output methods
public class RegressionAggregation
{
private RegressionAggregation() {}
@InputFunction
public static void input(RegressionState state, @SqlType(StandardTypes.DOUBLE) double dependentValue, @SqlType(StandardTypes.DOUBLE) double independentValue)
{
updateRegressionState(state, independentValue, dependentValue);
}
@CombineFunction
public static void combine(RegressionState state, RegressionState otherState)
{
mergeRegressionState(state, otherState);
}
@AggregationFunction("regr_slope")
@OutputFunction(StandardTypes.DOUBLE)
public static void regrSlope(RegressionState state, BlockBuilder out)
{
// Math comes from ISO9075-2:2011(E) 10.9 General Rules 7 c xii
double dividend = state.getCount() * state.getSumXY() - state.getSumX() * state.getSumY();
double divisor = state.getCount() * state.getSumXSquare() - state.getSumX() * state.getSumX();
// divisor deliberately not checked for zero because the result can be Infty or NaN even if it is not zero
double result = dividend / divisor;
if (Double.isFinite(result)) {
DOUBLE.writeDouble(out, result);
}
else {
out.appendNull();
}
}
@AggregationFunction("regr_intercept")
@OutputFunction(StandardTypes.DOUBLE)
public static void regrIntercept(RegressionState state, BlockBuilder out)
{
// Math comes from ISO9075-2:2011(E) 10.9 General Rules 7 c xiii
double dividend = state.getSumY() * state.getSumXSquare() - state.getSumX() * state.getSumXY();
double divisor = state.getCount() * state.getSumXSquare() - state.getSumX() * state.getSumX();
// divisor deliberately not checked for zero because the result can be Infty or NaN even if it is not zero
double result = dividend / divisor;
if (Double.isFinite(result)) {
DOUBLE.writeDouble(out, result);
}
else {
out.appendNull();
}
}
}
| apache-2.0 |
android-ia/platform_tools_idea | java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/GenerifyFileTest.java | 665 | package com.intellij.codeInsight.daemon.quickFix;
import com.intellij.codeInspection.LocalInspectionTool;
import com.intellij.codeInspection.uncheckedWarnings.UncheckedWarningLocalInspection;
import org.jetbrains.annotations.NotNull;
public class GenerifyFileTest extends LightQuickFixAvailabilityTestCase {
@NotNull
@Override
protected LocalInspectionTool[] configureLocalInspectionTools() {
return new LocalInspectionTool[] {new UncheckedWarningLocalInspection()};
}
public void test() throws Exception { doAllTests(); }
@Override
protected String getBasePath() {
return "/codeInsight/daemonCodeAnalyzer/quickFix/generifyFile";
}
}
| apache-2.0 |
vlajos/hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestGetBlocks.java | 11426 | /**
* 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.hdfs;
import static org.junit.Assert.*;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CommonConfigurationKeys;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.protocol.Block;
import org.apache.hadoop.hdfs.protocol.ClientProtocol;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.HdfsConstants;
import org.apache.hadoop.hdfs.protocol.HdfsConstants.DatanodeReportType;
import org.apache.hadoop.hdfs.protocol.LocatedBlock;
import org.apache.hadoop.hdfs.protocol.LocatedBlocks;
import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeDescriptor;
import org.apache.hadoop.hdfs.server.datanode.DataNode;
import org.apache.hadoop.hdfs.server.datanode.DataNodeTestUtils;
import org.apache.hadoop.hdfs.server.namenode.NameNode;
import org.apache.hadoop.hdfs.server.protocol.BlocksWithLocations.BlockWithLocations;
import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocol;
import org.apache.hadoop.ipc.RemoteException;
import org.junit.Test;
/**
* This class tests if getblocks request works correctly.
*/
public class TestGetBlocks {
private static final int blockSize = 8192;
private static final String racks[] = new String[] { "/d1/r1", "/d1/r1",
"/d1/r2", "/d1/r2", "/d1/r2", "/d2/r3", "/d2/r3" };
private static final int numDatanodes = racks.length;
/**
* Stop the heartbeat of a datanode in the MiniDFSCluster
*
* @param cluster
* The MiniDFSCluster
* @param hostName
* The hostName of the datanode to be stopped
* @return The DataNode whose heartbeat has been stopped
*/
private DataNode stopDataNodeHeartbeat(MiniDFSCluster cluster, String hostName) {
for (DataNode dn : cluster.getDataNodes()) {
if (dn.getDatanodeId().getHostName().equals(hostName)) {
DataNodeTestUtils.setHeartbeatsDisabledForTests(dn, true);
return dn;
}
}
return null;
}
/**
* Test if the datanodes returned by
* {@link ClientProtocol#getBlockLocations(String, long, long)} is correct
* when stale nodes checking is enabled. Also test during the scenario when 1)
* stale nodes checking is enabled, 2) a writing is going on, 3) a datanode
* becomes stale happen simultaneously
*
* @throws Exception
*/
@Test
public void testReadSelectNonStaleDatanode() throws Exception {
HdfsConfiguration conf = new HdfsConfiguration();
conf.setBoolean(DFSConfigKeys.DFS_NAMENODE_AVOID_STALE_DATANODE_FOR_READ_KEY, true);
long staleInterval = 30 * 1000 * 60;
conf.setLong(DFSConfigKeys.DFS_NAMENODE_STALE_DATANODE_INTERVAL_KEY,
staleInterval);
MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(numDatanodes).racks(racks).build();
cluster.waitActive();
InetSocketAddress addr = new InetSocketAddress("localhost",
cluster.getNameNodePort());
DFSClient client = new DFSClient(addr, conf);
List<DatanodeDescriptor> nodeInfoList = cluster.getNameNode()
.getNamesystem().getBlockManager().getDatanodeManager()
.getDatanodeListForReport(DatanodeReportType.LIVE);
assertEquals("Unexpected number of datanodes", numDatanodes,
nodeInfoList.size());
FileSystem fileSys = cluster.getFileSystem();
FSDataOutputStream stm = null;
try {
// do the writing but do not close the FSDataOutputStream
// in order to mimic the ongoing writing
final Path fileName = new Path("/file1");
stm = fileSys.create(fileName, true,
fileSys.getConf().getInt(
CommonConfigurationKeys.IO_FILE_BUFFER_SIZE_KEY, 4096),
(short) 3, blockSize);
stm.write(new byte[(blockSize * 3) / 2]);
// We do not close the stream so that
// the writing seems to be still ongoing
stm.hflush();
LocatedBlocks blocks = client.getNamenode().getBlockLocations(
fileName.toString(), 0, blockSize);
DatanodeInfo[] nodes = blocks.get(0).getLocations();
assertEquals(nodes.length, 3);
DataNode staleNode = null;
DatanodeDescriptor staleNodeInfo = null;
// stop the heartbeat of the first node
staleNode = this.stopDataNodeHeartbeat(cluster, nodes[0].getHostName());
assertNotNull(staleNode);
// set the first node as stale
staleNodeInfo = cluster.getNameNode().getNamesystem().getBlockManager()
.getDatanodeManager()
.getDatanode(staleNode.getDatanodeId());
DFSTestUtil.resetLastUpdatesWithOffset(staleNodeInfo,
-(staleInterval + 1));
LocatedBlocks blocksAfterStale = client.getNamenode().getBlockLocations(
fileName.toString(), 0, blockSize);
DatanodeInfo[] nodesAfterStale = blocksAfterStale.get(0).getLocations();
assertEquals(nodesAfterStale.length, 3);
assertEquals(nodesAfterStale[2].getHostName(), nodes[0].getHostName());
// restart the staleNode's heartbeat
DataNodeTestUtils.setHeartbeatsDisabledForTests(staleNode, false);
// reset the first node as non-stale, so as to avoid two stale nodes
DFSTestUtil.resetLastUpdatesWithOffset(staleNodeInfo, 0);
LocatedBlock lastBlock = client.getLocatedBlocks(fileName.toString(), 0,
Long.MAX_VALUE).getLastLocatedBlock();
nodes = lastBlock.getLocations();
assertEquals(nodes.length, 3);
// stop the heartbeat of the first node for the last block
staleNode = this.stopDataNodeHeartbeat(cluster, nodes[0].getHostName());
assertNotNull(staleNode);
// set the node as stale
DatanodeDescriptor dnDesc = cluster.getNameNode().getNamesystem()
.getBlockManager().getDatanodeManager()
.getDatanode(staleNode.getDatanodeId());
DFSTestUtil.resetLastUpdatesWithOffset(dnDesc, -(staleInterval + 1));
LocatedBlock lastBlockAfterStale = client.getLocatedBlocks(
fileName.toString(), 0, Long.MAX_VALUE).getLastLocatedBlock();
nodesAfterStale = lastBlockAfterStale.getLocations();
assertEquals(nodesAfterStale.length, 3);
assertEquals(nodesAfterStale[2].getHostName(), nodes[0].getHostName());
} finally {
if (stm != null) {
stm.close();
}
client.close();
cluster.shutdown();
}
}
/** test getBlocks */
@Test
public void testGetBlocks() throws Exception {
final Configuration CONF = new HdfsConfiguration();
final short REPLICATION_FACTOR = (short) 2;
final int DEFAULT_BLOCK_SIZE = 1024;
CONF.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, DEFAULT_BLOCK_SIZE);
MiniDFSCluster cluster = new MiniDFSCluster.Builder(CONF).numDataNodes(
REPLICATION_FACTOR).build();
try {
cluster.waitActive();
long fileLen = 2 * DEFAULT_BLOCK_SIZE;
DFSTestUtil.createFile(cluster.getFileSystem(), new Path("/tmp.txt"),
fileLen, REPLICATION_FACTOR, 0L);
// get blocks & data nodes
List<LocatedBlock> locatedBlocks;
DatanodeInfo[] dataNodes = null;
boolean notWritten;
do {
final DFSClient dfsclient = new DFSClient(NameNode.getAddress(CONF),
CONF);
locatedBlocks = dfsclient.getNamenode()
.getBlockLocations("/tmp.txt", 0, fileLen).getLocatedBlocks();
assertEquals(2, locatedBlocks.size());
notWritten = false;
for (int i = 0; i < 2; i++) {
dataNodes = locatedBlocks.get(i).getLocations();
if (dataNodes.length != REPLICATION_FACTOR) {
notWritten = true;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
break;
}
}
} while (notWritten);
// get RPC client to namenode
InetSocketAddress addr = new InetSocketAddress("localhost",
cluster.getNameNodePort());
NamenodeProtocol namenode = NameNodeProxies.createProxy(CONF,
NameNode.getUri(addr), NamenodeProtocol.class).getProxy();
// get blocks of size fileLen from dataNodes[0]
BlockWithLocations[] locs;
locs = namenode.getBlocks(dataNodes[0], fileLen).getBlocks();
assertEquals(locs.length, 2);
assertEquals(locs[0].getStorageIDs().length, 2);
assertEquals(locs[1].getStorageIDs().length, 2);
// get blocks of size BlockSize from dataNodes[0]
locs = namenode.getBlocks(dataNodes[0], DEFAULT_BLOCK_SIZE).getBlocks();
assertEquals(locs.length, 1);
assertEquals(locs[0].getStorageIDs().length, 2);
// get blocks of size 1 from dataNodes[0]
locs = namenode.getBlocks(dataNodes[0], 1).getBlocks();
assertEquals(locs.length, 1);
assertEquals(locs[0].getStorageIDs().length, 2);
// get blocks of size 0 from dataNodes[0]
getBlocksWithException(namenode, dataNodes[0], 0);
// get blocks of size -1 from dataNodes[0]
getBlocksWithException(namenode, dataNodes[0], -1);
// get blocks of size BlockSize from a non-existent datanode
DatanodeInfo info = DFSTestUtil.getDatanodeInfo("1.2.3.4");
getBlocksWithException(namenode, info, 2);
} finally {
cluster.shutdown();
}
}
private void getBlocksWithException(NamenodeProtocol namenode,
DatanodeInfo datanode, long size) throws IOException {
boolean getException = false;
try {
namenode.getBlocks(DFSTestUtil.getLocalDatanodeInfo(), 2);
} catch (RemoteException e) {
getException = true;
assertTrue(e.getClassName().contains("HadoopIllegalArgumentException"));
}
assertTrue(getException);
}
@Test
public void testBlockKey() {
Map<Block, Long> map = new HashMap<Block, Long>();
final Random RAN = new Random();
final long seed = RAN.nextLong();
System.out.println("seed=" + seed);
RAN.setSeed(seed);
long[] blkids = new long[10];
for (int i = 0; i < blkids.length; i++) {
blkids[i] = 1000L + RAN.nextInt(100000);
map.put(new Block(blkids[i], 0, blkids[i]), blkids[i]);
}
System.out.println("map=" + map.toString().replace(",", "\n "));
for (int i = 0; i < blkids.length; i++) {
Block b = new Block(blkids[i], 0,
HdfsConstants.GRANDFATHER_GENERATION_STAMP);
Long v = map.get(b);
System.out.println(b + " => " + v);
assertEquals(blkids[i], v.longValue());
}
}
}
| apache-2.0 |
ernestp/consulo | platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/projectRoot/daemon/PlaceInProjectStructureBase.java | 1658 | /*
* Copyright 2000-2011 JetBrains s.r.o.
*
* 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.intellij.openapi.roots.ui.configuration.projectRoot.daemon;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ui.configuration.ProjectStructureConfigurable;
import com.intellij.openapi.util.ActionCallback;
import com.intellij.ui.navigation.Place;
import org.jetbrains.annotations.NotNull;
/**
* @author nik
*/
public class PlaceInProjectStructureBase extends PlaceInProjectStructure {
private final Project myProject;
private final Place myPlace;
private final ProjectStructureElement myElement;
public PlaceInProjectStructureBase(Project project, Place place, ProjectStructureElement element) {
myProject = project;
myPlace = place;
myElement = element;
}
@Override
public String getPlacePath() {
return null;
}
@NotNull
@Override
public ProjectStructureElement getContainingElement() {
return myElement;
}
@NotNull
@Override
public ActionCallback navigate() {
return ProjectStructureConfigurable.getInstance(myProject).navigateTo(myPlace, true);
}
}
| apache-2.0 |
nikvaessen/camel | components/camel-ironmq/src/test/java/org/apache/camel/component/ironmq/IronMQPreserveHeadersTest.java | 2656 | /**
* 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.ironmq;
import org.apache.camel.CamelContext;
import org.apache.camel.EndpointInject;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Assert;
import org.junit.Test;
public class IronMQPreserveHeadersTest extends CamelTestSupport {
private IronMQEndpoint endpoint;
@EndpointInject(uri = "mock:result")
private MockEndpoint result;
@Test
public void testPreserveHeaders() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMinimumMessageCount(1);
mock.expectedBodiesReceived("some payload");
mock.expectedHeaderReceived("MyHeader", "HeaderValue");
template.sendBodyAndHeader("direct:start", "some payload", "MyHeader", "HeaderValue");
assertMockEndpointsSatisfied();
String id = mock.getExchanges().get(0).getIn().getHeader(IronMQConstants.MESSAGE_ID, String.class);
Assert.assertNotNull(id);
}
@Override
protected CamelContext createCamelContext() throws Exception {
CamelContext context = super.createCamelContext();
IronMQComponent component = new IronMQComponent(context);
endpoint = (IronMQEndpoint)component.createEndpoint("ironmq://TestQueue?projectId=xxx&token=yyy&preserveHeaders=true");
endpoint.setClient(new IronMQClientMock("dummy", "dummy"));
context.addComponent("ironmq", component);
return context;
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
public void configure() {
from("direct:start").to(endpoint);
from(endpoint).to("mock:result");
}
};
}
}
| apache-2.0 |
10045125/guava | guava/src/com/google/common/hash/package-info.java | 958 | /*
* Copyright (C) 2011 The Guava 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.
*/
// TODO(user): when things stabilize, flesh this out
/**
* Hash functions and related structures.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/HashingExplained">
* hashing</a>.
*/
@ParametersAreNonnullByDefault
package com.google.common.hash;
import javax.annotation.ParametersAreNonnullByDefault;
| apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk2/langtools/test/tools/javac/processing/model/type/TestTypeKind.java | 2478 | /*
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 6347716
* @summary Test TypeKind.isPrimitive
* @author Joseph D. Darcy
*/
import javax.lang.model.type.TypeKind;
import static javax.lang.model.type.TypeKind.*;
import javax.lang.model.util.*;
import java.util.*;
public class TestTypeKind {
static int testIsPrimitive() {
int failures = 0;
// The eight primitive types
Set<TypeKind> primitives = EnumSet.of(BOOLEAN, // 1
BYTE, // 2
CHAR, // 3
DOUBLE, // 4
FLOAT, // 5
INT, // 6
LONG, // 7
SHORT); // 8
for(TypeKind tk : TypeKind.values()) {
boolean primitiveness;
if ((primitiveness=tk.isPrimitive()) != primitives.contains(tk) ) {
failures++;
System.err.println("Unexpected isPrimitive value " + primitiveness +
"for " + tk);
}
}
return failures;
}
public static void main(String... argv) {
int failures = 0;
failures += testIsPrimitive();
if (failures > 0)
throw new RuntimeException();
}
}
| mit |
guiquanz/binnavi | src/test/java/com/google/security/zynamics/binnavi/Database/PostgreSQL/Notifications/parsers/PostgreSQLViewNotificationParserTest.java | 17823 | /*
Copyright 2014 Google Inc. 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.
*/
package com.google.security.zynamics.binnavi.Database.PostgreSQL.Notifications.parsers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import com.google.common.base.Optional;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.security.zynamics.binnavi.Database.CTableNames;
import com.google.security.zynamics.binnavi.Database.Exceptions.CouldntLoadDataException;
import com.google.security.zynamics.binnavi.Database.Interfaces.SQLProvider;
import com.google.security.zynamics.binnavi.Database.MockClasses.MockSqlProvider;
import com.google.security.zynamics.binnavi.Database.PostgreSQL.Notifications.containers.ViewNotificationContainer;
import com.google.security.zynamics.binnavi.Database.PostgreSQL.Notifications.parsers.PostgreSQLViewNotificationParser;
import com.google.security.zynamics.binnavi.disassembly.INaviModule;
import com.google.security.zynamics.binnavi.disassembly.INaviProject;
import com.google.security.zynamics.binnavi.disassembly.MockProject;
import com.google.security.zynamics.binnavi.disassembly.MockView;
import com.google.security.zynamics.binnavi.disassembly.Modules.MockModule;
import com.google.security.zynamics.binnavi.disassembly.views.INaviView;
import com.google.security.zynamics.zylib.disassembly.ViewType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.postgresql.PGNotification;
import java.util.ArrayList;
import java.util.Collection;
@RunWith(JUnit4.class)
public class PostgreSQLViewNotificationParserTest {
private final SQLProvider provider = new MockSqlProvider();
private final INaviView view = MockView.getFullView(provider, ViewType.NonNative, null);
private final Collection<PGNotification> notifications = new ArrayList<PGNotification>();
private void testParser(final String table, final String databaseOperation, final String viewId,
final String containerId) {
final String NOTIFICATION =
containerId != null ? table + " " + databaseOperation + " " + viewId + " " + containerId
: table + " " + databaseOperation + " " + viewId;
notifications.add(new MockPGNotification("view_changes", NOTIFICATION));
final PostgreSQLViewNotificationParser parser = new PostgreSQLViewNotificationParser();
final Collection<ViewNotificationContainer> result = parser.parse(notifications, provider);
assertNotNull(result);
assertTrue(!result.isEmpty());
assertTrue(result.size() == 1);
final ViewNotificationContainer container = Iterables.getFirst(result, null);
assertNotNull(container);
assertEquals(databaseOperation, container.getDatabaseOperation());
assertEquals(viewId, container.getViewId().toString());
if (containerId != null) {
assertEquals(containerId, container.getNotificationObjectId().get().toString());
}
}
@Test
public void testModuleViewParsing1() {
testParser(CTableNames.MODULE_VIEWS_TABLE, "INSERT",
String.valueOf(view.getConfiguration().getId()), "1");
}
@Test
public void testModuleViewParsing2() {
testParser(CTableNames.MODULE_VIEWS_TABLE, "UPDATE",
String.valueOf(view.getConfiguration().getId()), "1");
}
@Test
public void testModuleViewParsing3() {
testParser(CTableNames.MODULE_VIEWS_TABLE, "DELETE",
String.valueOf(view.getConfiguration().getId()), "1");
}
@Test(expected = IllegalStateException.class)
public void testModuleViewParsing4() {
testParser(CTableNames.MODULE_VIEWS_TABLE, "XXXXXX",
String.valueOf(view.getConfiguration().getId()), "1");
}
@Test(expected = IllegalStateException.class)
public void testModuleViewParsing5() {
testParser(CTableNames.MODULE_VIEWS_TABLE, "DELETE", "0xDEADBEEF", "1");
}
@Test(expected = IllegalStateException.class)
public void testModuleViewParsing6() {
testParser(CTableNames.MODULE_VIEWS_TABLE, "DELETE",
String.valueOf(view.getConfiguration().getId()), "XXXX");
}
@Test(expected = IllegalStateException.class)
public void testModuleViewParsing7() {
testParser("bn_module_view", "INSERT", String.valueOf(view.getConfiguration().getId()), "1");
}
@Test
public void testProjectViewParsing1() {
testParser(CTableNames.PROJECT_VIEWS_TABLE, "INSERT",
String.valueOf(view.getConfiguration().getId()), "1");
}
@Test
public void testProjectViewParsing2() {
testParser(CTableNames.PROJECT_VIEWS_TABLE, "UPDATE",
String.valueOf(view.getConfiguration().getId()), "1");
}
@Test
public void testProjectViewParsing3() {
testParser(CTableNames.PROJECT_VIEWS_TABLE, "DELETE",
String.valueOf(view.getConfiguration().getId()), "1");
}
@Test(expected = IllegalStateException.class)
public void testProjectViewParsing4() {
testParser(CTableNames.PROJECT_VIEWS_TABLE, "XXXXXX",
String.valueOf(view.getConfiguration().getId()), "1");
}
@Test(expected = IllegalStateException.class)
public void testProjectViewParsing5() {
testParser(CTableNames.PROJECT_VIEWS_TABLE, "DELETE", "0xDEADBEEF", "1");
}
@Test(expected = IllegalStateException.class)
public void testProjectViewParsing6() {
testParser(CTableNames.PROJECT_VIEWS_TABLE, "DELETE",
String.valueOf(view.getConfiguration().getId()), "XXXX");
}
@Test(expected = IllegalStateException.class)
public void testProjectViewParsing7() {
testParser("bn_project_view", "INSERT", String.valueOf(view.getConfiguration().getId()), null);
}
@Test
public void testViewParsing1() {
testParser(
CTableNames.VIEWS_TABLE, "INSERT", String.valueOf(view.getConfiguration().getId()), null);
}
@Test
public void testViewParsing2() {
testParser(
CTableNames.VIEWS_TABLE, "UPDATE", String.valueOf(view.getConfiguration().getId()), null);
}
@Test
public void testViewParsing3() {
testParser(
CTableNames.VIEWS_TABLE, "DELETE", String.valueOf(view.getConfiguration().getId()), null);
}
@Test(expected = IllegalStateException.class)
public void testViewParsing4() {
testParser(
CTableNames.VIEWS_TABLE, "XXXXXX", String.valueOf(view.getConfiguration().getId()), null);
}
@Test(expected = IllegalStateException.class)
public void testViewParsing5() {
testParser(CTableNames.VIEWS_TABLE, "DELETE", "0xDEADBEEF", null);
}
@Test(expected = IllegalStateException.class)
public void testViewParsing7() {
testParser("bn_view", "INSERT", String.valueOf(view.getConfiguration().getId()), null);
}
@Test
public void testViewInform0() throws CouldntLoadDataException {
final ViewNotificationContainer container =
new ViewNotificationContainer(view.getConfiguration().getId(),
Optional.fromNullable(view),
Optional.<Integer>absent(),
Optional.<INaviModule>absent(),
Optional.<INaviProject>absent(),
"INSERT");
final PostgreSQLViewNotificationParser parser = new PostgreSQLViewNotificationParser();
parser.inform(Lists.<ViewNotificationContainer>newArrayList(container), provider);
}
@Test
public void testViewInform1() throws CouldntLoadDataException {
final String description2 = "TEST DESCRIPTION STATE CHANGE";
view.getConfiguration().setDescriptionInternal(description2);
assertEquals(description2, view.getConfiguration().getDescription());
final ViewNotificationContainer container =
new ViewNotificationContainer(view.getConfiguration().getId(),
Optional.fromNullable(view),
Optional.<Integer>absent(),
Optional.<INaviModule>absent(),
Optional.<INaviProject>absent(),
"UPDATE");
final PostgreSQLViewNotificationParser parser = new PostgreSQLViewNotificationParser();
parser.inform(Lists.<ViewNotificationContainer>newArrayList(container), provider);
assertEquals("DB PROJECT VIEW DESCRIPTION", view.getConfiguration().getDescription());
}
@Test
public void testViewInform2() throws CouldntLoadDataException {
final String name2 = "TEST NAME STATE CHANGE";
view.getConfiguration().setNameInternal(name2);
assertEquals(name2, view.getConfiguration().getName());
final ViewNotificationContainer container =
new ViewNotificationContainer(view.getConfiguration().getId(),
Optional.fromNullable(view),
Optional.<Integer>absent(),
Optional.<INaviModule>absent(),
Optional.<INaviProject>absent(),
"UPDATE");
final PostgreSQLViewNotificationParser parser = new PostgreSQLViewNotificationParser();
parser.inform(Lists.<ViewNotificationContainer>newArrayList(container), provider);
assertEquals("DB PROJECT VIEW NAME", view.getConfiguration().getName());
}
@Test
public void testViewInform3() throws CouldntLoadDataException {
final boolean starState2 = true;
view.getConfiguration().setStaredInternal(starState2);
assertEquals(starState2, view.getConfiguration().isStared());
final ViewNotificationContainer container =
new ViewNotificationContainer(view.getConfiguration().getId(),
Optional.fromNullable(view),
Optional.<Integer>absent(),
Optional.<INaviModule>absent(),
Optional.<INaviProject>absent(),
"UPDATE");
final PostgreSQLViewNotificationParser parser = new PostgreSQLViewNotificationParser();
parser.inform(Lists.<ViewNotificationContainer>newArrayList(container), provider);
assertEquals(false, view.getConfiguration().isStared());
}
@Test
public void testViewInform4() throws CouldntLoadDataException {
final ViewNotificationContainer container =
new ViewNotificationContainer(view.getConfiguration().getId(),
Optional.fromNullable(view),
Optional.<Integer>absent(),
Optional.<INaviModule>absent(),
Optional.<INaviProject>absent(),
"DELETE");
final PostgreSQLViewNotificationParser parser = new PostgreSQLViewNotificationParser();
parser.inform(Lists.<ViewNotificationContainer>newArrayList(container), provider);
}
@Test
public void testModuleViewInform0() throws CouldntLoadDataException {
final INaviModule module = new MockModule(provider);
final int currentUserViewSize = module.getContent().getViewContainer().getUserViews().size();
final ViewNotificationContainer container =
new ViewNotificationContainer(view.getConfiguration().getId(),
Optional.fromNullable(view),
Optional.of(module.getConfiguration().getId()),
Optional.of(module),
Optional.<INaviProject>absent(),
"INSERT");
final PostgreSQLViewNotificationParser parser = new PostgreSQLViewNotificationParser();
parser.inform(Lists.<ViewNotificationContainer>newArrayList(container), provider);
assertEquals(
currentUserViewSize + 1, module.getContent().getViewContainer().getUserViews().size());
}
@Test
public void testModuleViewInform1() throws CouldntLoadDataException {
final INaviModule module = new MockModule(provider);
final ViewNotificationContainer container =
new ViewNotificationContainer(view.getConfiguration().getId(),
Optional.fromNullable(view),
Optional.of(module.getConfiguration().getId()),
Optional.of(module),
Optional.<INaviProject>absent(),
"UPDATE");
final PostgreSQLViewNotificationParser parser = new PostgreSQLViewNotificationParser();
parser.inform(Lists.<ViewNotificationContainer>newArrayList(container), provider);
}
@Test(expected = IllegalArgumentException.class)
public void testModuleViewInform2() throws CouldntLoadDataException {
final INaviModule module = new MockModule(provider);
final ViewNotificationContainer container =
new ViewNotificationContainer(view.getConfiguration().getId(),
Optional.fromNullable(view),
Optional.of(module.getConfiguration().getId()),
Optional.of(module),
Optional.<INaviProject>absent(),
"DELETE");
final PostgreSQLViewNotificationParser parser = new PostgreSQLViewNotificationParser();
parser.inform(Lists.<ViewNotificationContainer>newArrayList(container), provider);
}
@Test
public void testModuleViewInform3() throws CouldntLoadDataException {
final INaviModule module = new MockModule(provider);
final int currentUserViewSize = module.getContent().getViewContainer().getUserViews().size();
final ViewNotificationContainer container =
new ViewNotificationContainer(view.getConfiguration().getId(),
Optional.fromNullable(view),
Optional.of(module.getConfiguration().getId()),
Optional.of(module),
Optional.<INaviProject>absent(),
"INSERT");
final PostgreSQLViewNotificationParser parser = new PostgreSQLViewNotificationParser();
parser.inform(Lists.<ViewNotificationContainer>newArrayList(container), provider);
assertEquals(
currentUserViewSize + 1, module.getContent().getViewContainer().getUserViews().size());
final ViewNotificationContainer container2 =
new ViewNotificationContainer(view.getConfiguration().getId(),
Optional.fromNullable(view),
Optional.of(module.getConfiguration().getId()),
Optional.of(module),
Optional.<INaviProject>absent(),
"DELETE");
parser.inform(Lists.<ViewNotificationContainer>newArrayList(container2), provider);
assertEquals(currentUserViewSize, module.getContent().getViewContainer().getUserViews().size());
}
@Test
public void testProjectViewInform0() throws CouldntLoadDataException {
final INaviProject project = new MockProject(provider);
final int currentUserViewSize = project.getContent().getViews().size();
final ViewNotificationContainer container =
new ViewNotificationContainer(view.getConfiguration().getId(),
Optional.fromNullable(view),
Optional.of(project.getConfiguration().getId()),
Optional.<INaviModule>absent(),
Optional.of(project),
"INSERT");
final PostgreSQLViewNotificationParser parser = new PostgreSQLViewNotificationParser();
parser.inform(Lists.<ViewNotificationContainer>newArrayList(container), provider);
assertEquals(currentUserViewSize + 1, project.getContent().getViews().size());
}
@Test
public void testProjectViewInform1() throws CouldntLoadDataException {
final INaviProject project = new MockProject(provider);
final ViewNotificationContainer container =
new ViewNotificationContainer(view.getConfiguration().getId(),
Optional.fromNullable(view),
Optional.of(project.getConfiguration().getId()),
Optional.<INaviModule>absent(),
Optional.of(project),
"UPDATE");
final PostgreSQLViewNotificationParser parser = new PostgreSQLViewNotificationParser();
parser.inform(Lists.<ViewNotificationContainer>newArrayList(container), provider);
}
@Test(expected = IllegalArgumentException.class)
public void testProjectViewInform2() throws CouldntLoadDataException {
final INaviProject project = new MockProject(provider);
final ViewNotificationContainer container =
new ViewNotificationContainer(view.getConfiguration().getId(),
Optional.fromNullable(view),
Optional.of(project.getConfiguration().getId()),
Optional.<INaviModule>absent(),
Optional.of(project),
"DELETE");
final PostgreSQLViewNotificationParser parser = new PostgreSQLViewNotificationParser();
parser.inform(Lists.<ViewNotificationContainer>newArrayList(container), provider);
}
@Test
public void testProjectViewInform3() throws CouldntLoadDataException {
final INaviProject project = new MockProject(provider);
final int currentUserViewSize = project.getContent().getViews().size();
final ViewNotificationContainer container =
new ViewNotificationContainer(view.getConfiguration().getId(),
Optional.fromNullable(view),
Optional.of(project.getConfiguration().getId()),
Optional.<INaviModule>absent(),
Optional.of(project),
"INSERT");
final PostgreSQLViewNotificationParser parser = new PostgreSQLViewNotificationParser();
parser.inform(Lists.<ViewNotificationContainer>newArrayList(container), provider);
assertEquals(currentUserViewSize + 1, project.getContent().getViews().size());
final ViewNotificationContainer container2 =
new ViewNotificationContainer(view.getConfiguration().getId(),
Optional.fromNullable(view),
Optional.of(project.getConfiguration().getId()),
Optional.<INaviModule>absent(),
Optional.of(project),
"DELETE");
parser.inform(Lists.<ViewNotificationContainer>newArrayList(container2), provider);
assertEquals(currentUserViewSize, project.getContent().getViews().size());
}
}
| apache-2.0 |
fhchina/actor-platform | actor-apps/app-android/src/main/java/im/actor/messenger/app/fragment/group/JoinPublicGroupActivity.java | 600 | package im.actor.messenger.app.fragment.group;
import android.os.Bundle;
import im.actor.messenger.R;
import im.actor.messenger.app.activity.BaseFragmentActivity;
/**
* Created by korka on 25.05.15.
*/
public class JoinPublicGroupActivity extends BaseFragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setTitle(R.string.join_public_group_title);
if (savedInstanceState == null) {
showFragment(new JoinPublicGroupFragment(), false, false);
}
}
}
| mit |
asedunov/intellij-community | jps/model-api/src/org/jetbrains/jps/model/java/JpsJavaDependencyExtension.java | 985 | /*
* Copyright 2000-2012 JetBrains s.r.o.
*
* 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.jetbrains.jps.model.java;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.model.JpsElement;
/**
* @author nik
*/
public interface JpsJavaDependencyExtension extends JpsElement {
boolean isExported();
void setExported(boolean exported);
@NotNull
JpsJavaDependencyScope getScope();
void setScope(@NotNull JpsJavaDependencyScope scope);
}
| apache-2.0 |
asedunov/intellij-community | java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createLocalFromUsage/beforeMethodRef.java | 138 | // "Create local variable 'zeit'" "true"
public class A {
void foo() {
ze<caret>it = A::foo;
}
static void foo(){}
}
| apache-2.0 |
asedunov/intellij-community | java/java-tests/testData/codeInsight/completion/normal/SuperErasure_after.java | 395 | import java.util.*;
abstract class GenericPanelControl {
protected abstract void _performAction(List<?> rowVector);
}
class WorkflowPanelControl extends GenericPanelControl {
protected void _performAction(List rowVector) {
}
}
class WorkflowSubPanelControl extends WorkflowPanelControl {
protected void _performAction(List rowVector) {
super._performAction();
}
} | apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk2/jdk/src/share/classes/sun/awt/geom/Order0.java | 3227 | /*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.awt.geom;
import java.awt.geom.Rectangle2D;
import java.awt.geom.PathIterator;
import java.util.Vector;
final class Order0 extends Curve {
private double x;
private double y;
public Order0(double x, double y) {
super(INCREASING);
this.x = x;
this.y = y;
}
public int getOrder() {
return 0;
}
public double getXTop() {
return x;
}
public double getYTop() {
return y;
}
public double getXBot() {
return x;
}
public double getYBot() {
return y;
}
public double getXMin() {
return x;
}
public double getXMax() {
return x;
}
public double getX0() {
return x;
}
public double getY0() {
return y;
}
public double getX1() {
return x;
}
public double getY1() {
return y;
}
public double XforY(double y) {
return y;
}
public double TforY(double y) {
return 0;
}
public double XforT(double t) {
return x;
}
public double YforT(double t) {
return y;
}
public double dXforT(double t, int deriv) {
return 0;
}
public double dYforT(double t, int deriv) {
return 0;
}
public double nextVertical(double t0, double t1) {
return t1;
}
public int crossingsFor(double x, double y) {
return 0;
}
public boolean accumulateCrossings(Crossings c) {
return (x > c.getXLo() &&
x < c.getXHi() &&
y > c.getYLo() &&
y < c.getYHi());
}
public void enlarge(Rectangle2D r) {
r.add(x, y);
}
public Curve getSubCurve(double ystart, double yend, int dir) {
return this;
}
public Curve getReversedCurve() {
return this;
}
public int getSegment(double coords[]) {
coords[0] = x;
coords[1] = y;
return PathIterator.SEG_MOVETO;
}
}
| mit |
asedunov/intellij-community | java/java-tests/testData/codeInsight/completeStatement/SCR11147_after.java | 117 |
public class Foo {
{
int x = 0;
if (x == 0) {
<caret>
}
}
} | apache-2.0 |
zshift/spring-security | samples/x509-jc/src/main/java/org/springframework/security/samples/config/MessageSecurityWebApplicationInitializer.java | 998 | /*
* Copyright 2002-2013 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 org.springframework.security.samples.config;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
/**
* No customizations of {@link AbstractSecurityWebApplicationInitializer} are necessary.
*
* @author Rob Winch
*/
public class MessageSecurityWebApplicationInitializer extends
AbstractSecurityWebApplicationInitializer {
}
| apache-2.0 |
rbouckaert/YABBY | src/yabby/org/json/JSONWriter.java | 10677 | package org.json;
import java.io.IOException;
import java.io.Writer;
/*
Copyright (c) 2006 JSON.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* JSONWriter provides a quick and convenient way of producing JSON text.
* The texts produced strictly conform to JSON syntax rules. No whitespace is
* added, so the results are ready for transmission or storage. Each instance of
* JSONWriter can produce one JSON text.
* <p>
* A JSONWriter instance provides a <code>value</code> method for appending
* values to the
* text, and a <code>key</code>
* method for adding keys before values in objects. There are <code>array</code>
* and <code>endArray</code> methods that make and bound array values, and
* <code>object</code> and <code>endObject</code> methods which make and bound
* object values. All of these methods return the JSONWriter instance,
* permitting a cascade style. For example, <pre>
* new JSONWriter(myWriter)
* .object()
* .key("JSON")
* .value("Hello, World!")
* .endObject();</pre> which writes <pre>
* {"JSON":"Hello, World!"}</pre>
* <p>
* The first method called must be <code>array</code> or <code>object</code>.
* There are no methods for adding commas or colons. JSONWriter adds them for
* you. Objects and arrays can be nested up to 20 levels deep.
* <p>
* This can sometimes be easier than using a JSONObject to build a string.
* @author JSON.org
* @version 2011-11-24
*/
public class JSONWriter {
private static final int maxdepth = 200;
/**
* The comma flag determines if a comma should be output before the next
* value.
*/
private boolean comma;
/**
* The current mode. Values:
* 'a' (array),
* 'd' (done),
* 'i' (initial),
* 'k' (key),
* 'o' (object).
*/
protected char mode;
/**
* The object/array stack.
*/
private final JSONObject stack[];
/**
* The stack top index. A value of 0 indicates that the stack is empty.
*/
private int top;
/**
* The writer that will receive the output.
*/
protected Writer writer;
/**
* Make a fresh JSONWriter. It can be used to build one JSON text.
*/
public JSONWriter(Writer w) {
this.comma = false;
this.mode = 'i';
this.stack = new JSONObject[maxdepth];
this.top = 0;
this.writer = w;
}
/**
* Append a value.
* @param string A string value.
* @return this
* @throws JSONException If the value is out of sequence.
*/
private JSONWriter append(String string) throws JSONException {
if (string == null) {
throw new JSONException("Null pointer");
}
if (this.mode == 'o' || this.mode == 'a') {
try {
if (this.comma && this.mode == 'a') {
this.writer.write(',');
}
this.writer.write(string);
} catch (IOException e) {
throw new JSONException(e);
}
if (this.mode == 'o') {
this.mode = 'k';
}
this.comma = true;
return this;
}
throw new JSONException("Value out of sequence.");
}
/**
* Begin appending a new array. All values until the balancing
* <code>endArray</code> will be appended to this array. The
* <code>endArray</code> method must be called to mark the array's end.
* @return this
* @throws JSONException If the nesting is too deep, or if the object is
* started in the wrong place (for example as a key or after the end of the
* outermost array or object).
*/
public JSONWriter array() throws JSONException {
if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') {
this.push(null);
this.append("[");
this.comma = false;
return this;
}
throw new JSONException("Misplaced array.");
}
/**
* End something.
* @param mode Mode
* @param c Closing character
* @return this
* @throws JSONException If unbalanced.
*/
private JSONWriter end(char mode, char c) throws JSONException {
if (this.mode != mode) {
throw new JSONException(mode == 'a'
? "Misplaced endArray."
: "Misplaced endObject.");
}
this.pop(mode);
try {
this.writer.write(c);
} catch (IOException e) {
throw new JSONException(e);
}
this.comma = true;
return this;
}
/**
* End an array. This method most be called to balance calls to
* <code>array</code>.
* @return this
* @throws JSONException If incorrectly nested.
*/
public JSONWriter endArray() throws JSONException {
return this.end('a', ']');
}
/**
* End an object. This method most be called to balance calls to
* <code>object</code>.
* @return this
* @throws JSONException If incorrectly nested.
*/
public JSONWriter endObject() throws JSONException {
return this.end('k', '}');
}
/**
* Append a key. The key will be associated with the next value. In an
* object, every value must be preceded by a key.
* @param string A key string.
* @return this
* @throws JSONException If the key is out of place. For example, keys
* do not belong in arrays or if the key is null.
*/
public JSONWriter key(String string) throws JSONException {
if (string == null) {
throw new JSONException("Null key.");
}
if (this.mode == 'k') {
try {
this.stack[this.top - 1].putOnce(string, Boolean.TRUE);
if (this.comma) {
this.writer.write(',');
}
this.writer.write(JSONObject.quote(string));
this.writer.write(':');
this.comma = false;
this.mode = 'o';
return this;
} catch (IOException e) {
throw new JSONException(e);
}
}
throw new JSONException("Misplaced key.");
}
/**
* Begin appending a new object. All keys and values until the balancing
* <code>endObject</code> will be appended to this object. The
* <code>endObject</code> method must be called to mark the object's end.
* @return this
* @throws JSONException If the nesting is too deep, or if the object is
* started in the wrong place (for example as a key or after the end of the
* outermost array or object).
*/
public JSONWriter object() throws JSONException {
if (this.mode == 'i') {
this.mode = 'o';
}
if (this.mode == 'o' || this.mode == 'a') {
this.append("{");
this.push(new JSONObject());
this.comma = false;
return this;
}
throw new JSONException("Misplaced object.");
}
/**
* Pop an array or object scope.
* @param c The scope to close.
* @throws JSONException If nesting is wrong.
*/
private void pop(char c) throws JSONException {
if (this.top <= 0) {
throw new JSONException("Nesting error.");
}
char m = this.stack[this.top - 1] == null ? 'a' : 'k';
if (m != c) {
throw new JSONException("Nesting error.");
}
this.top -= 1;
this.mode = this.top == 0
? 'd'
: this.stack[this.top - 1] == null
? 'a'
: 'k';
}
/**
* Push an array or object scope.
* @param c The scope to open.
* @throws JSONException If nesting is too deep.
*/
private void push(JSONObject jo) throws JSONException {
if (this.top >= maxdepth) {
throw new JSONException("Nesting too deep.");
}
this.stack[this.top] = jo;
this.mode = jo == null ? 'a' : 'k';
this.top += 1;
}
/**
* Append either the value <code>true</code> or the value
* <code>false</code>.
* @param b A boolean.
* @return this
* @throws JSONException
*/
public JSONWriter value(boolean b) throws JSONException {
return this.append(b ? "true" : "false");
}
/**
* Append a double value.
* @param d A double.
* @return this
* @throws JSONException If the number is not finite.
*/
public JSONWriter value(double d) throws JSONException {
return this.value(new Double(d));
}
/**
* Append a long value.
* @param l A long.
* @return this
* @throws JSONException
*/
public JSONWriter value(long l) throws JSONException {
return this.append(Long.toString(l));
}
/**
* Append an object value.
* @param object The object to append. It can be null, or a Boolean, Number,
* String, JSONObject, or JSONArray, or an object that implements JSONString.
* @return this
* @throws JSONException If the value is out of sequence.
*/
public JSONWriter value(Object object) throws JSONException {
return this.append(JSONObject.valueToString(object));
}
}
| lgpl-3.0 |
kazuto1011/rcnn-server | tms_ss_android/openCVLibrary2411/src/main/java/org/opencv/ml/CvGBTreesParams.java | 4257 |
//
// This file is auto-generated. Please don't modify it!
//
package org.opencv.ml;
// C++: class CvGBTreesParams
/**
* <p>GBT training parameters.</p>
*
* <p>The structure contains parameters for each single decision tree in the
* ensemble, as well as the whole model characteristics. The structure is
* derived from "CvDTreeParams" but not all of the decision tree parameters are
* supported: cross-validation, pruning, and class priorities are not used.</p>
*
* @see <a href="http://docs.opencv.org/modules/ml/doc/gradient_boosted_trees.html#cvgbtreesparams">org.opencv.ml.CvGBTreesParams : public CvDTreeParams</a>
*/
public class CvGBTreesParams extends CvDTreeParams {
protected CvGBTreesParams(long addr) { super(addr); }
//
// C++: CvGBTreesParams::CvGBTreesParams()
//
/**
* <p>By default the following constructor is used: CvGBTreesParams(CvGBTrees.SQUARED_LOSS,
* 200, 0.8f, 0.01f, 3, false) <code></p>
*
* <p>// C++ code:</p>
*
* <p>: CvDTreeParams(3, 10, 0, false, 10, 0, false, false, 0)</p>
*
* @see <a href="http://docs.opencv.org/modules/ml/doc/gradient_boosted_trees.html#cvgbtreesparams-cvgbtreesparams">org.opencv.ml.CvGBTreesParams.CvGBTreesParams</a>
*/
public CvGBTreesParams()
{
super( CvGBTreesParams_0() );
return;
}
//
// C++: int CvGBTreesParams::weak_count
//
public int get_weak_count()
{
int retVal = get_weak_count_0(nativeObj);
return retVal;
}
//
// C++: void CvGBTreesParams::weak_count
//
public void set_weak_count(int weak_count)
{
set_weak_count_0(nativeObj, weak_count);
return;
}
//
// C++: int CvGBTreesParams::loss_function_type
//
public int get_loss_function_type()
{
int retVal = get_loss_function_type_0(nativeObj);
return retVal;
}
//
// C++: void CvGBTreesParams::loss_function_type
//
public void set_loss_function_type(int loss_function_type)
{
set_loss_function_type_0(nativeObj, loss_function_type);
return;
}
//
// C++: float CvGBTreesParams::subsample_portion
//
public float get_subsample_portion()
{
float retVal = get_subsample_portion_0(nativeObj);
return retVal;
}
//
// C++: void CvGBTreesParams::subsample_portion
//
public void set_subsample_portion(float subsample_portion)
{
set_subsample_portion_0(nativeObj, subsample_portion);
return;
}
//
// C++: float CvGBTreesParams::shrinkage
//
public float get_shrinkage()
{
float retVal = get_shrinkage_0(nativeObj);
return retVal;
}
//
// C++: void CvGBTreesParams::shrinkage
//
public void set_shrinkage(float shrinkage)
{
set_shrinkage_0(nativeObj, shrinkage);
return;
}
@Override
protected void finalize() throws Throwable {
delete(nativeObj);
}
// C++: CvGBTreesParams::CvGBTreesParams()
private static native long CvGBTreesParams_0();
// C++: int CvGBTreesParams::weak_count
private static native int get_weak_count_0(long nativeObj);
// C++: void CvGBTreesParams::weak_count
private static native void set_weak_count_0(long nativeObj, int weak_count);
// C++: int CvGBTreesParams::loss_function_type
private static native int get_loss_function_type_0(long nativeObj);
// C++: void CvGBTreesParams::loss_function_type
private static native void set_loss_function_type_0(long nativeObj, int loss_function_type);
// C++: float CvGBTreesParams::subsample_portion
private static native float get_subsample_portion_0(long nativeObj);
// C++: void CvGBTreesParams::subsample_portion
private static native void set_subsample_portion_0(long nativeObj, float subsample_portion);
// C++: float CvGBTreesParams::shrinkage
private static native float get_shrinkage_0(long nativeObj);
// C++: void CvGBTreesParams::shrinkage
private static native void set_shrinkage_0(long nativeObj, float shrinkage);
// native support for java finalize()
private static native void delete(long nativeObj);
}
| mit |
prayuditb/tryout-01 | websocket/client/Client/node_modules/react-native/ReactAndroid/src/main/java/com/facebook/react/EagerModuleProvider.java | 496 | // Copyright 2004-present Facebook. All Rights Reserved.
package com.facebook.react;
import javax.inject.Provider;
import com.facebook.react.bridge.NativeModule;
/**
* Provider for an already initialized and non-lazy NativeModule.
*/
public class EagerModuleProvider implements Provider<NativeModule> {
private final NativeModule mModule;
public EagerModuleProvider(NativeModule module) {
mModule = module;
}
@Override
public NativeModule get() {
return mModule;
}
}
| mit |
ooon/java-design-patterns | callback/src/main/java/com/iluwatar/callback/Callback.java | 122 | package com.iluwatar.callback;
/**
*
* Callback interface
*
*/
public interface Callback {
public void call();
}
| mit |
YMartsynkevych/camel | camel-core/src/test/java/org/apache/camel/component/seda/SedaInOnlyTest.java | 1582 | /**
* 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.seda;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
/**
* @version
*/
public class SedaInOnlyTest extends ContextTestSupport {
public void testInOnly() throws Exception {
getMockEndpoint("mock:result").expectedBodiesReceived("Hello World");
template.sendBody("direct:start", "Hello World");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start").to("seda:foo");
from("seda:foo").to("mock:result");
}
};
}
}
| apache-2.0 |
sreeramjayan/elasticsearch | plugins/analysis-icu/src/test/java/org/elasticsearch/index/analysis/IndexableBinaryStringToolsTests.java | 9964 | package org.elasticsearch.index.analysis;
/*
* 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 com.carrotsearch.randomizedtesting.annotations.Listeners;
import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope;
import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope;
import com.carrotsearch.randomizedtesting.annotations.TimeoutSuite;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.TimeUnits;
import org.elasticsearch.test.junit.listeners.ReproduceInfoPrinter;
import org.junit.BeforeClass;
import java.util.Locale;
/**
* @deprecated Remove when IndexableBinaryStringTools is removed.
*/
@Deprecated
@Listeners({
ReproduceInfoPrinter.class
})
@ThreadLeakScope(Scope.NONE)
@TimeoutSuite(millis = TimeUnits.HOUR)
@LuceneTestCase.SuppressSysoutChecks(bugUrl = "we log a lot on purpose")
public class IndexableBinaryStringToolsTests extends LuceneTestCase {
private static int NUM_RANDOM_TESTS;
private static int MAX_RANDOM_BINARY_LENGTH;
private static final String LINE_SEPARATOR = System.lineSeparator();
@BeforeClass
public static void beforeClass() throws Exception {
NUM_RANDOM_TESTS = atLeast(200);
MAX_RANDOM_BINARY_LENGTH = atLeast(300);
}
public void testSingleBinaryRoundTrip() {
byte[] binary = new byte[] { (byte) 0x23, (byte) 0x98, (byte) 0x13,
(byte) 0xE4, (byte) 0x76, (byte) 0x41, (byte) 0xB2, (byte) 0xC9,
(byte) 0x7F, (byte) 0x0A, (byte) 0xA6, (byte) 0xD8 };
int encodedLen = IndexableBinaryStringTools.getEncodedLength(binary, 0,
binary.length);
char encoded[] = new char[encodedLen];
IndexableBinaryStringTools.encode(binary, 0, binary.length, encoded, 0,
encoded.length);
int decodedLen = IndexableBinaryStringTools.getDecodedLength(encoded, 0,
encoded.length);
byte decoded[] = new byte[decodedLen];
IndexableBinaryStringTools.decode(encoded, 0, encoded.length, decoded, 0,
decoded.length);
assertEquals("Round trip decode/decode returned different results:"
+ LINE_SEPARATOR + "original: "
+ binaryDump(binary, binary.length)
+ LINE_SEPARATOR + " encoded: "
+ charArrayDump(encoded, encoded.length)
+ LINE_SEPARATOR + " decoded: "
+ binaryDump(decoded, decoded.length),
binaryDump(binary, binary.length), binaryDump(decoded, decoded.length));
}
public void testEncodedSortability() {
byte[] originalArray1 = new byte[MAX_RANDOM_BINARY_LENGTH];
char[] originalString1 = new char[MAX_RANDOM_BINARY_LENGTH];
char[] encoded1 = new char[MAX_RANDOM_BINARY_LENGTH * 10];
byte[] original2 = new byte[MAX_RANDOM_BINARY_LENGTH];
char[] originalString2 = new char[MAX_RANDOM_BINARY_LENGTH];
char[] encoded2 = new char[MAX_RANDOM_BINARY_LENGTH * 10];
for (int testNum = 0; testNum < NUM_RANDOM_TESTS; ++testNum) {
int numBytes1 = random().nextInt(MAX_RANDOM_BINARY_LENGTH - 1) + 1; // Min == 1
for (int byteNum = 0; byteNum < numBytes1; ++byteNum) {
int randomInt = random().nextInt(0x100);
originalArray1[byteNum] = (byte) randomInt;
originalString1[byteNum] = (char) randomInt;
}
int numBytes2 = random().nextInt(MAX_RANDOM_BINARY_LENGTH - 1) + 1; // Min == 1
for (int byteNum = 0; byteNum < numBytes2; ++byteNum) {
int randomInt = random().nextInt(0x100);
original2[byteNum] = (byte) randomInt;
originalString2[byteNum] = (char) randomInt;
}
int originalComparison = new String(originalString1, 0, numBytes1)
.compareTo(new String(originalString2, 0, numBytes2));
originalComparison = originalComparison < 0 ? -1
: originalComparison > 0 ? 1 : 0;
int encodedLen1 = IndexableBinaryStringTools.getEncodedLength(
originalArray1, 0, numBytes1);
if (encodedLen1 > encoded1.length)
encoded1 = new char[ArrayUtil.oversize(encodedLen1, Character.BYTES)];
IndexableBinaryStringTools.encode(originalArray1, 0, numBytes1, encoded1,
0, encodedLen1);
int encodedLen2 = IndexableBinaryStringTools.getEncodedLength(original2,
0, numBytes2);
if (encodedLen2 > encoded2.length)
encoded2 = new char[ArrayUtil.oversize(encodedLen2, Character.BYTES)];
IndexableBinaryStringTools.encode(original2, 0, numBytes2, encoded2, 0,
encodedLen2);
int encodedComparison = new String(encoded1, 0, encodedLen1)
.compareTo(new String(encoded2, 0, encodedLen2));
encodedComparison = encodedComparison < 0 ? -1
: encodedComparison > 0 ? 1 : 0;
assertEquals("Test #" + (testNum + 1)
+ ": Original bytes and encoded chars compare differently:"
+ LINE_SEPARATOR + " binary 1: "
+ binaryDump(originalArray1, numBytes1)
+ LINE_SEPARATOR + " binary 2: "
+ binaryDump(original2, numBytes2)
+ LINE_SEPARATOR + "encoded 1: "
+ charArrayDump(encoded1, encodedLen1)
+ LINE_SEPARATOR + "encoded 2: "
+ charArrayDump(encoded2, encodedLen2)
+ LINE_SEPARATOR, originalComparison,
encodedComparison);
}
}
public void testEmptyInput() {
byte[] binary = new byte[0];
int encodedLen = IndexableBinaryStringTools.getEncodedLength(binary, 0,
binary.length);
char[] encoded = new char[encodedLen];
IndexableBinaryStringTools.encode(binary, 0, binary.length, encoded, 0,
encoded.length);
int decodedLen = IndexableBinaryStringTools.getDecodedLength(encoded, 0,
encoded.length);
byte[] decoded = new byte[decodedLen];
IndexableBinaryStringTools.decode(encoded, 0, encoded.length, decoded, 0,
decoded.length);
assertEquals("decoded empty input was not empty", decoded.length, 0);
}
public void testAllNullInput() {
byte[] binary = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int encodedLen = IndexableBinaryStringTools.getEncodedLength(binary, 0,
binary.length);
char encoded[] = new char[encodedLen];
IndexableBinaryStringTools.encode(binary, 0, binary.length, encoded, 0,
encoded.length);
int decodedLen = IndexableBinaryStringTools.getDecodedLength(encoded, 0,
encoded.length);
byte[] decoded = new byte[decodedLen];
IndexableBinaryStringTools.decode(encoded, 0, encoded.length, decoded, 0,
decoded.length);
assertEquals("Round trip decode/decode returned different results:"
+ LINE_SEPARATOR + " original: "
+ binaryDump(binary, binary.length)
+ LINE_SEPARATOR + "decodedBuf: "
+ binaryDump(decoded, decoded.length),
binaryDump(binary, binary.length), binaryDump(decoded, decoded.length));
}
public void testRandomBinaryRoundTrip() {
byte[] binary = new byte[MAX_RANDOM_BINARY_LENGTH];
char[] encoded = new char[MAX_RANDOM_BINARY_LENGTH * 10];
byte[] decoded = new byte[MAX_RANDOM_BINARY_LENGTH];
for (int testNum = 0; testNum < NUM_RANDOM_TESTS; ++testNum) {
int numBytes = random().nextInt(MAX_RANDOM_BINARY_LENGTH - 1) + 1; // Min == 1
for (int byteNum = 0; byteNum < numBytes; ++byteNum) {
binary[byteNum] = (byte) random().nextInt(0x100);
}
int encodedLen = IndexableBinaryStringTools.getEncodedLength(binary, 0,
numBytes);
if (encoded.length < encodedLen)
encoded = new char[ArrayUtil.oversize(encodedLen, Character.BYTES)];
IndexableBinaryStringTools.encode(binary, 0, numBytes, encoded, 0,
encodedLen);
int decodedLen = IndexableBinaryStringTools.getDecodedLength(encoded, 0,
encodedLen);
IndexableBinaryStringTools.decode(encoded, 0, encodedLen, decoded, 0,
decodedLen);
assertEquals("Test #" + (testNum + 1)
+ ": Round trip decode/decode returned different results:"
+ LINE_SEPARATOR + " original: "
+ binaryDump(binary, numBytes) + LINE_SEPARATOR
+ "encodedBuf: " + charArrayDump(encoded, encodedLen)
+ LINE_SEPARATOR + "decodedBuf: "
+ binaryDump(decoded, decodedLen), binaryDump(binary, numBytes),
binaryDump(decoded, decodedLen));
}
}
public String binaryDump(byte[] binary, int numBytes) {
StringBuilder buf = new StringBuilder();
for (int byteNum = 0 ; byteNum < numBytes ; ++byteNum) {
String hex = Integer.toHexString(binary[byteNum] & 0xFF);
if (hex.length() == 1) {
buf.append('0');
}
buf.append(hex.toUpperCase(Locale.ROOT));
if (byteNum < numBytes - 1) {
buf.append(' ');
}
}
return buf.toString();
}
public String charArrayDump(char[] charArray, int numBytes) {
StringBuilder buf = new StringBuilder();
for (int charNum = 0 ; charNum < numBytes ; ++charNum) {
String hex = Integer.toHexString(charArray[charNum]);
for (int digit = 0 ; digit < 4 - hex.length() ; ++digit) {
buf.append('0');
}
buf.append(hex.toUpperCase(Locale.ROOT));
if (charNum < numBytes - 1) {
buf.append(' ');
}
}
return buf.toString();
}
}
| apache-2.0 |
KyCodeHuynh/QRU | zxing-master/zxing-master/core/src/test/java/com/google/zxing/pdf417/decoder/ec/ErrorCorrectionTestCase.java | 4353 | /*
* Copyright 2012 ZXing 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 com.google.zxing.pdf417.decoder.ec;
import com.google.zxing.ChecksumException;
import org.junit.Ignore;
import org.junit.Test;
import java.util.Random;
/**
* @author Sean Owen
*/
public final class ErrorCorrectionTestCase extends AbstractErrorCorrectionTestCase {
private static final int[] PDF417_TEST = {
48, 901, 56, 141, 627, 856, 330, 69, 244, 900, 852, 169, 843, 895, 852, 895, 913, 154, 845, 778, 387, 89, 869,
901, 219, 474, 543, 650, 169, 201, 9, 160, 35, 70, 900, 900, 900, 900, 900, 900, 900, 900, 900, 900, 900, 900,
900, 900};
private static final int[] PDF417_TEST_WITH_EC = {
48, 901, 56, 141, 627, 856, 330, 69, 244, 900, 852, 169, 843, 895, 852, 895, 913, 154, 845, 778, 387, 89, 869,
901, 219, 474, 543, 650, 169, 201, 9, 160, 35, 70, 900, 900, 900, 900, 900, 900, 900, 900, 900, 900, 900, 900,
900, 900, 769, 843, 591, 910, 605, 206, 706, 917, 371, 469, 79, 718, 47, 777, 249, 262, 193, 620, 597, 477, 450,
806, 908, 309, 153, 871, 686, 838, 185, 674, 68, 679, 691, 794, 497, 479, 234, 250, 496, 43, 347, 582, 882, 536,
322, 317, 273, 194, 917, 237, 420, 859, 340, 115, 222, 808, 866, 836, 417, 121, 833, 459, 64, 159};
private static final int ECC_BYTES = PDF417_TEST_WITH_EC.length - PDF417_TEST.length;
private static final int ERROR_LIMIT = ECC_BYTES;
private static final int MAX_ERRORS = ERROR_LIMIT / 2;
private static final int MAX_ERASURES = ERROR_LIMIT;
private final ErrorCorrection ec = new ErrorCorrection();
@Test
public void testNoError() throws ChecksumException {
int[] received = PDF417_TEST_WITH_EC.clone();
// no errors
checkDecode(received);
}
@Test
public void testOneError() throws ChecksumException {
Random random = getRandom();
for (int i = 0; i < PDF417_TEST_WITH_EC.length; i++) {
int[] received = PDF417_TEST_WITH_EC.clone();
received[i] = random.nextInt(256);
checkDecode(received);
}
}
@Test
public void testMaxErrors() throws ChecksumException {
Random random = getRandom();
for (int testIterations = 0; testIterations < 100; testIterations++) { // # iterations is kind of arbitrary
int[] received = PDF417_TEST_WITH_EC.clone();
corrupt(received, MAX_ERRORS, random);
checkDecode(received);
}
}
@Test
public void testTooManyErrors() {
int[] received = PDF417_TEST_WITH_EC.clone();
Random random = getRandom();
corrupt(received, MAX_ERRORS + 1, random);
try {
checkDecode(received);
fail("Should not have decoded");
} catch (ChecksumException ce) {
// good
}
}
@Ignore("Erasures not implemented yet")
@Test
public void testMaxErasures() throws ChecksumException {
Random random = getRandom();
for (int test : PDF417_TEST) { // # iterations is kind of arbitrary
int[] received = PDF417_TEST_WITH_EC.clone();
int[] erasures = erase(received, MAX_ERASURES, random);
checkDecode(received, erasures);
}
}
@Ignore("Erasures not implemented yet")
@Test
public void testTooManyErasures() {
Random random = getRandom();
int[] received = PDF417_TEST_WITH_EC.clone();
int[] erasures = erase(received, MAX_ERASURES + 1, random);
try {
checkDecode(received, erasures);
fail("Should not have decoded");
} catch (ChecksumException ce) {
// good
}
}
private void checkDecode(int[] received) throws ChecksumException {
checkDecode(received, new int[0]);
}
private void checkDecode(int[] received, int[] erasures) throws ChecksumException {
ec.decode(received, ECC_BYTES, erasures);
for (int i = 0; i < PDF417_TEST.length; i++) {
assertEquals(received[i], PDF417_TEST[i]);
}
}
}
| gpl-2.0 |
SanDisk-Open-Source/SSD_Dashboard | uefi/gcc/gcc-4.6.3/libjava/classpath/javax/management/openmbean/TabularData.java | 9916 | /* TabularData.java -- Tables of composite data structures.
Copyright (C) 2006, 2007 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package javax.management.openmbean;
import java.util.Collection;
import java.util.Set;
/**
* Provides an interface to a specific type of composite
* data structure, where keys (the columns) map to the
* {@link CompositeData} objects that form the rows of
* the table.
*
* @author Andrew John Hughes (gnu_andrew@member.fsf.org)
* @since 1.5
*/
public interface TabularData
{
/**
* Calculates the index the specified {@link CompositeData} value
* would have, if it was to be added to this {@link TabularData}
* instance. This method includes a check that the type of the
* given value is the same as the row type of this instance, but not
* a check for existing instances of the given value. The value
* must also not be <code>null</code>. Possible indices are
* returned by the {@link TabularType#getIndexNames()} method of
* this instance's tabular type. The returned indices are the
* values of the fields in the supplied {@link CompositeData}
* instance that match the names given in the {@link TabularType}.
*
* @param val the {@link CompositeData} value whose index should
* be calculated.
* @return the index the value would take on, if it were to be added.
* @throws NullPointerException if the value is <code>null</code>.
* @throws InvalidOpenTypeException if the value does not match the
* row type of this instance.
*/
Object[] calculateIndex(CompositeData val);
/**
* Removes all {@link CompositeData} values from the table.
*/
void clear();
/**
* Returns true iff this instance of the {@link TabularData} class
* contains a {@link CompositeData} value at the specified index.
* In any other circumstance, including if the given key
* is <code>null</code> or of the incorrect type, according to
* the {@link TabularType} of this instance, this method returns
* false.
*
* @param key the key to test for.
* @return true if the key maps to a {@link CompositeData} value.
*/
boolean containsKey(Object[] key);
/**
* Returns true iff this instance of the {@link TabularData} class
* contains the specified {@link CompositeData} value.
* In any other circumstance, including if the given value
* is <code>null</code> or of the incorrect type, according to
* the {@link TabularType} of this instance, this method returns
* false.
*
* @param val the value to test for.
* @return true if the value exists.
*/
boolean containsValue(CompositeData val);
/**
* Compares the specified object with this object for equality.
* The object is judged equivalent if it is non-null, and also
* an instance of {@link TabularData} with the same row type,
* and {@link CompositeData} values. The two compared instances may
* be equivalent even if they represent different implementations
* of {@link TabularData}.
*
* @param obj the object to compare for equality.
* @return true if <code>obj</code> is equal to <code>this</code>.
*/
boolean equals(Object obj);
/**
* Retrieves the {@link CompositeData} value for the specified
* key, or <code>null</code> if no such mapping exists.
*
* @param key the key whose value should be returned.
* @return the matching {@link CompositeData} value, or
* <code>null</code> if one does not exist.
* @throws NullPointerException if the key is <code>null</code>.
* @throws InvalidKeyException if the key does not match
* the {@link TabularType} of this
* instance.
*/
CompositeData get(Object[] key);
/**
* Returns the tabular type which corresponds to this instance
* of {@link TabularData}.
*
* @return the tabular type for this instance.
*/
TabularType getTabularType();
/**
* Returns the hash code of the composite data type. This is
* computed as the sum of the hash codes of each value, together
* with the hash code of the tabular type. These are the same
* elements of the type that are compared as part of the {@link
* #equals(java.lang.Object)} method, thus ensuring that the
* hashcode is compatible with the equality test.
*
* @return the hash code of this instance.
*/
int hashCode();
/**
* Returns true if this {@link TabularData} instance
* contains no {@link CompositeData} values.
*
* @return true if the instance is devoid of rows.
*/
boolean isEmpty();
/**
* Returns a {@link java.util.Set} view of the keys or
* indices of this {@link TabularData} instance.
*
* @return a set containing the keys of this instance.
*/
Set<?> keySet();
/**
* Adds the specified {@link CompositeData} value to the
* table. The value must be non-null, of the same type
* as the row type of this instance, and must not have
* the same index as an existing value. The index is
* calculated using the index names of the
* {@link TabularType} for this instance.
*
* @param val the {@link CompositeData} value to add.
* @throws NullPointerException if <code>val</code> is
* <code>null</code>.
* @throws InvalidOpenTypeException if the type of the
* given value does not
* match the row type.
* @throws KeyAlreadyExistsException if the value has the
* same calculated index
* as an existing value.
*/
void put(CompositeData val);
/**
* Adds each of the specified {@link CompositeData} values
* to the table. Each element of the array must meet the
* conditions given for the {@link #put(CompositeData)}
* method. In addition, the index of each value in the
* array must be distinct from the index of the other
* values in the array, as well as from the existing values
* in the table. The operation should be atomic; if one
* value can not be added, then none of the values should
* be. If the array is <code>null</code> or empty, the
* method simply returns.
*
* @param vals the {@link CompositeData} values to add.
* @throws NullPointerException if a value from the array is
* <code>null</code>.
* @throws InvalidOpenTypeException if the type of a
* given value does not
* match the row type.
* @throws KeyAlreadyExistsException if a value has the
* same calculated index
* as an existing value or
* of one of the other
* specified values.
*/
void putAll(CompositeData[] vals);
/**
* Removes the {@link CompositeData} value located at the
* specified index. <code>null</code> is returned if the
* value does not exist. Otherwise, the removed value is
* returned.
*
* @param key the key of the value to remove.
* @return the removed value, or <code>null</code> if
* there is no value for the given key.
* @throws NullPointerException if the key is <code>null</code>.
* @throws InvalidOpenTypeException if the key does not match
* the {@link TabularType} of this
* instance.
*/
CompositeData remove(Object[] key);
/**
* Returns the number of {@link CompositeData} values or rows
* in the table.
*
* @return the number of rows in the table.
*/
int size();
/**
* Returns a textual representation of this instance. The
* exact format is left up to the implementation, but it
* should contain the name of the implementing class and
* the tabular type.
*
* @return a {@link java.lang.String} representation of the
* object.
*/
String toString();
/**
* Returns the values associated with this instance.
*
* @return the values of this instance.
*/
Collection<?> values();
}
| gpl-2.0 |
ooon/java-design-patterns | service-layer/src/main/java/com/iluwatar/servicelayer/wizard/Wizard.java | 1383 | package com.iluwatar.servicelayer.wizard;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import com.iluwatar.servicelayer.common.BaseEntity;
import com.iluwatar.servicelayer.spellbook.Spellbook;
/**
*
* Wizard entity.
*
*/
@Entity
@Table(name="WIZARD")
public class Wizard extends BaseEntity {
public Wizard() {
spellbooks = new HashSet<Spellbook>();
}
public Wizard(String name) {
this();
this.name = name;
}
@Id
@GeneratedValue
@Column(name = "WIZARD_ID")
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
private String name;
@ManyToMany(cascade = CascadeType.ALL)
private Set<Spellbook> spellbooks;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Spellbook> getSpellbooks() {
return spellbooks;
}
public void setSpellbooks(Set<Spellbook> spellbooks) {
this.spellbooks = spellbooks;
}
public void addSpellbook(Spellbook spellbook) {
spellbook.getWizards().add(this);
spellbooks.add(spellbook);
}
@Override
public String toString() {
return name;
}
}
| mit |
tseen/Federated-HDFS | tseenliu/FedHDFS-hadoop-src/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/file/tfile/MetaBlockDoesNotExist.java | 1320 | /**
* 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.io.file.tfile;
import java.io.IOException;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
/**
* Exception - No such Meta Block with the given name.
*/
@SuppressWarnings("serial")
@InterfaceAudience.Public
@InterfaceStability.Stable
public class MetaBlockDoesNotExist extends IOException {
/**
* Constructor
*
* @param s
* message.
*/
MetaBlockDoesNotExist(String s) {
super(s);
}
}
| apache-2.0 |
io7m/jcanephora | com.io7m.jcanephora.fake/src/main/java/com/io7m/jcanephora/fake/FakeArrayBuffers.java | 7055 | /*
* Copyright © 2015 <code@io7m.com> http://io7m.com
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.io7m.jcanephora.fake;
import com.io7m.jcanephora.core.JCGLArrayBufferType;
import com.io7m.jcanephora.core.JCGLArrayBufferUsableType;
import com.io7m.jcanephora.core.JCGLBufferUpdateType;
import com.io7m.jcanephora.core.JCGLException;
import com.io7m.jcanephora.core.JCGLExceptionBufferNotBound;
import com.io7m.jcanephora.core.JCGLExceptionDeleted;
import com.io7m.jcanephora.core.JCGLResources;
import com.io7m.jcanephora.core.JCGLUsageHint;
import com.io7m.jcanephora.core.api.JCGLArrayBuffersType;
import com.io7m.jcanephora.core.api.JCGLByteBufferProducerType;
import com.io7m.jnull.NullCheck;
import com.io7m.jnull.Nullable;
import com.io7m.jranges.RangeCheck;
import com.io7m.jranges.Ranges;
import com.io7m.junsigned.ranges.UnsignedRangeInclusiveL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer;
import java.util.Objects;
import java.util.Optional;
final class FakeArrayBuffers implements JCGLArrayBuffersType
{
private static final Logger LOG;
static {
LOG = LoggerFactory.getLogger(FakeArrayBuffers.class);
}
private final FakeContext context;
private @Nullable FakeArrayBuffer bind;
FakeArrayBuffers(final FakeContext c)
{
this.context = NullCheck.notNull(c, "Context");
}
private void actualBind(final FakeArrayBuffer a)
{
LOG.trace("bind {} -> {}", this.bind, a);
if (!Objects.equals(a, this.bind)) {
this.bind = a;
}
}
private void actualUnbind()
{
LOG.trace(
"unbind {} -> {}", this.bind, null);
if (this.bind != null) {
this.bind = null;
}
}
@Override
public ByteBuffer arrayBufferRead(
final JCGLArrayBufferUsableType a,
final JCGLByteBufferProducerType f)
throws JCGLException, JCGLExceptionDeleted, JCGLExceptionBufferNotBound
{
NullCheck.notNull(a, "Array");
this.checkArray(a);
if (Objects.equals(a, this.bind)) {
final UnsignedRangeInclusiveL r = a.byteRange();
final long size = r.getInterval();
final ByteBuffer b = f.apply(size);
b.rewind();
final FakeArrayBuffer fa = (FakeArrayBuffer) a;
final ByteBuffer fa_data = fa.getData();
/*
* XXX: Clearly overflowing integers.
*/
final long lo = r.getLower();
final long hi = r.getUpper();
for (long index = lo; Long.compareUnsigned(index, hi) <= 0; ++index) {
final int ii = (int) index;
final byte x = fa_data.get(ii);
b.put(ii, x);
}
return b;
}
throw this.notBound(a);
}
@Override
public JCGLArrayBufferType arrayBufferAllocate(
final long size,
final JCGLUsageHint usage)
throws JCGLException
{
RangeCheck.checkIncludedInLong(
size, "Size", Ranges.NATURAL_LONG, "Valid size range");
LOG.debug(
"allocate ({} bytes, {})", Long.valueOf(size), usage);
final ByteBuffer data = ByteBuffer.allocate((int) size);
final FakeArrayBuffer ao = new FakeArrayBuffer(
this.context, this.context.getFreshID(), data, usage);
this.actualBind(ao);
return ao;
}
@Override
public void arrayBufferReallocate(final JCGLArrayBufferUsableType a)
throws JCGLException, JCGLExceptionDeleted, JCGLExceptionBufferNotBound
{
this.checkArray(a);
if (Objects.equals(a, this.bind)) {
final UnsignedRangeInclusiveL r = a.byteRange();
final long size = r.getInterval();
final JCGLUsageHint usage = a.usageHint();
if (LOG.isDebugEnabled()) {
LOG.debug(
"reallocate ({} bytes, {})", Long.valueOf(size), usage);
}
} else {
throw this.notBound(a);
}
}
@Override
public Optional<JCGLArrayBufferUsableType> arrayBufferGetCurrentlyBound()
throws JCGLException
{
return Optional.ofNullable(this.bind);
}
@Override
public boolean arrayBufferAnyIsBound()
throws JCGLException
{
return this.bind != null;
}
@Override
public boolean arrayBufferIsBound(
final JCGLArrayBufferUsableType a)
throws JCGLException
{
this.checkArray(a);
return Objects.equals(a, this.bind);
}
@Override
public void arrayBufferBind(final JCGLArrayBufferUsableType a)
throws JCGLException, JCGLExceptionDeleted
{
this.checkArray(a);
this.actualBind((FakeArrayBuffer) a);
}
private void checkArray(final JCGLArrayBufferUsableType a)
{
FakeCompatibilityChecks.checkArrayBuffer(this.context, a);
JCGLResources.checkNotDeleted(a);
}
@Override
public void arrayBufferUnbind()
throws JCGLException
{
this.actualUnbind();
}
@Override
public void arrayBufferDelete(final JCGLArrayBufferType a)
throws JCGLException, JCGLExceptionDeleted
{
this.checkArray(a);
LOG.debug("delete {}", Integer.valueOf(a.glName()));
((FakeArrayBuffer) a).setDeleted();
if (Objects.equals(a, this.bind)) {
this.actualUnbind();
}
}
@Override
public void arrayBufferUpdate(
final JCGLBufferUpdateType<JCGLArrayBufferType> u)
throws JCGLException, JCGLExceptionDeleted, JCGLExceptionBufferNotBound
{
NullCheck.notNull(u, "Update");
final JCGLArrayBufferType a = u.buffer();
this.checkArray(a);
if (Objects.equals(a, this.bind)) {
final UnsignedRangeInclusiveL r = u.dataUpdateRange();
final ByteBuffer data = u.data();
data.rewind();
final FakeArrayBuffer fa = (FakeArrayBuffer) a;
final ByteBuffer fa_data = fa.getData();
/*
* XXX: Clearly overflowing integers.
*/
final long lo = r.getLower();
final long hi = r.getUpper();
for (long index = lo; Long.compareUnsigned(index, hi) <= 0; ++index) {
final int ii = (int) index;
fa_data.put(ii, data.get(ii));
}
} else {
throw this.notBound(a);
}
}
private JCGLExceptionBufferNotBound notBound(
final JCGLArrayBufferUsableType a)
{
final StringBuilder sb = new StringBuilder(128);
sb.append("Buffer is not bound.");
sb.append(System.lineSeparator());
sb.append(" Required: ");
sb.append(a);
sb.append(System.lineSeparator());
sb.append(" Actual: ");
sb.append(this.bind == null ? "none" : this.bind);
return new JCGLExceptionBufferNotBound(sb.toString());
}
}
| isc |
tbian7/pst | design_patterns/headfirst/adapter/ducks/TurkeyTestDrive.java | 383 | package headfirst.adapter.ducks;
public class TurkeyTestDrive {
public static void main(String[] args) {
MallardDuck duck = new MallardDuck();
Turkey duckAdapter = new DuckAdapter(duck);
for(int i=0;i<10;i++) {
System.out.println("The DuckAdapter says...");
duckAdapter.gobble();
duckAdapter.fly();
}
}
}
| mit |
jeremiq/tic-tac-toe | src/main/java/com/jeremiq/tictactoe/game/board/InvalidMoveException.java | 179 | package com.jeremiq.tictactoe.game.board;
public class InvalidMoveException extends Exception {
public InvalidMoveException(String message) {
super(message);
}
}
| mit |
ssouris/mewbase | src/test/java/io/mewbase/rwtest/MemoryMappedFileRWTest.java | 1622 | package io.mewbase.rwtest;
import io.mewbase.TestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.RandomAccessFile;
/**
* Created by tim on 11/10/16.
*/
public class MemoryMappedFileRWTest implements RWTest {
private final static Logger logger = LoggerFactory.getLogger(MemoryMappedFileRWTest.class);
private static final int PAGE_SIZE = 4 * 1024;
@Override
public int testRead(File testFile) throws Exception {
RandomAccessFile raf = new RandomAccessFile(testFile, "rw");
long len = testFile.length();
int its = (int)(len / PAGE_SIZE);
logger.trace("File length is {} iterations are {}", len, its);
byte[] bytes = new byte[PAGE_SIZE];
int bytesRead;
int cnt = 0;
while (-1 != (bytesRead = raf.read(bytes))) {
for (int i = 0; i < bytesRead; i++) {
cnt += bytes[i];
}
}
raf.close();
return cnt;
}
@Override
public int testWrite(File testFile) throws Exception {
RandomAccessFile raf = new RandomAccessFile(testFile, "rw");
long len = testFile.length();
int its = (int)(len / PAGE_SIZE);
logger.trace("File length is {} iterations are {}", len, its);
byte[] bytes = TestUtils.randomByteArray(PAGE_SIZE);
int cnt = 0;
for (int i = 0; i < its; i++) {
for (int j = 0; j < bytes.length; j++) {
cnt += bytes[j];
}
raf.write(bytes, 0, PAGE_SIZE);
}
raf.close();
return cnt;
}
}
| mit |
equus52/java-web-stack | src/test/java/equus/webstack/application/JettyStarter.java | 2013 | package equus.webstack.application;
import java.net.URI;
import javax.ws.rs.core.UriBuilder;
import lombok.Setter;
import lombok.SneakyThrows;
import lombok.val;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
@Slf4j
public class JettyStarter {
private final int port = 9010;
private final String contextPath = "/java-web-stack/";
private final String apiPath = "api";
@Setter
private boolean resourceEnable = true;
private String resourceBase = "WebContent";
public static void main(String[] args) {
JettyStarter jetty = new JettyStarter();
if (args.length > 0) {
jetty.resourceBase = args[0];
}
jetty.start();
}
@SneakyThrows
public void start() {
Server server = startServer();
server.join();
}
@SneakyThrows
public Server startServer() {
val server = createServer();
val shutdownHook = new Thread(() -> {
try {
server.stop();
} catch (Throwable t) {
log.error("unknown error occurred.", t);
}
}, "shutdown-hook");
Runtime.getRuntime().addShutdownHook(shutdownHook);
server.start();
if (resourceEnable) {
System.out.println("URL " + getBaseURI());
}
System.out.println("API URL " + getAPIBaseURI());
return server;
}
public URI getBaseURI() {
return UriBuilder.fromUri("http://localhost/").port(port).path(contextPath).build();
}
public URI getAPIBaseURI() {
return UriBuilder.fromUri("http://localhost/").port(port).path(contextPath).path(apiPath).build();
}
private Server createServer() {
val server = new Server(port);
val context = new WebAppContext();
context.setServer(server);
context.setContextPath(contextPath);
context.setDescriptor("WebContent/WEB-INF/web.xml");
context.setParentLoaderPriority(true);
if (resourceEnable) {
context.setResourceBase(resourceBase);
}
server.setHandler(context);
return server;
}
}
| mit |
liggetm/Tweaking | TweakingGitHub/src/tweaking/concurrency/reetrantLockExample/MainClass.java | 594 | package tweaking.concurrency.reetrantLockExample;
public class MainClass {
public static void main(final String[] args) {
final ThreadSafeArrayList<String> threadSafeList = new ThreadSafeArrayList<>();
final ListAdderThread threadA = new ListAdderThread("threadA", threadSafeList);
final ListAdderThread threadB = new ListAdderThread("threadB", threadSafeList);
final ListAdderThread threadC = new ListAdderThread("threadC", threadSafeList);
threadA.start();
threadB.start();
threadC.start();
}
}
| mit |
chrislucas/repo-android | views/support/StudyListAndCards/app/src/main/java/wiselabs/com/br/studylistandcards/entity/TipoProjeto.java | 214 | package wiselabs.com.br.studylistandcards.entity;
/**
* Created by C.Lucas on 18/12/2016.
*/
public enum TipoProjeto {
LEI_ORDINARIA, LEI_COMPLEMENTAR, EMENDA_LEI_ORGANICA, DECRETO_LEGISLATIVO, RESOLUCAO;
}
| mit |
basking2/sdsai-dsds | sdsai-dsds-core/src/main/java/com/github/basking2/sdsai/dsds/fs/package-info.java | 90 | /**
* Filesystem based directory storage.
*/
package com.github.basking2.sdsai.dsds.fs;
| mit |
Azure/azure-sdk-for-java | sdk/peering/azure-resourcemanager-peering/src/main/java/com/azure/resourcemanager/peering/models/ReceivedRoutes.java | 2571 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.peering.models;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.util.Context;
/** Resource collection API of ReceivedRoutes. */
public interface ReceivedRoutes {
/**
* Lists the prefixes received over the specified peering under the given subscription and resource group.
*
* @param resourceGroupName The name of the resource group.
* @param peeringName The name of the peering.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the paginated list of received routes for the peering.
*/
PagedIterable<PeeringReceivedRoute> listByPeering(String resourceGroupName, String peeringName);
/**
* Lists the prefixes received over the specified peering under the given subscription and resource group.
*
* @param resourceGroupName The name of the resource group.
* @param peeringName The name of the peering.
* @param prefix The optional prefix that can be used to filter the routes.
* @param asPath The optional AS path that can be used to filter the routes.
* @param originAsValidationState The optional origin AS validation state that can be used to filter the routes.
* @param rpkiValidationState The optional RPKI validation state that can be used to filter the routes.
* @param skipToken The optional page continuation token that is used in the event of paginated result.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the paginated list of received routes for the peering.
*/
PagedIterable<PeeringReceivedRoute> listByPeering(
String resourceGroupName,
String peeringName,
String prefix,
String asPath,
String originAsValidationState,
String rpkiValidationState,
String skipToken,
Context context);
}
| mit |
juniormesquitadandao/report4all | lib/src/net/sf/jasperreports/engine/component/ContextAwareComponent.java | 1351 | /*
* JasperReports - Free Java Reporting Library.
* Copyright (C) 2001 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is part of JasperReports.
*
* JasperReports 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.
*
* JasperReports 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 JasperReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.jasperreports.engine.component;
/**
* @author Teodor Danciu (teodord@users.sourceforge.net)
* @version $Id: ContextAwareComponent.java 7199 2014-08-27 13:58:10Z teodord $
*/
public interface ContextAwareComponent extends Component
{
/**
*
*/
void setContext(ComponentContext context);
/**
*
*/
ComponentContext getContext();
}
| mit |
meleap/myo_AndoridEMG | BLE_myo/app/src/main/java/example/naoki/ble_myo/EmgData.java | 2341 | package example.naoki.ble_myo;
import java.util.ArrayList;
import java.util.StringTokenizer;
/**
* Created by naoki on 15/04/09.
*
*/
public class EmgData {
private ArrayList<Double> emgData = new ArrayList<>();
public EmgData() {
}
public EmgData(EmgCharacteristicData characteristicData) {
this.emgData = new ArrayList<>( characteristicData.getEmg8Data_abs().getEmgArray() );
}
public EmgData(ArrayList<Double> emgData) {
this.emgData = emgData;
}
public String getLine() {
StringBuilder return_SB = new StringBuilder();
for (int i_emg_num = 0; i_emg_num < 8; i_emg_num++) {
return_SB.append(String.format("%f,", emgData.get(i_emg_num)));
}
return return_SB.toString();
}
public void setLine(String line) {
ArrayList<Double> data = new ArrayList<>();
StringTokenizer st = new StringTokenizer(line , ",");
for (int i_emg_num = 0; i_emg_num < 8; i_emg_num++) {
data.add(Double.parseDouble(st.nextToken()));
}
emgData = data;
}
public void addElement(double element) {
emgData.add(element);
}
public void setElement(int index ,double element) {
emgData.set(index,element);
}
public Double getElement(int index) {
if (index < 0 || index > emgData.size() - 1) {
return null;
} else {
return emgData.get(index);
}
}
public ArrayList<Double> getEmgArray() {
return this.emgData;
}
public Double getDistanceFrom(EmgData baseData) {
Double distance = 0.00;
for (int i_element = 0; i_element < 8; i_element++) {
distance += Math.pow((emgData.get(i_element) - baseData.getElement(i_element)),2.0);
}
return Math.sqrt(distance);
}
public Double getInnerProductionTo(EmgData baseData) {
Double val = 0.00;
for (int i_element = 0; i_element < 8; i_element++) {
val += emgData.get(i_element) * baseData.getElement(i_element);
}
return val;
}
public Double getNorm(){
Double norm = 0.00;
for (int i_element = 0; i_element < 8; i_element++) {
norm += Math.pow( emgData.get(i_element) ,2.0);
}
return Math.sqrt(norm);
}
}
| mit |