repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
chromium/chromium | chrome/browser/download/android/java/src/org/chromium/chrome/browser/download/DownloadInfo.java | 20987 | // 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.chrome.browser.download;
import android.graphics.Bitmap;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.chrome.browser.profiles.OTRProfileID;
import org.chromium.components.download.DownloadState;
import org.chromium.components.offline_items_collection.ContentId;
import org.chromium.components.offline_items_collection.FailState;
import org.chromium.components.offline_items_collection.LegacyHelpers;
import org.chromium.components.offline_items_collection.OfflineItem;
import org.chromium.components.offline_items_collection.OfflineItem.Progress;
import org.chromium.components.offline_items_collection.OfflineItemProgressUnit;
import org.chromium.components.offline_items_collection.OfflineItemSchedule;
import org.chromium.components.offline_items_collection.OfflineItemState;
import org.chromium.components.offline_items_collection.OfflineItemVisuals;
import org.chromium.components.offline_items_collection.PendingState;
import org.chromium.url.GURL;
/**
* Class representing the state of a single download.
*/
public final class DownloadInfo {
private final GURL mUrl;
private final String mUserAgent;
private final String mMimeType;
private final String mCookie;
private final String mFileName;
private final String mDescription;
private final String mFilePath;
// TODO(https://crbug.com/1278805): Migrate mReferrer and mOriginalUrl to GURL
private final String mReferrer;
private final String mOriginalUrl;
private final long mBytesReceived;
private final long mBytesTotalSize;
private final String mDownloadGuid;
private final boolean mHasUserGesture;
private final String mContentDisposition;
private final boolean mIsGETRequest;
private final Progress mProgress;
private final long mTimeRemainingInMillis;
private final boolean mIsResumable;
private final boolean mIsPaused;
private final boolean mIsOffTheRecord;
private final OTRProfileID mOTRProfileId;
private final boolean mIsOfflinePage;
private final int mState;
private final long mLastAccessTime;
private final boolean mIsDangerous;
// New variables to assist with the migration to OfflineItems.
private final ContentId mContentId;
private final boolean mIsOpenable;
private final boolean mIsTransient;
private final boolean mIsParallelDownload;
private final Bitmap mIcon;
@PendingState
private final int mPendingState;
@FailState
private final int mFailState;
private final boolean mShouldPromoteOrigin;
private final OfflineItemSchedule mSchedule;
private DownloadInfo(Builder builder) {
mUrl = builder.mUrl;
mUserAgent = builder.mUserAgent;
mMimeType = builder.mMimeType;
mCookie = builder.mCookie;
mFileName = builder.mFileName;
mDescription = builder.mDescription;
mFilePath = builder.mFilePath;
mReferrer = builder.mReferrer;
mOriginalUrl = builder.mOriginalUrl;
mBytesReceived = builder.mBytesReceived;
mBytesTotalSize = builder.mBytesTotalSize;
mDownloadGuid = builder.mDownloadGuid;
mHasUserGesture = builder.mHasUserGesture;
mIsGETRequest = builder.mIsGETRequest;
mContentDisposition = builder.mContentDisposition;
mProgress = builder.mProgress;
mTimeRemainingInMillis = builder.mTimeRemainingInMillis;
mIsResumable = builder.mIsResumable;
mIsPaused = builder.mIsPaused;
mIsOffTheRecord = builder.mIsOffTheRecord;
mOTRProfileId = builder.mOTRProfileId;
mIsOfflinePage = builder.mIsOfflinePage;
mState = builder.mState;
mLastAccessTime = builder.mLastAccessTime;
mIsDangerous = builder.mIsDangerous;
if (builder.mContentId != null) {
mContentId = builder.mContentId;
} else {
mContentId = LegacyHelpers.buildLegacyContentId(mIsOfflinePage, mDownloadGuid);
}
mIsOpenable = builder.mIsOpenable;
mIsTransient = builder.mIsTransient;
mIsParallelDownload = builder.mIsParallelDownload;
mIcon = builder.mIcon;
mPendingState = builder.mPendingState;
mFailState = builder.mFailState;
mShouldPromoteOrigin = builder.mShouldPromoteOrigin;
mSchedule = builder.mSchedule;
}
public GURL getUrl() {
return mUrl;
}
public String getUserAgent() {
return mUserAgent;
}
public String getMimeType() {
return mMimeType;
}
public String getCookie() {
return mCookie;
}
public String getFileName() {
return mFileName;
}
public String getDescription() {
return mDescription;
}
public String getFilePath() {
return mFilePath;
}
public String getReferrer() {
return mReferrer;
}
public String getOriginalUrl() {
return mOriginalUrl;
}
public long getBytesReceived() {
return mBytesReceived;
}
public long getBytesTotalSize() {
return mBytesTotalSize;
}
public boolean isGETRequest() {
return mIsGETRequest;
}
public String getDownloadGuid() {
return mDownloadGuid;
}
public boolean hasUserGesture() {
return mHasUserGesture;
}
public String getContentDisposition() {
return mContentDisposition;
}
public Progress getProgress() {
return mProgress;
}
/**
* @return Remaining download time in milliseconds or -1 if it is unknown.
*/
public long getTimeRemainingInMillis() {
return mTimeRemainingInMillis;
}
public boolean isResumable() {
return mIsResumable;
}
public boolean isPaused() {
return mIsPaused;
}
public boolean isOffTheRecord() {
return mIsOffTheRecord;
}
public OTRProfileID getOTRProfileId() {
return mOTRProfileId;
}
public boolean isOfflinePage() {
return mIsOfflinePage;
}
public int state() {
return mState;
}
public long getLastAccessTime() {
return mLastAccessTime;
}
public boolean getIsDangerous() {
return mIsDangerous;
}
public ContentId getContentId() {
return mContentId;
}
public boolean getIsOpenable() {
return mIsOpenable;
}
public boolean getIsTransient() {
return mIsTransient;
}
public boolean getIsParallelDownload() {
return mIsParallelDownload;
}
public Bitmap getIcon() {
return mIcon;
}
public @PendingState int getPendingState() {
return mPendingState;
}
public @FailState int getFailState() {
return mFailState;
}
public boolean getShouldPromoteOrigin() {
return mShouldPromoteOrigin;
}
public OfflineItemSchedule getOfflineItemSchedule() {
return mSchedule;
}
/**
* Helper method to build a {@link DownloadInfo} from an {@link OfflineItem}.
* @param item The {@link OfflineItem} to mimic.
* @param visuals The {@link OfflineItemVisuals} to mimic.
* @return A {@link DownloadInfo} containing the relevant fields from {@code item}.
*/
public static DownloadInfo fromOfflineItem(OfflineItem item, OfflineItemVisuals visuals) {
return builderFromOfflineItem(item, visuals).build();
}
/**
* Helper method to build a {@link DownloadInfo.Builder} from an {@link OfflineItem}.
* @param item The {@link OfflineItem} to mimic.
* @param visuals The {@link OfflineItemVisuals} to mimic.
* @return A {@link DownloadInfo.Builder} containing the relevant fields from
* {@code item}.
*/
public static DownloadInfo.Builder builderFromOfflineItem(
OfflineItem item, OfflineItemVisuals visuals) {
int state;
switch (item.state) {
case OfflineItemState.COMPLETE:
state = DownloadState.COMPLETE;
break;
case OfflineItemState.CANCELLED:
state = DownloadState.CANCELLED;
break;
case OfflineItemState.INTERRUPTED:
state = DownloadState.INTERRUPTED;
break;
case OfflineItemState.FAILED:
state = DownloadState.INTERRUPTED; // TODO(dtrainor): Validate what this state is.
break;
case OfflineItemState.PENDING: // TODO(dtrainor): Validate what this state is.
case OfflineItemState.IN_PROGRESS:
case OfflineItemState.PAUSED: // TODO(dtrainor): Validate what this state is.
default:
state = DownloadState.IN_PROGRESS;
break;
}
return new DownloadInfo.Builder()
.setContentId(item.id)
.setDownloadGuid(item.id.id)
.setFileName(item.title)
.setFilePath(item.filePath)
.setDescription(item.description)
.setIsTransient(item.isTransient)
.setLastAccessTime(item.lastAccessedTimeMs)
.setIsOpenable(item.isOpenable)
.setMimeType(item.mimeType)
.setUrl(item.url)
.setOriginalUrl(item.originalUrl)
.setOTRProfileId(OTRProfileID.deserialize(item.otrProfileId))
.setState(state)
.setIsPaused(item.state == OfflineItemState.PAUSED)
.setIsResumable(item.isResumable)
.setBytesReceived(item.receivedBytes)
.setBytesTotalSize(item.totalSizeBytes)
.setProgress(item.progress)
.setTimeRemainingInMillis(item.timeRemainingMs)
.setIsDangerous(item.isDangerous)
.setIsParallelDownload(item.isAccelerated)
.setIcon(visuals == null ? null : visuals.icon)
.setPendingState(item.pendingState)
.setFailState(item.failState)
.setShouldPromoteOrigin(item.promoteOrigin)
.setOfflineItemSchedule(item.schedule);
}
/**
* Helper class for building the DownloadInfo object.
*/
public static class Builder {
private GURL mUrl;
private String mUserAgent;
private String mMimeType;
private String mCookie;
private String mFileName;
private String mDescription;
private String mFilePath;
private String mReferrer;
private String mOriginalUrl;
private long mBytesReceived;
private long mBytesTotalSize;
private boolean mIsGETRequest;
private String mDownloadGuid;
private boolean mHasUserGesture;
private String mContentDisposition;
private Progress mProgress = Progress.createIndeterminateProgress();
private long mTimeRemainingInMillis;
private boolean mIsResumable = true;
private boolean mIsPaused;
private boolean mIsOffTheRecord;
private OTRProfileID mOTRProfileId;
private boolean mIsOfflinePage;
private int mState = DownloadState.IN_PROGRESS;
private long mLastAccessTime;
private boolean mIsDangerous;
private ContentId mContentId;
private boolean mIsOpenable = true;
private boolean mIsTransient;
private boolean mIsParallelDownload;
private Bitmap mIcon;
@PendingState
private int mPendingState;
@FailState
private int mFailState;
private boolean mShouldPromoteOrigin;
private OfflineItemSchedule mSchedule;
public Builder setUrl(GURL url) {
mUrl = url;
return this;
}
public Builder setUserAgent(String userAgent) {
mUserAgent = userAgent;
return this;
}
public Builder setMimeType(String mimeType) {
mMimeType = mimeType;
return this;
}
public Builder setCookie(String cookie) {
mCookie = cookie;
return this;
}
public Builder setFileName(String fileName) {
mFileName = fileName;
return this;
}
public Builder setDescription(String description) {
mDescription = description;
return this;
}
public Builder setFilePath(String filePath) {
mFilePath = filePath;
return this;
}
public Builder setReferrer(String referer) {
mReferrer = referer;
return this;
}
public Builder setOriginalUrl(String originalUrl) {
mOriginalUrl = originalUrl;
return this;
}
public Builder setBytesReceived(long bytesReceived) {
mBytesReceived = bytesReceived;
return this;
}
public Builder setBytesTotalSize(long bytesTotalSize) {
mBytesTotalSize = bytesTotalSize;
return this;
}
public Builder setIsGETRequest(boolean isGETRequest) {
mIsGETRequest = isGETRequest;
return this;
}
public Builder setDownloadGuid(String downloadGuid) {
mDownloadGuid = downloadGuid;
return this;
}
public Builder setHasUserGesture(boolean hasUserGesture) {
mHasUserGesture = hasUserGesture;
return this;
}
public Builder setContentDisposition(String contentDisposition) {
mContentDisposition = contentDisposition;
return this;
}
public Builder setProgress(OfflineItem.Progress progress) {
mProgress = progress;
return this;
}
public Builder setTimeRemainingInMillis(long timeRemainingInMillis) {
mTimeRemainingInMillis = timeRemainingInMillis;
return this;
}
public Builder setIsResumable(boolean isResumable) {
mIsResumable = isResumable;
return this;
}
public Builder setIsPaused(boolean isPaused) {
mIsPaused = isPaused;
return this;
}
public Builder setOTRProfileId(OTRProfileID otrProfileId) {
mOTRProfileId = otrProfileId;
mIsOffTheRecord = OTRProfileID.isOffTheRecord(otrProfileId);
return this;
}
public Builder setIsOfflinePage(boolean isOfflinePage) {
mIsOfflinePage = isOfflinePage;
return this;
}
public Builder setState(int downloadState) {
mState = downloadState;
return this;
}
public Builder setLastAccessTime(long lastAccessTime) {
mLastAccessTime = lastAccessTime;
return this;
}
public Builder setIsDangerous(boolean isDangerous) {
mIsDangerous = isDangerous;
return this;
}
public Builder setContentId(ContentId contentId) {
mContentId = contentId;
return this;
}
public Builder setIsOpenable(boolean isOpenable) {
mIsOpenable = isOpenable;
return this;
}
public Builder setIsTransient(boolean isTransient) {
mIsTransient = isTransient;
return this;
}
public Builder setIsParallelDownload(boolean isParallelDownload) {
mIsParallelDownload = isParallelDownload;
return this;
}
public Builder setIcon(Bitmap icon) {
mIcon = icon;
return this;
}
public Builder setPendingState(@PendingState int pendingState) {
mPendingState = pendingState;
return this;
}
public Builder setFailState(@FailState int failState) {
mFailState = failState;
return this;
}
public Builder setShouldPromoteOrigin(boolean shouldPromoteOrigin) {
mShouldPromoteOrigin = shouldPromoteOrigin;
return this;
}
public Builder setOfflineItemSchedule(OfflineItemSchedule schedule) {
mSchedule = schedule;
return this;
}
public DownloadInfo build() {
return new DownloadInfo(this);
}
/**
* Create a builder from the DownloadInfo object.
* @param downloadInfo DownloadInfo object from which builder fields are populated.
* @return A builder initialized with fields from downloadInfo object.
*/
public static Builder fromDownloadInfo(final DownloadInfo downloadInfo) {
Builder builder = new Builder();
builder.setUrl(downloadInfo.getUrl())
.setUserAgent(downloadInfo.getUserAgent())
.setMimeType(downloadInfo.getMimeType())
.setCookie(downloadInfo.getCookie())
.setFileName(downloadInfo.getFileName())
.setDescription(downloadInfo.getDescription())
.setFilePath(downloadInfo.getFilePath())
.setReferrer(downloadInfo.getReferrer())
.setOriginalUrl(downloadInfo.getOriginalUrl())
.setBytesReceived(downloadInfo.getBytesReceived())
.setBytesTotalSize(downloadInfo.getBytesTotalSize())
.setDownloadGuid(downloadInfo.getDownloadGuid())
.setHasUserGesture(downloadInfo.hasUserGesture())
.setContentDisposition(downloadInfo.getContentDisposition())
.setIsGETRequest(downloadInfo.isGETRequest())
.setProgress(downloadInfo.getProgress())
.setTimeRemainingInMillis(downloadInfo.getTimeRemainingInMillis())
.setIsDangerous(downloadInfo.getIsDangerous())
.setIsResumable(downloadInfo.isResumable())
.setIsPaused(downloadInfo.isPaused())
.setOTRProfileId(downloadInfo.getOTRProfileId())
.setIsOfflinePage(downloadInfo.isOfflinePage())
.setState(downloadInfo.state())
.setLastAccessTime(downloadInfo.getLastAccessTime())
.setIsTransient(downloadInfo.getIsTransient())
.setIsParallelDownload(downloadInfo.getIsParallelDownload())
.setIcon(downloadInfo.getIcon())
.setPendingState(downloadInfo.getPendingState())
.setFailState(downloadInfo.getFailState())
.setShouldPromoteOrigin(downloadInfo.getShouldPromoteOrigin())
.setOfflineItemSchedule(downloadInfo.getOfflineItemSchedule());
return builder;
}
}
@CalledByNative
private static DownloadInfo createDownloadInfo(String downloadGuid, String fileName,
String filePath, GURL url, String mimeType, long bytesReceived, long bytesTotalSize,
OTRProfileID otrProfileId, int state, int percentCompleted, boolean isPaused,
boolean hasUserGesture, boolean isResumable, boolean isParallelDownload,
String originalUrl, String referrerUrl, long timeRemainingInMs, long lastAccessTime,
boolean isDangerous, @FailState int failState, OfflineItemSchedule schedule) {
String remappedMimeType = MimeUtils.remapGenericMimeType(mimeType, url.getSpec(), fileName);
Progress progress = new Progress(bytesReceived,
percentCompleted == -1 ? null : bytesTotalSize, OfflineItemProgressUnit.BYTES);
return new DownloadInfo.Builder()
.setBytesReceived(bytesReceived)
.setBytesTotalSize(bytesTotalSize)
.setDescription(fileName)
.setDownloadGuid(downloadGuid)
.setFileName(fileName)
.setFilePath(filePath)
.setHasUserGesture(hasUserGesture)
.setOTRProfileId(otrProfileId)
.setIsPaused(isPaused)
.setIsResumable(isResumable)
.setIsParallelDownload(isParallelDownload)
.setMimeType(remappedMimeType)
.setOriginalUrl(originalUrl)
.setProgress(progress)
.setReferrer(referrerUrl)
.setState(state)
.setTimeRemainingInMillis(timeRemainingInMs)
.setLastAccessTime(lastAccessTime)
.setIsDangerous(isDangerous)
.setUrl(url)
.setFailState(failState)
.setOfflineItemSchedule(schedule)
.build();
}
}
| bsd-3-clause |
n4ybn/yavijava | src/main/java/com/vmware/vim25/VirtualDeviceFileExtension.java | 2015 | /*================================================================================
Copyright (c) 2013 Steve Jin. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of VMware, Inc. nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25;
/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/
public enum VirtualDeviceFileExtension {
iso("iso"),
flp("flp"),
vmdk("vmdk"),
dsk("dsk"),
rdm("rdm");
@SuppressWarnings("unused")
private final String val;
private VirtualDeviceFileExtension(String val) {
this.val = val;
}
} | bsd-3-clause |
garyttierney/apollo | game/src/main/org/apollo/game/release/r377/SecondItemOptionMessageDecoder.java | 989 | package org.apollo.game.release.r377;
import org.apollo.game.message.impl.ItemOptionMessage;
import org.apollo.net.codec.game.DataOrder;
import org.apollo.net.codec.game.DataTransformation;
import org.apollo.net.codec.game.DataType;
import org.apollo.net.codec.game.GamePacket;
import org.apollo.net.codec.game.GamePacketReader;
import org.apollo.net.release.MessageDecoder;
/**
* A {@link MessageDecoder} for the second {@link ItemOptionMessage}.
*
* @author Graham
*/
public final class SecondItemOptionMessageDecoder extends MessageDecoder<ItemOptionMessage> {
@Override
public ItemOptionMessage decode(GamePacket packet) {
GamePacketReader reader = new GamePacketReader(packet);
int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE);
int id = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE);
int slot = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD);
return new ItemOptionMessage(2, interfaceId, id, slot);
}
} | isc |
Fewlaps/quitnow-cache | src/test/java/com/fewlaps/quitnowcache/util/RandomGenerator.java | 687 | package com.fewlaps.quitnowcache.util;
import java.util.Date;
import java.util.Random;
public class RandomGenerator {
private static Random random = new Random((new Date()).getTime());
public static String generateRandomString() {
char[] values = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9'};
String out = "";
for (int i = 0; i < 100; i++) {
int idx = random.nextInt(values.length);
out += values[idx];
}
return out;
}
} | mit |
LeonidShamis/XChange | xchange-wex/src/test/java/org/knowm/xchange/wex/v3/dto/trade/WexTradeHistoryJSONTest.java | 1754 | package org.knowm.xchange.wex.v3.dto.trade;
import static org.assertj.core.api.Assertions.assertThat;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Map;
import java.util.Map.Entry;
import org.junit.Test;
/** @author Benedikt Bünz Test WexTradeHistoryReturn JSON parsing */
public class WexTradeHistoryJSONTest {
@Test
public void testUnmarshal() throws IOException {
// Read in the JSON from the example resources
InputStream is =
WexTradeHistoryJSONTest.class.getResourceAsStream(
"/org/knowm/xchange/wex/v3/trade/example-trade-history-data.json");
// Use Jackson to parse it
ObjectMapper mapper = new ObjectMapper();
WexTradeHistoryReturn transactions = mapper.readValue(is, WexTradeHistoryReturn.class);
Map<Long, WexTradeHistoryResult> result = transactions.getReturnValue();
assertThat(result.size()).isEqualTo(32);
Entry<Long, WexTradeHistoryResult> firstEntry = result.entrySet().iterator().next();
// Verify that the example data was unmarshalled correctly
assertThat(firstEntry.getKey()).isEqualTo(7258275L);
assertThat(firstEntry.getValue().getAmount()).isEqualTo(new BigDecimal("0.1"));
assertThat(firstEntry.getValue().getOrderId()).isEqualTo(34870919L);
assertThat(firstEntry.getValue().getPair()).isEqualTo("btc_usd");
assertThat(firstEntry.getValue().getRate()).isEqualTo(new BigDecimal("125.75"));
assertThat(firstEntry.getValue().getTimestamp()).isEqualTo(1378194574L);
assertThat(firstEntry.getValue().getType()).isEqualTo(WexTradeHistoryResult.Type.sell);
assertThat(firstEntry.getValue().isYourOrder()).isEqualTo(false);
}
}
| mit |
conde2/DC-UFSCar-ES2-201701-BoxTesters | src/main/java/org/jabref/gui/customentrytypes/FieldSetComponent.java | 11648 | package org.jabref.gui.customentrytypes;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import javax.swing.Box;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JViewport;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.event.ListDataListener;
import javax.swing.event.ListSelectionListener;
import org.jabref.Globals;
import org.jabref.gui.IconTheme;
import org.jabref.logic.bibtexkeypattern.BibtexKeyPatternUtil;
import org.jabref.logic.l10n.Localization;
import org.jabref.preferences.JabRefPreferences;
/**
* @author alver
*/
class FieldSetComponent extends JPanel {
protected final JList<String> list;
protected DefaultListModel<String> listModel;
protected final JButton remove;
protected final GridBagLayout gbl = new GridBagLayout();
protected final GridBagConstraints con = new GridBagConstraints();
protected final boolean forceLowerCase;
protected boolean changesMade;
private final Set<ActionListener> additionListeners = new HashSet<>();
private final JScrollPane sp;
private JComboBox<String> sel;
private JTextField input;
private final JButton add;
private JButton up;
private JButton down;
private final Set<ListDataListener> modelListeners = new HashSet<>();
/**
* Creates a new instance of FieldSetComponent, with preset selection
* values. These are put into a JComboBox.
*/
public FieldSetComponent(String title, List<String> fields, List<String> preset, boolean arrows, boolean forceLowerCase) {
this(title, fields, preset, Localization.lang("Add"),
Localization.lang("Remove"), arrows, forceLowerCase);
}
/**
* Creates a new instance of FieldSetComponent without preset selection
* values. Replaces the JComboBox with a JTextField.
*/
FieldSetComponent(String title, List<String> fields, boolean arrows, boolean forceLowerCase) {
this(title, fields, null, Localization.lang("Add"),
Localization.lang("Remove"), arrows, forceLowerCase);
}
private FieldSetComponent(String title, List<String> fields, List<String> preset, String addText, String removeText,
boolean arrows, boolean forceLowerCase) {
this.forceLowerCase = forceLowerCase;
add = new JButton(addText);
remove = new JButton(removeText);
listModel = new DefaultListModel<>();
JLabel title1 = null;
if (title != null) {
title1 = new JLabel(title);
}
for (String field : fields) {
listModel.addElement(field);
}
list = new JList<>(listModel);
list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
// Set up GUI:
add.addActionListener(e -> {
// Selection has been made, or add button pressed:
if ((sel != null) && (sel.getSelectedItem() != null)) {
String s = sel.getSelectedItem().toString();
addField(s);
} else if ((input != null) && !"".equals(input.getText())) {
addField(input.getText());
}
});
remove.addActionListener(e -> removeSelected()); // Remove button pressed
setLayout(gbl);
con.insets = new Insets(1, 1, 1, 1);
con.fill = GridBagConstraints.BOTH;
con.weightx = 1;
con.gridwidth = GridBagConstraints.REMAINDER;
if (title1 != null) {
gbl.setConstraints(title1, con);
add(title1);
}
con.weighty = 1;
sp = new JScrollPane(list, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
gbl.setConstraints(sp, con);
add(sp);
con.weighty = 0;
con.gridwidth = 1;
if (arrows) {
con.weightx = 0;
up = new JButton(IconTheme.JabRefIcon.UP.getSmallIcon());
down = new JButton(IconTheme.JabRefIcon.DOWN.getSmallIcon());
up.addActionListener(e -> move(-1));
down.addActionListener(e -> move(1));
up.setToolTipText(Localization.lang("Move up"));
down.setToolTipText(Localization.lang("Move down"));
gbl.setConstraints(up, con);
add(up);
gbl.setConstraints(down, con);
add(down);
con.weightx = 0;
}
Component strut = Box.createHorizontalStrut(5);
gbl.setConstraints(strut, con);
add(strut);
con.weightx = 1;
con.gridwidth = GridBagConstraints.REMAINDER;
//Component b = Box.createHorizontalGlue();
//gbl.setConstraints(b, con);
//add(b);
//if (!arrows)
con.gridwidth = GridBagConstraints.REMAINDER;
gbl.setConstraints(remove, con);
add(remove);
con.gridwidth = 3;
con.weightx = 1;
if (preset == null) {
input = new JTextField(20);
input.addActionListener(e -> addField(input.getText()));
gbl.setConstraints(input, con);
add(input);
} else {
sel = new JComboBox<>(preset.toArray(new String[preset.size()]));
sel.setEditable(true);
gbl.setConstraints(sel, con);
add(sel);
}
con.gridwidth = GridBagConstraints.REMAINDER;
con.weighty = 0;
con.weightx = 0.5;
con.gridwidth = 1;
gbl.setConstraints(add, con);
add(add);
FieldListFocusListener<String> fieldListFocusListener = new FieldListFocusListener<>(list);
list.addFocusListener(fieldListFocusListener);
}
public void setListSelectionMode(int mode) {
list.setSelectionMode(mode);
}
public void selectField(String fieldName) {
int idx = listModel.indexOf(fieldName);
if (idx >= 0) {
list.setSelectedIndex(idx);
}
// Make sure it is visible:
JViewport viewport = sp.getViewport();
Rectangle rectangle = list.getCellBounds(idx, idx);
if (rectangle != null) {
viewport.scrollRectToVisible(rectangle);
}
}
public String getFirstSelected() {
return list.getSelectedValue();
}
@Override
public void setEnabled(boolean en) {
if (input != null) {
input.setEnabled(en);
}
if (sel != null) {
sel.setEnabled(en);
}
if (up != null) {
up.setEnabled(en);
down.setEnabled(en);
}
add.setEnabled(en);
remove.setEnabled(en);
}
public void setFields(List<String> fields) {
DefaultListModel<String> newListModel = new DefaultListModel<>();
for (String field : fields) {
newListModel.addElement(field);
}
this.listModel = newListModel;
for (ListDataListener modelListener : modelListeners) {
newListModel.addListDataListener(modelListener);
}
list.setModel(newListModel);
}
/**
* This method is called when a new field should be added to the list. Performs validation of the
* field.
*/
protected void addField(String str) {
String s = str.trim();
if (forceLowerCase) {
s = s.toLowerCase(Locale.ROOT);
}
if ("".equals(s) || listModel.contains(s)) {
return;
}
String testString = BibtexKeyPatternUtil.checkLegalKey(s,
Globals.prefs.getBoolean(JabRefPreferences.ENFORCE_LEGAL_BIBTEX_KEY));
if (!testString.equals(s) || (s.indexOf('&') >= 0)) {
// Report error and exit.
JOptionPane.showMessageDialog(this, Localization.lang("Field names are not allowed to contain white space or the following "
+ "characters") + ": # { } ~ , ^ &",
Localization.lang("Error"), JOptionPane.ERROR_MESSAGE);
return;
}
addFieldUncritically(s);
}
/**
* This method adds a new field to the list, without any regard to validation. This method can be
* useful for classes that overrides addField(s) to provide different validation.
*/
protected void addFieldUncritically(String s) {
listModel.addElement(s);
changesMade = true;
for (ActionListener additionListener : additionListeners) {
additionListener.actionPerformed(new ActionEvent(this, 0, s));
}
}
protected void removeSelected() {
int[] selected = list.getSelectedIndices();
if (selected.length > 0) {
changesMade = true;
}
for (int i = 0; i < selected.length; i++) {
listModel.removeElementAt(selected[selected.length - 1 - i]);
}
}
/**
* Return the current list.
*/
public List<String> getFields() {
List<String> res = new ArrayList<>(listModel.getSize());
Enumeration<String> elements = listModel.elements();
while (elements.hasMoreElements()) {
res.add(elements.nextElement());
}
return res;
}
/**
* Add a ListSelectionListener to the JList component displayed as part of this component.
*/
public void addListSelectionListener(ListSelectionListener l) {
list.addListSelectionListener(l);
}
/**
* Adds an ActionListener that will receive events each time a field is added. The ActionEvent
* will specify this component as source, and the added field as action command.
*/
public void addAdditionActionListener(ActionListener l) {
additionListeners.add(l);
}
public void addListDataListener(ListDataListener l) {
listModel.addListDataListener(l);
modelListeners.add(l);
}
/**
* If a field is selected in the list, move it dy positions.
*/
private void move(int dy) {
int oldIdx = list.getSelectedIndex();
if (oldIdx < 0) {
return;
}
String o = listModel.get(oldIdx);
// Compute the new index:
int newInd = Math.max(0, Math.min(listModel.size() - 1, oldIdx + dy));
listModel.remove(oldIdx);
listModel.add(newInd, o);
list.setSelectedIndex(newInd);
}
/**
* FocusListener to select the first entry in the list of fields when they are focused
*/
protected class FieldListFocusListener<T> implements FocusListener {
private final JList<T> list;
public FieldListFocusListener(JList<T> list) {
this.list = list;
}
@Override
public void focusGained(FocusEvent e) {
if (list.getSelectedValue() == null) {
list.setSelectedIndex(0);
}
}
@Override
public void focusLost(FocusEvent e) {
//focus should remain at the same position so nothing to do here
}
}
}
| mit |
afuechsel/openhab2 | addons/binding/org.openhab.binding.enocean/src/main/java/org/openhab/binding/enocean/internal/eep/D2_01/D2_01.java | 9134 | /**
* Copyright (c) 2010-2019 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.enocean.internal.eep.D2_01;
import static org.openhab.binding.enocean.internal.EnOceanBindingConstants.*;
import org.eclipse.smarthome.config.core.Configuration;
import org.eclipse.smarthome.config.discovery.DiscoveryResultBuilder;
import org.eclipse.smarthome.core.library.types.DecimalType;
import org.eclipse.smarthome.core.library.types.OnOffType;
import org.eclipse.smarthome.core.library.types.PercentType;
import org.eclipse.smarthome.core.library.types.QuantityType;
import org.eclipse.smarthome.core.library.unit.SmartHomeUnits;
import org.eclipse.smarthome.core.types.Command;
import org.eclipse.smarthome.core.types.RefreshType;
import org.eclipse.smarthome.core.types.State;
import org.eclipse.smarthome.core.types.UnDefType;
import org.eclipse.smarthome.core.util.HexUtils;
import org.openhab.binding.enocean.internal.config.EnOceanChannelDimmerConfig;
import org.openhab.binding.enocean.internal.eep.Base._VLDMessage;
import org.openhab.binding.enocean.internal.messages.ERP1Message;
/**
*
* @author Daniel Weber - Initial contribution
*/
public abstract class D2_01 extends _VLDMessage {
protected final byte cmdMask = 0x0f;
protected final byte outputValueMask = 0x7f;
protected final byte outputChannelMask = 0x1f;
protected final byte CMD_ACTUATOR_SET_STATUS = 0x01;
protected final byte CMD_ACTUATOR_STATUS_QUERY = 0x03;
protected final byte CMD_ACTUATOR_STATUS_RESPONE = 0x04;
protected final byte CMD_ACTUATOR_MEASUREMENT_QUERY = 0x06;
protected final byte CMD_ACTUATOR_MEASUREMENT_RESPONE = 0x07;
protected final byte AllChannels_Mask = 0x1e;
protected final byte ChannelA_Mask = 0x00;
protected final byte ChannelB_Mask = 0x01;
protected final byte STATUS_SWITCHING_ON = 0x01;
protected final byte STATUS_SWITCHING_OFF = 0x00;
protected final byte STATUS_DIMMING_100 = 0x64;
public D2_01() {
super();
}
public D2_01(ERP1Message packet) {
super(packet);
}
protected byte getCMD() {
return (byte) (bytes[0] & cmdMask);
}
protected void setSwitchingData(OnOffType command, byte outputChannel) {
if (command == OnOffType.ON) {
setData(CMD_ACTUATOR_SET_STATUS, outputChannel, STATUS_SWITCHING_ON);
} else {
setData(CMD_ACTUATOR_SET_STATUS, outputChannel, STATUS_SWITCHING_OFF);
}
}
protected void setSwitchingQueryData(byte outputChannel) {
setData(CMD_ACTUATOR_STATUS_QUERY, outputChannel);
}
protected State getSwitchingData() {
if (getCMD() == CMD_ACTUATOR_STATUS_RESPONE) {
return (bytes[bytes.length - 1] & outputValueMask) == STATUS_SWITCHING_OFF ? OnOffType.OFF : OnOffType.ON;
}
return UnDefType.UNDEF;
}
protected byte getChannel() {
return (byte) (bytes[1] & outputChannelMask);
}
protected State getSwitchingData(byte channel) {
if (getCMD() == CMD_ACTUATOR_STATUS_RESPONE && (getChannel() == channel || getChannel() == AllChannels_Mask)) {
return (bytes[bytes.length - 1] & outputValueMask) == STATUS_SWITCHING_OFF ? OnOffType.OFF : OnOffType.ON;
}
return UnDefType.UNDEF;
}
protected void setDimmingData(Command command, byte outputChannel, Configuration config) {
byte outputValue;
if (command instanceof DecimalType) {
if (((DecimalType) command).equals(DecimalType.ZERO)) {
outputValue = STATUS_SWITCHING_OFF;
} else {
outputValue = ((DecimalType) command).byteValue();
}
} else if ((OnOffType) command == OnOffType.ON) {
outputValue = STATUS_DIMMING_100;
} else {
outputValue = STATUS_SWITCHING_OFF;
}
EnOceanChannelDimmerConfig c = config.as(EnOceanChannelDimmerConfig.class);
byte rampingTime = (c.rampingTime == null) ? Zero : c.rampingTime.byteValue();
setData(CMD_ACTUATOR_SET_STATUS, (byte) ((rampingTime << 5) | outputChannel), outputValue);
}
protected State getDimmingData() {
if (getCMD() == CMD_ACTUATOR_STATUS_RESPONE) {
return new PercentType((bytes[bytes.length - 1] & outputValueMask));
}
return UnDefType.UNDEF;
}
protected void setEnergyMeasurementQueryData(byte outputChannel) {
setData(CMD_ACTUATOR_MEASUREMENT_QUERY, outputChannel);
}
protected void setPowerMeasurementQueryData(byte outputChannel) {
setData(CMD_ACTUATOR_MEASUREMENT_QUERY, (byte) (0x20 | outputChannel));
}
protected State getEnergyMeasurementData() {
if (getCMD() == CMD_ACTUATOR_MEASUREMENT_RESPONE) {
float factor = 1;
switch (bytes[1] >>> 5) {
case 0:
factor /= 3600.0;
break;
case 1:
factor /= 1000;
break;
case 2:
factor = 1;
break;
default:
return UnDefType.UNDEF;
}
float energy = Long.parseLong(HexUtils.bytesToHex(new byte[] { bytes[2], bytes[3], bytes[4], bytes[5] }),
16) * factor;
return new QuantityType<>(energy, SmartHomeUnits.KILOWATT_HOUR);
}
return UnDefType.UNDEF;
}
protected State getPowerMeasurementData() {
if (getCMD() == CMD_ACTUATOR_MEASUREMENT_RESPONE) {
float factor = 1;
switch (bytes[1] >>> 5) {
case 3:
factor = 1;
break;
case 4:
factor /= 1000;
break;
default:
return UnDefType.UNDEF;
}
float power = Long.parseLong(HexUtils.bytesToHex(new byte[] { bytes[2], bytes[3], bytes[4], bytes[5] }), 16)
* factor;
return new QuantityType<>(power, SmartHomeUnits.WATT);
}
return UnDefType.UNDEF;
}
@Override
public void addConfigPropertiesTo(DiscoveryResultBuilder discoveredThingResultBuilder) {
discoveredThingResultBuilder.withProperty(PARAMETER_SENDINGEEPID, getEEPType().getId())
.withProperty(PARAMETER_RECEIVINGEEPID, getEEPType().getId());
}
@Override
protected void convertFromCommandImpl(String channelId, String channelTypeId, Command command, State currentState,
Configuration config) {
if (channelId.equals(CHANNEL_GENERAL_SWITCHING)) {
if (command == RefreshType.REFRESH) {
setSwitchingQueryData(AllChannels_Mask);
} else {
setSwitchingData((OnOffType) command, AllChannels_Mask);
}
} else if (channelId.equals(CHANNEL_GENERAL_SWITCHINGA)) {
if (command == RefreshType.REFRESH) {
setSwitchingQueryData(ChannelA_Mask);
} else {
setSwitchingData((OnOffType) command, ChannelA_Mask);
}
} else if (channelId.equals(CHANNEL_GENERAL_SWITCHINGB)) {
if (command == RefreshType.REFRESH) {
setSwitchingQueryData(ChannelB_Mask);
} else {
setSwitchingData((OnOffType) command, ChannelB_Mask);
}
} else if (channelId.equals(CHANNEL_DIMMER)) {
if (command == RefreshType.REFRESH) {
setSwitchingQueryData(AllChannels_Mask);
} else {
setDimmingData(command, AllChannels_Mask, config);
}
} else if (channelId.equals(CHANNEL_INSTANTPOWER) && command == RefreshType.REFRESH) {
setPowerMeasurementQueryData(AllChannels_Mask);
} else if (channelId.equals(CHANNEL_TOTALUSAGE) && command == RefreshType.REFRESH) {
setEnergyMeasurementQueryData(AllChannels_Mask);
}
}
@Override
protected State convertToStateImpl(String channelId, String channelTypeId, State currentState,
Configuration config) {
switch (channelId) {
case CHANNEL_GENERAL_SWITCHING:
return getSwitchingData();
case CHANNEL_GENERAL_SWITCHINGA:
return getSwitchingData(ChannelA_Mask);
case CHANNEL_GENERAL_SWITCHINGB:
return getSwitchingData(ChannelB_Mask);
case CHANNEL_DIMMER:
return getDimmingData();
case CHANNEL_INSTANTPOWER:
return getPowerMeasurementData();
case CHANNEL_TOTALUSAGE:
return getEnergyMeasurementData();
}
return UnDefType.UNDEF;
}
}
| epl-1.0 |
RallySoftware/eclipselink.runtime | foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/security/PrivilegedGetMethodParameterTypes.java | 1211 | /*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.internal.security;
import java.lang.reflect.Method;
import java.security.PrivilegedExceptionAction;
public class PrivilegedGetMethodParameterTypes implements PrivilegedExceptionAction<Class[]> {
private final Method method;
public PrivilegedGetMethodParameterTypes(Method method) {
this.method = method;
}
@Override
public Class[] run() {
return PrivilegedAccessHelper.getMethodParameterTypes(method);
}
}
| epl-1.0 |
RallySoftware/eclipselink.runtime | foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/expressions/SQLUpdateStatement.java | 4367 | /*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.internal.expressions;
import java.io.*;
import java.util.*;
import org.eclipse.persistence.exceptions.*;
import org.eclipse.persistence.expressions.Expression;
import org.eclipse.persistence.internal.helper.*;
import org.eclipse.persistence.queries.*;
import org.eclipse.persistence.internal.sessions.AbstractSession;
/**
* <p><b>Purpose</b>: Print UPDATE statement.
* <p><b>Responsibilities</b>:<ul>
* <li> Print UPDATE statement.
* </ul>
* @author Dorin Sandu
* @since TOPLink/Java 1.0
*/
public class SQLUpdateStatement extends SQLModifyStatement {
/**
* Append the string containing the SQL insert string for the given table.
*/
protected SQLCall buildCallWithoutReturning(AbstractSession session) {
SQLCall call = new SQLCall();
call.returnNothing();
Writer writer = new CharArrayWriter(100);
try {
writer.write("UPDATE ");
if (getHintString() != null) {
writer.write(getHintString());
writer.write(" ");
}
writer.write(getTable().getQualifiedNameDelimited(session.getPlatform()));
writer.write(" SET ");
ExpressionSQLPrinter printer = null;
Vector fieldsForTable = new Vector();
Enumeration valuesEnum = getModifyRow().getValues().elements();
Vector values = new Vector();
for (Enumeration fieldsEnum = getModifyRow().keys(); fieldsEnum.hasMoreElements();) {
DatabaseField field = (DatabaseField)fieldsEnum.nextElement();
Object value = valuesEnum.nextElement();
if (field.getTable().equals(getTable()) || (!field.hasTableName())) {
fieldsForTable.addElement(field);
values.addElement(value);
}
}
if (fieldsForTable.isEmpty()) {
return null;
}
for (int i = 0; i < fieldsForTable.size(); i++) {
DatabaseField field = (DatabaseField)fieldsForTable.elementAt(i);
writer.write(field.getNameDelimited(session.getPlatform()));
writer.write(" = ");
if(values.elementAt(i) instanceof Expression) {
// the value in the modify row is an expression - assign it.
Expression exp = (Expression)values.elementAt(i);
if(printer == null) {
printer = new ExpressionSQLPrinter(session, getTranslationRow(), call, false, getBuilder());
printer.setWriter(writer);
}
printer.printExpression(exp);
} else {
// the value in the modify row is ignored, the parameter corresponding to the key field will be assigned.
call.appendModify(writer, field);
}
if ((i + 1) < fieldsForTable.size()) {
writer.write(", ");
}
}
if (!(getWhereClause() == null)) {
writer.write(" WHERE ");
if(printer == null) {
printer = new ExpressionSQLPrinter(session, getTranslationRow(), call, false, getBuilder());
printer.setWriter(writer);
}
printer.printExpression(getWhereClause());
}
call.setSQLString(writer.toString());
return call;
} catch (IOException exception) {
throw ValidationException.fileError(exception);
}
}
}
| epl-1.0 |
Johnson-Chou/test | opendaylight/md-sal/messagebus-impl/src/main/java/org/opendaylight/controller/config/yang/messagebus/app/impl/MessageBusAppImplModule.java | 2549 | /*
* Copyright (c) 2015 Cisco Systems, Inc. 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.opendaylight.controller.config.yang.messagebus.app.impl;
import org.opendaylight.controller.config.api.DependencyResolver;
import org.opendaylight.controller.config.api.ModuleIdentifier;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.messagebus.app.impl.EventSourceTopology;
import org.opendaylight.controller.messagebus.app.util.Providers;
import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.ProviderContext;
import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MessageBusAppImplModule extends org.opendaylight.controller.config.yang.messagebus.app.impl.AbstractMessageBusAppImplModule {
private static final Logger LOGGER = LoggerFactory.getLogger(MessageBusAppImplModule.class);
private BundleContext bundleContext;
public BundleContext getBundleContext() {
return bundleContext;
}
public void setBundleContext(final BundleContext bundleContext) {
this.bundleContext = bundleContext;
}
public MessageBusAppImplModule(final ModuleIdentifier identifier, final DependencyResolver dependencyResolver) {
super(identifier, dependencyResolver);
}
public MessageBusAppImplModule(final ModuleIdentifier identifier, final DependencyResolver dependencyResolver,
final MessageBusAppImplModule oldModule, final java.lang.AutoCloseable oldInstance) {
super(identifier, dependencyResolver, oldModule, oldInstance);
}
@Override
protected void customValidation() {
}
@Override
public java.lang.AutoCloseable createInstance() {
final ProviderContext bindingCtx = getBindingBrokerDependency().registerProvider(new Providers.BindingAware());
final DataBroker dataBroker = bindingCtx.getSALService(DataBroker.class);
final RpcProviderRegistry rpcRegistry = bindingCtx.getSALService(RpcProviderRegistry.class);
final EventSourceTopology eventSourceTopology = new EventSourceTopology(dataBroker, rpcRegistry);
LOGGER.info("Messagebus initialized");
return eventSourceTopology;
}
}
| epl-1.0 |
rgerkin/neuroConstruct | src/ucl/physiol/neuroconstruct/gui/InputRequestElement.java | 2112 | /**
* neuroConstruct
* Software for developing large scale 3D networks of biologically realistic neurons
*
* Copyright (c) 2009 Padraig Gleeson
* UCL Department of Neuroscience, Physiology and Pharmacology
*
* Development of this software was made possible with funding from the
* Medical Research Council and the Wellcome Trust
*
* This program 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 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package ucl.physiol.neuroconstruct.gui;
/**
* Used to build generic input requests
*
* @author Padraig Gleeson
*
*/
public class InputRequestElement
{
private String ref = null;
private String request = null;
private String toolTip = null;
private String value = null;
private String units = null;
public InputRequestElement(String ref, String request, String toolTip, String initialVal, String units)
{
this.ref = ref;
this.request = request;
this.toolTip = toolTip;
this.value = initialVal;
this.units = units;
}
public void setValue(String val)
{
this.value = val;
}
public String getRef()
{
return this.ref;
}
public String getRequest()
{
return this.request;
}
public String getToolTip()
{
return this.toolTip;
}
public String getValue()
{
return this.value;
}
public String getUnits()
{
return this.units;
}
}
| gpl-2.0 |
md-5/jdk10 | test/hotspot/jtreg/serviceability/jvmti/GetObjectSizeOverflow.java | 2854 | /*
* Copyright (c) 2014, 2018, 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 to verify GetObjectSize does not overflow on a 600M element int[]
*
* @test
* @bug 8027230
* @library /test/lib
* @modules java.base/jdk.internal.misc
* java.compiler
* java.instrument
* java.management
* jdk.internal.jvmstat/sun.jvmstat.monitor
* @requires vm.bits == 64
* @build GetObjectSizeOverflowAgent
* @run driver ClassFileInstaller GetObjectSizeOverflowAgent
* @run main GetObjectSizeOverflow
*/
import java.io.PrintWriter;
import jdk.test.lib.JDKToolFinder;
import jdk.test.lib.Platform;
import jdk.test.lib.process.OutputAnalyzer;
import jdk.test.lib.process.ProcessTools;
import jtreg.SkippedException;
public class GetObjectSizeOverflow {
public static void main(String[] args) throws Exception {
PrintWriter pw = new PrintWriter("MANIFEST.MF");
pw.println("Premain-Class: GetObjectSizeOverflowAgent");
pw.close();
ProcessBuilder pb = new ProcessBuilder();
pb.command(new String[] { JDKToolFinder.getJDKTool("jar"), "cmf", "MANIFEST.MF", "agent.jar", "GetObjectSizeOverflowAgent.class"});
pb.start().waitFor();
ProcessBuilder pt = ProcessTools.createJavaProcessBuilder(true, "-Xmx4000m", "-javaagent:agent.jar", "GetObjectSizeOverflowAgent");
OutputAnalyzer output = new OutputAnalyzer(pt.start());
if (output.getStdout().contains("Could not reserve enough space") || output.getStderr().contains("java.lang.OutOfMemoryError")) {
System.out.println("stdout: " + output.getStdout());
System.out.println("stderr: " + output.getStderr());
throw new SkippedException("Test could not reserve or allocate enough space");
}
output.stdoutShouldContain("GetObjectSizeOverflow passed");
}
}
| gpl-2.0 |
md-5/jdk10 | test/hotspot/jtreg/vmTestbase/nsk/jdi/ThreadReference/currentContendedMonitor/currentcm001.java | 18431 | /*
* Copyright (c) 2001, 2019, 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 nsk.jdi.ThreadReference.currentContendedMonitor;
import nsk.share.*;
import nsk.share.jpda.*;
import nsk.share.jdi.*;
import com.sun.jdi.*;
import java.util.*;
import java.io.*;
import com.sun.jdi.event.*;
import com.sun.jdi.request.*;
/**
* The test for the implementation of an object of the type <BR>
* ThreadReference. <BR>
* <BR>
* The test checks up that results of the method <BR>
* <code>com.sun.jdi.ThreadReference.currentContendedMonitor()</code> <BR>
* complies with its spec. <BR>
* <BR>
* The test checks up that if a target VM doesn't support <BR>
* this operation, that is, the method <BR>
* VirtualMachine.canGetCurrentContendedMonitor() <BR>
* returns false, and a thread in the target VM is suspended, <BR>
* invoking the method currentContendedMonitor() on the thread <BR>
* throws UnsupportedOperationException. <BR>
*/
public class currentcm001 {
//----------------------------------------------------- templete section
static final int PASSED = 0;
static final int FAILED = 2;
static final int PASS_BASE = 95;
//----------------------------------------------------- templete parameters
static final String
sHeader1 = "\n==> nsk/jdi/ThreadReference/currentContendedMonitor/currentcm001 ",
sHeader2 = "--> debugger: ",
sHeader3 = "##> debugger: ";
//----------------------------------------------------- main method
public static void main (String argv[]) {
int result = run(argv, System.out);
System.exit(result + PASS_BASE);
}
public static int run (String argv[], PrintStream out) {
return new currentcm001().runThis(argv, out);
}
//-------------------------------------------------- log procedures
private static Log logHandler;
private static void log1(String message) {
logHandler.display(sHeader1 + message);
}
private static void log2(String message) {
logHandler.display(sHeader2 + message);
}
private static void log3(String message) {
logHandler.complain(sHeader3 + message);
}
// ************************************************ test parameters
private String debuggeeName =
"nsk.jdi.ThreadReference.currentContendedMonitor.currentcm001a";
private String testedClassName =
"nsk.jdi.ThreadReference.currentContendedMonitor.Threadcurrentcm001a";
//String mName = "nsk.jdi.ThreadReference.currentContendedMonitor";
//====================================================== test program
//------------------------------------------------------ common section
static ArgumentHandler argsHandler;
static int waitTime;
static VirtualMachine vm = null;
//static EventRequestManager eventRManager = null;
//static EventQueue eventQueue = null;
//static EventSet eventSet = null;
ReferenceType testedclass = null;
ThreadReference thread2 = null;
ThreadReference mainThread = null;
static int testExitCode = PASSED;
static final int returnCode0 = 0;
static final int returnCode1 = 1;
static final int returnCode2 = 2;
static final int returnCode3 = 3;
static final int returnCode4 = 4;
//------------------------------------------------------ methods
private int runThis (String argv[], PrintStream out) {
Debugee debuggee;
argsHandler = new ArgumentHandler(argv);
logHandler = new Log(out, argsHandler);
Binder binder = new Binder(argsHandler, logHandler);
if (argsHandler.verbose()) {
debuggee = binder.bindToDebugee(debuggeeName + " -vbs");
} else {
debuggee = binder.bindToDebugee(debuggeeName);
}
waitTime = argsHandler.getWaitTime();
IOPipe pipe = new IOPipe(debuggee);
debuggee.redirectStderr(out);
log2(debuggeeName + " debuggee launched");
debuggee.resume();
String line = pipe.readln();
if ((line == null) || !line.equals("ready")) {
log3("signal received is not 'ready' but: " + line);
return FAILED;
} else {
log2("'ready' recieved");
}
vm = debuggee.VM();
//------------------------------------------------------ testing section
log1(" TESTING BEGINS");
for (int i = 0; ; i++) {
pipe.println("newcheck");
line = pipe.readln();
if (line.equals("checkend")) {
log2(" : returned string is 'checkend'");
break ;
} else if (!line.equals("checkready")) {
log3("ERROR: returned string is not 'checkready'");
testExitCode = FAILED;
break ;
}
log1("new checkready: #" + i);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ variable part
int expresult = returnCode0;
//eventRManager = vm.eventRequestManager();
//eventQueue = vm.eventQueue();
String threadName = "testedThread";
//String breakpointMethod1 = "runt1";
//String breakpointMethod2 = "runt2";
//String bpLine1 = "breakpointLineNumber1";
//String bpLine2 = "breakpointLineNumber2";
//String bpLine3 = "breakpointLineNumber3";
List allThreads = null;
ObjectReference monitor = null;
ListIterator listIterator = null;
List classes = null;
//BreakpointRequest breakpRequest1 = null;
//BreakpointRequest breakpRequest2 = null;
//BreakpointRequest breakpRequest3 = null;
label0: {
log2("getting ThreadReference objects");
try {
allThreads = vm.allThreads();
// classes = vm.classesByName(testedClassName);
// testedclass = (ReferenceType) classes.get(0);
} catch ( Exception e) {
log3("ERROR: Exception at very beginning !? : " + e);
expresult = returnCode1;
break label0;
}
listIterator = allThreads.listIterator();
for (;;) {
try {
mainThread = (ThreadReference) listIterator.next();
if (mainThread.name().equals("main"))
break ;
} catch ( NoSuchElementException e ) {
log3("ERROR: NoSuchElementException for listIterator.next()");
log3("ERROR: NO 'main' thread ?????????!!!!!!!");
expresult = returnCode1;
break label0;
}
}
}
label1: {
if (expresult != 0 )
break label1;
log2(" suspending the main thread");
mainThread.suspend();
log2("......checking up on canGetCurrentContendedMonitor()");
if (!vm.canGetCurrentContendedMonitor()) {
log2(" !vm.canGetCurrentContendedMonitor()");
log2("......checking up throwing UnsupportedOperationException");
try {
monitor = mainThread.currentContendedMonitor();
log3("ERROR: no UnsupportedOperationException thrown");
expresult = returnCode1;
} catch ( UnsupportedOperationException e1 ) {
log2(" UnsupportedOperationException is thrown");
} catch ( IncompatibleThreadStateException e2 ) {
log3("ERROR: IncompatibleThreadStateException for a suspended thread");
expresult = returnCode1;
} catch ( Exception e3 ) {
log3("ERROR: unspecified Exception is thrown" + e3);
expresult = returnCode1;
}
}
log2(" resuming the main thread");
mainThread.resume();
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
log2(" the end of testing");
if (expresult != returnCode0)
testExitCode = FAILED;
}
log1(" TESTING ENDS");
//-------------------------------------------------- test summary section
//------------------------------------------------- standard end section
pipe.println("quit");
log2("waiting for the debuggee to finish ...");
debuggee.waitFor();
int status = debuggee.getStatus();
if (status != PASSED + PASS_BASE) {
log3("debuggee returned UNEXPECTED exit status: " +
status + " != PASS_BASE");
testExitCode = FAILED;
} else {
log2("debuggee returned expected exit status: " +
status + " == PASS_BASE");
}
if (testExitCode != PASSED) {
logHandler.complain("TEST FAILED");
}
return testExitCode;
}
/*
* private BreakpointRequest settingBreakpoint(String, String, String)
*
* It sets up a breakpoint within a given method at given line number
* for the thread2 only.
* Third parameter is required for any case in future debugging, as if.
*
* Return codes:
* = BreakpointRequest object in case of success
* = null in case of an Exception thrown within the method
*/
/*
private BreakpointRequest settingBreakpoint ( String methodName,
String bpLine,
String property) {
log2("setting up a breakpoint: method: '" + methodName + "' line: " + bpLine );
List alllineLocations = null;
Location lineLocation = null;
BreakpointRequest breakpRequest = null;
try {
Method method = (Method) testedclass.methodsByName(methodName).get(0);
alllineLocations = method.allLineLocations();
int n =
( (IntegerValue) testedclass.getValue(testedclass.fieldByName(bpLine) ) ).value();
if (n > alllineLocations.size()) {
log3("ERROR: TEST_ERROR_IN_settingBreakpoint(): number is out of bound of method's lines");
} else {
lineLocation = (Location) alllineLocations.get(n);
try {
breakpRequest = eventRManager.createBreakpointRequest(lineLocation);
breakpRequest.putProperty("number", property);
breakpRequest.addThreadFilter(thread2);
breakpRequest.setSuspendPolicy( EventRequest.SUSPEND_EVENT_THREAD);
} catch ( Exception e1 ) {
log3("ERROR: inner Exception within settingBreakpoint() : " + e1);
breakpRequest = null;
}
}
} catch ( Exception e2 ) {
log3("ERROR: ATTENTION: outer Exception within settingBreakpoint() : " + e2);
breakpRequest = null;
}
if (breakpRequest == null)
log2(" A BREAKPOINT HAS NOT BEEN SET UP");
else
log2(" a breakpoint has been set up");
return breakpRequest;
}
*/
/*
* private int breakpoint ()
*
* It removes events from EventQueue until gets first BreakpointEvent.
* To get next EventSet value, it uses the method
* EventQueue.remove(int timeout)
* The timeout argument passed to the method, is "waitTime*60000".
* Note: the value of waitTime is set up with
* the method ArgumentHandler.getWaitTime() at the beginning of the test.
*
* Return codes:
* = returnCode0 - success;
* = returnCode2 - Exception when "eventSet = eventQueue.remove()" is executed
* = returnCode3 - default case when loop of processing an event, that is,
* an unspecified event was taken from the EventQueue
*/
/*
private int breakpoint () {
int returnCode = returnCode0;
log2(" waiting for BreakpointEvent");
labelBP:
for (;;) {
log2(" new: eventSet = eventQueue.remove();");
try {
eventSet = eventQueue.remove(waitTime*60000);
if (eventSet == null) {
log3("ERROR: timeout for waiting for a BreakpintEvent");
returnCode = returnCode3;
break labelBP;
}
} catch ( Exception e ) {
log3("ERROR: Exception for eventSet = eventQueue.remove(); : " + e);
returnCode = 1;
break labelBP;
}
if (eventSet != null) {
log2(" : eventSet != null; size == " + eventSet.size());
EventIterator eIter = eventSet.eventIterator();
Event ev = null;
for (; eIter.hasNext(); ) {
if (returnCode != returnCode0)
break;
ev = eIter.nextEvent();
ll: for (int ifor =0; ; ifor++) {
try {
switch (ifor) {
case 0: AccessWatchpointEvent awe = (AccessWatchpointEvent) ev;
log2(" AccessWatchpointEvent removed");
break ll;
case 1: BreakpointEvent be = (BreakpointEvent) ev;
log2(" BreakpointEvent removed");
break labelBP;
case 2: ClassPrepareEvent cpe = (ClassPrepareEvent) ev;
log2(" ClassPreparEvent removed");
break ll;
case 3: ClassUnloadEvent cue = (ClassUnloadEvent) ev;
log2(" ClassUnloadEvent removed");
break ll;
case 4: ExceptionEvent ee = (ExceptionEvent) ev;
log2(" ExceptionEvent removed");
break ll;
case 5: MethodEntryEvent mene = (MethodEntryEvent) ev;
log2(" MethodEntryEvent removed");
break ll;
case 6: MethodExitEvent mexe = (MethodExitEvent) ev;
log2(" MethodExiEvent removed");
break ll;
case 7: ModificationWatchpointEvent mwe = (ModificationWatchpointEvent) ev;
log2(" ModificationWatchpointEvent removed");
break ll;
case 8: StepEvent se = (StepEvent) ev;
log2(" StepEvent removed");
break ll;
case 9: ThreadDeathEvent tde = (ThreadDeathEvent) ev;
log2(" ThreadDeathEvent removed");
break ll;
case 10: ThreadStartEvent tse = (ThreadStartEvent) ev;
log2(" ThreadStartEvent removed");
break ll;
case 11: VMDeathEvent vmde = (VMDeathEvent) ev;
log2(" VMDeathEvent removed");
break ll;
case 12: VMStartEvent vmse = (VMStartEvent) ev;
log2(" VMStartEvent removed");
break ll;
case 13: WatchpointEvent we = (WatchpointEvent) ev;
log2(" WatchpointEvent removed");
break ll;
default: log3("ERROR: default case for casting event");
returnCode = returnCode3;
break ll;
} // switch
} catch ( ClassCastException e ) {
} // try
} // ll: for (int ifor =0; ; ifor++)
} // for (; ev.hasNext(); )
}
}
if (returnCode == returnCode0)
log2(" : eventSet == null: EventQueue is empty");
return returnCode;
}
*/
}
| gpl-2.0 |
CURocketry/Ground_Station_GUI | src/org/openstreetmap/josm/gui/widgets/AbstractTextComponentValidator.java | 6645 | // License: GPL. For details, see LICENSE file.
package org.openstreetmap.josm.gui.widgets;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.BorderFactory;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.JTextComponent;
import org.openstreetmap.josm.tools.CheckParameterUtil;
import org.openstreetmap.josm.tools.Utils;
/**
* This is an abstract class for a validator on a text component.
*
* Subclasses implement {@link #validate()}. {@link #validate()} is invoked whenever
* <ul>
* <li>the content of the text component changes (the validator is a {@link DocumentListener})</li>
* <li>the text component loses focus (the validator is a {@link FocusListener})</li>
* <li>the text component is a {@link JosmTextField} and an {@link ActionEvent} is detected</li>
* </ul>
*
*
*/
public abstract class AbstractTextComponentValidator implements ActionListener, FocusListener, DocumentListener, PropertyChangeListener{
static final private Border ERROR_BORDER = BorderFactory.createLineBorder(Color.RED, 1);
static final private Color ERROR_BACKGROUND = new Color(255,224,224);
private JTextComponent tc;
/** remembers whether the content of the text component is currently valid or not; null means,
* we don't know yet
*/
private Boolean valid = null;
// remember the message
private String msg;
protected void feedbackInvalid(String msg) {
if (valid == null || valid || !Utils.equal(msg, this.msg)) {
// only provide feedback if the validity has changed. This avoids
// unnecessary UI updates.
tc.setBorder(ERROR_BORDER);
tc.setBackground(ERROR_BACKGROUND);
tc.setToolTipText(msg);
valid = false;
this.msg = msg;
}
}
protected void feedbackDisabled() {
feedbackValid(null);
}
protected void feedbackValid(String msg) {
if (valid == null || !valid || !Utils.equal(msg, this.msg)) {
// only provide feedback if the validity has changed. This avoids
// unnecessary UI updates.
tc.setBorder(UIManager.getBorder("TextField.border"));
tc.setBackground(UIManager.getColor("TextField.background"));
tc.setToolTipText(msg == null ? "" : msg);
valid = true;
this.msg = msg;
}
}
/**
* Replies the decorated text component
*
* @return the decorated text component
*/
public JTextComponent getComponent() {
return tc;
}
/**
* Creates the validator and weires it to the text component <code>tc</code>.
*
* @param tc the text component. Must not be null.
* @throws IllegalArgumentException thrown if tc is null
*/
public AbstractTextComponentValidator(JTextComponent tc) throws IllegalArgumentException {
this(tc, true);
}
/**
* Alternative constructor that allows to turn off the actionListener.
* This can be useful if the enter key stroke needs to be forwarded to the default button in a dialog.
*/
public AbstractTextComponentValidator(JTextComponent tc, boolean addActionListener) throws IllegalArgumentException {
this(tc, true, true, addActionListener);
}
public AbstractTextComponentValidator(JTextComponent tc, boolean addFocusListener, boolean addDocumentListener, boolean addActionListener) throws IllegalArgumentException {
CheckParameterUtil.ensureParameterNotNull(tc, "tc");
this.tc = tc;
if (addFocusListener) {
tc.addFocusListener(this);
}
if (addDocumentListener) {
tc.getDocument().addDocumentListener(this);
}
if (addActionListener) {
if (tc instanceof JosmTextField) {
JosmTextField tf = (JosmTextField)tc;
tf.addActionListener(this);
}
}
tc.addPropertyChangeListener("enabled", this);
}
/**
* Implement in subclasses to validate the content of the text component.
*
*/
public abstract void validate();
/**
* Replies true if the current content of the decorated text component is valid;
* false otherwise
*
* @return true if the current content of the decorated text component is valid
*/
public abstract boolean isValid();
/* -------------------------------------------------------------------------------- */
/* interface FocusListener */
/* -------------------------------------------------------------------------------- */
@Override
public void focusGained(FocusEvent arg0) {}
@Override
public void focusLost(FocusEvent arg0) {
validate();
}
/* -------------------------------------------------------------------------------- */
/* interface ActionListener */
/* -------------------------------------------------------------------------------- */
@Override
public void actionPerformed(ActionEvent arg0) {
validate();
}
/* -------------------------------------------------------------------------------- */
/* interface DocumentListener */
/* -------------------------------------------------------------------------------- */
@Override
public void changedUpdate(DocumentEvent arg0) {
validate();
}
@Override
public void insertUpdate(DocumentEvent arg0) {
validate();
}
@Override
public void removeUpdate(DocumentEvent arg0) {
validate();
}
/* -------------------------------------------------------------------------------- */
/* interface PropertyChangeListener */
/* -------------------------------------------------------------------------------- */
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals("enabled")) {
boolean enabled = (Boolean)evt.getNewValue();
if (enabled) {
validate();
} else {
feedbackDisabled();
}
}
}
}
| gpl-3.0 |
jtux270/translate | ovirt/3.6_source/backend/manager/modules/restapi/jaxrs/src/test/java/org/ovirt/engine/api/restapi/resource/BackendDiskProfileResourceTest.java | 7622 | package org.ovirt.engine.api.restapi.resource;
import static org.easymock.EasyMock.expect;
import javax.ws.rs.WebApplicationException;
import org.junit.Test;
import org.ovirt.engine.api.model.DiskProfile;
import org.ovirt.engine.core.common.action.DiskProfileParameters;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.queries.IdQueryParameters;
import org.ovirt.engine.core.common.queries.VdcQueryType;
public class BackendDiskProfileResourceTest
extends AbstractBackendSubResourceTest<DiskProfile, org.ovirt.engine.core.common.businessentities.profiles.DiskProfile, BackendDiskProfileResource> {
public BackendDiskProfileResourceTest() {
super(new BackendDiskProfileResource(GUIDS[0].toString()));
}
@Test
public void testBadGuid() throws Exception {
control.replay();
try {
new BackendDiskProfileResource("foo");
fail("expected WebApplicationException");
} catch (WebApplicationException wae) {
verifyNotFoundException(wae);
}
}
@Test
public void testGetNotFound() throws Exception {
setUriInfo(setUpBasicUriExpectations());
setUpEntityQueryExpectations(1, 0, true);
control.replay();
try {
resource.get();
fail("expected WebApplicationException");
} catch (WebApplicationException wae) {
verifyNotFoundException(wae);
}
}
@Test
public void testGet() throws Exception {
setUriInfo(setUpBasicUriExpectations());
setUpEntityQueryExpectations(1, 0, false);
control.replay();
verifyModel(resource.get(), 0);
}
@Test
public void testUpdateNotFound() throws Exception {
setUriInfo(setUpBasicUriExpectations());
setUpEntityQueryExpectations(1, 0, true);
control.replay();
try {
resource.update(getModel(0));
fail("expected WebApplicationException");
} catch (WebApplicationException wae) {
verifyNotFoundException(wae);
}
}
@Test
public void testUpdate() throws Exception {
setUpEntityQueryExpectations(2, 0, false);
setUriInfo(setUpActionExpectations(VdcActionType.UpdateDiskProfile,
DiskProfileParameters.class,
new String[] {},
new Object[] {},
true,
true));
verifyModel(resource.update(getModel(0)), 0);
}
@Test
public void testUpdateCantDo() throws Exception {
doTestBadUpdate(false, true, CANT_DO);
}
@Test
public void testUpdateFailed() throws Exception {
doTestBadUpdate(true, false, FAILURE);
}
private void doTestBadUpdate(boolean canDo, boolean success, String detail) throws Exception {
setUpEntityQueryExpectations(1, 0, false);
setUriInfo(setUpActionExpectations(VdcActionType.UpdateDiskProfile,
DiskProfileParameters.class,
new String[] {},
new Object[] {},
canDo,
success));
try {
resource.update(getModel(0));
fail("expected WebApplicationException");
} catch (WebApplicationException wae) {
verifyFault(wae, detail);
}
}
@Test
public void testConflictedUpdate() throws Exception {
setUriInfo(setUpBasicUriExpectations());
setUpEntityQueryExpectations(1, 0, false);
control.replay();
DiskProfile model = getModel(1);
model.setId(GUIDS[1].toString());
try {
resource.update(model);
fail("expected WebApplicationException");
} catch (WebApplicationException wae) {
verifyImmutabilityConstraint(wae);
}
}
@Test
public void testRemoveNotFound() throws Exception {
setUpEntityQueryExpectations(1, 0, true);
control.replay();
try {
resource.remove();
fail("expected WebApplicationException");
} catch (WebApplicationException wae) {
verifyNotFoundException(wae);
}
}
@Test
public void testRemove() throws Exception {
setUpEntityQueryExpectations(2, 0, false);
setUriInfo(
setUpActionExpectations(
VdcActionType.RemoveDiskProfile,
DiskProfileParameters.class,
new String[] {},
new Object[] {},
true,
true
)
);
verifyRemove(resource.remove());
}
@Test
public void testRemoveNonExistant() throws Exception {
setUpEntityQueryExpectations(
VdcQueryType.GetDiskProfileById,
IdQueryParameters.class,
new String[] { "Id" },
new Object[] { GUIDS[0] },
null
);
control.replay();
try {
resource.remove();
fail("expected WebApplicationException");
}
catch (WebApplicationException wae) {
assertNotNull(wae.getResponse());
assertEquals(404, wae.getResponse().getStatus());
}
}
@Test
public void testRemoveCantDo() throws Exception {
doTestBadRemove(false, true, CANT_DO);
}
@Test
public void testRemoveFailed() throws Exception {
doTestBadRemove(true, false, FAILURE);
}
protected void doTestBadRemove(boolean canDo, boolean success, String detail) throws Exception {
setUpEntityQueryExpectations(2, 0, false);
setUriInfo(
setUpActionExpectations(
VdcActionType.RemoveDiskProfile,
DiskProfileParameters.class,
new String[] {},
new Object[] {},
canDo,
success
)
);
try {
resource.remove();
fail("expected WebApplicationException");
}
catch (WebApplicationException wae) {
verifyFault(wae, detail);
}
}
protected void setUpEntityQueryExpectations(int times, int index, boolean notFound) throws Exception {
while (times-- > 0) {
setUpEntityQueryExpectations(VdcQueryType.GetDiskProfileById,
IdQueryParameters.class,
new String[] { "Id" },
new Object[] { GUIDS[index] },
notFound ? null : getEntity(index));
}
}
static DiskProfile getModel(int index) {
DiskProfile model = new DiskProfile();
model.setId(GUIDS[index].toString());
model.setName(NAMES[index]);
model.setDescription(DESCRIPTIONS[index]);
return model;
}
@Override
protected org.ovirt.engine.core.common.businessentities.profiles.DiskProfile getEntity(int index) {
return setUpEntityExpectations(control.createMock(org.ovirt.engine.core.common.businessentities.profiles.DiskProfile.class),
index);
}
static org.ovirt.engine.core.common.businessentities.profiles.DiskProfile setUpEntityExpectations(org.ovirt.engine.core.common.businessentities.profiles.DiskProfile entity,
int index) {
expect(entity.getId()).andReturn(GUIDS[index]).anyTimes();
expect(entity.getName()).andReturn(NAMES[index]).anyTimes();
expect(entity.getDescription()).andReturn(DESCRIPTIONS[index]).anyTimes();
expect(entity.getStorageDomainId()).andReturn(GUIDS[index]).anyTimes();
return entity;
}
}
| gpl-3.0 |
jtux270/translate | ovirt/3.6_source/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/RemoveAllVmImagesCommand.java | 5661 | package org.ovirt.engine.core.bll;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.ovirt.engine.core.bll.context.CommandContext;
import org.ovirt.engine.core.common.action.RemoveAllVmImagesParameters;
import org.ovirt.engine.core.common.action.RemoveImageParameters;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.action.VdcReturnValueBase;
import org.ovirt.engine.core.common.businessentities.StorageDomain;
import org.ovirt.engine.core.common.businessentities.StorageDomainType;
import org.ovirt.engine.core.common.businessentities.storage.DiskImage;
import org.ovirt.engine.core.common.businessentities.storage.ImageStatus;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.TransactionScopeOption;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.utils.transaction.TransactionMethod;
import org.ovirt.engine.core.utils.transaction.TransactionSupport;
/**
* This command removes all Vm images and all created snapshots both from Irs
* and Db.
*/
@InternalCommandAttribute
@NonTransactiveCommandAttribute
public class RemoveAllVmImagesCommand<T extends RemoveAllVmImagesParameters> extends VmCommand<T> {
public RemoveAllVmImagesCommand(T parameters, CommandContext cmdContext) {
super(parameters, cmdContext);
}
@Override
protected void executeVmCommand() {
Set<Guid> imagesToBeRemoved = new HashSet<>();
List<DiskImage> images = getParameters().images;
if (images == null) {
images =
ImagesHandler.filterImageDisks(DbFacade.getInstance().getDiskDao().getAllForVm(getVmId()),
true,
false,
true);
}
for (DiskImage image : images) {
if (Boolean.TRUE.equals(image.getActive())) {
imagesToBeRemoved.add(image.getImageId());
}
}
Collection<DiskImage> failedRemoving = new LinkedList<>();
for (final DiskImage image : images) {
if (imagesToBeRemoved.contains(image.getImageId())) {
VdcReturnValueBase vdcReturnValue =
runInternalActionWithTasksContext(
VdcActionType.RemoveImage,
buildRemoveImageParameters(image)
);
if (vdcReturnValue.getSucceeded()) {
getReturnValue().getInternalVdsmTaskIdList().addAll(vdcReturnValue.getInternalVdsmTaskIdList());
} else {
StorageDomain domain = getStorageDomainDao().get(image.getStorageIds().get(0));
failedRemoving.add(image);
log.error("Can't remove image id '{}' for VM id '{}' from domain id '{}' due to: {}.",
image.getImageId(),
getParameters().getVmId(),
image.getStorageIds().get(0),
vdcReturnValue.getFault().getMessage());
if (domain.getStorageDomainType() == StorageDomainType.Data) {
log.info("Image id '{}' will be set at illegal state with no snapshot id.", image.getImageId());
TransactionSupport.executeInScope(TransactionScopeOption.Required,
new TransactionMethod<Object>() {
@Override
public Object runInTransaction() {
// If VDSM task didn't succeed to initiate a task we change the disk to at illegal
// state.
updateDiskImagesToIllegal(image);
return true;
}
});
} else {
log.info("Image id '{}' is not on a data domain and will not be marked as illegal.", image.getImageId());
}
}
}
}
setActionReturnValue(failedRemoving);
setSucceeded(true);
}
private RemoveImageParameters buildRemoveImageParameters(DiskImage image) {
RemoveImageParameters result = new RemoveImageParameters(image.getImageId());
result.setParentCommand(getParameters().getParentCommand());
result.setParentParameters(getParameters().getParentParameters());
result.setDiskImage(image);
result.setEntityInfo(getParameters().getEntityInfo());
result.setForceDelete(getParameters().getForceDelete());
result.setShouldLockImage(false);
return result;
}
/**
* Update all disks images of specific disk image to illegal state, and set the vm snapshot id to null, since now
* they are not connected to any VM.
*
* @param diskImage - The disk to update.
*/
private void updateDiskImagesToIllegal(DiskImage diskImage) {
List<DiskImage> snapshotDisks =
getDbFacade().getDiskImageDao().getAllSnapshotsForImageGroup(diskImage.getId());
for (DiskImage diskSnapshot : snapshotDisks) {
diskSnapshot.setVmSnapshotId(null);
diskSnapshot.setImageStatus(ImageStatus.ILLEGAL);
getDbFacade().getImageDao().update(diskSnapshot.getImage());
}
}
@Override
protected void endVmCommand() {
setSucceeded(true);
}
}
| gpl-3.0 |
s20121035/rk3288_android5.1_repo | cts/tools/vm-tests-tf/src/dot/junit/opcodes/iget_boolean/d/T_iget_boolean_12.java | 793 | /*
* Copyright (C) 2010 The Android Open Source Project
*
* 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 dot.junit.opcodes.iget_boolean.d;
public class T_iget_boolean_12 extends T_iget_boolean_1 {
@Override
public boolean run(){
return false;
}
}
| gpl-3.0 |
sbandur84/micro-Blagajna | src-data/com/openbravo/data/user/BrowsableData.java | 11396 | // uniCenta oPOS - Touch Friendly Point Of Sale
// Copyright (c) 2009-2014 uniCenta & previous Openbravo POS works
// http://www.unicenta.com
//
// This file is part of uniCenta oPOS
//
// uniCenta oPOS 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 3 of the License, or
// (at your option) any later version.
//
// uniCenta oPOS 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 uniCenta oPOS. If not, see <http://www.gnu.org/licenses/>.
package com.openbravo.data.user;
import com.openbravo.basic.BasicException;
import com.openbravo.data.loader.LocalRes;
import java.util.*;
import javax.swing.ListModel;
import javax.swing.event.EventListenerList;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
/**
*
* @author JG uniCenta
*/
public class BrowsableData implements ListModel {
/**
*
*/
protected EventListenerList listeners = new EventListenerList();
private boolean m_bIsAdjusting;
private ListProvider m_dataprov;
private SaveProvider m_saveprov;
private List m_aData; // List<Object>
private Comparator m_comparer;
/** Creates a new instance of BrowsableData
* @param dataprov
* @param saveprov
* @param c */
public BrowsableData(ListProvider dataprov, SaveProvider saveprov, Comparator c) {
m_dataprov = dataprov;
m_saveprov = saveprov;
m_comparer = c;
m_bIsAdjusting = false;
m_aData = new ArrayList();
}
/**
*
* @param dataprov
* @param saveprov
*/
public BrowsableData(ListProvider dataprov, SaveProvider saveprov) {
this(dataprov, saveprov, null);
}
/**
*
* @param dataprov
*/
public BrowsableData(ListProvider dataprov) {
this(dataprov, null, null);
}
public final void addListDataListener(ListDataListener l) {
listeners.add(ListDataListener.class, l);
}
public final void removeListDataListener(ListDataListener l) {
listeners.remove(ListDataListener.class, l);
}
// Metodos de acceso
public final Object getElementAt(int index) {
return m_aData.get(index);
}
public final int getSize() {
return m_aData.size();
}
/**
*
* @return
*/
public final boolean isAdjusting() {
return m_bIsAdjusting;
}
/**
*
* @param index0
* @param index1
*/
protected void fireDataIntervalAdded(int index0, int index1) {
m_bIsAdjusting = true;
EventListener[] l = listeners.getListeners(ListDataListener.class);
ListDataEvent e = null;
for (int i = 0; i < l.length; i++) {
if (e == null) {
e = new ListDataEvent(this, ListDataEvent.INTERVAL_ADDED, index0, index1);
}
((ListDataListener) l[i]).intervalAdded(e);
}
m_bIsAdjusting = false;
}
/**
*
* @param index0
* @param index1
*/
protected void fireDataContentsChanged(int index0, int index1) {
m_bIsAdjusting = true;
EventListener[] l = listeners.getListeners(ListDataListener.class);
ListDataEvent e = null;
for (int i = 0; i < l.length; i++) {
if (e == null) {
e = new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, index0, index1);
}
((ListDataListener) l[i]).contentsChanged(e);
}
m_bIsAdjusting = false;
}
/**
*
* @param index0
* @param index1
*/
protected void fireDataIntervalRemoved(int index0, int index1) {
m_bIsAdjusting = true;
EventListener[] l = listeners.getListeners(ListDataListener.class);
ListDataEvent e = null;
for (int i = 0; i < l.length; i++) {
if (e == null) {
e = new ListDataEvent(this, ListDataEvent.INTERVAL_REMOVED, index0, index1);
}
((ListDataListener) l[i]).intervalRemoved(e);
}
m_bIsAdjusting = false;
}
/**
*
* @throws BasicException
*/
public void refreshData() throws BasicException {
putNewData(m_dataprov == null
? null
: m_dataprov.refreshData());
}
/**
*
* @throws BasicException
*/
public void loadData() throws BasicException {
putNewData(m_dataprov == null
? null
: m_dataprov.loadData());
}
/**
*
* @throws BasicException
*/
public void unloadData() throws BasicException {
putNewData(null);
}
/**
*
* @param l
*/
public void loadList(List l) {
putNewData(l);
}
/**
*
* @param c
* @throws BasicException
*/
public void sort(Comparator c) throws BasicException {
Collections.sort(m_aData, c);
putNewData(m_aData);
}
/**
*
* @return
*/
public final boolean canLoadData() {
return m_dataprov != null;
}
/**
*
* @return
*/
public boolean canInsertData() {
return m_saveprov != null && m_saveprov.canInsert();
}
/**
*
* @return
*/
public boolean canDeleteData() {
return m_saveprov != null && m_saveprov.canDelete();
}
/**
*
* @return
*/
public boolean canUpdateData() {
return m_saveprov != null && m_saveprov.canUpdate();
}
/**
*
* @param index
* @param f
* @return
* @throws BasicException
*/
public final int findNext(int index, Finder f) throws BasicException {
int i = index + 1;
// search up to the end of the recordset
while (i < m_aData.size()) {
if (f.match(this.getElementAt(i))) {
return i;
}
i++;
}
// search from the begining
i = 0;
while (i < index) {
if (f.match(this.getElementAt(i))) {
return i;
}
i++;
}
// No se ha encontrado
return -1;
}
/**
*
* @param index
* @return
* @throws BasicException
*/
public final int removeRecord(int index) throws BasicException {
if (canDeleteData() && index >= 0 && index < m_aData.size()) {
if (m_saveprov.deleteData(getElementAt(index)) > 0) {
// borramos el elemento indicado
m_aData.remove(index);
// disparamos los eventos
fireDataIntervalRemoved(index, index);
int newindex;
if (index < m_aData.size()) {
newindex = index;
} else {
newindex = m_aData.size() - 1;
}
return newindex;
} else {
throw new BasicException(LocalRes.getIntString("exception.nodelete"));
}
} else {
// indice no valido
throw new BasicException(LocalRes.getIntString("exception.nodelete"));
}
}
/**
*
* @param index
* @param value
* @return
* @throws BasicException
*/
public final int updateRecord(int index, Object value) throws BasicException {
if (canUpdateData() && index >= 0 && index < m_aData.size()) {
if (m_saveprov.updateData(value) > 0) {
// Modificamos el elemento indicado
int newindex;
if (m_comparer == null) {
newindex = index;
m_aData.set(newindex, value);
} else {
// lo movemos
newindex = insertionPoint(value);
if (newindex == index + 1) {
newindex = index;
m_aData.set(newindex, value);
} else if (newindex > index + 1) {
m_aData.remove(index);
newindex --;
m_aData.add(newindex, value);
} else {
m_aData.remove(index);
m_aData.add(newindex, value);
}
}
if (newindex >= index) {
fireDataContentsChanged(index, newindex);
} else {
fireDataContentsChanged(newindex, index);
}
return newindex;
} else {
// fallo la actualizacion
throw new BasicException(LocalRes.getIntString("exception.noupdate"));
}
} else {
// registro invalido
throw new BasicException(LocalRes.getIntString("exception.noupdate"));
}
}
/**
*
* @param value
* @return
* @throws BasicException
*/
public final int insertRecord(Object value) throws BasicException {
if (canInsertData() && m_saveprov.insertData(value) > 0) {
int newindex;
if (m_comparer == null) {
// Anadimos el elemento indicado al final...
newindex = m_aData.size();
} else {
// lo insertamos en el lugar adecuado
newindex = insertionPoint(value);
}
m_aData.add(newindex, value);
// Disparamos la inserccion
fireDataIntervalAdded(newindex, newindex);
return newindex;
} else {
throw new BasicException(LocalRes.getIntString("exception.noinsert"));
}
}
private void putNewData(List aData) {
int oldSize = m_aData.size();
m_aData = (aData == null) ? new ArrayList() : aData;
int newSize = m_aData.size();
// Ordeno si es un Browsabledata ordenado
if (m_comparer != null) {
Collections.sort(m_aData, m_comparer);
}
fireDataContentsChanged(0, newSize - 1);
if (oldSize > newSize) {
fireDataIntervalRemoved(newSize, oldSize - 1);
} else if (oldSize < newSize) {
fireDataIntervalAdded(oldSize, newSize - 1);
}
}
private final int insertionPoint(Object value) {
int low = 0;
int high = m_aData.size() - 1;
while (low <= high) {
int mid = (low + high) >> 1;
Object midVal = m_aData.get(mid);
int cmp = m_comparer.compare(midVal, value);
if (cmp <= 0) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return low;
}
}
| gpl-3.0 |
eethomas/eucalyptus | clc/modules/simpleworkflow-common/src/main/java/com/eucalyptus/simpleworkflow/common/model/CloseStatusFilter.java | 7268 | /*************************************************************************
* Copyright 2014 Eucalyptus Systems, Inc.
*
* This program 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; version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
* Please contact Eucalyptus Systems, Inc., 6755 Hollister Ave., Goleta
* CA 93117, USA or visit http://www.eucalyptus.com/licenses/ if you
* need additional information or have any questions.
*
* This file may incorporate work covered under the following copyright
* and permission notice:
*
* Copyright 2010-2014 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.eucalyptus.simpleworkflow.common.model;
import static com.eucalyptus.simpleworkflow.common.model.SimpleWorkflowMessage.FieldRegex;
import static com.eucalyptus.simpleworkflow.common.model.SimpleWorkflowMessage.FieldRegexValue;
import java.io.Serializable;
import javax.annotation.Nonnull;
/**
* <p>
* Used to filter the closed workflow executions in visibility APIs by
* their close status.
* </p>
*/
public class CloseStatusFilter implements Serializable {
/**
* The close status that must match the close status of an execution for
* it to meet the criteria of this filter. This field is required.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>COMPLETED, FAILED, CANCELED, TERMINATED, CONTINUED_AS_NEW, TIMED_OUT
*/
@Nonnull
@FieldRegex( FieldRegexValue.CLOSE_STATUS )
private String status;
/**
* The close status that must match the close status of an execution for
* it to meet the criteria of this filter. This field is required.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>COMPLETED, FAILED, CANCELED, TERMINATED, CONTINUED_AS_NEW, TIMED_OUT
*
* @return The close status that must match the close status of an execution for
* it to meet the criteria of this filter. This field is required.
*
* @see CloseStatus
*/
public String getStatus() {
return status;
}
/**
* The close status that must match the close status of an execution for
* it to meet the criteria of this filter. This field is required.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>COMPLETED, FAILED, CANCELED, TERMINATED, CONTINUED_AS_NEW, TIMED_OUT
*
* @param status The close status that must match the close status of an execution for
* it to meet the criteria of this filter. This field is required.
*
* @see CloseStatus
*/
public void setStatus(String status) {
this.status = status;
}
/**
* The close status that must match the close status of an execution for
* it to meet the criteria of this filter. This field is required.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>COMPLETED, FAILED, CANCELED, TERMINATED, CONTINUED_AS_NEW, TIMED_OUT
*
* @param status The close status that must match the close status of an execution for
* it to meet the criteria of this filter. This field is required.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*
* @see CloseStatus
*/
public CloseStatusFilter withStatus(String status) {
this.status = status;
return this;
}
/**
* The close status that must match the close status of an execution for
* it to meet the criteria of this filter. This field is required.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>COMPLETED, FAILED, CANCELED, TERMINATED, CONTINUED_AS_NEW, TIMED_OUT
*
* @param status The close status that must match the close status of an execution for
* it to meet the criteria of this filter. This field is required.
*
* @see CloseStatus
*/
public void setStatus(CloseStatus status) {
this.status = status.toString();
}
/**
* The close status that must match the close status of an execution for
* it to meet the criteria of this filter. This field is required.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>COMPLETED, FAILED, CANCELED, TERMINATED, CONTINUED_AS_NEW, TIMED_OUT
*
* @param status The close status that must match the close status of an execution for
* it to meet the criteria of this filter. This field is required.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*
* @see CloseStatus
*/
public CloseStatusFilter withStatus(CloseStatus status) {
this.status = status.toString();
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 (getStatus() != null) sb.append("Status: " + getStatus() );
sb.append("}");
return sb.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode());
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (obj instanceof CloseStatusFilter == false) return false;
CloseStatusFilter other = (CloseStatusFilter)obj;
if (other.getStatus() == null ^ this.getStatus() == null) return false;
if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false) return false;
return true;
}
}
| gpl-3.0 |
open-health-hub/openMAXIMS | openmaxims_workspace/Clinical/src/ims/clinical/forms/patientassessmentlistandsearch/FormInfo.java | 2720 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.clinical.forms.patientassessmentlistandsearch;
public final class FormInfo extends ims.framework.FormInfo
{
private static final long serialVersionUID = 1L;
public FormInfo(Integer formId)
{
super(formId);
}
public String getNamespaceName()
{
return "Clinical";
}
public String getFormName()
{
return "PatientAssessmentListAndSearch";
}
public int getWidth()
{
return 848;
}
public int getHeight()
{
return 632;
}
public String[] getContextVariables()
{
return new String[] { "_cv_Clinical.PatientAssessment.SelectedAssessment", "_cv_Clinical.ReturnToFormName" };
}
public String getLocalVariablesPrefix()
{
return "_lv_Clinical.PatientAssessmentListAndSearch.__internal_x_context__" + String.valueOf(getFormId());
}
public ims.framework.FormInfo[] getComponentsFormInfo()
{
ims.framework.FormInfo[] componentsInfo = new ims.framework.FormInfo[1];
componentsInfo[0] = new ims.core.forms.mosquery.FormInfo(102256);
return componentsInfo;
}
public String getImagePath()
{
return "";
}
}
| agpl-3.0 |
open-health-hub/openMAXIMS | openmaxims_workspace/ValueObjects/src/ims/emergency/vo/domain/DNWForOutcomeVoAssembler.java | 14908 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
/*
* This code was generated
* Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved.
* IMS Development Environment (version 1.80 build 5007.25751)
* WARNING: DO NOT MODIFY the content of this file
* Generated on 16/04/2014, 12:32
*
*/
package ims.emergency.vo.domain;
import ims.vo.domain.DomainObjectMap;
import java.util.HashMap;
import org.hibernate.proxy.HibernateProxy;
/**
* @author Bogdan Tofei
*/
public class DNWForOutcomeVoAssembler
{
/**
* Copy one ValueObject to another
* @param valueObjectDest to be updated
* @param valueObjectSrc to copy values from
*/
public static ims.emergency.vo.DNWForOutcomeVo copy(ims.emergency.vo.DNWForOutcomeVo valueObjectDest, ims.emergency.vo.DNWForOutcomeVo valueObjectSrc)
{
if (null == valueObjectSrc)
{
return valueObjectSrc;
}
valueObjectDest.setID_DNW(valueObjectSrc.getID_DNW());
valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE());
// CurrentStatus
valueObjectDest.setCurrentStatus(valueObjectSrc.getCurrentStatus());
return valueObjectDest;
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* This is a convenience method only.
* It is intended to be used when one called to an Assembler is made.
* If more than one call to an Assembler is made then #createDNWForOutcomeVoCollectionFromDNW(DomainObjectMap, Set) should be used.
* @param domainObjectSet - Set of ims.emergency.domain.objects.DNW objects.
*/
public static ims.emergency.vo.DNWForOutcomeVoCollection createDNWForOutcomeVoCollectionFromDNW(java.util.Set domainObjectSet)
{
return createDNWForOutcomeVoCollectionFromDNW(new DomainObjectMap(), domainObjectSet);
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectSet - Set of ims.emergency.domain.objects.DNW objects.
*/
public static ims.emergency.vo.DNWForOutcomeVoCollection createDNWForOutcomeVoCollectionFromDNW(DomainObjectMap map, java.util.Set domainObjectSet)
{
ims.emergency.vo.DNWForOutcomeVoCollection voList = new ims.emergency.vo.DNWForOutcomeVoCollection();
if ( null == domainObjectSet )
{
return voList;
}
int rieCount=0;
int activeCount=0;
java.util.Iterator iterator = domainObjectSet.iterator();
while( iterator.hasNext() )
{
ims.emergency.domain.objects.DNW domainObject = (ims.emergency.domain.objects.DNW) iterator.next();
ims.emergency.vo.DNWForOutcomeVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param domainObjectList - List of ims.emergency.domain.objects.DNW objects.
*/
public static ims.emergency.vo.DNWForOutcomeVoCollection createDNWForOutcomeVoCollectionFromDNW(java.util.List domainObjectList)
{
return createDNWForOutcomeVoCollectionFromDNW(new DomainObjectMap(), domainObjectList);
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectList - List of ims.emergency.domain.objects.DNW objects.
*/
public static ims.emergency.vo.DNWForOutcomeVoCollection createDNWForOutcomeVoCollectionFromDNW(DomainObjectMap map, java.util.List domainObjectList)
{
ims.emergency.vo.DNWForOutcomeVoCollection voList = new ims.emergency.vo.DNWForOutcomeVoCollection();
if ( null == domainObjectList )
{
return voList;
}
int rieCount=0;
int activeCount=0;
for (int i = 0; i < domainObjectList.size(); i++)
{
ims.emergency.domain.objects.DNW domainObject = (ims.emergency.domain.objects.DNW) domainObjectList.get(i);
ims.emergency.vo.DNWForOutcomeVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ims.emergency.domain.objects.DNW set from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.Set extractDNWSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.DNWForOutcomeVoCollection voCollection)
{
return extractDNWSet(domainFactory, voCollection, null, new HashMap());
}
public static java.util.Set extractDNWSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.DNWForOutcomeVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectSet == null)
{
domainObjectSet = new java.util.HashSet();
}
java.util.Set newSet = new java.util.HashSet();
for(int i=0; i<size; i++)
{
ims.emergency.vo.DNWForOutcomeVo vo = voCollection.get(i);
ims.emergency.domain.objects.DNW domainObject = DNWForOutcomeVoAssembler.extractDNW(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
//Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add)
if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject);
newSet.add(domainObject);
}
java.util.Set removedSet = new java.util.HashSet();
java.util.Iterator iter = domainObjectSet.iterator();
//Find out which objects need to be removed
while (iter.hasNext())
{
ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next();
if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o))
{
removedSet.add(o);
}
}
iter = removedSet.iterator();
//Remove the unwanted objects
while (iter.hasNext())
{
domainObjectSet.remove(iter.next());
}
return domainObjectSet;
}
/**
* Create the ims.emergency.domain.objects.DNW list from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.List extractDNWList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.DNWForOutcomeVoCollection voCollection)
{
return extractDNWList(domainFactory, voCollection, null, new HashMap());
}
public static java.util.List extractDNWList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.DNWForOutcomeVoCollection voCollection, java.util.List domainObjectList, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectList == null)
{
domainObjectList = new java.util.ArrayList();
}
for(int i=0; i<size; i++)
{
ims.emergency.vo.DNWForOutcomeVo vo = voCollection.get(i);
ims.emergency.domain.objects.DNW domainObject = DNWForOutcomeVoAssembler.extractDNW(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
int domIdx = domainObjectList.indexOf(domainObject);
if (domIdx == -1)
{
domainObjectList.add(i, domainObject);
}
else if (i != domIdx && i < domainObjectList.size())
{
Object tmp = domainObjectList.get(i);
domainObjectList.set(i, domainObjectList.get(domIdx));
domainObjectList.set(domIdx, tmp);
}
}
//Remove all ones in domList where index > voCollection.size() as these should
//now represent the ones removed from the VO collection. No longer referenced.
int i1=domainObjectList.size();
while (i1 > size)
{
domainObjectList.remove(i1-1);
i1=domainObjectList.size();
}
return domainObjectList;
}
/**
* Create the ValueObject from the ims.emergency.domain.objects.DNW object.
* @param domainObject ims.emergency.domain.objects.DNW
*/
public static ims.emergency.vo.DNWForOutcomeVo create(ims.emergency.domain.objects.DNW domainObject)
{
if (null == domainObject)
{
return null;
}
DomainObjectMap map = new DomainObjectMap();
return create(map, domainObject);
}
/**
* Create the ValueObject from the ims.emergency.domain.objects.DNW object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param domainObject
*/
public static ims.emergency.vo.DNWForOutcomeVo create(DomainObjectMap map, ims.emergency.domain.objects.DNW domainObject)
{
if (null == domainObject)
{
return null;
}
// check if the domainObject already has a valueObject created for it
ims.emergency.vo.DNWForOutcomeVo valueObject = (ims.emergency.vo.DNWForOutcomeVo) map.getValueObject(domainObject, ims.emergency.vo.DNWForOutcomeVo.class);
if ( null == valueObject )
{
valueObject = new ims.emergency.vo.DNWForOutcomeVo(domainObject.getId(), domainObject.getVersion());
map.addValueObject(domainObject, valueObject);
valueObject = insert(map, valueObject, domainObject);
}
return valueObject;
}
/**
* Update the ValueObject with the Domain Object.
* @param valueObject to be updated
* @param domainObject ims.emergency.domain.objects.DNW
*/
public static ims.emergency.vo.DNWForOutcomeVo insert(ims.emergency.vo.DNWForOutcomeVo valueObject, ims.emergency.domain.objects.DNW domainObject)
{
if (null == domainObject)
{
return valueObject;
}
DomainObjectMap map = new DomainObjectMap();
return insert(map, valueObject, domainObject);
}
/**
* Update the ValueObject with the Domain Object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param valueObject to be updated
* @param domainObject ims.emergency.domain.objects.DNW
*/
public static ims.emergency.vo.DNWForOutcomeVo insert(DomainObjectMap map, ims.emergency.vo.DNWForOutcomeVo valueObject, ims.emergency.domain.objects.DNW domainObject)
{
if (null == domainObject)
{
return valueObject;
}
if (null == map)
{
map = new DomainObjectMap();
}
valueObject.setID_DNW(domainObject.getId());
valueObject.setIsRIE(domainObject.getIsRIE());
// If this is a recordedInError record, and the domainObject
// value isIncludeRecord has not been set, then we return null and
// not the value object
if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord())
return null;
// If this is not a recordedInError record, and the domainObject
// value isIncludeRecord has been set, then we return null and
// not the value object
if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord())
return null;
// CurrentStatus
valueObject.setCurrentStatus(ims.emergency.vo.domain.DNWStatusForTrackingVoAssembler.create(map, domainObject.getCurrentStatus()) );
return valueObject;
}
/**
* Create the domain object from the value object.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param valueObject - extract the domain object fields from this.
*/
public static ims.emergency.domain.objects.DNW extractDNW(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.DNWForOutcomeVo valueObject)
{
return extractDNW(domainFactory, valueObject, new HashMap());
}
public static ims.emergency.domain.objects.DNW extractDNW(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.DNWForOutcomeVo valueObject, HashMap domMap)
{
if (null == valueObject)
{
return null;
}
Integer id = valueObject.getID_DNW();
ims.emergency.domain.objects.DNW domainObject = null;
if ( null == id)
{
if (domMap.get(valueObject) != null)
{
return (ims.emergency.domain.objects.DNW)domMap.get(valueObject);
}
// ims.emergency.vo.DNWForOutcomeVo ID_DNW field is unknown
domainObject = new ims.emergency.domain.objects.DNW();
domMap.put(valueObject, domainObject);
}
else
{
String key = (valueObject.getClass().getName() + "__" + valueObject.getID_DNW());
if (domMap.get(key) != null)
{
return (ims.emergency.domain.objects.DNW)domMap.get(key);
}
domainObject = (ims.emergency.domain.objects.DNW) domainFactory.getDomainObject(ims.emergency.domain.objects.DNW.class, id );
//TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up.
if (domainObject == null)
return null;
domMap.put(key, domainObject);
}
domainObject.setVersion(valueObject.getVersion_DNW());
domainObject.setCurrentStatus(ims.emergency.vo.domain.DNWStatusForTrackingVoAssembler.extractDNWStatus(domainFactory, valueObject.getCurrentStatus(), domMap));
return domainObject;
}
}
| agpl-3.0 |
open-health-hub/openMAXIMS | openmaxims_workspace/DomainObjects/src/ims/core/admin/pas/domain/objects/AllocatedWardHistory.java | 13658 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
/*
* This code was generated
* Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved.
* IMS Development Environment (version 1.80 build 5007.25751)
* WARNING: DO NOT MODIFY the content of this file
* Generated: 16/04/2014, 12:34
*
*/
package ims.core.admin.pas.domain.objects;
/**
*
* @author Neil McAnaspie
* Generated.
*/
public class AllocatedWardHistory extends ims.domain.DomainObject implements ims.domain.SystemInformationRetainer, java.io.Serializable {
public static final int CLASSID = 1014100015;
private static final long serialVersionUID = 1014100015L;
public static final String CLASSVERSION = "${ClassVersion}";
@Override
public boolean shouldCapQuery()
{
return true;
}
/** Allocated Ward */
private ims.core.resource.place.domain.objects.Location allocatedWard;
/** Allocated Ward Date Time */
private java.util.Date allocatedWardDateTime;
/** User who allocated the ward */
private ims.core.configuration.domain.objects.AppUser allocatingUser;
/** SystemInformation */
private ims.domain.SystemInformation systemInformation = new ims.domain.SystemInformation();
public AllocatedWardHistory (Integer id, int ver)
{
super(id, ver);
}
public AllocatedWardHistory ()
{
super();
}
public AllocatedWardHistory (Integer id, int ver, Boolean includeRecord)
{
super(id, ver, includeRecord);
}
public Class getRealDomainClass()
{
return ims.core.admin.pas.domain.objects.AllocatedWardHistory.class;
}
public ims.core.resource.place.domain.objects.Location getAllocatedWard() {
return allocatedWard;
}
public void setAllocatedWard(ims.core.resource.place.domain.objects.Location allocatedWard) {
this.allocatedWard = allocatedWard;
}
public java.util.Date getAllocatedWardDateTime() {
return allocatedWardDateTime;
}
public void setAllocatedWardDateTime(java.util.Date allocatedWardDateTime) {
this.allocatedWardDateTime = allocatedWardDateTime;
}
public ims.core.configuration.domain.objects.AppUser getAllocatingUser() {
return allocatingUser;
}
public void setAllocatingUser(ims.core.configuration.domain.objects.AppUser allocatingUser) {
this.allocatingUser = allocatingUser;
}
public ims.domain.SystemInformation getSystemInformation() {
if (systemInformation == null) systemInformation = new ims.domain.SystemInformation();
return systemInformation;
}
/**
* isConfigurationObject
* Taken from the Usage property of the business object, this method will return
* a boolean indicating whether this is a configuration object or not
* Configuration = true, Instantiation = false
*/
public static boolean isConfigurationObject()
{
if ( "Instantiation".equals("Configuration") )
return true;
else
return false;
}
public int getClassId() {
return CLASSID;
}
public String getClassVersion()
{
return CLASSVERSION;
}
public String toAuditString()
{
StringBuffer auditStr = new StringBuffer();
auditStr.append("\r\n*allocatedWard* :");
if (allocatedWard != null)
{
auditStr.append(toShortClassName(allocatedWard));
auditStr.append(allocatedWard.getId());
}
auditStr.append("; ");
auditStr.append("\r\n*allocatedWardDateTime* :");
auditStr.append(allocatedWardDateTime);
auditStr.append("; ");
auditStr.append("\r\n*allocatingUser* :");
if (allocatingUser != null)
{
auditStr.append(toShortClassName(allocatingUser));
auditStr.append(allocatingUser.getId());
}
auditStr.append("; ");
return auditStr.toString();
}
public String toXMLString()
{
return toXMLString(new java.util.HashMap());
}
public String toXMLString(java.util.HashMap domMap)
{
StringBuffer sb = new StringBuffer();
sb.append("<class type=\"" + this.getClass().getName() + "\" ");
sb.append(" id=\"" + this.getId() + "\"");
sb.append(" source=\"" + ims.configuration.EnvironmentConfig.getImportExportSourceName() + "\" ");
sb.append(" classVersion=\"" + this.getClassVersion() + "\" ");
sb.append(" component=\"" + this.getIsComponentClass() + "\" >");
if (domMap.get(this) == null)
{
domMap.put(this, this);
sb.append(this.fieldsToXMLString(domMap));
}
sb.append("</class>");
String keyClassName = "AllocatedWardHistory";
String externalSource = ims.configuration.EnvironmentConfig.getImportExportSourceName();
ims.configuration.ImportedObject impObj = (ims.configuration.ImportedObject)domMap.get(keyClassName + "_" + externalSource + "_" + this.getId());
if (impObj == null)
{
impObj = new ims.configuration.ImportedObject();
impObj.setExternalId(this.getId());
impObj.setExternalSource(externalSource);
impObj.setDomainObject(this);
impObj.setLocalId(this.getId());
impObj.setClassName(keyClassName);
domMap.put(keyClassName + "_" + externalSource + "_" + this.getId(), impObj);
}
return sb.toString();
}
public String fieldsToXMLString(java.util.HashMap domMap)
{
StringBuffer sb = new StringBuffer();
if (this.getAllocatedWard() != null)
{
sb.append("<allocatedWard>");
sb.append(this.getAllocatedWard().toXMLString(domMap));
sb.append("</allocatedWard>");
}
if (this.getAllocatedWardDateTime() != null)
{
sb.append("<allocatedWardDateTime>");
sb.append(new ims.framework.utils.DateTime(this.getAllocatedWardDateTime()).toString(ims.framework.utils.DateTimeFormat.MILLI));
sb.append("</allocatedWardDateTime>");
}
if (this.getAllocatingUser() != null)
{
sb.append("<allocatingUser>");
sb.append(this.getAllocatingUser().toXMLString(domMap));
sb.append("</allocatingUser>");
}
return sb.toString();
}
public static java.util.List fromListXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.List list, java.util.HashMap domMap) throws Exception
{
if (list == null)
list = new java.util.ArrayList();
fillListFromXMLString(list, el, factory, domMap);
return list;
}
public static java.util.Set fromSetXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.Set set, java.util.HashMap domMap) throws Exception
{
if (set == null)
set = new java.util.HashSet();
fillSetFromXMLString(set, el, factory, domMap);
return set;
}
private static void fillSetFromXMLString(java.util.Set set, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
if (el == null)
return;
java.util.List cl = el.elements("class");
int size = cl.size();
java.util.Set newSet = new java.util.HashSet();
for(int i=0; i<size; i++)
{
org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i);
AllocatedWardHistory domainObject = getAllocatedWardHistoryfromXML(itemEl, factory, domMap);
if (domainObject == null)
{
continue;
}
//Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add)
if (!set.contains(domainObject))
set.add(domainObject);
newSet.add(domainObject);
}
java.util.Set removedSet = new java.util.HashSet();
java.util.Iterator iter = set.iterator();
//Find out which objects need to be removed
while (iter.hasNext())
{
ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next();
if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o))
{
removedSet.add(o);
}
}
iter = removedSet.iterator();
//Remove the unwanted objects
while (iter.hasNext())
{
set.remove(iter.next());
}
}
private static void fillListFromXMLString(java.util.List list, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
if (el == null)
return;
java.util.List cl = el.elements("class");
int size = cl.size();
for(int i=0; i<size; i++)
{
org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i);
AllocatedWardHistory domainObject = getAllocatedWardHistoryfromXML(itemEl, factory, domMap);
if (domainObject == null)
{
continue;
}
int domIdx = list.indexOf(domainObject);
if (domIdx == -1)
{
list.add(i, domainObject);
}
else if (i != domIdx && i < list.size())
{
Object tmp = list.get(i);
list.set(i, list.get(domIdx));
list.set(domIdx, tmp);
}
}
//Remove all ones in domList where index > voCollection.size() as these should
//now represent the ones removed from the VO collection. No longer referenced.
int i1=list.size();
while (i1 > size)
{
list.remove(i1-1);
i1=list.size();
}
}
public static AllocatedWardHistory getAllocatedWardHistoryfromXML(String xml, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
org.dom4j.Document doc = new org.dom4j.io.SAXReader().read(new org.xml.sax.InputSource(xml));
return getAllocatedWardHistoryfromXML(doc.getRootElement(), factory, domMap);
}
public static AllocatedWardHistory getAllocatedWardHistoryfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
if (el == null)
return null;
String className = el.attributeValue("type");
if (!AllocatedWardHistory.class.getName().equals(className))
{
Class clz = Class.forName(className);
if (!AllocatedWardHistory.class.isAssignableFrom(clz))
throw new Exception("Element of type = " + className + " cannot be imported using the AllocatedWardHistory class");
String shortClassName = className.substring(className.lastIndexOf(".")+1);
String methodName = "get" + shortClassName + "fromXML";
java.lang.reflect.Method m = clz.getMethod(methodName, new Class[]{org.dom4j.Element.class, ims.domain.DomainFactory.class, java.util.HashMap.class});
return (AllocatedWardHistory)m.invoke(null, new Object[]{el, factory, domMap});
}
String impVersion = el.attributeValue("classVersion");
if(!impVersion.equals(AllocatedWardHistory.CLASSVERSION))
{
throw new Exception("Incompatible class structure found. Cannot import instance.");
}
AllocatedWardHistory ret = null;
int extId = Integer.parseInt(el.attributeValue("id"));
String externalSource = el.attributeValue("source");
ret = (AllocatedWardHistory)factory.getImportedDomainObject(AllocatedWardHistory.class, externalSource, extId);
if (ret == null)
{
ret = new AllocatedWardHistory();
}
String keyClassName = "AllocatedWardHistory";
ims.configuration.ImportedObject impObj = (ims.configuration.ImportedObject)domMap.get(keyClassName + "_" + externalSource + "_" + extId);
if (impObj != null)
{
return (AllocatedWardHistory)impObj.getDomainObject();
}
else
{
impObj = new ims.configuration.ImportedObject();
impObj.setExternalId(extId);
impObj.setExternalSource(externalSource);
impObj.setDomainObject(ret);
domMap.put(keyClassName + "_" + externalSource + "_" + extId, impObj);
}
fillFieldsfromXML(el, factory, ret, domMap);
return ret;
}
public static void fillFieldsfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, AllocatedWardHistory obj, java.util.HashMap domMap) throws Exception
{
org.dom4j.Element fldEl;
fldEl = el.element("allocatedWard");
if(fldEl != null)
{
fldEl = fldEl.element("class");
obj.setAllocatedWard(ims.core.resource.place.domain.objects.Location.getLocationfromXML(fldEl, factory, domMap));
}
fldEl = el.element("allocatedWardDateTime");
if(fldEl != null)
{
obj.setAllocatedWardDateTime(new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").parse(fldEl.getTextTrim()));
}
fldEl = el.element("allocatingUser");
if(fldEl != null)
{
fldEl = fldEl.element("class");
obj.setAllocatingUser(ims.core.configuration.domain.objects.AppUser.getAppUserfromXML(fldEl, factory, domMap));
}
}
public static String[] getCollectionFields()
{
return new String[]{
};
}
public static class FieldNames
{
public static final String ID = "id";
public static final String AllocatedWard = "allocatedWard";
public static final String AllocatedWardDateTime = "allocatedWardDateTime";
public static final String AllocatingUser = "allocatingUser";
}
}
| agpl-3.0 |
open-health-hub/openMAXIMS | openmaxims_workspace/Core/src/ims/core/domain/PatientDocumentErrors.java | 1811 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.core.domain;
// Generated from form domain impl
public interface PatientDocumentErrors extends ims.domain.DomainInterface
{
}
| agpl-3.0 |
marcocast/scheduling | rm/rm-client/src/main/java/org/ow2/proactive/resourcemanager/frontend/RMConnection.java | 4454 | /*
* ProActive Parallel Suite(TM):
* The Open Source library for parallel and distributed
* Workflows & Scheduling, Orchestration, Cloud Automation
* and Big Data Analysis on Enterprise Grids & Clouds.
*
* Copyright (c) 2007 - 2017 ActiveEon
* Contact: contact@activeeon.com
*
* This library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation: version 3 of
* the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*/
package org.ow2.proactive.resourcemanager.frontend;
import org.apache.log4j.Logger;
import org.objectweb.proactive.annotation.PublicAPI;
import org.objectweb.proactive.core.util.URIBuilder;
import org.ow2.proactive.authentication.Connection;
import org.ow2.proactive.resourcemanager.authentication.RMAuthentication;
import org.ow2.proactive.resourcemanager.common.RMConstants;
import org.ow2.proactive.resourcemanager.exception.RMException;
/**
* This class provides means to connect to an existing RM.
* As a result of connection returns {@link RMAuthentication} for further authentication.
*
* @author The ProActive Team
* @since ProActive Scheduling 0.9
*
*/
@PublicAPI
public class RMConnection extends Connection<RMAuthentication> {
private static RMConnection instance;
private RMConnection() {
super(RMAuthentication.class);
}
public Logger getLogger() {
return Logger.getLogger(RMConnection.class);
}
public static synchronized RMConnection getInstance() {
if (instance == null) {
instance = new RMConnection();
}
return instance;
}
/**
* Returns the {@link RMAuthentication} from the specified
* URL. If resource manager is not available or initializing throws an exception.
*
* @param url the URL of the resource manager to join.
* @return the resource manager authentication at the specified URL.
* @throws RMException
* thrown if the connection to the resource manager cannot be
* established.
*/
public static RMAuthentication join(String url) throws RMException {
try {
return getInstance().connect(normalizeRM(url));
} catch (Exception e) {
throw new RMException("Cannot join the Resource Manager at " + url + " due to " + e.getMessage(), e);
}
}
/**
* Connects to the resource manager using given URL. The current thread will be block until
* connection established or an error occurs.
*/
public static RMAuthentication waitAndJoin(String url) throws RMException {
return waitAndJoin(url, 0);
}
/**
* Connects to the resource manager with a specified timeout value. A timeout of
* zero is interpreted as an infinite timeout. The connection will then
* block until established or an error occurs.
*/
public static RMAuthentication waitAndJoin(String url, long timeout) throws RMException {
try {
return getInstance().waitAndConnect(normalizeRM(url), timeout);
} catch (Exception e) {
throw new RMException("Cannot join the Resource Manager at " + url + " due to " + e.getMessage(), e);
}
}
/**
* Normalize the URL of the RESOURCE MANAGER.<br>
*
* @param url, the URL to normalize.
* @return //localhost/RM_NAME if the given url is null.<br>
* the given URL if it terminates by the RM_NAME<br>
* the given URL with /RM_NAME appended if URL does not end with /<br>
* the given URL with RM_NAME appended if URL does end with /<br>
* the given URL with RM_NAME appended if URL does not end with RM_NAME
*/
private static String normalizeRM(String url) {
return URIBuilder.buildURI(Connection.normalize(url), RMConstants.NAME_ACTIVE_OBJECT_RMAUTHENTICATION)
.toString();
}
}
| agpl-3.0 |
luacs1998/MinecraftForge | src/test/java/net/minecraftforge/debug/ModelBakeEventDebug.java | 13609 | package net.minecraftforge.debug;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyInteger;
import net.minecraft.block.state.BlockState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
import net.minecraft.client.renderer.block.statemap.StateMapperBase;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.resources.model.IBakedModel;
import net.minecraft.client.resources.model.ModelResourceLocation;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.Vec3;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.client.event.ModelBakeEvent;
import net.minecraftforge.client.model.ISmartBlockModel;
import net.minecraftforge.client.model.ISmartItemModel;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.property.ExtendedBlockState;
import net.minecraftforge.common.property.IExtendedBlockState;
import net.minecraftforge.common.property.IUnlistedProperty;
import net.minecraftforge.common.property.Properties;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;
import com.google.common.primitives.Ints;
@SuppressWarnings("deprecation")
@Mod(modid = ModelBakeEventDebug.MODID, version = ModelBakeEventDebug.VERSION)
public class ModelBakeEventDebug
{
public static final String MODID = "ForgeDebugModelBakeEvent";
public static final String VERSION = "1.0";
public static final int cubeSize = 3;
private static String blockName = MODID.toLowerCase() + ":" + CustomModelBlock.name;
@SuppressWarnings("unchecked")
public static final IUnlistedProperty<Integer>[] properties = new IUnlistedProperty[6];
static
{
for(EnumFacing f : EnumFacing.values())
{
properties[f.ordinal()] = Properties.toUnlisted(PropertyInteger.create(f.getName(), 0, (1 << (cubeSize * cubeSize)) - 1));
}
}
@SidedProxy
public static CommonProxy proxy;
@EventHandler
public void preInit(FMLPreInitializationEvent event) { proxy.preInit(event); }
public static class CommonProxy
{
public void preInit(FMLPreInitializationEvent event)
{
GameRegistry.registerBlock(CustomModelBlock.instance, CustomModelBlock.name);
GameRegistry.registerTileEntity(CustomTileEntity.class, MODID.toLowerCase() + ":custom_tile_entity");
}
}
public static class ServerProxy extends CommonProxy {}
public static class ClientProxy extends CommonProxy
{
private static ModelResourceLocation blockLocation = new ModelResourceLocation(blockName, "normal");
private static ModelResourceLocation itemLocation = new ModelResourceLocation(blockName, "inventory");
@Override
public void preInit(FMLPreInitializationEvent event)
{
super.preInit(event);
Item item = Item.getItemFromBlock(CustomModelBlock.instance);
ModelLoader.setCustomModelResourceLocation(item, 0, itemLocation);
ModelLoader.setCustomStateMapper(CustomModelBlock.instance, new StateMapperBase(){
protected ModelResourceLocation getModelResourceLocation(IBlockState p_178132_1_)
{
return blockLocation;
}
});
MinecraftForge.EVENT_BUS.register(BakeEventHandler.instance);
}
}
public static class BakeEventHandler
{
public static final BakeEventHandler instance = new BakeEventHandler();
private BakeEventHandler() {};
@SubscribeEvent
public void onModelBakeEvent(ModelBakeEvent event)
{
TextureAtlasSprite base = Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite("minecraft:blocks/slime");
TextureAtlasSprite overlay = Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite("minecraft:blocks/redstone_block");
IBakedModel customModel = new CustomModel(base, overlay);
event.modelRegistry.putObject(ClientProxy.blockLocation, customModel);
event.modelRegistry.putObject(ClientProxy.itemLocation, customModel);
}
}
public static class CustomModelBlock extends BlockContainer
{
public static final CustomModelBlock instance = new CustomModelBlock();
public static final String name = "custom_model_block";
private CustomModelBlock()
{
super(Material.iron);
setCreativeTab(CreativeTabs.tabBlock);
setUnlocalizedName(MODID + ":" + name);
}
@Override
public int getRenderType() { return 3; }
@Override
public boolean isOpaqueCube() { return false; }
@Override
public boolean isFullCube() { return false; }
@Override
public boolean isVisuallyOpaque() { return false; }
@Override
public TileEntity createNewTileEntity(World world, int meta)
{
return new CustomTileEntity();
}
@Override
public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumFacing side, float hitX, float hitY, float hitZ)
{
TileEntity te = world.getTileEntity(pos);
if(te instanceof CustomTileEntity)
{
CustomTileEntity cte = (CustomTileEntity) te;
Vec3 vec = revRotate(new Vec3(hitX - .5, hitY - .5, hitZ - .5), side).addVector(.5, .5, .5);
IUnlistedProperty<Integer> property = properties[side.ordinal()];
Integer value = cte.getState().getValue(property);
if(value == null) value = 0;
value ^= (1 << ( cubeSize * ((int)(vec.xCoord * (cubeSize - .0001))) + ((int)(vec.zCoord * (cubeSize - .0001))) ));
cte.setState(cte.getState().withProperty(property, value));
world.markBlockRangeForRenderUpdate(pos, pos);
}
return true;
}
@Override
public IBlockState getExtendedState(IBlockState state, IBlockAccess world, BlockPos pos)
{
TileEntity te = world.getTileEntity(pos);
if(te instanceof CustomTileEntity)
{
CustomTileEntity cte = (CustomTileEntity) te;
return cte.getState();
}
return state;
}
@Override
protected BlockState createBlockState()
{
return new ExtendedBlockState(this, new IProperty[0], properties);
}
}
public static class CustomTileEntity extends TileEntity
{
private IExtendedBlockState state;
public CustomTileEntity() {}
public IExtendedBlockState getState()
{
if(state == null)
{
state = (IExtendedBlockState)getBlockType().getDefaultState();
}
return state;
}
public void setState(IExtendedBlockState state)
{
this.state = state;
}
}
public static class CustomModel implements IBakedModel, ISmartBlockModel, ISmartItemModel
{
private final TextureAtlasSprite base, overlay;
//private boolean hasStateSet = false;
private final IExtendedBlockState state;
public CustomModel(TextureAtlasSprite base, TextureAtlasSprite overlay)
{
this(base, overlay, null);
}
public CustomModel(TextureAtlasSprite base, TextureAtlasSprite overlay, IExtendedBlockState state)
{
this.base = base;
this.overlay = overlay;
this.state = state;
}
@Override
public List<BakedQuad> getFaceQuads(EnumFacing side)
{
return Collections.emptyList();
}
private int[] vertexToInts(float x, float y, float z, int color, TextureAtlasSprite texture, float u, float v)
{
return new int[] {
Float.floatToRawIntBits(x),
Float.floatToRawIntBits(y),
Float.floatToRawIntBits(z),
color,
Float.floatToRawIntBits(texture.getInterpolatedU(u)),
Float.floatToRawIntBits(texture.getInterpolatedV(v)),
0
};
}
private BakedQuad createSidedBakedQuad(float x1, float x2, float z1, float z2, float y, TextureAtlasSprite texture, EnumFacing side)
{
Vec3 v1 = rotate(new Vec3(x1 - .5, y - .5, z1 - .5), side).addVector(.5, .5, .5);
Vec3 v2 = rotate(new Vec3(x1 - .5, y - .5, z2 - .5), side).addVector(.5, .5, .5);
Vec3 v3 = rotate(new Vec3(x2 - .5, y - .5, z2 - .5), side).addVector(.5, .5, .5);
Vec3 v4 = rotate(new Vec3(x2 - .5, y - .5, z1 - .5), side).addVector(.5, .5, .5);
return new BakedQuad(Ints.concat(
vertexToInts((float)v1.xCoord, (float)v1.yCoord, (float)v1.zCoord, -1, texture, 0, 0),
vertexToInts((float)v2.xCoord, (float)v2.yCoord, (float)v2.zCoord, -1, texture, 0, 16),
vertexToInts((float)v3.xCoord, (float)v3.yCoord, (float)v3.zCoord, -1, texture, 16, 16),
vertexToInts((float)v4.xCoord, (float)v4.yCoord, (float)v4.zCoord, -1, texture, 16, 0)
), -1, side);
}
@Override
public List<BakedQuad> getGeneralQuads()
{
int len = cubeSize * 5 + 1;
List<BakedQuad> ret = new ArrayList<BakedQuad>();
for(EnumFacing f : EnumFacing.values())
{
ret.add(createSidedBakedQuad(0, 1, 0, 1, 1, base, f));
for(int i = 0; i < cubeSize; i++)
{
for(int j = 0; j < cubeSize; j++)
{
if(state != null)
{
Integer value = state.getValue(properties[f.ordinal()]);
if(value != null && (value & (1 << (i * cubeSize + j))) != 0)
{
ret.add(createSidedBakedQuad((float)(1 + i * 5) / len, (float)(5 + i * 5) / len, (float)(1 + j * 5) / len, (float)(5 + j * 5) / len, 1.0001f, overlay, f));
}
}
}
}
}
return ret;
}
@Override
public boolean isGui3d() { return true; }
@Override
public boolean isAmbientOcclusion() { return true; }
@Override
public boolean isBuiltInRenderer() { return false; }
@Override
public TextureAtlasSprite getParticleTexture() { return this.base; }
@Override
public ItemCameraTransforms getItemCameraTransforms()
{
return ItemCameraTransforms.DEFAULT;
}
@Override
public IBakedModel handleBlockState(IBlockState state)
{
return new CustomModel(base, overlay, (IExtendedBlockState)state);
}
@Override
public IBakedModel handleItemState(ItemStack stack)
{
IExtendedBlockState itemState = ((IExtendedBlockState)CustomModelBlock.instance.getDefaultState()).withProperty(properties[1], (1 << (cubeSize * cubeSize)) - 1);
return new CustomModel(base, overlay, itemState);
}
}
private static Vec3 rotate(Vec3 vec, EnumFacing side)
{
switch(side)
{
case DOWN: return new Vec3( vec.xCoord, -vec.yCoord, -vec.zCoord);
case UP: return new Vec3( vec.xCoord, vec.yCoord, vec.zCoord);
case NORTH: return new Vec3( vec.xCoord, vec.zCoord, -vec.yCoord);
case SOUTH: return new Vec3( vec.xCoord, -vec.zCoord, vec.yCoord);
case WEST: return new Vec3(-vec.yCoord, vec.xCoord, vec.zCoord);
case EAST: return new Vec3( vec.yCoord, -vec.xCoord, vec.zCoord);
}
return null;
}
private static Vec3 revRotate(Vec3 vec, EnumFacing side)
{
switch(side)
{
case DOWN: return new Vec3( vec.xCoord, -vec.yCoord, -vec.zCoord);
case UP: return new Vec3( vec.xCoord, vec.yCoord, vec.zCoord);
case NORTH: return new Vec3( vec.xCoord, -vec.zCoord, vec.yCoord);
case SOUTH: return new Vec3( vec.xCoord, vec.zCoord, -vec.yCoord);
case WEST: return new Vec3( vec.yCoord, -vec.xCoord, vec.zCoord);
case EAST: return new Vec3(-vec.yCoord, vec.xCoord, vec.zCoord);
}
return null;
}
}
| lgpl-2.1 |
tterrag1098/EnderiumPowerArmor | src/main/java/cofh/api/transport/IItemConduit.java | 1180 | package cofh.api.transport;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.ForgeDirection;
/**
* This interface is implemented on Item Conduits. Use it to attempt to eject items into an entry point.
*
* @author Zeldo Kavira, King Lemming
*
*/
public interface IItemConduit {
/**
* Insert an ItemStack into the IItemConduit. Will only accept items if there is a valid destination. This returns what is remaining of the original stack -
* a null return means that the entire stack was accepted/routed!
*
* @param from
* Orientation the item is inserted from.
* @param item
* ItemStack to be inserted. The size of this stack corresponds to the maximum amount to insert.
* @return An ItemStack representing how much is remaining after the item was inserted (or would have been, if simulated) into the Conduit.
*/
public ItemStack insertItem(ForgeDirection from, ItemStack item);
/* THE FOLLOWING WILL BE REMOVED IN 3.0.1.X */
@Deprecated
public ItemStack insertItem(ForgeDirection from, ItemStack item, boolean simulate);
@Deprecated
public ItemStack sendItems(ItemStack item, ForgeDirection from);
}
| lgpl-3.0 |
GeoinformationSystems/GeoprocessingAppstore | src/com/esri/gpt/catalog/harvest/protocols/HarvestProtocolArcIms.java | 5810 | /* See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* Esri Inc. 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 com.esri.gpt.catalog.harvest.protocols;
import com.esri.gpt.control.webharvest.IterationContext;
import com.esri.gpt.control.webharvest.client.arcims.ArcImsQueryBuilder;
import com.esri.gpt.framework.collection.StringAttributeMap;
import com.esri.gpt.framework.resource.query.QueryBuilder;
import com.esri.gpt.framework.util.Val;
/**
* ArcIMS protocol.
*/
public class HarvestProtocolArcIms extends AbstractHTTPHarvestProtocol {
// class variables =============================================================
public static final int DEFAULT_PORT_NO = 80;
// instance variables ==========================================================
/** Port number. */
private int _portNo = DEFAULT_PORT_NO;
/** Port number as string. */
private String _portNoAsString = Integer.toString(_portNo);
/** Service name. */
private String _serviceName = "";
/** Root folder. */
private String _rootFolder = "";
// constructors ================================================================
// properties ==================================================================
/**
* Gets port number.
* @return port number
*/
public int getPortNo() {
return _portNo;
}
/**
* Sets port number.
* @param portNo port number
*/
public void setPortNo(int portNo) {
_portNo = portNo >= 0 && portNo < 65536 ? portNo : DEFAULT_PORT_NO;
_portNoAsString = Integer.toString(_portNo);
}
/**
* Gets port number as string.
* @return port number as string
*/
public String getPortNoAsString() {
return _portNoAsString;
}
/**
* Sets port number as string.
* @param portNoAsString port number as string
*/
public void setPortNoAsString(String portNoAsString) {
_portNoAsString = Val.chkStr(portNoAsString);
try {
int portNo = Integer.parseInt(_portNoAsString);
if (portNo >= 0 && portNo < 65536) {
_portNo = portNo;
}
} catch (NumberFormatException ex) {
}
}
/**
* Gets service name.
* @return service name
*/
public String getServiceName() {
return _serviceName;
}
/**
* Sets servie name.
* @param serviceName service name
*/
public void setServiceName(String serviceName) {
_serviceName = Val.chkStr(serviceName);
}
/**
* Gets root folder.
* @return root folder
*/
public String getRootFolder() {
return _rootFolder;
}
/**
* Sets root folder.
* @param rootFolder root folder
*/
public void setRootFolder(String rootFolder) {
_rootFolder = Val.chkStr(rootFolder);
}
// methods =====================================================================
/**
* Gets protocol type.
* @return protocol type
* @deprecated
*/
@Override
@Deprecated
public final ProtocolType getType() {
return ProtocolType.ArcIms;
}
@Override
public String getKind() {
return "ArcIms";
}
/**
* Gets all the attributes.
* @return attributes as attribute map
*/
@Override
public StringAttributeMap extractAttributeMap() {
StringAttributeMap properties = new StringAttributeMap();
properties.set("username", encryptString(getUserName()));
properties.set("password", encryptString(getUserPassword()));
properties.set("service", getServiceName());
properties.set("port", Integer.toString(getPortNo()));
properties.set("rootFolder", getRootFolder());
return properties;
}
/**
* Gets all the attributes.
* @return attributes as attribute map
*/
@Override
public StringAttributeMap getAttributeMap() {
StringAttributeMap properties = new StringAttributeMap();
properties.set("arcims.username", getUserName());
properties.set("arcims.password", getUserPassword());
properties.set("service", getServiceName());
properties.set("port", Integer.toString(getPortNo()));
properties.set("rootFolder", getRootFolder());
return properties;
}
/**
* Sets all the attributes.
* @param attributeMap attributes as attribute map
*/
@Override
public void applyAttributeMap(StringAttributeMap attributeMap) {
setUserName(decryptString(chckAttr(attributeMap.get("username"))));
setUserPassword(decryptString(chckAttr(attributeMap.get("password"))));
setServiceName(chckAttr(attributeMap.get("service")));
setPortNo(Val.chkInt(chckAttr(attributeMap.get("port")), DEFAULT_PORT_NO));
setRootFolder(chckAttr(attributeMap.get("rootFolder")));
}
/**
* Sets all the attributes.
* @param attributeMap attributes as attribute map
*/
@Override
public void setAttributeMap(StringAttributeMap attributeMap) {
setUserName(chckAttr(attributeMap.get("arcims.username")));
setUserPassword(chckAttr(attributeMap.get("arcims.password")));
setServiceName(chckAttr(attributeMap.get("service")));
setPortNo(Val.chkInt(chckAttr(attributeMap.get("port")), DEFAULT_PORT_NO));
setRootFolder(chckAttr(attributeMap.get("rootFolder")));
}
@Override
public QueryBuilder newQueryBuilder(IterationContext context, String url) {
return new ArcImsQueryBuilder(context, this, url);
}
}
| apache-2.0 |
googleapis/google-api-java-client-services | clients/google-api-services-cloudkms/v1/1.31.0/com/google/api/services/cloudkms/v1/model/RestoreCryptoKeyVersionRequest.java | 1679 | /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.cloudkms.v1.model;
/**
* Request message for KeyManagementService.RestoreCryptoKeyVersion.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Cloud Key Management Service (KMS) API. For a
* detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class RestoreCryptoKeyVersionRequest extends com.google.api.client.json.GenericJson {
@Override
public RestoreCryptoKeyVersionRequest set(String fieldName, Object value) {
return (RestoreCryptoKeyVersionRequest) super.set(fieldName, value);
}
@Override
public RestoreCryptoKeyVersionRequest clone() {
return (RestoreCryptoKeyVersionRequest) super.clone();
}
}
| apache-2.0 |
vivekkiran/digits-android | samples/app/src/main/java/com/example/app/digits/ContactsReceiver.java | 1897 | /*
* Copyright (C) 2015 Twitter, 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.example.app.digits;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import com.example.app.R;
public class ContactsReceiver extends BroadcastReceiver {
static final int NOTIFICATION_ID = 0;
@Override
public void onReceive(Context context, Intent intent) {
final NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
final Intent notifIntent = new Intent(context, FoundFriendsActivity.class);
final PendingIntent notifPendingIntent = PendingIntent.getActivity(context, 0,
notifIntent, 0);
final String notifString = context.getString(R.string.you_have_new_friends);
final Notification notification = new NotificationCompat.Builder(context)
.setContentTitle(notifString)
.setContentIntent(notifPendingIntent)
.setSmallIcon(android.R.drawable.sym_def_app_icon)
.build();
notificationManager.notify(NOTIFICATION_ID, notification);
}
}
| apache-2.0 |
shun634501730/java_source_cn | src_en/java/security/spec/ECGenParameterSpec.java | 1494 | /*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package java.security.spec;
/**
* This immutable class specifies the set of parameters used for
* generating elliptic curve (EC) domain parameters.
*
* @see AlgorithmParameterSpec
*
* @author Valerie Peng
*
* @since 1.5
*/
public class ECGenParameterSpec implements AlgorithmParameterSpec {
private String name;
/**
* Creates a parameter specification for EC parameter
* generation using a standard (or predefined) name
* {@code stdName} in order to generate the corresponding
* (precomputed) elliptic curve domain parameters. For the
* list of supported names, please consult the documentation
* of provider whose implementation will be used.
* @param stdName the standard name of the to-be-generated EC
* domain parameters.
* @exception NullPointerException if {@code stdName}
* is null.
*/
public ECGenParameterSpec(String stdName) {
if (stdName == null) {
throw new NullPointerException("stdName is null");
}
this.name = stdName;
}
/**
* Returns the standard or predefined name of the
* to-be-generated EC domain parameters.
* @return the standard or predefined name.
*/
public String getName() {
return name;
}
}
| apache-2.0 |
maheshika/wso2-synapse | modules/core/src/main/java/org/apache/synapse/rest/AbstractRESTProcessor.java | 2067 | /*
* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.synapse.rest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.synapse.MessageContext;
import org.apache.synapse.SynapseException;
/**
* Abstract representation of an entity that can process REST messages. The caller can
* first invoke the canProcess method of the processor to validate whether this processor
* can process the given request or not.
*/
public abstract class AbstractRESTProcessor {
protected Log log = LogFactory.getLog(getClass());
protected String name;
public AbstractRESTProcessor(String name) {
this.name = name;
}
/**
* Check whether this processor can handle the given request
*
* @param synCtx MessageContext of the message to be processed
* @return true if the processor is suitable for handling the message
*/
abstract boolean canProcess(MessageContext synCtx);
/**
* Process the given message through this processor instance
*
* @param synCtx MessageContext of the message to be processed
*/
abstract void process(MessageContext synCtx);
protected void handleException(String msg) {
log.error(msg);
throw new SynapseException(msg);
}
protected void handleException(String msg, Exception e) {
log.error(msg, e);
throw new SynapseException(msg, e);
}
}
| apache-2.0 |
unratito/ceylon.language | runtime/com/redhat/ceylon/compiler/java/metadata/CompileTimeError.java | 449 | package com.redhat.ceylon.compiler.java.metadata;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation applied to a Java class which had a compile time error but
* got generated anyway because of error recovery.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface CompileTimeError {
}
| apache-2.0 |
ebyhr/presto | core/trino-main/src/test/java/io/trino/operator/aggregation/TestLongVarianceAggregation.java | 1904 | /*
* 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.trino.operator.aggregation;
import com.google.common.collect.ImmutableList;
import io.trino.spi.block.Block;
import io.trino.spi.block.BlockBuilder;
import io.trino.spi.type.Type;
import org.apache.commons.math3.stat.descriptive.moment.Variance;
import java.util.List;
import static io.trino.spi.type.BigintType.BIGINT;
public class TestLongVarianceAggregation
extends AbstractTestAggregationFunction
{
@Override
protected Block[] getSequenceBlocks(int start, int length)
{
BlockBuilder blockBuilder = BIGINT.createBlockBuilder(null, length);
for (int i = start; i < start + length; i++) {
BIGINT.writeLong(blockBuilder, i);
}
return new Block[] {blockBuilder.build()};
}
@Override
protected Number getExpectedValue(int start, int length)
{
if (length < 2) {
return null;
}
double[] values = new double[length];
for (int i = 0; i < length; i++) {
values[i] = start + i;
}
Variance variance = new Variance();
return variance.evaluate(values);
}
@Override
protected String getFunctionName()
{
return "variance";
}
@Override
protected List<Type> getFunctionParameterTypes()
{
return ImmutableList.of(BIGINT);
}
}
| apache-2.0 |
BUPTAnderson/apache-hive-2.1.1-src | orc/src/test/org/apache/orc/impl/TestStringRedBlackTree.java | 8010 | /**
* 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.orc.impl;
import org.apache.hadoop.io.DataOutputBuffer;
import org.apache.hadoop.io.IntWritable;
import org.apache.orc.impl.RedBlackTree;
import org.apache.orc.impl.StringRedBlackTree;
import org.junit.Test;
import java.io.IOException;
import static junit.framework.Assert.assertEquals;
/**
* Test the red-black tree with string keys.
*/
public class TestStringRedBlackTree {
/**
* Checks the red-black tree rules to make sure that we have correctly built
* a valid tree.
*
* Properties:
* 1. Red nodes must have black children
* 2. Each node must have the same black height on both sides.
*
* @param node The id of the root of the subtree to check for the red-black
* tree properties.
* @return The black-height of the subtree.
*/
private int checkSubtree(RedBlackTree tree, int node, IntWritable count
) throws IOException {
if (node == RedBlackTree.NULL) {
return 1;
}
count.set(count.get() + 1);
boolean is_red = tree.isRed(node);
int left = tree.getLeft(node);
int right = tree.getRight(node);
if (is_red) {
if (tree.isRed(left)) {
printTree(tree, "", tree.root);
throw new IllegalStateException("Left node of " + node + " is " + left +
" and both are red.");
}
if (tree.isRed(right)) {
printTree(tree, "", tree.root);
throw new IllegalStateException("Right node of " + node + " is " +
right + " and both are red.");
}
}
int left_depth = checkSubtree(tree, left, count);
int right_depth = checkSubtree(tree, right, count);
if (left_depth != right_depth) {
printTree(tree, "", tree.root);
throw new IllegalStateException("Lopsided tree at node " + node +
" with depths " + left_depth + " and " + right_depth);
}
if (is_red) {
return left_depth;
} else {
return left_depth + 1;
}
}
/**
* Checks the validity of the entire tree. Also ensures that the number of
* nodes visited is the same as the size of the set.
*/
void checkTree(RedBlackTree tree) throws IOException {
IntWritable count = new IntWritable(0);
if (tree.isRed(tree.root)) {
printTree(tree, "", tree.root);
throw new IllegalStateException("root is red");
}
checkSubtree(tree, tree.root, count);
if (count.get() != tree.size) {
printTree(tree, "", tree.root);
throw new IllegalStateException("Broken tree! visited= " + count.get() +
" size=" + tree.size);
}
}
void printTree(RedBlackTree tree, String indent, int node
) throws IOException {
if (node == RedBlackTree.NULL) {
System.err.println(indent + "NULL");
} else {
System.err.println(indent + "Node " + node + " color " +
(tree.isRed(node) ? "red" : "black"));
printTree(tree, indent + " ", tree.getLeft(node));
printTree(tree, indent + " ", tree.getRight(node));
}
}
private static class MyVisitor implements StringRedBlackTree.Visitor {
private final String[] words;
private final int[] order;
private final DataOutputBuffer buffer = new DataOutputBuffer();
int current = 0;
MyVisitor(String[] args, int[] order) {
words = args;
this.order = order;
}
@Override
public void visit(StringRedBlackTree.VisitorContext context
) throws IOException {
String word = context.getText().toString();
assertEquals("in word " + current, words[current], word);
assertEquals("in word " + current, order[current],
context.getOriginalPosition());
buffer.reset();
context.writeBytes(buffer);
assertEquals(word, new String(buffer.getData(),0,buffer.getLength()));
current += 1;
}
}
void checkContents(StringRedBlackTree tree, int[] order,
String... params
) throws IOException {
tree.visit(new MyVisitor(params, order));
}
StringRedBlackTree buildTree(String... params) throws IOException {
StringRedBlackTree result = new StringRedBlackTree(1000);
for(String word: params) {
result.add(word);
checkTree(result);
}
return result;
}
@Test
public void test1() throws Exception {
StringRedBlackTree tree = new StringRedBlackTree(5);
assertEquals(0, tree.getSizeInBytes());
checkTree(tree);
assertEquals(0, tree.add("owen"));
checkTree(tree);
assertEquals(1, tree.add("ashutosh"));
checkTree(tree);
assertEquals(0, tree.add("owen"));
checkTree(tree);
assertEquals(2, tree.add("alan"));
checkTree(tree);
assertEquals(2, tree.add("alan"));
checkTree(tree);
assertEquals(1, tree.add("ashutosh"));
checkTree(tree);
assertEquals(3, tree.add("greg"));
checkTree(tree);
assertEquals(4, tree.add("eric"));
checkTree(tree);
assertEquals(5, tree.add("arun"));
checkTree(tree);
assertEquals(6, tree.size());
checkTree(tree);
assertEquals(6, tree.add("eric14"));
checkTree(tree);
assertEquals(7, tree.add("o"));
checkTree(tree);
assertEquals(8, tree.add("ziggy"));
checkTree(tree);
assertEquals(9, tree.add("z"));
checkTree(tree);
checkContents(tree, new int[]{2,5,1,4,6,3,7,0,9,8},
"alan", "arun", "ashutosh", "eric", "eric14", "greg",
"o", "owen", "z", "ziggy");
assertEquals(32888, tree.getSizeInBytes());
// check that adding greg again bumps the count
assertEquals(3, tree.add("greg"));
assertEquals(41, tree.getCharacterSize());
// add some more strings to test the different branches of the
// rebalancing
assertEquals(10, tree.add("zak"));
checkTree(tree);
assertEquals(11, tree.add("eric1"));
checkTree(tree);
assertEquals(12, tree.add("ash"));
checkTree(tree);
assertEquals(13, tree.add("harry"));
checkTree(tree);
assertEquals(14, tree.add("john"));
checkTree(tree);
tree.clear();
checkTree(tree);
assertEquals(0, tree.getSizeInBytes());
assertEquals(0, tree.getCharacterSize());
}
@Test
public void test2() throws Exception {
StringRedBlackTree tree =
buildTree("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
"m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z");
assertEquals(26, tree.size());
checkContents(tree, new int[]{0,1,2, 3,4,5, 6,7,8, 9,10,11, 12,13,14,
15,16,17, 18,19,20, 21,22,23, 24,25},
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j","k", "l", "m", "n", "o",
"p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z");
}
@Test
public void test3() throws Exception {
StringRedBlackTree tree =
buildTree("z", "y", "x", "w", "v", "u", "t", "s", "r", "q", "p", "o", "n",
"m", "l", "k", "j", "i", "h", "g", "f", "e", "d", "c", "b", "a");
assertEquals(26, tree.size());
checkContents(tree, new int[]{25,24,23, 22,21,20, 19,18,17, 16,15,14,
13,12,11, 10,9,8, 7,6,5, 4,3,2, 1,0},
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o",
"p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z");
}
}
| apache-2.0 |
atishagrawal/cw-android | Service/FakePlayer/src/com/commonsware/android/fakeplayer/FakePlayer.java | 1352 | /***
Copyright (c) 2008-2012 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License.
From _The Busy Coder's Guide to Android Development_
http://commonsware.com/Android
*/
package com.commonsware.android.fakeplayer;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class FakePlayer extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void startPlayer(View v) {
Intent i=new Intent(this, PlayerService.class);
i.putExtra(PlayerService.EXTRA_PLAYLIST, "main");
i.putExtra(PlayerService.EXTRA_SHUFFLE, true);
startService(i);
}
public void stopPlayer(View v) {
stopService(new Intent(this, PlayerService.class));
}
}
| apache-2.0 |
electrum/presto | core/trino-main/src/test/java/io/trino/operator/aggregation/TestApproximateCountDistinctAggregations.java | 2695 | /*
* 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.trino.operator.aggregation;
import org.testng.annotations.Test;
import static io.trino.operator.aggregation.ApproximateCountDistinctAggregation.standardErrorToBuckets;
import static io.trino.spi.StandardErrorCode.INVALID_FUNCTION_ARGUMENT;
import static io.trino.testing.assertions.TrinoExceptionAssert.assertTrinoExceptionThrownBy;
import static org.testng.Assert.assertEquals;
public class TestApproximateCountDistinctAggregations
{
@Test
public void testStandardErrorToBuckets()
{
assertEquals(standardErrorToBuckets(0.0326), 1024);
assertEquals(standardErrorToBuckets(0.0325), 1024);
assertEquals(standardErrorToBuckets(0.0324), 2048);
assertEquals(standardErrorToBuckets(0.0231), 2048);
assertEquals(standardErrorToBuckets(0.0230), 2048);
assertEquals(standardErrorToBuckets(0.0229), 4096);
assertEquals(standardErrorToBuckets(0.0164), 4096);
assertEquals(standardErrorToBuckets(0.0163), 4096);
assertEquals(standardErrorToBuckets(0.0162), 8192);
assertEquals(standardErrorToBuckets(0.0116), 8192);
assertEquals(standardErrorToBuckets(0.0115), 8192);
assertEquals(standardErrorToBuckets(0.0114), 16384);
assertEquals(standardErrorToBuckets(0.008126), 16384);
assertEquals(standardErrorToBuckets(0.008125), 16384);
assertEquals(standardErrorToBuckets(0.008124), 32768);
assertEquals(standardErrorToBuckets(0.00576), 32768);
assertEquals(standardErrorToBuckets(0.00575), 32768);
assertEquals(standardErrorToBuckets(0.00574), 65536);
assertEquals(standardErrorToBuckets(0.0040626), 65536);
assertEquals(standardErrorToBuckets(0.0040625), 65536);
}
@Test
public void testStandardErrorToBucketsBounds()
{
// Lower bound
assertTrinoExceptionThrownBy(() -> standardErrorToBuckets(0.0040624))
.hasErrorCode(INVALID_FUNCTION_ARGUMENT);
// Upper bound
assertTrinoExceptionThrownBy(() -> standardErrorToBuckets(0.26001))
.hasErrorCode(INVALID_FUNCTION_ARGUMENT);
}
}
| apache-2.0 |
pwz3n0/presto | presto-raptor/src/test/java/com/facebook/presto/raptor/TestRaptorDistributedQueries.java | 3260 | /*
* 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.raptor;
import com.facebook.presto.testing.MaterializedResult;
import com.facebook.presto.testing.MaterializedRow;
import com.facebook.presto.tests.AbstractTestDistributedQueries;
import com.google.common.collect.ImmutableList;
import org.testng.annotations.Test;
import java.util.List;
import java.util.UUID;
import static com.facebook.presto.raptor.RaptorQueryRunner.createRaptorQueryRunner;
import static com.facebook.presto.raptor.RaptorQueryRunner.createSampledSession;
import static com.facebook.presto.spi.type.BigintType.BIGINT;
import static com.facebook.presto.spi.type.DateType.DATE;
import static com.facebook.presto.spi.type.VarcharType.VARCHAR;
import static io.airlift.testing.Assertions.assertInstanceOf;
import static io.airlift.tpch.TpchTable.getTables;
import static org.testng.Assert.assertEquals;
public class TestRaptorDistributedQueries
extends AbstractTestDistributedQueries
{
public TestRaptorDistributedQueries()
throws Exception
{
super(createRaptorQueryRunner(getTables()), createSampledSession());
}
@Test
public void testCreateArrayTable()
throws Exception
{
assertQuery("CREATE TABLE array_test AS SELECT ARRAY [1, 2, 3] AS c", "SELECT 1");
assertQuery("SELECT cardinality(c) FROM array_test", "SELECT 3");
assertQueryTrue("DROP TABLE array_test");
}
@Test
public void testMapTable()
throws Exception
{
assertQuery("CREATE TABLE map_test AS SELECT MAP(ARRAY [1, 2, 3], ARRAY ['hi', 'bye', NULL]) AS c", "SELECT 1");
assertQuery("SELECT c[1] FROM map_test", "SELECT 'hi'");
assertQuery("SELECT c[3] FROM map_test", "SELECT NULL");
assertQueryTrue("DROP TABLE map_test");
}
@Test
public void testShardUuidHiddenColumn()
throws Exception
{
assertQuery("CREATE TABLE test_shard_uuid AS " + "SELECT orderdate, orderkey FROM orders", "SELECT count(*) FROM orders");
MaterializedResult actualResults = computeActual("SELECT *, \"$shard_uuid\" FROM test_shard_uuid");
assertEquals(actualResults.getTypes(), ImmutableList.of(DATE, BIGINT, VARCHAR));
List<MaterializedRow> actualRows = actualResults.getMaterializedRows();
for (MaterializedRow row : actualRows) {
Object uuid = row.getField(2);
assertInstanceOf(uuid, String.class);
// check that the string can be parsed into a UUID
UUID.fromString((String) uuid);
}
}
@Override
public void testAddColumn()
throws Exception
{
// Raptor currently does not support add column
}
}
| apache-2.0 |
gabby2212/gs-collections | collections/src/main/java/com/gs/collections/impl/multimap/list/MultiReaderFastListMultimap.java | 4667 | /*
* Copyright 2014 Goldman Sachs.
*
* 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.gs.collections.impl.multimap.list;
import java.io.Externalizable;
import com.gs.collections.api.block.predicate.Predicate2;
import com.gs.collections.api.list.MutableList;
import com.gs.collections.api.map.MutableMap;
import com.gs.collections.api.multimap.Multimap;
import com.gs.collections.api.multimap.bag.MutableBagMultimap;
import com.gs.collections.api.tuple.Pair;
import com.gs.collections.impl.list.mutable.MultiReaderFastList;
import com.gs.collections.impl.map.mutable.ConcurrentHashMap;
import com.gs.collections.impl.utility.Iterate;
public final class MultiReaderFastListMultimap<K, V>
extends AbstractMutableListMultimap<K, V> implements Externalizable
{
private static final long serialVersionUID = 1L;
// Default from FastList
private static final int DEFAULT_CAPACITY = 1;
private int initialListCapacity;
public MultiReaderFastListMultimap()
{
this.initialListCapacity = DEFAULT_CAPACITY;
}
public MultiReaderFastListMultimap(int distinctKeys, int valuesPerKey)
{
super(Math.max(distinctKeys * 2, 16));
if (distinctKeys < 0 || valuesPerKey < 0)
{
throw new IllegalArgumentException("Both arguments must be positive.");
}
this.initialListCapacity = valuesPerKey;
}
public MultiReaderFastListMultimap(Multimap<? extends K, ? extends V> multimap)
{
this(
multimap.keysView().size(),
multimap instanceof MultiReaderFastListMultimap
? ((MultiReaderFastListMultimap<?, ?>) multimap).initialListCapacity
: DEFAULT_CAPACITY);
this.putAll(multimap);
}
public MultiReaderFastListMultimap(Pair<K, V>... pairs)
{
super(pairs);
}
public MultiReaderFastListMultimap(Iterable<Pair<K, V>> inputIterable)
{
super(inputIterable);
}
public static <K, V> MultiReaderFastListMultimap<K, V> newMultimap()
{
return new MultiReaderFastListMultimap<K, V>();
}
public static <K, V> MultiReaderFastListMultimap<K, V> newMultimap(Multimap<? extends K, ? extends V> multimap)
{
return new MultiReaderFastListMultimap<K, V>(multimap);
}
public static <K, V> MultiReaderFastListMultimap<K, V> newMultimap(Pair<K, V>... pairs)
{
return new MultiReaderFastListMultimap<K, V>(pairs);
}
public static <K, V> MultiReaderFastListMultimap<K, V> newMultimap(Iterable<Pair<K, V>> inputIterable)
{
return new MultiReaderFastListMultimap<K, V>(inputIterable);
}
@Override
protected MutableMap<K, MutableList<V>> createMap()
{
return ConcurrentHashMap.newMap();
}
@Override
protected MutableMap<K, MutableList<V>> createMapWithKeyCount(int keyCount)
{
return ConcurrentHashMap.newMap(keyCount);
}
@Override
protected MutableList<V> createCollection()
{
return MultiReaderFastList.newList(this.initialListCapacity);
}
public MultiReaderFastListMultimap<K, V> newEmpty()
{
return new MultiReaderFastListMultimap<K, V>();
}
public MutableBagMultimap<V, K> flip()
{
return Iterate.flip(this);
}
public FastListMultimap<K, V> selectKeysValues(Predicate2<? super K, ? super V> predicate)
{
return this.selectKeysValues(predicate, FastListMultimap.<K, V>newMultimap());
}
public FastListMultimap<K, V> rejectKeysValues(Predicate2<? super K, ? super V> predicate)
{
return this.rejectKeysValues(predicate, FastListMultimap.<K, V>newMultimap());
}
public FastListMultimap<K, V> selectKeysMultiValues(Predicate2<? super K, ? super Iterable<V>> predicate)
{
return this.selectKeysMultiValues(predicate, FastListMultimap.<K, V>newMultimap());
}
public FastListMultimap<K, V> rejectKeysMultiValues(Predicate2<? super K, ? super Iterable<V>> predicate)
{
return this.rejectKeysMultiValues(predicate, FastListMultimap.<K, V>newMultimap());
}
}
| apache-2.0 |
rmsamitha/product-pc | modules/components/analytics/core/generic/org.wso2.carbon.pc.analytics.core.generic/src/main/java/org/wso2/carbon/pc/analytics/core/generic/internal/AnalyticsServiceComponent.java | 2302 | /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) 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 org.wso2.carbon.pc.analytics.core.generic.internal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.pc.core.ProcessCenterService;
import static org.wso2.carbon.pc.analytics.core.generic.internal.AnalyticsServerHolder.getInstance;
/**
* @scr.component name="org.wso2.carbon.pc.analytics.core.kpi.internal.PCAnalticsServiceComponent" immediate="true"
* @scr.reference name="process.center" interface="org.wso2.carbon.pc.core.ProcessCenterService"
* cardinality="1..1" policy="dynamic" bind="setProcessCenter" unbind="unsetProcessCenter"
*/
public class AnalyticsServiceComponent {
private static Log log = LogFactory.getLog(AnalyticsServiceComponent.class);
protected void activate(ComponentContext ctxt) {
log.info("Initializing the Process Center Analytics component");
}
protected void deactivate(ComponentContext ctxt) {
log.info("Stopping the Process Center Analytics core component");
}
protected void setProcessCenter(ProcessCenterService processCenterService) {
if (log.isDebugEnabled()) {
log.debug("ProcessCenter bound to Process Center Analytics Publisher component");
}
getInstance().setProcessCenter(processCenterService.getProcessCenter());
}
protected void unsetProcessCenter(
ProcessCenterService processCenterService) {
if (log.isDebugEnabled()) {
log.debug("ProcessCenter unbound from the Process Center Analytics Publisher component");
}
getInstance().setProcessCenter(null);
}
}
| apache-2.0 |
gmarz/elasticsearch | modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/ConvertProcessor.java | 6869 | /*
* 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 java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import static org.elasticsearch.ingest.ConfigurationUtils.newConfigurationException;
/**
* Processor that converts fields content to a different type. Supported types are: integer, float, boolean and string.
* Throws exception if the field is not there or the conversion fails.
*/
public final class ConvertProcessor extends AbstractProcessor {
enum Type {
INTEGER {
@Override
public Object convert(Object value) {
try {
return Integer.parseInt(value.toString());
} catch(NumberFormatException e) {
throw new IllegalArgumentException("unable to convert [" + value + "] to integer", e);
}
}
}, FLOAT {
@Override
public Object convert(Object value) {
try {
return Float.parseFloat(value.toString());
} catch(NumberFormatException e) {
throw new IllegalArgumentException("unable to convert [" + value + "] to float", e);
}
}
}, BOOLEAN {
@Override
public Object convert(Object value) {
if (value.toString().equalsIgnoreCase("true")) {
return true;
} else if (value.toString().equalsIgnoreCase("false")) {
return false;
} else {
throw new IllegalArgumentException("[" + value + "] is not a boolean value, cannot convert to boolean");
}
}
}, STRING {
@Override
public Object convert(Object value) {
return value.toString();
}
}, AUTO {
@Override
public Object convert(Object value) {
if (!(value instanceof String)) {
return value;
}
try {
return BOOLEAN.convert(value);
} catch (IllegalArgumentException e) { }
try {
return INTEGER.convert(value);
} catch (IllegalArgumentException e) {}
try {
return FLOAT.convert(value);
} catch (IllegalArgumentException e) {}
return value;
}
};
@Override
public String toString() {
return name().toLowerCase(Locale.ROOT);
}
public abstract Object convert(Object value);
public static Type fromString(String processorTag, String propertyName, String type) {
try {
return Type.valueOf(type.toUpperCase(Locale.ROOT));
} catch(IllegalArgumentException e) {
throw newConfigurationException(TYPE, processorTag, propertyName, "type [" + type +
"] not supported, cannot convert field.");
}
}
}
public static final String TYPE = "convert";
private final String field;
private final String targetField;
private final Type convertType;
private final boolean ignoreMissing;
ConvertProcessor(String tag, String field, String targetField, Type convertType, boolean ignoreMissing) {
super(tag);
this.field = field;
this.targetField = targetField;
this.convertType = convertType;
this.ignoreMissing = ignoreMissing;
}
String getField() {
return field;
}
String getTargetField() {
return targetField;
}
Type getConvertType() {
return convertType;
}
boolean isIgnoreMissing() {
return ignoreMissing;
}
@Override
public void execute(IngestDocument document) {
Object oldValue = null;
Object newValue;
try {
oldValue = document.getFieldValue(field, Object.class);
} catch (IllegalArgumentException e) {
if (ignoreMissing) {
return;
}
throw e;
}
if (oldValue == null && ignoreMissing) {
return;
} else if (oldValue == null) {
throw new IllegalArgumentException("Field [" + field + "] is null, cannot be converted to type [" + convertType + "]");
}
if (oldValue instanceof List) {
List<?> list = (List<?>) oldValue;
List<Object> newList = new ArrayList<>();
for (Object value : list) {
newList.add(convertType.convert(value));
}
newValue = newList;
} else {
newValue = convertType.convert(oldValue);
}
document.setFieldValue(targetField, newValue);
}
@Override
public String getType() {
return TYPE;
}
public static final class Factory implements Processor.Factory {
@Override
public ConvertProcessor create(Map<String, Processor.Factory> registry, String processorTag,
Map<String, Object> config) throws Exception {
String field = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "field");
String typeProperty = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "type");
String targetField = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "target_field", field);
Type convertType = Type.fromString(processorTag, "type", typeProperty);
boolean ignoreMissing = ConfigurationUtils.readBooleanProperty(TYPE, processorTag, config, "ignore_missing", false);
return new ConvertProcessor(processorTag, field, targetField, convertType, ignoreMissing);
}
}
}
| apache-2.0 |
kevinearls/camel | examples/camel-example-fhir-auth-tx-spring-boot/src/main/java/sample/camel/MyCamelRouter.java | 2786 | /**
* 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 sample.camel;
import java.util.ArrayList;
import java.util.List;
import org.apache.camel.LoggingLevel;
import org.apache.camel.builder.RouteBuilder;
import org.apache.http.ProtocolException;
import org.hl7.fhir.dstu3.model.Patient;
import org.springframework.stereotype.Component;
/**
* A simple Camel route that triggers from a file and pushes to a FHIR server.
* <p/>
* Use <tt>@Component</tt> to make Camel auto detect this route when starting.
*/
@Component
public class MyCamelRouter extends RouteBuilder {
@Override
public void configure() throws Exception {
from("file:{{input}}").routeId("fhir-example")
.onException(ProtocolException.class)
.handled(true)
.log(LoggingLevel.ERROR, "Error connecting to FHIR server with URL:{{serverUrl}}, please check the application.properties file ${exception.message}")
.end()
.log("Converting ${file:name}")
.unmarshal().csv()
.process(exchange -> {
List<Patient> bundle = new ArrayList<>();
@SuppressWarnings("unchecked")
List<List<String>> patients = (List<List<String>>) exchange.getIn().getBody();
for (List<String> patient: patients) {
Patient fhirPatient = new Patient();
fhirPatient.setId(patient.get(0));
fhirPatient.addName().addGiven(patient.get(1));
fhirPatient.getNameFirstRep().setFamily(patient.get(2));
bundle.add(fhirPatient);
}
exchange.getIn().setBody(bundle);
})
// create Patient in our FHIR server
.to("fhir://transaction/withResources?inBody=resources&serverUrl={{serverUrl}}&username={{serverUser}}&password={{serverPassword}}&fhirVersion={{fhirVersion}}")
// log the outcome
.log("Patients created successfully: ${body}");
}
}
| apache-2.0 |
mreutegg/jackrabbit-oak | oak-upgrade/src/main/java/org/apache/jackrabbit/oak/upgrade/cli/blob/LoopbackBlobStore.java | 4214 | /*
* 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.upgrade.cli.blob;
import org.apache.jackrabbit.oak.spi.blob.BlobOptions;
import org.apache.jackrabbit.oak.spi.blob.BlobStore;
import org.jetbrains.annotations.NotNull;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Utility BlobStore implementation to be used in tooling that can work with a
* FileStore without the need of the DataStore being present locally.
*
* Additionally instead of failing it tries to mimic and return blob reference
* passed in by <b>caller</b> by passing it back as a binary.
*
* Example: requesting <code>blobId = e7c22b994c59d9</code> it will return the
* <code>e7c22b994c59d9</code> text as a UTF-8 encoded binary file.
*/
public class LoopbackBlobStore implements BlobStore {
@Override
public String writeBlob(InputStream in) {
throw new UnsupportedOperationException();
}
@Override
public String writeBlob(InputStream in, BlobOptions options) throws IOException {
return writeBlob(in);
}
@Override
public int readBlob(String blobId, long pos, byte[] buff, int off,
int length) {
// Only a part of binary can be requested!
final int binaryLength = blobId.length();
checkBinaryOffsetInRange(pos, binaryLength);
final int effectiveSrcPos = Math.toIntExact(pos);
final int effectiveBlobLengthToBeRead = Math.min(
binaryLength - effectiveSrcPos, length);
checkForBufferOverflow(buff, off, effectiveBlobLengthToBeRead);
final byte[] blobIdBytes = getBlobIdStringAsByteArray(blobId);
System.arraycopy(blobIdBytes, effectiveSrcPos, buff, off,
effectiveBlobLengthToBeRead);
return effectiveBlobLengthToBeRead;
}
private void checkForBufferOverflow(final byte[] buff, final int off,
final int effectiveBlobLengthToBeRead) {
if (buff.length < effectiveBlobLengthToBeRead + off) {
// We cannot recover if buffer used to write is too small
throw new UnsupportedOperationException("Edge case: cannot fit " +
"blobId in a buffer (buffer too small)");
}
}
private void checkBinaryOffsetInRange(final long pos, final int binaryLength) {
if (pos > binaryLength) {
throw new IllegalArgumentException(
String.format("Offset %d out of range of %d", pos,
binaryLength));
}
}
private byte[] getBlobIdStringAsByteArray(final String blobId) {
return blobId.getBytes(StandardCharsets.UTF_8);
}
@Override
public long getBlobLength(String blobId) throws IOException {
return blobId.length();
}
@Override
public InputStream getInputStream(String blobId) throws IOException {
checkNotNull(blobId);
return new ByteArrayInputStream(getBlobIdStringAsByteArray(blobId));
}
@Override
public String getBlobId(@NotNull String reference) {
return checkNotNull(reference);
}
@Override
public String getReference(@NotNull String blobId) {
return checkNotNull(blobId);
}
@Override
public void close() throws Exception {
}
}
| apache-2.0 |
mirkosertic/Bytecoder | classlib/java.xml/src/main/resources/META-INF/modules/java.xml/classes/com/sun/org/apache/bcel/internal/generic/INVOKEINTERFACE.java | 4443 | /*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/*
* 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 com.sun.org.apache.bcel.internal.generic;
import java.io.DataOutputStream;
import java.io.IOException;
import com.sun.org.apache.bcel.internal.Const;
import com.sun.org.apache.bcel.internal.ExceptionConst;
import com.sun.org.apache.bcel.internal.classfile.ConstantPool;
import com.sun.org.apache.bcel.internal.util.ByteSequence;
/**
* INVOKEINTERFACE - Invoke interface method
* <PRE>Stack: ..., objectref, [arg1, [arg2 ...]] -> ...</PRE>
*
* @see
* <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-6.html#jvms-6.5.invokeinterface">
* The invokeinterface instruction in The Java Virtual Machine Specification</a>
*/
public final class INVOKEINTERFACE extends InvokeInstruction {
private int nargs; // Number of arguments on stack (number of stack slots), called "count" in vmspec2
/**
* Empty constructor needed for Instruction.readInstruction.
* Not to be used otherwise.
*/
INVOKEINTERFACE() {
}
public INVOKEINTERFACE(final int index, final int nargs) {
super(Const.INVOKEINTERFACE, index);
super.setLength(5);
if (nargs < 1) {
throw new ClassGenException("Number of arguments must be > 0 " + nargs);
}
this.nargs = nargs;
}
/**
* Dump instruction as byte code to stream out.
* @param out Output stream
*/
@Override
public void dump( final DataOutputStream out ) throws IOException {
out.writeByte(super.getOpcode());
out.writeShort(super.getIndex());
out.writeByte(nargs);
out.writeByte(0);
}
/**
* The <B>count</B> argument according to the Java Language Specification,
* Second Edition.
*/
public int getCount() {
return nargs;
}
/**
* Read needed data (i.e., index) from file.
*/
@Override
protected void initFromFile( final ByteSequence bytes, final boolean wide ) throws IOException {
super.initFromFile(bytes, wide);
super.setLength(5);
nargs = bytes.readUnsignedByte();
bytes.readByte(); // Skip 0 byte
}
/**
* @return mnemonic for instruction with symbolic references resolved
*/
@Override
public String toString( final ConstantPool cp ) {
return super.toString(cp) + " " + nargs;
}
@Override
public int consumeStack( final ConstantPoolGen cpg ) { // nargs is given in byte-code
return nargs; // nargs includes this reference
}
@Override
public Class<?>[] getExceptions() {
return ExceptionConst.createExceptions(ExceptionConst.EXCS.EXCS_INTERFACE_METHOD_RESOLUTION,
ExceptionConst.UNSATISFIED_LINK_ERROR,
ExceptionConst.ABSTRACT_METHOD_ERROR,
ExceptionConst.ILLEGAL_ACCESS_ERROR,
ExceptionConst.INCOMPATIBLE_CLASS_CHANGE_ERROR);
}
/**
* Call corresponding visitor method(s). The order is:
* Call visitor methods of implemented interfaces first, then
* call methods according to the class hierarchy in descending order,
* i.e., the most specific visitXXX() call comes last.
*
* @param v Visitor object
*/
@Override
public void accept( final Visitor v ) {
v.visitExceptionThrower(this);
v.visitTypedInstruction(this);
v.visitStackConsumer(this);
v.visitStackProducer(this);
v.visitLoadClass(this);
v.visitCPInstruction(this);
v.visitFieldOrMethod(this);
v.visitInvokeInstruction(this);
v.visitINVOKEINTERFACE(this);
}
}
| apache-2.0 |
jeorme/OG-Platform | projects/OG-Analytics/src/main/java/com/opengamma/analytics/math/curve/SubtractCurveSpreadFunction.java | 2054 | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.analytics.math.curve;
import com.opengamma.analytics.math.function.Function;
import com.opengamma.util.ArgumentChecker;
/**
* A function that performs subtraction on each of the constituent curves.
* <p>
* Given a number of curves $C_1(x_{i_1}, y_{i_1}) , C_2(x_{i_2}, y_{i_2}), \ldots C_n(x_{i_n}, y_{i_n})$, returns a function $F$
* that for a value $x$ will return:
* $$
* \begin{eqnarray*}
* F(x) = C_1 |_x - C_2 |_x - \ldots - C_n |_x
* \end{eqnarray*}
* $$
*/
public class SubtractCurveSpreadFunction implements CurveSpreadFunction {
/** The operation name */
public static final String NAME = "-";
/** An instance of this function */
private static final SubtractCurveSpreadFunction INSTANCE = new SubtractCurveSpreadFunction();
/**
* Gets an instance of this function
* @return The instance
*/
public static CurveSpreadFunction getInstance() {
return INSTANCE;
}
/**
* @deprecated Use {@link #getInstance()}
*/
@Deprecated
public SubtractCurveSpreadFunction() {
}
/**
* @param curves An array of curves, not null or empty
* @return A function that will find the value of each curve at the given input <i>x</i> and subtract each in turn
*/
@SuppressWarnings("unchecked")
@Override
public Function<Double, Double> evaluate(final Curve<Double, Double>... curves) {
ArgumentChecker.notEmpty(curves, "curves");
return new Function<Double, Double>() {
@Override
public Double evaluate(final Double... x) {
ArgumentChecker.notEmpty(x, "x");
final double x0 = x[0];
double y = curves[0].getYValue(x0);
for (int i = 1; i < curves.length; i++) {
y -= curves[i].getYValue(x0);
}
return y;
}
};
}
@Override
public String getOperationName() {
return NAME;
}
@Override
public String getName() {
return NAME;
}
}
| apache-2.0 |
wso2/siddhi | modules/siddhi-core/src/main/java/io/siddhi/core/query/selector/attribute/aggregator/MaxForeverAttributeAggregatorExecutor.java | 11651 | /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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 io.siddhi.core.query.selector.attribute.aggregator;
import io.siddhi.annotation.Example;
import io.siddhi.annotation.Extension;
import io.siddhi.annotation.Parameter;
import io.siddhi.annotation.ParameterOverload;
import io.siddhi.annotation.ReturnAttribute;
import io.siddhi.annotation.util.DataType;
import io.siddhi.core.config.SiddhiQueryContext;
import io.siddhi.core.exception.OperationNotSupportedException;
import io.siddhi.core.executor.ExpressionExecutor;
import io.siddhi.core.query.processor.ProcessingMode;
import io.siddhi.core.util.config.ConfigReader;
import io.siddhi.core.util.snapshot.state.State;
import io.siddhi.core.util.snapshot.state.StateFactory;
import io.siddhi.query.api.definition.Attribute;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* {@link AttributeAggregatorExecutor} to calculate max value for life time based on an event attribute.
*/
@Extension(
name = "maxForever",
namespace = "",
description = "This is the attribute aggregator to store the maximum value for a given attribute throughout " +
"the lifetime of the query regardless of any windows in-front.",
parameters = {
@Parameter(name = "arg",
description = "The value that needs to be compared to find the maximum value.",
type = {DataType.INT, DataType.LONG, DataType.DOUBLE, DataType.FLOAT},
dynamic = true)
},
parameterOverloads = {
@ParameterOverload(parameterNames = {"arg"})
},
returnAttributes = @ReturnAttribute(
description = "Returns the maximum value in the same data type as the input.",
type = {DataType.INT, DataType.LONG, DataType.DOUBLE, DataType.FLOAT}),
examples = @Example(
syntax = "from inputStream\n" +
"select maxForever(temp) as max\n" +
"insert into outputStream;",
description = "maxForever(temp) returns the maximum temp value recorded for all the events throughout" +
" the lifetime of the query."
)
)
public class MaxForeverAttributeAggregatorExecutor
extends AttributeAggregatorExecutor<MaxForeverAttributeAggregatorExecutor.MaxAggregatorState> {
private Attribute.Type returnType;
/**
* The initialization method for FunctionExecutor
*
* @param attributeExpressionExecutors are the executors of each attributes in the function
* @param processingMode query processing mode
* @param outputExpectsExpiredEvents is expired events sent as output
* @param configReader this hold the {@link MaxForeverAttributeAggregatorExecutor}
* configuration reader.
* @param siddhiQueryContext Siddhi query runtime context
*/
@Override
protected StateFactory<MaxAggregatorState> init(ExpressionExecutor[] attributeExpressionExecutors,
ProcessingMode processingMode,
boolean outputExpectsExpiredEvents, ConfigReader configReader,
SiddhiQueryContext siddhiQueryContext) {
if (attributeExpressionExecutors.length != 1) {
throw new OperationNotSupportedException("MaxForever aggregator has to have exactly 1 parameter, " +
"currently " +
attributeExpressionExecutors.length + " parameters provided");
}
returnType = attributeExpressionExecutors[0].getReturnType();
return new StateFactory<MaxAggregatorState>() {
@Override
public MaxAggregatorState createNewState() {
switch (returnType) {
case FLOAT:
return new MaxForeverAttributeAggregatorStateFloat();
case INT:
return new MaxForeverAttributeAggregatorStateInt();
case LONG:
return new MaxForeverAttributeAggregatorStateLong();
case DOUBLE:
return new MaxForeverAttributeAggregatorStateDouble();
default:
throw new OperationNotSupportedException("MaxForever not supported for " + returnType);
}
}
};
}
public Attribute.Type getReturnType() {
return returnType;
}
@Override
public Object processAdd(Object data, MaxAggregatorState state) {
if (data == null) {
return state.currentValue();
}
return state.processAdd(data);
}
@Override
public Object processAdd(Object[] data, MaxAggregatorState state) {
// will not occur
return new IllegalStateException("MaxForever cannot process data array, but found " +
Arrays.deepToString(data));
}
@Override
public Object processRemove(Object data, MaxAggregatorState state) {
if (data == null) {
return state.currentValue();
}
return state.processRemove(data);
}
@Override
public Object processRemove(Object[] data, MaxAggregatorState state) {
// will not occur
return new IllegalStateException("MaxForever cannot process data array, but found " +
Arrays.deepToString(data));
}
@Override
public Object reset(MaxAggregatorState state) {
return state.reset();
}
class MaxForeverAttributeAggregatorStateDouble extends MaxAggregatorState {
private volatile Double maxValue = null;
@Override
public Object processAdd(Object data) {
Double value = (Double) data;
if (maxValue == null || maxValue < value) {
maxValue = value;
}
return maxValue;
}
@Override
public Object processRemove(Object data) {
Double value = (Double) data;
if (maxValue == null || maxValue < value) {
maxValue = value;
}
return maxValue;
}
@Override
public Object reset() {
return maxValue;
}
@Override
public boolean canDestroy() {
return maxValue == null;
}
@Override
public Map<String, Object> snapshot() {
Map<String, Object> state = new HashMap<>();
state.put("MaxValue", maxValue);
return state;
}
@Override
public void restore(Map<String, Object> state) {
maxValue = (Double) state.get("MaxValue");
}
protected Object currentValue() {
return maxValue;
}
}
class MaxForeverAttributeAggregatorStateFloat extends MaxAggregatorState {
private volatile Float maxValue = null;
@Override
public Object processAdd(Object data) {
Float value = (Float) data;
if (maxValue == null || maxValue < value) {
maxValue = value;
}
return maxValue;
}
@Override
public Object processRemove(Object data) {
Float value = (Float) data;
if (maxValue == null || maxValue < value) {
maxValue = value;
}
return maxValue;
}
@Override
public Object reset() {
return maxValue;
}
@Override
public boolean canDestroy() {
return maxValue == null;
}
@Override
public Map<String, Object> snapshot() {
Map<String, Object> state = new HashMap<>();
state.put("MaxValue", maxValue);
return state;
}
@Override
public void restore(Map<String, Object> state) {
maxValue = (Float) state.get("MaxValue");
}
protected Object currentValue() {
return maxValue;
}
}
class MaxForeverAttributeAggregatorStateInt extends MaxAggregatorState {
private volatile Integer maxValue = null;
@Override
public Object processAdd(Object data) {
Integer value = (Integer) data;
if (maxValue == null || maxValue < value) {
maxValue = value;
}
return maxValue;
}
@Override
public Object processRemove(Object data) {
Integer value = (Integer) data;
if (maxValue == null || maxValue < value) {
maxValue = value;
}
return maxValue;
}
@Override
public Object reset() {
return maxValue;
}
@Override
public boolean canDestroy() {
return maxValue == null;
}
@Override
public Map<String, Object> snapshot() {
Map<String, Object> state = new HashMap<>();
state.put("MaxValue", maxValue);
return state;
}
@Override
public void restore(Map<String, Object> state) {
maxValue = (Integer) state.get("MaxValue");
}
protected Object currentValue() {
return maxValue;
}
}
class MaxForeverAttributeAggregatorStateLong extends MaxAggregatorState {
private volatile Long maxValue = null;
@Override
public Object processAdd(Object data) {
Long value = (Long) data;
if (maxValue == null || maxValue < value) {
maxValue = value;
}
return maxValue;
}
@Override
public Object processRemove(Object data) {
Long value = (Long) data;
if (maxValue == null || maxValue < value) {
maxValue = value;
}
return maxValue;
}
@Override
public Object reset() {
return maxValue;
}
@Override
public boolean canDestroy() {
return maxValue == null;
}
@Override
public Map<String, Object> snapshot() {
Map<String, Object> state = new HashMap<>();
state.put("MaxValue", maxValue);
return state;
}
@Override
public void restore(Map<String, Object> state) {
maxValue = (Long) state.get("MaxValue");
}
protected Object currentValue() {
return maxValue;
}
}
abstract class MaxAggregatorState extends State {
public abstract Object processAdd(Object data);
public abstract Object processRemove(Object data);
public abstract Object reset();
protected abstract Object currentValue();
}
}
| apache-2.0 |
mproch/apache-ode | bpel-dao/src/main/java/org/apache/ode/bpel/dao/BpelDAOConnectionFactoryJDBC.java | 1565 | /*
* 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.ode.bpel.dao;
import javax.sql.DataSource;
/**
* Extension of the {@link BpelDAOConnectionFactory} interface for DAOs that
* are based on J2EE/JDBC data sources.
*
* @author Maciej Szefler - m s z e f l e r @ g m a i l . c o m
*/
public interface BpelDAOConnectionFactoryJDBC extends BpelDAOConnectionFactory {
/**
* Set the managed data source (transactions tied to transaction manager).
* @param ds
*/
public void setDataSource(DataSource ds);
/**
* Set the unmanaged data source.
* @param ds
*/
public void setUnmanagedDataSource(DataSource ds);
/**
* Set the transaction manager.
* @param tm
*/
public void setTransactionManager(Object tm);
}
| apache-2.0 |
eg-eng/Priam | priam/src/main/java/com/netflix/priam/backup/IncrementalBackup.java | 3837 | /**
* Copyright 2013 Netflix, 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.netflix.priam.backup;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import com.netflix.priam.IConfiguration;
import com.netflix.priam.backup.AbstractBackupPath.BackupFileType;
import com.netflix.priam.backup.IMessageObserver.BACKUP_MESSAGE_TYPE;
import com.netflix.priam.scheduler.SimpleTimer;
import com.netflix.priam.scheduler.TaskTimer;
/*
* Incremental/SSTable backup
*/
@Singleton
public class IncrementalBackup extends AbstractBackup
{
public static final String JOBNAME = "INCR_BACKUP_THREAD";
private static final Logger logger = LoggerFactory.getLogger(IncrementalBackup.class);
private final List<String> incrementalRemotePaths = new ArrayList<String>();
static List<IMessageObserver> observers = new ArrayList<IMessageObserver>();
@Inject
public IncrementalBackup(IConfiguration config, @Named("backup")IBackupFileSystem fs, Provider<AbstractBackupPath> pathFactory)
{
super(config, fs, pathFactory);
}
@Override
public void execute() throws Exception
{
//Clearing remotePath List
incrementalRemotePaths.clear();
File dataDir = new File(config.getDataFileLocation());
if (!dataDir.exists())
{
throw new IllegalArgumentException("The configured 'data file location' does not exist: "
+ config.getDataFileLocation());
}
logger.debug("Scanning for backup in: {}", dataDir.getAbsolutePath());
for (File keyspaceDir : dataDir.listFiles())
{
if (keyspaceDir.isFile())
continue;
for (File columnFamilyDir : keyspaceDir.listFiles())
{
File backupDir = new File(columnFamilyDir, "backups");
if (!isValidBackupDir(keyspaceDir, columnFamilyDir, backupDir))
continue;
upload(backupDir, BackupFileType.SST);
}
}
if(incrementalRemotePaths.size() > 0)
{
notifyObservers();
}
}
/**
* Run every 10 Sec
*/
public static TaskTimer getTimer()
{
return new SimpleTimer(JOBNAME, 10L * 1000);
}
@Override
public String getName()
{
return JOBNAME;
}
public static void addObserver(IMessageObserver observer)
{
observers.add(observer);
}
public static void removeObserver(IMessageObserver observer)
{
observers.remove(observer);
}
public void notifyObservers()
{
for(IMessageObserver observer : observers)
{
if(observer != null)
{
logger.debug("Updating incremental observers now ...");
observer.update(BACKUP_MESSAGE_TYPE.INCREMENTAL,incrementalRemotePaths);
}
else
logger.info("Observer is Null, hence can not notify ...");
}
}
@Override
protected void addToRemotePath(String remotePath) {
incrementalRemotePaths.add(remotePath);
}
}
| apache-2.0 |
facebook/buck | test/com/facebook/buck/util/concurrent/AssertScopeExclusiveAccessTest.java | 1506 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.buck.util.concurrent;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class AssertScopeExclusiveAccessTest {
@Rule public ExpectedException expectedException = ExpectedException.none();
@Test
public void noExceptionOnSingleScope() {
AssertScopeExclusiveAccess singleThreadedAccess = new AssertScopeExclusiveAccess();
AssertScopeExclusiveAccess.Scope scope = singleThreadedAccess.scope();
scope.close();
}
@Test
public void exceptionOnTwoScopes() {
AssertScopeExclusiveAccess singleThreadedAccess = new AssertScopeExclusiveAccess();
try (AssertScopeExclusiveAccess.Scope scope = singleThreadedAccess.scope()) {
expectedException.expect(IllegalStateException.class);
AssertScopeExclusiveAccess.Scope scope2 = singleThreadedAccess.scope();
scope2.close();
}
}
}
| apache-2.0 |
narry/score | worker/worker-manager/score-worker-manager-api/src/main/java/io/cloudslang/worker/management/services/WorkerRecoveryManager.java | 810 | /*******************************************************************************
* (c) Copyright 2014 Hewlett-Packard Development Company, L.P.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License v2.0 which accompany this distribution.
*
* The Apache License is available at
* http://www.apache.org/licenses/LICENSE-2.0
*
*******************************************************************************/
package io.cloudslang.worker.management.services;
/**
* Date: 6/13/13
*
* Manages the worker internal recovery.
* Holds the current WRV (worker recovery version) as known to worker.
*/
public interface WorkerRecoveryManager {
void doRecovery();
boolean isInRecovery();
String getWRV();
void setWRV(String newWrv);
}
| apache-2.0 |
ascherbakoff/ignite | modules/core/src/main/java/org/apache/ignite/internal/managers/systemview/walker/ReentrantLockViewWalker.java | 2529 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.managers.systemview.walker;
import org.apache.ignite.spi.systemview.view.SystemViewRowAttributeWalker;
import org.apache.ignite.spi.systemview.view.datastructures.ReentrantLockView;
/**
* Generated by {@code org.apache.ignite.codegen.SystemViewRowAttributeWalkerGenerator}.
* {@link ReentrantLockView} attributes walker.
*
* @see ReentrantLockView
*/
public class ReentrantLockViewWalker implements SystemViewRowAttributeWalker<ReentrantLockView> {
/** {@inheritDoc} */
@Override public void visitAll(AttributeVisitor v) {
v.accept(0, "name", String.class);
v.accept(1, "locked", boolean.class);
v.accept(2, "hasQueuedThreads", boolean.class);
v.accept(3, "failoverSafe", boolean.class);
v.accept(4, "fair", boolean.class);
v.accept(5, "broken", boolean.class);
v.accept(6, "groupName", String.class);
v.accept(7, "groupId", int.class);
v.accept(8, "removed", boolean.class);
}
/** {@inheritDoc} */
@Override public void visitAll(ReentrantLockView row, AttributeWithValueVisitor v) {
v.accept(0, "name", String.class, row.name());
v.acceptBoolean(1, "locked", row.locked());
v.acceptBoolean(2, "hasQueuedThreads", row.hasQueuedThreads());
v.acceptBoolean(3, "failoverSafe", row.failoverSafe());
v.acceptBoolean(4, "fair", row.fair());
v.acceptBoolean(5, "broken", row.broken());
v.accept(6, "groupName", String.class, row.groupName());
v.acceptInt(7, "groupId", row.groupId());
v.acceptBoolean(8, "removed", row.removed());
}
/** {@inheritDoc} */
@Override public int count() {
return 9;
}
}
| apache-2.0 |
asedunov/intellij-community | platform/core-api/src/com/intellij/openapi/application/ApplicationInfo.java | 2993 | /*
* 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.openapi.application;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.util.BuildNumber;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.util.Calendar;
public abstract class ApplicationInfo {
public abstract Calendar getBuildDate();
public abstract BuildNumber getBuild();
public abstract String getApiVersion();
public abstract String getMajorVersion();
public abstract String getMinorVersion();
public abstract String getMicroVersion();
public abstract String getPatchVersion();
public abstract String getVersionName();
@Nullable
public abstract String getHelpURL();
/**
* Use this method to refer to the company in official contexts where it may have any legal implications.
* @see #getShortCompanyName()
* @return full name of the product vendor, e.g. 'JetBrains s.r.o.' for JetBrains products
*/
public abstract String getCompanyName();
/**
* Use this method to refer to the company in a less formal way, e.g. in UI messages or directory names.
* @see #getCompanyName()
* @return shortened name of the product vendor without 'Inc.' or similar suffixes, e.g. 'JetBrains' for JetBrains products
*/
public abstract String getShortCompanyName();
public abstract String getCompanyURL();
@Nullable
public abstract String getThirdPartySoftwareURL();
public abstract String getJetbrainsTvUrl();
public abstract String getEvalLicenseUrl();
public abstract String getKeyConversionUrl();
@Nullable
public abstract Rectangle getAboutLogoRect();
public abstract boolean hasHelp();
public abstract boolean hasContextHelp();
public abstract String getFullVersion();
public abstract String getStrictVersion();
public static ApplicationInfo getInstance() {
return ServiceManager.getService(ApplicationInfo.class);
}
public static boolean helpAvailable() {
return ApplicationManager.getApplication() != null && getInstance() != null && getInstance().hasHelp();
}
public static boolean contextHelpAvailable() {
return ApplicationManager.getApplication() != null && getInstance() != null && getInstance().hasContextHelp();
}
/** @deprecated use {@link #getBuild()} instead (to remove in IDEA 16) */
@SuppressWarnings("UnusedDeclaration")
public String getBuildNumber() {
return getBuild().asString();
}
}
| apache-2.0 |
juwi/hbase | hbase-client/src/test/java/org/apache/hadoop/hbase/client/TestSnapshotFromAdmin.java | 7718 | /**
* 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.client;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsSnapshotDoneRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsSnapshotDoneResponse;
import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.SnapshotRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.SnapshotResponse;
import org.apache.hadoop.hbase.testclassification.ClientTests;
import org.apache.hadoop.hbase.testclassification.SmallTests;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.mockito.Mockito;
import com.google.protobuf.RpcController;
/**
* Test snapshot logic from the client
*/
@Category({SmallTests.class, ClientTests.class})
public class TestSnapshotFromAdmin {
private static final Log LOG = LogFactory.getLog(TestSnapshotFromAdmin.class);
/**
* Test that the logic for doing 'correct' back-off based on exponential increase and the max-time
* passed from the server ensures the correct overall waiting for the snapshot to finish.
* @throws Exception
*/
@Test(timeout = 60000)
public void testBackoffLogic() throws Exception {
final int pauseTime = 100;
final int maxWaitTime =
HConstants.RETRY_BACKOFF[HConstants.RETRY_BACKOFF.length - 1] * pauseTime;
final int numRetries = HConstants.RETRY_BACKOFF.length;
// calculate the wait time, if we just do straight backoff (ignoring the expected time from
// master)
long ignoreExpectedTime = 0;
for (int i = 0; i < HConstants.RETRY_BACKOFF.length; i++) {
ignoreExpectedTime += HConstants.RETRY_BACKOFF[i] * pauseTime;
}
// the correct wait time, capping at the maxTime/tries + fudge room
final long time = pauseTime * 3 + ((maxWaitTime / numRetries) * 3) + 300;
assertTrue("Capped snapshot wait time isn't less that the uncapped backoff time "
+ "- further testing won't prove anything.", time < ignoreExpectedTime);
// setup the mocks
ConnectionImplementation mockConnection = Mockito
.mock(ConnectionImplementation.class);
Configuration conf = HBaseConfiguration.create();
// setup the conf to match the expected properties
conf.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, numRetries);
conf.setLong("hbase.client.pause", pauseTime);
// mock the master admin to our mock
MasterKeepAliveConnection mockMaster = Mockito.mock(MasterKeepAliveConnection.class);
Mockito.when(mockConnection.getConfiguration()).thenReturn(conf);
Mockito.when(mockConnection.getKeepAliveMasterService()).thenReturn(mockMaster);
// set the max wait time for the snapshot to complete
SnapshotResponse response = SnapshotResponse.newBuilder()
.setExpectedTimeout(maxWaitTime)
.build();
Mockito
.when(
mockMaster.snapshot((RpcController) Mockito.isNull(),
Mockito.any(SnapshotRequest.class))).thenReturn(response);
// setup the response
IsSnapshotDoneResponse.Builder builder = IsSnapshotDoneResponse.newBuilder();
builder.setDone(false);
// first five times, we return false, last we get success
Mockito.when(
mockMaster.isSnapshotDone((RpcController) Mockito.isNull(),
Mockito.any(IsSnapshotDoneRequest.class))).thenReturn(builder.build(), builder.build(),
builder.build(), builder.build(), builder.build(), builder.setDone(true).build());
// setup the admin and run the test
Admin admin = new HBaseAdmin(mockConnection);
String snapshot = "snapshot";
TableName table = TableName.valueOf("table");
// get start time
long start = System.currentTimeMillis();
admin.snapshot(snapshot, table);
long finish = System.currentTimeMillis();
long elapsed = (finish - start);
assertTrue("Elapsed time:" + elapsed + " is more than expected max:" + time, elapsed <= time);
admin.close();
}
/**
* Make sure that we validate the snapshot name and the table name before we pass anything across
* the wire
* @throws Exception on failure
*/
@Test
public void testValidateSnapshotName() throws Exception {
ConnectionImplementation mockConnection = Mockito
.mock(ConnectionImplementation.class);
Configuration conf = HBaseConfiguration.create();
Mockito.when(mockConnection.getConfiguration()).thenReturn(conf);
Admin admin = new HBaseAdmin(mockConnection);
SnapshotDescription.Builder builder = SnapshotDescription.newBuilder();
// check that invalid snapshot names fail
failSnapshotStart(admin, builder.setName(HConstants.SNAPSHOT_DIR_NAME).build());
failSnapshotStart(admin, builder.setName("-snapshot").build());
failSnapshotStart(admin, builder.setName("snapshot fails").build());
failSnapshotStart(admin, builder.setName("snap$hot").build());
failSnapshotStart(admin, builder.setName("snap:hot").build());
// check the table name also get verified
failSnapshotStart(admin, builder.setName("snapshot").setTable(".table").build());
failSnapshotStart(admin, builder.setName("snapshot").setTable("-table").build());
failSnapshotStart(admin, builder.setName("snapshot").setTable("table fails").build());
failSnapshotStart(admin, builder.setName("snapshot").setTable("tab%le").build());
// mock the master connection
MasterKeepAliveConnection master = Mockito.mock(MasterKeepAliveConnection.class);
Mockito.when(mockConnection.getKeepAliveMasterService()).thenReturn(master);
SnapshotResponse response = SnapshotResponse.newBuilder().setExpectedTimeout(0).build();
Mockito.when(
master.snapshot((RpcController) Mockito.isNull(), Mockito.any(SnapshotRequest.class)))
.thenReturn(response);
IsSnapshotDoneResponse doneResponse = IsSnapshotDoneResponse.newBuilder().setDone(true).build();
Mockito.when(
master.isSnapshotDone((RpcController) Mockito.isNull(),
Mockito.any(IsSnapshotDoneRequest.class))).thenReturn(doneResponse);
// make sure that we can use valid names
admin.snapshot(builder.setName("snapshot").setTable("table").build());
}
private void failSnapshotStart(Admin admin, SnapshotDescription snapshot) throws IOException {
try {
admin.snapshot(snapshot);
fail("Snapshot should not have succeed with name:" + snapshot.getName());
} catch (IllegalArgumentException e) {
LOG.debug("Correctly failed to start snapshot:" + e.getMessage());
}
}
}
| apache-2.0 |
tomatoKiller/Hadoop_Source_Learn | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/DFSClient.java | 95752 | /**
* 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.apache.hadoop.hdfs.DFSConfigKeys.DFS_BLOCK_SIZE_DEFAULT;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BLOCK_SIZE_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BYTES_PER_CHECKSUM_DEFAULT;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BYTES_PER_CHECKSUM_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_BLOCK_WRITE_LOCATEFOLLOWINGBLOCK_RETRIES_DEFAULT;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_BLOCK_WRITE_LOCATEFOLLOWINGBLOCK_RETRIES_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_BLOCK_WRITE_RETRIES_DEFAULT;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_BLOCK_WRITE_RETRIES_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_CACHED_CONN_RETRY_DEFAULT;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_CACHED_CONN_RETRY_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_FAILOVER_MAX_ATTEMPTS_DEFAULT;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_FAILOVER_MAX_ATTEMPTS_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_FAILOVER_SLEEPTIME_BASE_DEFAULT;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_FAILOVER_SLEEPTIME_BASE_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_FAILOVER_SLEEPTIME_MAX_DEFAULT;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_FAILOVER_SLEEPTIME_MAX_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_MAX_BLOCK_ACQUIRE_FAILURES_DEFAULT;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_MAX_BLOCK_ACQUIRE_FAILURES_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_READ_PREFETCH_SIZE_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_RETRY_WINDOW_BASE;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_SOCKET_CACHE_CAPACITY_DEFAULT;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_SOCKET_CACHE_CAPACITY_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_SOCKET_CACHE_EXPIRY_MSEC_DEFAULT;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_SOCKET_CACHE_EXPIRY_MSEC_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_SOCKET_TIMEOUT_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_USE_DN_HOSTNAME;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_USE_DN_HOSTNAME_DEFAULT;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_CACHE_DROP_BEHIND_READS;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_CACHE_DROP_BEHIND_WRITES;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_CACHE_READAHEAD;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_WRITE_EXCLUDE_NODES_CACHE_EXPIRY_INTERVAL;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_WRITE_EXCLUDE_NODES_CACHE_EXPIRY_INTERVAL_DEFAULT;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_WRITE_PACKET_SIZE_DEFAULT;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_WRITE_PACKET_SIZE_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_SOCKET_WRITE_TIMEOUT_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_REPLICATION_DEFAULT;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_REPLICATION_KEY;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.net.SocketFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.BlockLocation;
import org.apache.hadoop.fs.BlockStorageLocation;
import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
import org.apache.hadoop.fs.ContentSummary;
import org.apache.hadoop.fs.CreateFlag;
import org.apache.hadoop.fs.FileAlreadyExistsException;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FsServerDefaults;
import org.apache.hadoop.fs.FsStatus;
import org.apache.hadoop.fs.HdfsBlockLocation;
import org.apache.hadoop.fs.InvalidPathException;
import org.apache.hadoop.fs.MD5MD5CRC32CastagnoliFileChecksum;
import org.apache.hadoop.fs.MD5MD5CRC32FileChecksum;
import org.apache.hadoop.fs.MD5MD5CRC32GzipFileChecksum;
import org.apache.hadoop.fs.Options;
import org.apache.hadoop.fs.Options.ChecksumOpt;
import org.apache.hadoop.fs.ParentNotDirectoryException;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.UnresolvedLinkException;
import org.apache.hadoop.fs.VolumeId;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hdfs.client.HdfsDataInputStream;
import org.apache.hadoop.hdfs.client.HdfsDataOutputStream;
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.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.DirectoryListing;
import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
import org.apache.hadoop.hdfs.protocol.HdfsBlocksMetadata;
import org.apache.hadoop.hdfs.protocol.HdfsConstants;
import org.apache.hadoop.hdfs.protocol.HdfsConstants.DatanodeReportType;
import org.apache.hadoop.hdfs.protocol.HdfsConstants.SafeModeAction;
import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
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.SnapshotAccessControlException;
import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport;
import org.apache.hadoop.hdfs.protocol.SnapshottableDirectoryStatus;
import org.apache.hadoop.hdfs.protocol.UnresolvedPathException;
import org.apache.hadoop.hdfs.protocol.datatransfer.DataTransferEncryptor;
import org.apache.hadoop.hdfs.protocol.datatransfer.IOStreamPair;
import org.apache.hadoop.hdfs.protocol.datatransfer.Op;
import org.apache.hadoop.hdfs.protocol.datatransfer.ReplaceDatanodeOnFailure;
import org.apache.hadoop.hdfs.protocol.datatransfer.Sender;
import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BlockOpResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpBlockChecksumResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.Status;
import org.apache.hadoop.hdfs.security.token.block.DataEncryptionKey;
import org.apache.hadoop.hdfs.protocolPB.PBHelper;
import org.apache.hadoop.hdfs.security.token.block.InvalidBlockTokenException;
import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier;
import org.apache.hadoop.hdfs.server.common.HdfsServerConstants;
import org.apache.hadoop.hdfs.server.datanode.CachingStrategy;
import org.apache.hadoop.hdfs.server.namenode.NameNode;
import org.apache.hadoop.hdfs.server.namenode.SafeModeException;
import org.apache.hadoop.io.DataOutputBuffer;
import org.apache.hadoop.io.EnumSetWritable;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.MD5Hash;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.retry.LossyRetryInvocationHandler;
import org.apache.hadoop.ipc.Client;
import org.apache.hadoop.ipc.RPC;
import org.apache.hadoop.ipc.RemoteException;
import org.apache.hadoop.net.DNS;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.security.AccessControlException;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.token.SecretManager.InvalidToken;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.security.token.TokenRenewer;
import org.apache.hadoop.util.DataChecksum;
import org.apache.hadoop.util.DataChecksum.Type;
import org.apache.hadoop.util.Progressable;
import org.apache.hadoop.util.Time;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.net.InetAddresses;
/********************************************************
* DFSClient can connect to a Hadoop Filesystem and
* perform basic file tasks. It uses the ClientProtocol
* to communicate with a NameNode daemon, and connects
* directly to DataNodes to read/write block data.
*
* Hadoop DFS users should obtain an instance of
* DistributedFileSystem, which uses DFSClient to handle
* filesystem tasks.
*
********************************************************/
@InterfaceAudience.Private
public class DFSClient implements java.io.Closeable {
public static final Log LOG = LogFactory.getLog(DFSClient.class);
public static final long SERVER_DEFAULTS_VALIDITY_PERIOD = 60 * 60 * 1000L; // 1 hour
static final int TCP_WINDOW_SIZE = 128 * 1024; // 128 KB
private final Configuration conf;
private final Conf dfsClientConf;
final ClientProtocol namenode;
/* The service used for delegation tokens */
private Text dtService;
final UserGroupInformation ugi;
volatile boolean clientRunning = true;
volatile long lastLeaseRenewal;
private volatile FsServerDefaults serverDefaults;
private volatile long serverDefaultsLastUpdate;
final String clientName;
SocketFactory socketFactory;
final ReplaceDatanodeOnFailure dtpReplaceDatanodeOnFailure;
final FileSystem.Statistics stats;
private final String authority;
final PeerCache peerCache;
private Random r = new Random();
private SocketAddress[] localInterfaceAddrs;
private DataEncryptionKey encryptionKey;
private boolean shouldUseLegacyBlockReaderLocal;
private final CachingStrategy defaultReadCachingStrategy;
private final CachingStrategy defaultWriteCachingStrategy;
/**
* DFSClient configuration
*/
public static class Conf {
final int hdfsTimeout; // timeout value for a DFS operation.
final int maxFailoverAttempts;
final int failoverSleepBaseMillis;
final int failoverSleepMaxMillis;
final int maxBlockAcquireFailures;
final int confTime;
final int ioBufferSize;
final ChecksumOpt defaultChecksumOpt;
final int writePacketSize;
final int socketTimeout;
final int socketCacheCapacity;
final long socketCacheExpiry;
final long excludedNodesCacheExpiry;
/** Wait time window (in msec) if BlockMissingException is caught */
final int timeWindow;
final int nCachedConnRetry;
final int nBlockWriteRetry;
final int nBlockWriteLocateFollowingRetry;
final long defaultBlockSize;
final long prefetchSize;
final short defaultReplication;
final String taskId;
final FsPermission uMask;
final boolean connectToDnViaHostname;
final boolean getHdfsBlocksMetadataEnabled;
final int getFileBlockStorageLocationsNumThreads;
final int getFileBlockStorageLocationsTimeout;
final boolean useLegacyBlockReader;
final boolean useLegacyBlockReaderLocal;
final String domainSocketPath;
final boolean skipShortCircuitChecksums;
final int shortCircuitBufferSize;
final boolean shortCircuitLocalReads;
final boolean domainSocketDataTraffic;
final int shortCircuitStreamsCacheSize;
final long shortCircuitStreamsCacheExpiryMs;
public Conf(Configuration conf) {
// The hdfsTimeout is currently the same as the ipc timeout
hdfsTimeout = Client.getTimeout(conf);
maxFailoverAttempts = conf.getInt(
DFS_CLIENT_FAILOVER_MAX_ATTEMPTS_KEY,
DFS_CLIENT_FAILOVER_MAX_ATTEMPTS_DEFAULT);
failoverSleepBaseMillis = conf.getInt(
DFS_CLIENT_FAILOVER_SLEEPTIME_BASE_KEY,
DFS_CLIENT_FAILOVER_SLEEPTIME_BASE_DEFAULT);
failoverSleepMaxMillis = conf.getInt(
DFS_CLIENT_FAILOVER_SLEEPTIME_MAX_KEY,
DFS_CLIENT_FAILOVER_SLEEPTIME_MAX_DEFAULT);
maxBlockAcquireFailures = conf.getInt(
DFS_CLIENT_MAX_BLOCK_ACQUIRE_FAILURES_KEY,
DFS_CLIENT_MAX_BLOCK_ACQUIRE_FAILURES_DEFAULT);
confTime = conf.getInt(DFS_DATANODE_SOCKET_WRITE_TIMEOUT_KEY,
HdfsServerConstants.WRITE_TIMEOUT);
ioBufferSize = conf.getInt(
CommonConfigurationKeysPublic.IO_FILE_BUFFER_SIZE_KEY,
CommonConfigurationKeysPublic.IO_FILE_BUFFER_SIZE_DEFAULT);
defaultChecksumOpt = getChecksumOptFromConf(conf);
socketTimeout = conf.getInt(DFS_CLIENT_SOCKET_TIMEOUT_KEY,
HdfsServerConstants.READ_TIMEOUT);
/** dfs.write.packet.size is an internal config variable */
writePacketSize = conf.getInt(DFS_CLIENT_WRITE_PACKET_SIZE_KEY,
DFS_CLIENT_WRITE_PACKET_SIZE_DEFAULT);
defaultBlockSize = conf.getLongBytes(DFS_BLOCK_SIZE_KEY,
DFS_BLOCK_SIZE_DEFAULT);
defaultReplication = (short) conf.getInt(
DFS_REPLICATION_KEY, DFS_REPLICATION_DEFAULT);
taskId = conf.get("mapreduce.task.attempt.id", "NONMAPREDUCE");
socketCacheCapacity = conf.getInt(DFS_CLIENT_SOCKET_CACHE_CAPACITY_KEY,
DFS_CLIENT_SOCKET_CACHE_CAPACITY_DEFAULT);
socketCacheExpiry = conf.getLong(DFS_CLIENT_SOCKET_CACHE_EXPIRY_MSEC_KEY,
DFS_CLIENT_SOCKET_CACHE_EXPIRY_MSEC_DEFAULT);
excludedNodesCacheExpiry = conf.getLong(
DFS_CLIENT_WRITE_EXCLUDE_NODES_CACHE_EXPIRY_INTERVAL,
DFS_CLIENT_WRITE_EXCLUDE_NODES_CACHE_EXPIRY_INTERVAL_DEFAULT);
prefetchSize = conf.getLong(DFS_CLIENT_READ_PREFETCH_SIZE_KEY,
10 * defaultBlockSize);
timeWindow = conf.getInt(DFS_CLIENT_RETRY_WINDOW_BASE, 3000);
nCachedConnRetry = conf.getInt(DFS_CLIENT_CACHED_CONN_RETRY_KEY,
DFS_CLIENT_CACHED_CONN_RETRY_DEFAULT);
nBlockWriteRetry = conf.getInt(DFS_CLIENT_BLOCK_WRITE_RETRIES_KEY,
DFS_CLIENT_BLOCK_WRITE_RETRIES_DEFAULT);
nBlockWriteLocateFollowingRetry = conf.getInt(
DFS_CLIENT_BLOCK_WRITE_LOCATEFOLLOWINGBLOCK_RETRIES_KEY,
DFS_CLIENT_BLOCK_WRITE_LOCATEFOLLOWINGBLOCK_RETRIES_DEFAULT);
uMask = FsPermission.getUMask(conf);
connectToDnViaHostname = conf.getBoolean(DFS_CLIENT_USE_DN_HOSTNAME,
DFS_CLIENT_USE_DN_HOSTNAME_DEFAULT);
getHdfsBlocksMetadataEnabled = conf.getBoolean(
DFSConfigKeys.DFS_HDFS_BLOCKS_METADATA_ENABLED,
DFSConfigKeys.DFS_HDFS_BLOCKS_METADATA_ENABLED_DEFAULT);
getFileBlockStorageLocationsNumThreads = conf.getInt(
DFSConfigKeys.DFS_CLIENT_FILE_BLOCK_STORAGE_LOCATIONS_NUM_THREADS,
DFSConfigKeys.DFS_CLIENT_FILE_BLOCK_STORAGE_LOCATIONS_NUM_THREADS_DEFAULT);
getFileBlockStorageLocationsTimeout = conf.getInt(
DFSConfigKeys.DFS_CLIENT_FILE_BLOCK_STORAGE_LOCATIONS_TIMEOUT,
DFSConfigKeys.DFS_CLIENT_FILE_BLOCK_STORAGE_LOCATIONS_TIMEOUT_DEFAULT);
useLegacyBlockReader = conf.getBoolean(
DFSConfigKeys.DFS_CLIENT_USE_LEGACY_BLOCKREADER,
DFSConfigKeys.DFS_CLIENT_USE_LEGACY_BLOCKREADER_DEFAULT);
useLegacyBlockReaderLocal = conf.getBoolean(
DFSConfigKeys.DFS_CLIENT_USE_LEGACY_BLOCKREADERLOCAL,
DFSConfigKeys.DFS_CLIENT_USE_LEGACY_BLOCKREADERLOCAL_DEFAULT);
shortCircuitLocalReads = conf.getBoolean(
DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_KEY,
DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_DEFAULT);
domainSocketDataTraffic = conf.getBoolean(
DFSConfigKeys.DFS_CLIENT_DOMAIN_SOCKET_DATA_TRAFFIC,
DFSConfigKeys.DFS_CLIENT_DOMAIN_SOCKET_DATA_TRAFFIC_DEFAULT);
domainSocketPath = conf.getTrimmed(
DFSConfigKeys.DFS_DOMAIN_SOCKET_PATH_KEY,
DFSConfigKeys.DFS_DOMAIN_SOCKET_PATH_DEFAULT);
if (BlockReaderLocal.LOG.isDebugEnabled()) {
BlockReaderLocal.LOG.debug(
DFSConfigKeys.DFS_CLIENT_USE_LEGACY_BLOCKREADERLOCAL
+ " = " + useLegacyBlockReaderLocal);
BlockReaderLocal.LOG.debug(
DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_KEY
+ " = " + shortCircuitLocalReads);
BlockReaderLocal.LOG.debug(
DFSConfigKeys.DFS_CLIENT_DOMAIN_SOCKET_DATA_TRAFFIC
+ " = " + domainSocketDataTraffic);
BlockReaderLocal.LOG.debug(
DFSConfigKeys.DFS_DOMAIN_SOCKET_PATH_KEY
+ " = " + domainSocketPath);
}
skipShortCircuitChecksums = conf.getBoolean(
DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_SKIP_CHECKSUM_KEY,
DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_SKIP_CHECKSUM_DEFAULT);
shortCircuitBufferSize = conf.getInt(
DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_BUFFER_SIZE_KEY,
DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_BUFFER_SIZE_DEFAULT);
shortCircuitStreamsCacheSize = conf.getInt(
DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_STREAMS_CACHE_SIZE_KEY,
DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_STREAMS_CACHE_SIZE_DEFAULT);
shortCircuitStreamsCacheExpiryMs = conf.getLong(
DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_STREAMS_CACHE_EXPIRY_MS_KEY,
DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_STREAMS_CACHE_EXPIRY_MS_DEFAULT);
}
private DataChecksum.Type getChecksumType(Configuration conf) {
final String checksum = conf.get(
DFSConfigKeys.DFS_CHECKSUM_TYPE_KEY,
DFSConfigKeys.DFS_CHECKSUM_TYPE_DEFAULT);
try {
return DataChecksum.Type.valueOf(checksum);
} catch(IllegalArgumentException iae) {
LOG.warn("Bad checksum type: " + checksum + ". Using default "
+ DFSConfigKeys.DFS_CHECKSUM_TYPE_DEFAULT);
return DataChecksum.Type.valueOf(
DFSConfigKeys.DFS_CHECKSUM_TYPE_DEFAULT);
}
}
// Construct a checksum option from conf
private ChecksumOpt getChecksumOptFromConf(Configuration conf) {
DataChecksum.Type type = getChecksumType(conf);
int bytesPerChecksum = conf.getInt(DFS_BYTES_PER_CHECKSUM_KEY,
DFS_BYTES_PER_CHECKSUM_DEFAULT);
return new ChecksumOpt(type, bytesPerChecksum);
}
// create a DataChecksum with the default option.
private DataChecksum createChecksum() throws IOException {
return createChecksum(null);
}
private DataChecksum createChecksum(ChecksumOpt userOpt)
throws IOException {
// Fill in any missing field with the default.
ChecksumOpt myOpt = ChecksumOpt.processChecksumOpt(
defaultChecksumOpt, userOpt);
DataChecksum dataChecksum = DataChecksum.newDataChecksum(
myOpt.getChecksumType(),
myOpt.getBytesPerChecksum());
if (dataChecksum == null) {
throw new IOException("Invalid checksum type specified: "
+ myOpt.getChecksumType().name());
}
return dataChecksum;
}
}
public Conf getConf() {
return dfsClientConf;
}
Configuration getConfiguration() {
return conf;
}
/**
* A map from file names to {@link DFSOutputStream} objects
* that are currently being written by this client.
* Note that a file can only be written by a single client.
*/
private final Map<String, DFSOutputStream> filesBeingWritten
= new HashMap<String, DFSOutputStream>();
private final DomainSocketFactory domainSocketFactory;
/**
* Same as this(NameNode.getAddress(conf), conf);
* @see #DFSClient(InetSocketAddress, Configuration)
* @deprecated Deprecated at 0.21
*/
@Deprecated
public DFSClient(Configuration conf) throws IOException {
this(NameNode.getAddress(conf), conf);
}
public DFSClient(InetSocketAddress address, Configuration conf) throws IOException {
this(NameNode.getUri(address), conf);
}
/**
* Same as this(nameNodeUri, conf, null);
* @see #DFSClient(URI, Configuration, FileSystem.Statistics)
*/
public DFSClient(URI nameNodeUri, Configuration conf
) throws IOException {
this(nameNodeUri, conf, null);
}
/**
* Same as this(nameNodeUri, null, conf, stats);
* @see #DFSClient(URI, ClientProtocol, Configuration, FileSystem.Statistics)
*/
public DFSClient(URI nameNodeUri, Configuration conf,
FileSystem.Statistics stats)
throws IOException {
this(nameNodeUri, null, conf, stats);
}
/**
* Create a new DFSClient connected to the given nameNodeUri or rpcNamenode.
* If HA is enabled and a positive value is set for
* {@link DFSConfigKeys#DFS_CLIENT_TEST_DROP_NAMENODE_RESPONSE_NUM_KEY} in the
* configuration, the DFSClient will use {@link LossyRetryInvocationHandler}
* as its RetryInvocationHandler. Otherwise one of nameNodeUri or rpcNamenode
* must be null.
*/
@VisibleForTesting
public DFSClient(URI nameNodeUri, ClientProtocol rpcNamenode,
Configuration conf, FileSystem.Statistics stats)
throws IOException {
// Copy only the required DFSClient configuration
this.dfsClientConf = new Conf(conf);
this.shouldUseLegacyBlockReaderLocal =
this.dfsClientConf.useLegacyBlockReaderLocal;
if (this.dfsClientConf.useLegacyBlockReaderLocal) {
LOG.debug("Using legacy short-circuit local reads.");
}
this.conf = conf;
this.stats = stats;
this.socketFactory = NetUtils.getSocketFactory(conf, ClientProtocol.class);
this.dtpReplaceDatanodeOnFailure = ReplaceDatanodeOnFailure.get(conf);
this.ugi = UserGroupInformation.getCurrentUser();
this.authority = nameNodeUri == null? "null": nameNodeUri.getAuthority();
this.clientName = "DFSClient_" + dfsClientConf.taskId + "_" +
DFSUtil.getRandom().nextInt() + "_" + Thread.currentThread().getId();
int numResponseToDrop = conf.getInt(
DFSConfigKeys.DFS_CLIENT_TEST_DROP_NAMENODE_RESPONSE_NUM_KEY,
DFSConfigKeys.DFS_CLIENT_TEST_DROP_NAMENODE_RESPONSE_NUM_DEFAULT);
NameNodeProxies.ProxyAndInfo<ClientProtocol> proxyInfo = null;
if (numResponseToDrop > 0) {
// This case is used for testing.
LOG.warn(DFSConfigKeys.DFS_CLIENT_TEST_DROP_NAMENODE_RESPONSE_NUM_KEY
+ " is set to " + numResponseToDrop
+ ", this hacked client will proactively drop responses");
proxyInfo = NameNodeProxies.createProxyWithLossyRetryHandler(conf,
nameNodeUri, ClientProtocol.class, numResponseToDrop);
}
if (proxyInfo != null) {
this.dtService = proxyInfo.getDelegationTokenService();
this.namenode = proxyInfo.getProxy();
} else if (rpcNamenode != null) {
// This case is used for testing.
Preconditions.checkArgument(nameNodeUri == null);
this.namenode = rpcNamenode;
dtService = null;
} else {
Preconditions.checkArgument(nameNodeUri != null,
"null URI");
proxyInfo = NameNodeProxies.createProxy(conf, nameNodeUri,
ClientProtocol.class);
this.dtService = proxyInfo.getDelegationTokenService();
this.namenode = proxyInfo.getProxy();
}
// read directly from the block file if configured.
this.domainSocketFactory = new DomainSocketFactory(dfsClientConf);
String localInterfaces[] =
conf.getTrimmedStrings(DFSConfigKeys.DFS_CLIENT_LOCAL_INTERFACES);
localInterfaceAddrs = getLocalInterfaceAddrs(localInterfaces);
if (LOG.isDebugEnabled() && 0 != localInterfaces.length) {
LOG.debug("Using local interfaces [" +
Joiner.on(',').join(localInterfaces)+ "] with addresses [" +
Joiner.on(',').join(localInterfaceAddrs) + "]");
}
this.peerCache = PeerCache.getInstance(dfsClientConf.socketCacheCapacity, dfsClientConf.socketCacheExpiry);
Boolean readDropBehind = (conf.get(DFS_CLIENT_CACHE_DROP_BEHIND_READS) == null) ?
null : conf.getBoolean(DFS_CLIENT_CACHE_DROP_BEHIND_READS, false);
Long readahead = (conf.get(DFS_CLIENT_CACHE_READAHEAD) == null) ?
null : conf.getLong(DFS_CLIENT_CACHE_READAHEAD, 0);
Boolean writeDropBehind = (conf.get(DFS_CLIENT_CACHE_DROP_BEHIND_WRITES) == null) ?
null : conf.getBoolean(DFS_CLIENT_CACHE_DROP_BEHIND_WRITES, false);
this.defaultReadCachingStrategy =
new CachingStrategy(readDropBehind, readahead);
this.defaultWriteCachingStrategy =
new CachingStrategy(writeDropBehind, readahead);
}
/**
* Return the socket addresses to use with each configured
* local interface. Local interfaces may be specified by IP
* address, IP address range using CIDR notation, interface
* name (e.g. eth0) or sub-interface name (e.g. eth0:0).
* The socket addresses consist of the IPs for the interfaces
* and the ephemeral port (port 0). If an IP, IP range, or
* interface name matches an interface with sub-interfaces
* only the IP of the interface is used. Sub-interfaces can
* be used by specifying them explicitly (by IP or name).
*
* @return SocketAddresses for the configured local interfaces,
* or an empty array if none are configured
* @throws UnknownHostException if a given interface name is invalid
*/
private static SocketAddress[] getLocalInterfaceAddrs(
String interfaceNames[]) throws UnknownHostException {
List<SocketAddress> localAddrs = new ArrayList<SocketAddress>();
for (String interfaceName : interfaceNames) {
if (InetAddresses.isInetAddress(interfaceName)) {
localAddrs.add(new InetSocketAddress(interfaceName, 0));
} else if (NetUtils.isValidSubnet(interfaceName)) {
for (InetAddress addr : NetUtils.getIPs(interfaceName, false)) {
localAddrs.add(new InetSocketAddress(addr, 0));
}
} else {
for (String ip : DNS.getIPs(interfaceName, false)) {
localAddrs.add(new InetSocketAddress(ip, 0));
}
}
}
return localAddrs.toArray(new SocketAddress[localAddrs.size()]);
}
/**
* Select one of the configured local interfaces at random. We use a random
* interface because other policies like round-robin are less effective
* given that we cache connections to datanodes.
*
* @return one of the local interface addresses at random, or null if no
* local interfaces are configured
*/
SocketAddress getRandomLocalInterfaceAddr() {
if (localInterfaceAddrs.length == 0) {
return null;
}
final int idx = r.nextInt(localInterfaceAddrs.length);
final SocketAddress addr = localInterfaceAddrs[idx];
if (LOG.isDebugEnabled()) {
LOG.debug("Using local interface " + addr);
}
return addr;
}
/**
* Return the number of times the client should go back to the namenode
* to retrieve block locations when reading.
*/
int getMaxBlockAcquireFailures() {
return dfsClientConf.maxBlockAcquireFailures;
}
/**
* Return the timeout that clients should use when writing to datanodes.
* @param numNodes the number of nodes in the pipeline.
*/
int getDatanodeWriteTimeout(int numNodes) {
return (dfsClientConf.confTime > 0) ?
(dfsClientConf.confTime + HdfsServerConstants.WRITE_TIMEOUT_EXTENSION * numNodes) : 0;
}
int getDatanodeReadTimeout(int numNodes) {
return dfsClientConf.socketTimeout > 0 ?
(HdfsServerConstants.READ_TIMEOUT_EXTENSION * numNodes +
dfsClientConf.socketTimeout) : 0;
}
int getHdfsTimeout() {
return dfsClientConf.hdfsTimeout;
}
@VisibleForTesting
public String getClientName() {
return clientName;
}
void checkOpen() throws IOException {
if (!clientRunning) {
IOException result = new IOException("Filesystem closed");
throw result;
}
}
/** Return the lease renewer instance. The renewer thread won't start
* until the first output stream is created. The same instance will
* be returned until all output streams are closed.
*/
public LeaseRenewer getLeaseRenewer() throws IOException {
return LeaseRenewer.getInstance(authority, ugi, this);
}
/** Get a lease and start automatic renewal */
private void beginFileLease(final String src, final DFSOutputStream out)
throws IOException {
getLeaseRenewer().put(src, out, this);
}
/** Stop renewal of lease for the file. */
void endFileLease(final String src) throws IOException {
getLeaseRenewer().closeFile(src, this);
}
/** Put a file. Only called from LeaseRenewer, where proper locking is
* enforced to consistently update its local dfsclients array and
* client's filesBeingWritten map.
*/
void putFileBeingWritten(final String src, final DFSOutputStream out) {
synchronized(filesBeingWritten) {
filesBeingWritten.put(src, out);
// update the last lease renewal time only when there was no
// writes. once there is one write stream open, the lease renewer
// thread keeps it updated well with in anyone's expiration time.
if (lastLeaseRenewal == 0) {
updateLastLeaseRenewal();
}
}
}
/** Remove a file. Only called from LeaseRenewer. */
void removeFileBeingWritten(final String src) {
synchronized(filesBeingWritten) {
filesBeingWritten.remove(src);
if (filesBeingWritten.isEmpty()) {
lastLeaseRenewal = 0;
}
}
}
/** Is file-being-written map empty? */
boolean isFilesBeingWrittenEmpty() {
synchronized(filesBeingWritten) {
return filesBeingWritten.isEmpty();
}
}
/** @return true if the client is running */
boolean isClientRunning() {
return clientRunning;
}
long getLastLeaseRenewal() {
return lastLeaseRenewal;
}
void updateLastLeaseRenewal() {
synchronized(filesBeingWritten) {
if (filesBeingWritten.isEmpty()) {
return;
}
lastLeaseRenewal = Time.now();
}
}
/**
* Renew leases.
* @return true if lease was renewed. May return false if this
* client has been closed or has no files open.
**/
boolean renewLease() throws IOException {
if (clientRunning && !isFilesBeingWrittenEmpty()) {
try {
namenode.renewLease(clientName);
updateLastLeaseRenewal();
return true;
} catch (IOException e) {
// Abort if the lease has already expired.
final long elapsed = Time.now() - getLastLeaseRenewal();
if (elapsed > HdfsConstants.LEASE_HARDLIMIT_PERIOD) {
LOG.warn("Failed to renew lease for " + clientName + " for "
+ (elapsed/1000) + " seconds (>= soft-limit ="
+ (HdfsConstants.LEASE_HARDLIMIT_PERIOD/1000) + " seconds.) "
+ "Closing all files being written ...", e);
closeAllFilesBeingWritten(true);
} else {
// Let the lease renewer handle it and retry.
throw e;
}
}
}
return false;
}
/**
* Close connections the Namenode.
*/
void closeConnectionToNamenode() {
RPC.stopProxy(namenode);
}
/** Abort and release resources held. Ignore all errors. */
void abort() {
clientRunning = false;
closeAllFilesBeingWritten(true);
try {
// remove reference to this client and stop the renewer,
// if there is no more clients under the renewer.
getLeaseRenewer().closeClient(this);
} catch (IOException ioe) {
LOG.info("Exception occurred while aborting the client " + ioe);
}
closeConnectionToNamenode();
}
/** Close/abort all files being written. */
private void closeAllFilesBeingWritten(final boolean abort) {
for(;;) {
final String src;
final DFSOutputStream out;
synchronized(filesBeingWritten) {
if (filesBeingWritten.isEmpty()) {
return;
}
src = filesBeingWritten.keySet().iterator().next();
out = filesBeingWritten.remove(src);
}
if (out != null) {
try {
if (abort) {
out.abort();
} else {
out.close();
}
} catch(IOException ie) {
LOG.error("Failed to " + (abort? "abort": "close") + " file " + src,
ie);
}
}
}
}
/**
* Close the file system, abandoning all of the leases and files being
* created and close connections to the namenode.
*/
@Override
public synchronized void close() throws IOException {
if(clientRunning) {
closeAllFilesBeingWritten(false);
clientRunning = false;
getLeaseRenewer().closeClient(this);
// close connections to the namenode
closeConnectionToNamenode();
}
}
/**
* Get the default block size for this cluster
* @return the default block size in bytes
*/
public long getDefaultBlockSize() {
return dfsClientConf.defaultBlockSize;
}
/**
* @see ClientProtocol#getPreferredBlockSize(String)
*/
public long getBlockSize(String f) throws IOException {
try {
return namenode.getPreferredBlockSize(f);
} catch (IOException ie) {
LOG.warn("Problem getting block size", ie);
throw ie;
}
}
/**
* Get server default values for a number of configuration params.
* @see ClientProtocol#getServerDefaults()
*/
public FsServerDefaults getServerDefaults() throws IOException {
long now = Time.now();
if (now - serverDefaultsLastUpdate > SERVER_DEFAULTS_VALIDITY_PERIOD) {
serverDefaults = namenode.getServerDefaults();
serverDefaultsLastUpdate = now;
}
return serverDefaults;
}
/**
* Get a canonical token service name for this client's tokens. Null should
* be returned if the client is not using tokens.
* @return the token service for the client
*/
@InterfaceAudience.LimitedPrivate( { "HDFS" })
public String getCanonicalServiceName() {
return (dtService != null) ? dtService.toString() : null;
}
/**
* @see ClientProtocol#getDelegationToken(Text)
*/
public Token<DelegationTokenIdentifier> getDelegationToken(Text renewer)
throws IOException {
assert dtService != null;
Token<DelegationTokenIdentifier> token =
namenode.getDelegationToken(renewer);
if (token != null) {
token.setService(this.dtService);
LOG.info("Created " + DelegationTokenIdentifier.stringifyToken(token));
} else {
LOG.info("Cannot get delegation token from " + renewer);
}
return token;
}
/**
* Renew a delegation token
* @param token the token to renew
* @return the new expiration time
* @throws InvalidToken
* @throws IOException
* @deprecated Use Token.renew instead.
*/
@Deprecated
public long renewDelegationToken(Token<DelegationTokenIdentifier> token)
throws InvalidToken, IOException {
LOG.info("Renewing " + DelegationTokenIdentifier.stringifyToken(token));
try {
return token.renew(conf);
} catch (InterruptedException ie) {
throw new RuntimeException("caught interrupted", ie);
} catch (RemoteException re) {
throw re.unwrapRemoteException(InvalidToken.class,
AccessControlException.class);
}
}
private static Map<String, Boolean> localAddrMap = Collections
.synchronizedMap(new HashMap<String, Boolean>());
static boolean isLocalAddress(InetSocketAddress targetAddr) {
InetAddress addr = targetAddr.getAddress();
Boolean cached = localAddrMap.get(addr.getHostAddress());
if (cached != null) {
if (LOG.isTraceEnabled()) {
LOG.trace("Address " + targetAddr +
(cached ? " is local" : " is not local"));
}
return cached;
}
boolean local = NetUtils.isLocalAddress(addr);
if (LOG.isTraceEnabled()) {
LOG.trace("Address " + targetAddr +
(local ? " is local" : " is not local"));
}
localAddrMap.put(addr.getHostAddress(), local);
return local;
}
/**
* Should the block access token be refetched on an exception
*
* @param ex Exception received
* @param targetAddr Target datanode address from where exception was received
* @return true if block access token has expired or invalid and it should be
* refetched
*/
private static boolean tokenRefetchNeeded(IOException ex,
InetSocketAddress targetAddr) {
/*
* Get a new access token and retry. Retry is needed in 2 cases. 1) When
* both NN and DN re-started while DFSClient holding a cached access token.
* 2) In the case that NN fails to update its access key at pre-set interval
* (by a wide margin) and subsequently restarts. In this case, DN
* re-registers itself with NN and receives a new access key, but DN will
* delete the old access key from its memory since it's considered expired
* based on the estimated expiration date.
*/
if (ex instanceof InvalidBlockTokenException || ex instanceof InvalidToken) {
LOG.info("Access token was invalid when connecting to " + targetAddr
+ " : " + ex);
return true;
}
return false;
}
/**
* Cancel a delegation token
* @param token the token to cancel
* @throws InvalidToken
* @throws IOException
* @deprecated Use Token.cancel instead.
*/
@Deprecated
public void cancelDelegationToken(Token<DelegationTokenIdentifier> token)
throws InvalidToken, IOException {
LOG.info("Cancelling " + DelegationTokenIdentifier.stringifyToken(token));
try {
token.cancel(conf);
} catch (InterruptedException ie) {
throw new RuntimeException("caught interrupted", ie);
} catch (RemoteException re) {
throw re.unwrapRemoteException(InvalidToken.class,
AccessControlException.class);
}
}
@InterfaceAudience.Private
public static class Renewer extends TokenRenewer {
static {
//Ensure that HDFS Configuration files are loaded before trying to use
// the renewer.
HdfsConfiguration.init();
}
@Override
public boolean handleKind(Text kind) {
return DelegationTokenIdentifier.HDFS_DELEGATION_KIND.equals(kind);
}
@SuppressWarnings("unchecked")
@Override
public long renew(Token<?> token, Configuration conf) throws IOException {
Token<DelegationTokenIdentifier> delToken =
(Token<DelegationTokenIdentifier>) token;
ClientProtocol nn = getNNProxy(delToken, conf);
try {
return nn.renewDelegationToken(delToken);
} catch (RemoteException re) {
throw re.unwrapRemoteException(InvalidToken.class,
AccessControlException.class);
}
}
@SuppressWarnings("unchecked")
@Override
public void cancel(Token<?> token, Configuration conf) throws IOException {
Token<DelegationTokenIdentifier> delToken =
(Token<DelegationTokenIdentifier>) token;
LOG.info("Cancelling " +
DelegationTokenIdentifier.stringifyToken(delToken));
ClientProtocol nn = getNNProxy(delToken, conf);
try {
nn.cancelDelegationToken(delToken);
} catch (RemoteException re) {
throw re.unwrapRemoteException(InvalidToken.class,
AccessControlException.class);
}
}
private static ClientProtocol getNNProxy(
Token<DelegationTokenIdentifier> token, Configuration conf)
throws IOException {
URI uri = HAUtil.getServiceUriFromToken(token);
if (HAUtil.isTokenForLogicalUri(token) &&
!HAUtil.isLogicalUri(conf, uri)) {
// If the token is for a logical nameservice, but the configuration
// we have disagrees about that, we can't actually renew it.
// This can be the case in MR, for example, if the RM doesn't
// have all of the HA clusters configured in its configuration.
throw new IOException("Unable to map logical nameservice URI '" +
uri + "' to a NameNode. Local configuration does not have " +
"a failover proxy provider configured.");
}
NameNodeProxies.ProxyAndInfo<ClientProtocol> info =
NameNodeProxies.createProxy(conf, uri, ClientProtocol.class);
assert info.getDelegationTokenService().equals(token.getService()) :
"Returned service '" + info.getDelegationTokenService().toString() +
"' doesn't match expected service '" +
token.getService().toString() + "'";
return info.getProxy();
}
@Override
public boolean isManaged(Token<?> token) throws IOException {
return true;
}
}
/**
* Report corrupt blocks that were discovered by the client.
* @see ClientProtocol#reportBadBlocks(LocatedBlock[])
*/
public void reportBadBlocks(LocatedBlock[] blocks) throws IOException {
namenode.reportBadBlocks(blocks);
}
public short getDefaultReplication() {
return dfsClientConf.defaultReplication;
}
public LocatedBlocks getLocatedBlocks(String src, long start)
throws IOException {
return getLocatedBlocks(src, start, dfsClientConf.prefetchSize);
}
/*
* This is just a wrapper around callGetBlockLocations, but non-static so that
* we can stub it out for tests.
*/
@VisibleForTesting
public LocatedBlocks getLocatedBlocks(String src, long start, long length)
throws IOException {
return callGetBlockLocations(namenode, src, start, length);
}
/**
* @see ClientProtocol#getBlockLocations(String, long, long)
*/
static LocatedBlocks callGetBlockLocations(ClientProtocol namenode,
String src, long start, long length)
throws IOException {
try {
return namenode.getBlockLocations(src, start, length);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
FileNotFoundException.class,
UnresolvedPathException.class);
}
}
/**
* Recover a file's lease
* @param src a file's path
* @return true if the file is already closed
* @throws IOException
*/
boolean recoverLease(String src) throws IOException {
checkOpen();
try {
return namenode.recoverLease(src, clientName);
} catch (RemoteException re) {
throw re.unwrapRemoteException(FileNotFoundException.class,
AccessControlException.class,
UnresolvedPathException.class);
}
}
/**
* Get block location info about file
*
* getBlockLocations() returns a list of hostnames that store
* data for a specific file region. It returns a set of hostnames
* for every block within the indicated region.
*
* This function is very useful when writing code that considers
* data-placement when performing operations. For example, the
* MapReduce system tries to schedule tasks on the same machines
* as the data-block the task processes.
*/
public BlockLocation[] getBlockLocations(String src, long start,
long length) throws IOException, UnresolvedLinkException {
LocatedBlocks blocks = getLocatedBlocks(src, start, length);
BlockLocation[] locations = DFSUtil.locatedBlocks2Locations(blocks);
HdfsBlockLocation[] hdfsLocations = new HdfsBlockLocation[locations.length];
for (int i = 0; i < locations.length; i++) {
hdfsLocations[i] = new HdfsBlockLocation(locations[i], blocks.get(i));
}
return hdfsLocations;
}
/**
* Get block location information about a list of {@link HdfsBlockLocation}.
* Used by {@link DistributedFileSystem#getFileBlockStorageLocations(List)} to
* get {@link BlockStorageLocation}s for blocks returned by
* {@link DistributedFileSystem#getFileBlockLocations(org.apache.hadoop.fs.FileStatus, long, long)}
* .
*
* This is done by making a round of RPCs to the associated datanodes, asking
* the volume of each block replica. The returned array of
* {@link BlockStorageLocation} expose this information as a
* {@link VolumeId}.
*
* @param blockLocations
* target blocks on which to query volume location information
* @return volumeBlockLocations original block array augmented with additional
* volume location information for each replica.
*/
public BlockStorageLocation[] getBlockStorageLocations(
List<BlockLocation> blockLocations) throws IOException,
UnsupportedOperationException, InvalidBlockTokenException {
if (!getConf().getHdfsBlocksMetadataEnabled) {
throw new UnsupportedOperationException("Datanode-side support for " +
"getVolumeBlockLocations() must also be enabled in the client " +
"configuration.");
}
// Downcast blockLocations and fetch out required LocatedBlock(s)
List<LocatedBlock> blocks = new ArrayList<LocatedBlock>();
for (BlockLocation loc : blockLocations) {
if (!(loc instanceof HdfsBlockLocation)) {
throw new ClassCastException("DFSClient#getVolumeBlockLocations " +
"expected to be passed HdfsBlockLocations");
}
HdfsBlockLocation hdfsLoc = (HdfsBlockLocation) loc;
blocks.add(hdfsLoc.getLocatedBlock());
}
// Re-group the LocatedBlocks to be grouped by datanodes, with the values
// a list of the LocatedBlocks on the datanode.
Map<DatanodeInfo, List<LocatedBlock>> datanodeBlocks =
new LinkedHashMap<DatanodeInfo, List<LocatedBlock>>();
for (LocatedBlock b : blocks) {
for (DatanodeInfo info : b.getLocations()) {
if (!datanodeBlocks.containsKey(info)) {
datanodeBlocks.put(info, new ArrayList<LocatedBlock>());
}
List<LocatedBlock> l = datanodeBlocks.get(info);
l.add(b);
}
}
// Make RPCs to the datanodes to get volume locations for its replicas
List<HdfsBlocksMetadata> metadatas = BlockStorageLocationUtil
.queryDatanodesForHdfsBlocksMetadata(conf, datanodeBlocks,
getConf().getFileBlockStorageLocationsNumThreads,
getConf().getFileBlockStorageLocationsTimeout,
getConf().connectToDnViaHostname);
// Regroup the returned VolumeId metadata to again be grouped by
// LocatedBlock rather than by datanode
Map<LocatedBlock, List<VolumeId>> blockVolumeIds = BlockStorageLocationUtil
.associateVolumeIdsWithBlocks(blocks, datanodeBlocks, metadatas);
// Combine original BlockLocations with new VolumeId information
BlockStorageLocation[] volumeBlockLocations = BlockStorageLocationUtil
.convertToVolumeBlockLocations(blocks, blockVolumeIds);
return volumeBlockLocations;
}
public DFSInputStream open(String src)
throws IOException, UnresolvedLinkException {
return open(src, dfsClientConf.ioBufferSize, true, null);
}
/**
* Create an input stream that obtains a nodelist from the
* namenode, and then reads from all the right places. Creates
* inner subclass of InputStream that does the right out-of-band
* work.
* @deprecated Use {@link #open(String, int, boolean)} instead.
*/
@Deprecated
public DFSInputStream open(String src, int buffersize, boolean verifyChecksum,
FileSystem.Statistics stats)
throws IOException, UnresolvedLinkException {
return open(src, buffersize, verifyChecksum);
}
/**
* Create an input stream that obtains a nodelist from the
* namenode, and then reads from all the right places. Creates
* inner subclass of InputStream that does the right out-of-band
* work.
*/
public DFSInputStream open(String src, int buffersize, boolean verifyChecksum)
throws IOException, UnresolvedLinkException {
checkOpen();
// Get block info from namenode
return new DFSInputStream(this, src, buffersize, verifyChecksum);
}
/**
* Get the namenode associated with this DFSClient object
* @return the namenode associated with this DFSClient object
*/
public ClientProtocol getNamenode() {
return namenode;
}
/**
* Call {@link #create(String, boolean, short, long, Progressable)} with
* default <code>replication</code> and <code>blockSize<code> and null <code>
* progress</code>.
*/
public OutputStream create(String src, boolean overwrite)
throws IOException {
return create(src, overwrite, dfsClientConf.defaultReplication,
dfsClientConf.defaultBlockSize, null);
}
/**
* Call {@link #create(String, boolean, short, long, Progressable)} with
* default <code>replication</code> and <code>blockSize<code>.
*/
public OutputStream create(String src,
boolean overwrite,
Progressable progress) throws IOException {
return create(src, overwrite, dfsClientConf.defaultReplication,
dfsClientConf.defaultBlockSize, progress);
}
/**
* Call {@link #create(String, boolean, short, long, Progressable)} with
* null <code>progress</code>.
*/
public OutputStream create(String src,
boolean overwrite,
short replication,
long blockSize) throws IOException {
return create(src, overwrite, replication, blockSize, null);
}
/**
* Call {@link #create(String, boolean, short, long, Progressable, int)}
* with default bufferSize.
*/
public OutputStream create(String src, boolean overwrite, short replication,
long blockSize, Progressable progress) throws IOException {
return create(src, overwrite, replication, blockSize, progress,
dfsClientConf.ioBufferSize);
}
/**
* Call {@link #create(String, FsPermission, EnumSet, short, long,
* Progressable, int, ChecksumOpt)} with default <code>permission</code>
* {@link FsPermission#getFileDefault()}.
*
* @param src File name
* @param overwrite overwrite an existing file if true
* @param replication replication factor for the file
* @param blockSize maximum block size
* @param progress interface for reporting client progress
* @param buffersize underlying buffersize
*
* @return output stream
*/
public OutputStream create(String src,
boolean overwrite,
short replication,
long blockSize,
Progressable progress,
int buffersize)
throws IOException {
return create(src, FsPermission.getFileDefault(),
overwrite ? EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE)
: EnumSet.of(CreateFlag.CREATE), replication, blockSize, progress,
buffersize, null);
}
/**
* Call {@link #create(String, FsPermission, EnumSet, boolean, short,
* long, Progressable, int, ChecksumOpt)} with <code>createParent</code>
* set to true.
*/
public DFSOutputStream create(String src,
FsPermission permission,
EnumSet<CreateFlag> flag,
short replication,
long blockSize,
Progressable progress,
int buffersize,
ChecksumOpt checksumOpt)
throws IOException {
return create(src, permission, flag, true,
replication, blockSize, progress, buffersize, checksumOpt, null);
}
/**
* Create a new dfs file with the specified block replication
* with write-progress reporting and return an output stream for writing
* into the file.
*
* @param src File name
* @param permission The permission of the directory being created.
* If null, use default permission {@link FsPermission#getFileDefault()}
* @param flag indicates create a new file or create/overwrite an
* existing file or append to an existing file
* @param createParent create missing parent directory if true
* @param replication block replication
* @param blockSize maximum block size
* @param progress interface for reporting client progress
* @param buffersize underlying buffer size
* @param checksumOpt checksum options
*
* @return output stream
*
* @see ClientProtocol#create(String, FsPermission, String, EnumSetWritable,
* boolean, short, long) for detailed description of exceptions thrown
*/
public DFSOutputStream create(String src,
FsPermission permission,
EnumSet<CreateFlag> flag,
boolean createParent,
short replication,
long blockSize,
Progressable progress,
int buffersize,
ChecksumOpt checksumOpt) throws IOException {
return create(src, permission, flag, createParent, replication, blockSize,
progress, buffersize, checksumOpt, null);
}
/**
* Same as {@link #create(String, FsPermission, EnumSet, boolean, short, long,
* Progressable, int, ChecksumOpt)} with the addition of favoredNodes that is
* a hint to where the namenode should place the file blocks.
* The favored nodes hint is not persisted in HDFS. Hence it may be honored
* at the creation time only. HDFS could move the blocks during balancing or
* replication, to move the blocks from favored nodes. A value of null means
* no favored nodes for this create
*/
public DFSOutputStream create(String src,
FsPermission permission,
EnumSet<CreateFlag> flag,
boolean createParent,
short replication,
long blockSize,
Progressable progress,
int buffersize,
ChecksumOpt checksumOpt,
InetSocketAddress[] favoredNodes) throws IOException {
checkOpen();
if (permission == null) {
permission = FsPermission.getFileDefault();
}
FsPermission masked = permission.applyUMask(dfsClientConf.uMask);
if(LOG.isDebugEnabled()) {
LOG.debug(src + ": masked=" + masked);
}
String[] favoredNodeStrs = null;
if (favoredNodes != null) {
favoredNodeStrs = new String[favoredNodes.length];
for (int i = 0; i < favoredNodes.length; i++) {
favoredNodeStrs[i] =
favoredNodes[i].getHostName() + ":"
+ favoredNodes[i].getPort();
}
}
final DFSOutputStream result = DFSOutputStream.newStreamForCreate(this,
src, masked, flag, createParent, replication, blockSize, progress,
buffersize, dfsClientConf.createChecksum(checksumOpt), favoredNodeStrs);
beginFileLease(src, result);
return result;
}
/**
* Append to an existing file if {@link CreateFlag#APPEND} is present
*/
private DFSOutputStream primitiveAppend(String src, EnumSet<CreateFlag> flag,
int buffersize, Progressable progress) throws IOException {
if (flag.contains(CreateFlag.APPEND)) {
HdfsFileStatus stat = getFileInfo(src);
if (stat == null) { // No file to append to
// New file needs to be created if create option is present
if (!flag.contains(CreateFlag.CREATE)) {
throw new FileNotFoundException("failed to append to non-existent file "
+ src + " on client " + clientName);
}
return null;
}
return callAppend(stat, src, buffersize, progress);
}
return null;
}
/**
* Same as {{@link #create(String, FsPermission, EnumSet, short, long,
* Progressable, int, ChecksumOpt)} except that the permission
* is absolute (ie has already been masked with umask.
*/
public DFSOutputStream primitiveCreate(String src,
FsPermission absPermission,
EnumSet<CreateFlag> flag,
boolean createParent,
short replication,
long blockSize,
Progressable progress,
int buffersize,
ChecksumOpt checksumOpt)
throws IOException, UnresolvedLinkException {
checkOpen();
CreateFlag.validate(flag);
DFSOutputStream result = primitiveAppend(src, flag, buffersize, progress);
if (result == null) {
DataChecksum checksum = dfsClientConf.createChecksum(checksumOpt);
result = DFSOutputStream.newStreamForCreate(this, src, absPermission,
flag, createParent, replication, blockSize, progress, buffersize,
checksum);
}
beginFileLease(src, result);
return result;
}
/**
* Creates a symbolic link.
*
* @see ClientProtocol#createSymlink(String, String,FsPermission, boolean)
*/
public void createSymlink(String target, String link, boolean createParent)
throws IOException {
try {
FsPermission dirPerm =
FsPermission.getDefault().applyUMask(dfsClientConf.uMask);
namenode.createSymlink(target, link, dirPerm, createParent);
} catch (RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
FileAlreadyExistsException.class,
FileNotFoundException.class,
ParentNotDirectoryException.class,
NSQuotaExceededException.class,
DSQuotaExceededException.class,
UnresolvedPathException.class,
SnapshotAccessControlException.class);
}
}
/**
* Resolve the *first* symlink, if any, in the path.
*
* @see ClientProtocol#getLinkTarget(String)
*/
public String getLinkTarget(String path) throws IOException {
checkOpen();
try {
return namenode.getLinkTarget(path);
} catch (RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
FileNotFoundException.class);
}
}
/** Method to get stream returned by append call */
private DFSOutputStream callAppend(HdfsFileStatus stat, String src,
int buffersize, Progressable progress) throws IOException {
LocatedBlock lastBlock = null;
try {
lastBlock = namenode.append(src, clientName);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
FileNotFoundException.class,
SafeModeException.class,
DSQuotaExceededException.class,
UnsupportedOperationException.class,
UnresolvedPathException.class,
SnapshotAccessControlException.class);
}
return DFSOutputStream.newStreamForAppend(this, src, buffersize, progress,
lastBlock, stat, dfsClientConf.createChecksum());
}
/**
* Append to an existing HDFS file.
*
* @param src file name
* @param buffersize buffer size
* @param progress for reporting write-progress; null is acceptable.
* @param statistics file system statistics; null is acceptable.
* @return an output stream for writing into the file
*
* @see ClientProtocol#append(String, String)
*/
public HdfsDataOutputStream append(final String src, final int buffersize,
final Progressable progress, final FileSystem.Statistics statistics
) throws IOException {
final DFSOutputStream out = append(src, buffersize, progress);
return new HdfsDataOutputStream(out, statistics, out.getInitialLen());
}
private DFSOutputStream append(String src, int buffersize, Progressable progress)
throws IOException {
checkOpen();
HdfsFileStatus stat = getFileInfo(src);
if (stat == null) { // No file found
throw new FileNotFoundException("failed to append to non-existent file "
+ src + " on client " + clientName);
}
final DFSOutputStream result = callAppend(stat, src, buffersize, progress);
beginFileLease(src, result);
return result;
}
/**
* Set replication for an existing file.
* @param src file name
* @param replication
*
* @see ClientProtocol#setReplication(String, short)
*/
public boolean setReplication(String src, short replication)
throws IOException {
try {
return namenode.setReplication(src, replication);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
FileNotFoundException.class,
SafeModeException.class,
DSQuotaExceededException.class,
UnresolvedPathException.class,
SnapshotAccessControlException.class);
}
}
/**
* Rename file or directory.
* @see ClientProtocol#rename(String, String)
* @deprecated Use {@link #rename(String, String, Options.Rename...)} instead.
*/
@Deprecated
public boolean rename(String src, String dst) throws IOException {
checkOpen();
try {
return namenode.rename(src, dst);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
NSQuotaExceededException.class,
DSQuotaExceededException.class,
UnresolvedPathException.class,
SnapshotAccessControlException.class);
}
}
/**
* Move blocks from src to trg and delete src
* See {@link ClientProtocol#concat(String, String [])}.
*/
public void concat(String trg, String [] srcs) throws IOException {
checkOpen();
try {
namenode.concat(trg, srcs);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
UnresolvedPathException.class,
SnapshotAccessControlException.class);
}
}
/**
* Rename file or directory.
* @see ClientProtocol#rename2(String, String, Options.Rename...)
*/
public void rename(String src, String dst, Options.Rename... options)
throws IOException {
checkOpen();
try {
namenode.rename2(src, dst, options);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
DSQuotaExceededException.class,
FileAlreadyExistsException.class,
FileNotFoundException.class,
ParentNotDirectoryException.class,
SafeModeException.class,
NSQuotaExceededException.class,
UnresolvedPathException.class,
SnapshotAccessControlException.class);
}
}
/**
* Delete file or directory.
* See {@link ClientProtocol#delete(String, boolean)}.
*/
@Deprecated
public boolean delete(String src) throws IOException {
checkOpen();
return namenode.delete(src, true);
}
/**
* delete file or directory.
* delete contents of the directory if non empty and recursive
* set to true
*
* @see ClientProtocol#delete(String, boolean)
*/
public boolean delete(String src, boolean recursive) throws IOException {
checkOpen();
try {
return namenode.delete(src, recursive);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
FileNotFoundException.class,
SafeModeException.class,
UnresolvedPathException.class,
SnapshotAccessControlException.class);
}
}
/** Implemented using getFileInfo(src)
*/
public boolean exists(String src) throws IOException {
checkOpen();
return getFileInfo(src) != null;
}
/**
* Get a partial listing of the indicated directory
* No block locations need to be fetched
*/
public DirectoryListing listPaths(String src, byte[] startAfter)
throws IOException {
return listPaths(src, startAfter, false);
}
/**
* Get a partial listing of the indicated directory
*
* Recommend to use HdfsFileStatus.EMPTY_NAME as startAfter
* if the application wants to fetch a listing starting from
* the first entry in the directory
*
* @see ClientProtocol#getListing(String, byte[], boolean)
*/
public DirectoryListing listPaths(String src, byte[] startAfter,
boolean needLocation)
throws IOException {
checkOpen();
try {
return namenode.getListing(src, startAfter, needLocation);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
FileNotFoundException.class,
UnresolvedPathException.class);
}
}
/**
* Get the file info for a specific file or directory.
* @param src The string representation of the path to the file
* @return object containing information regarding the file
* or null if file not found
*
* @see ClientProtocol#getFileInfo(String) for description of exceptions
*/
public HdfsFileStatus getFileInfo(String src) throws IOException {
checkOpen();
try {
return namenode.getFileInfo(src);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
FileNotFoundException.class,
UnresolvedPathException.class);
}
}
/**
* Close status of a file
* @return true if file is already closed
*/
public boolean isFileClosed(String src) throws IOException{
checkOpen();
try {
return namenode.isFileClosed(src);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
FileNotFoundException.class,
UnresolvedPathException.class);
}
}
/**
* Get the file info for a specific file or directory. If src
* refers to a symlink then the FileStatus of the link is returned.
* @param src path to a file or directory.
*
* For description of exceptions thrown
* @see ClientProtocol#getFileLinkInfo(String)
*/
public HdfsFileStatus getFileLinkInfo(String src) throws IOException {
checkOpen();
try {
return namenode.getFileLinkInfo(src);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
UnresolvedPathException.class);
}
}
/**
* Get the checksum of a file.
* @param src The file path
* @return The checksum
* @see DistributedFileSystem#getFileChecksum(Path)
*/
public MD5MD5CRC32FileChecksum getFileChecksum(String src) throws IOException {
checkOpen();
return getFileChecksum(src, clientName, namenode, socketFactory,
dfsClientConf.socketTimeout, getDataEncryptionKey(),
dfsClientConf.connectToDnViaHostname);
}
@InterfaceAudience.Private
public void clearDataEncryptionKey() {
LOG.debug("Clearing encryption key");
synchronized (this) {
encryptionKey = null;
}
}
/**
* @return true if data sent between this client and DNs should be encrypted,
* false otherwise.
* @throws IOException in the event of error communicating with the NN
*/
boolean shouldEncryptData() throws IOException {
FsServerDefaults d = getServerDefaults();
return d == null ? false : d.getEncryptDataTransfer();
}
@InterfaceAudience.Private
public DataEncryptionKey getDataEncryptionKey()
throws IOException {
if (shouldEncryptData()) {
synchronized (this) {
if (encryptionKey == null ||
encryptionKey.expiryDate < Time.now()) {
LOG.debug("Getting new encryption token from NN");
encryptionKey = namenode.getDataEncryptionKey();
}
return encryptionKey;
}
} else {
return null;
}
}
/**
* Get the checksum of a file.
* @param src The file path
* @param clientName the name of the client requesting the checksum.
* @param namenode the RPC proxy for the namenode
* @param socketFactory to create sockets to connect to DNs
* @param socketTimeout timeout to use when connecting and waiting for a response
* @param encryptionKey the key needed to communicate with DNs in this cluster
* @param connectToDnViaHostname whether the client should use hostnames instead of IPs
* @return The checksum
*/
private static MD5MD5CRC32FileChecksum getFileChecksum(String src,
String clientName,
ClientProtocol namenode, SocketFactory socketFactory, int socketTimeout,
DataEncryptionKey encryptionKey, boolean connectToDnViaHostname)
throws IOException {
//get all block locations
LocatedBlocks blockLocations = callGetBlockLocations(namenode, src, 0, Long.MAX_VALUE);
if (null == blockLocations) {
throw new FileNotFoundException("File does not exist: " + src);
}
List<LocatedBlock> locatedblocks = blockLocations.getLocatedBlocks();
final DataOutputBuffer md5out = new DataOutputBuffer();
int bytesPerCRC = -1;
DataChecksum.Type crcType = DataChecksum.Type.DEFAULT;
long crcPerBlock = 0;
boolean refetchBlocks = false;
int lastRetriedIndex = -1;
//get block checksum for each block
for(int i = 0; i < locatedblocks.size(); i++) {
if (refetchBlocks) { // refetch to get fresh tokens
blockLocations = callGetBlockLocations(namenode, src, 0, Long.MAX_VALUE);
if (null == blockLocations) {
throw new FileNotFoundException("File does not exist: " + src);
}
locatedblocks = blockLocations.getLocatedBlocks();
refetchBlocks = false;
}
LocatedBlock lb = locatedblocks.get(i);
final ExtendedBlock block = lb.getBlock();
final DatanodeInfo[] datanodes = lb.getLocations();
//try each datanode location of the block
final int timeout = 3000 * datanodes.length + socketTimeout;
boolean done = false;
for(int j = 0; !done && j < datanodes.length; j++) {
DataOutputStream out = null;
DataInputStream in = null;
try {
//connect to a datanode
IOStreamPair pair = connectToDN(socketFactory, connectToDnViaHostname,
encryptionKey, datanodes[j], timeout);
out = new DataOutputStream(new BufferedOutputStream(pair.out,
HdfsConstants.SMALL_BUFFER_SIZE));
in = new DataInputStream(pair.in);
if (LOG.isDebugEnabled()) {
LOG.debug("write to " + datanodes[j] + ": "
+ Op.BLOCK_CHECKSUM + ", block=" + block);
}
// get block MD5
new Sender(out).blockChecksum(block, lb.getBlockToken());
final BlockOpResponseProto reply =
BlockOpResponseProto.parseFrom(PBHelper.vintPrefixed(in));
if (reply.getStatus() != Status.SUCCESS) {
if (reply.getStatus() == Status.ERROR_ACCESS_TOKEN) {
throw new InvalidBlockTokenException();
} else {
throw new IOException("Bad response " + reply + " for block "
+ block + " from datanode " + datanodes[j]);
}
}
OpBlockChecksumResponseProto checksumData =
reply.getChecksumResponse();
//read byte-per-checksum
final int bpc = checksumData.getBytesPerCrc();
if (i == 0) { //first block
bytesPerCRC = bpc;
}
else if (bpc != bytesPerCRC) {
throw new IOException("Byte-per-checksum not matched: bpc=" + bpc
+ " but bytesPerCRC=" + bytesPerCRC);
}
//read crc-per-block
final long cpb = checksumData.getCrcPerBlock();
if (locatedblocks.size() > 1 && i == 0) {
crcPerBlock = cpb;
}
//read md5
final MD5Hash md5 = new MD5Hash(
checksumData.getMd5().toByteArray());
md5.write(md5out);
// read crc-type
final DataChecksum.Type ct;
if (checksumData.hasCrcType()) {
ct = PBHelper.convert(checksumData
.getCrcType());
} else {
LOG.debug("Retrieving checksum from an earlier-version DataNode: " +
"inferring checksum by reading first byte");
ct = inferChecksumTypeByReading(
clientName, socketFactory, socketTimeout, lb, datanodes[j],
encryptionKey, connectToDnViaHostname);
}
if (i == 0) { // first block
crcType = ct;
} else if (crcType != DataChecksum.Type.MIXED
&& crcType != ct) {
// if crc types are mixed in a file
crcType = DataChecksum.Type.MIXED;
}
done = true;
if (LOG.isDebugEnabled()) {
if (i == 0) {
LOG.debug("set bytesPerCRC=" + bytesPerCRC
+ ", crcPerBlock=" + crcPerBlock);
}
LOG.debug("got reply from " + datanodes[j] + ": md5=" + md5);
}
} catch (InvalidBlockTokenException ibte) {
if (i > lastRetriedIndex) {
if (LOG.isDebugEnabled()) {
LOG.debug("Got access token error in response to OP_BLOCK_CHECKSUM "
+ "for file " + src + " for block " + block
+ " from datanode " + datanodes[j]
+ ". Will retry the block once.");
}
lastRetriedIndex = i;
done = true; // actually it's not done; but we'll retry
i--; // repeat at i-th block
refetchBlocks = true;
break;
}
} catch (IOException ie) {
LOG.warn("src=" + src + ", datanodes["+j+"]=" + datanodes[j], ie);
} finally {
IOUtils.closeStream(in);
IOUtils.closeStream(out);
}
}
if (!done) {
throw new IOException("Fail to get block MD5 for " + block);
}
}
//compute file MD5
final MD5Hash fileMD5 = MD5Hash.digest(md5out.getData());
switch (crcType) {
case CRC32:
return new MD5MD5CRC32GzipFileChecksum(bytesPerCRC,
crcPerBlock, fileMD5);
case CRC32C:
return new MD5MD5CRC32CastagnoliFileChecksum(bytesPerCRC,
crcPerBlock, fileMD5);
default:
// If there is no block allocated for the file,
// return one with the magic entry that matches what previous
// hdfs versions return.
if (locatedblocks.size() == 0) {
return new MD5MD5CRC32GzipFileChecksum(0, 0, fileMD5);
}
// we should never get here since the validity was checked
// when getCrcType() was called above.
return null;
}
}
/**
* Connect to the given datanode's datantrasfer port, and return
* the resulting IOStreamPair. This includes encryption wrapping, etc.
*/
private static IOStreamPair connectToDN(
SocketFactory socketFactory, boolean connectToDnViaHostname,
DataEncryptionKey encryptionKey, DatanodeInfo dn, int timeout)
throws IOException
{
boolean success = false;
Socket sock = null;
try {
sock = socketFactory.createSocket();
String dnAddr = dn.getXferAddr(connectToDnViaHostname);
if (LOG.isDebugEnabled()) {
LOG.debug("Connecting to datanode " + dnAddr);
}
NetUtils.connect(sock, NetUtils.createSocketAddr(dnAddr), timeout);
sock.setSoTimeout(timeout);
OutputStream unbufOut = NetUtils.getOutputStream(sock);
InputStream unbufIn = NetUtils.getInputStream(sock);
IOStreamPair ret;
if (encryptionKey != null) {
ret = DataTransferEncryptor.getEncryptedStreams(
unbufOut, unbufIn, encryptionKey);
} else {
ret = new IOStreamPair(unbufIn, unbufOut);
}
success = true;
return ret;
} finally {
if (!success) {
IOUtils.closeSocket(sock);
}
}
}
/**
* Infer the checksum type for a replica by sending an OP_READ_BLOCK
* for the first byte of that replica. This is used for compatibility
* with older HDFS versions which did not include the checksum type in
* OpBlockChecksumResponseProto.
*
* @param in input stream from datanode
* @param out output stream to datanode
* @param lb the located block
* @param clientName the name of the DFSClient requesting the checksum
* @param dn the connected datanode
* @return the inferred checksum type
* @throws IOException if an error occurs
*/
private static Type inferChecksumTypeByReading(
String clientName, SocketFactory socketFactory, int socketTimeout,
LocatedBlock lb, DatanodeInfo dn,
DataEncryptionKey encryptionKey, boolean connectToDnViaHostname)
throws IOException {
IOStreamPair pair = connectToDN(socketFactory, connectToDnViaHostname,
encryptionKey, dn, socketTimeout);
try {
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(pair.out,
HdfsConstants.SMALL_BUFFER_SIZE));
DataInputStream in = new DataInputStream(pair.in);
new Sender(out).readBlock(lb.getBlock(), lb.getBlockToken(), clientName,
0, 1, true, CachingStrategy.newDefaultStrategy());
final BlockOpResponseProto reply =
BlockOpResponseProto.parseFrom(PBHelper.vintPrefixed(in));
if (reply.getStatus() != Status.SUCCESS) {
if (reply.getStatus() == Status.ERROR_ACCESS_TOKEN) {
throw new InvalidBlockTokenException();
} else {
throw new IOException("Bad response " + reply + " trying to read "
+ lb.getBlock() + " from datanode " + dn);
}
}
return PBHelper.convert(reply.getReadOpChecksumInfo().getChecksum().getType());
} finally {
IOUtils.cleanup(null, pair.in, pair.out);
}
}
/**
* Set permissions to a file or directory.
* @param src path name.
* @param permission
*
* @see ClientProtocol#setPermission(String, FsPermission)
*/
public void setPermission(String src, FsPermission permission)
throws IOException {
checkOpen();
try {
namenode.setPermission(src, permission);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
FileNotFoundException.class,
SafeModeException.class,
UnresolvedPathException.class,
SnapshotAccessControlException.class);
}
}
/**
* Set file or directory owner.
* @param src path name.
* @param username user id.
* @param groupname user group.
*
* @see ClientProtocol#setOwner(String, String, String)
*/
public void setOwner(String src, String username, String groupname)
throws IOException {
checkOpen();
try {
namenode.setOwner(src, username, groupname);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
FileNotFoundException.class,
SafeModeException.class,
UnresolvedPathException.class,
SnapshotAccessControlException.class);
}
}
/**
* @see ClientProtocol#getStats()
*/
public FsStatus getDiskStatus() throws IOException {
long rawNums[] = namenode.getStats();
return new FsStatus(rawNums[0], rawNums[1], rawNums[2]);
}
/**
* Returns count of blocks with no good replicas left. Normally should be
* zero.
* @throws IOException
*/
public long getMissingBlocksCount() throws IOException {
return namenode.getStats()[ClientProtocol.GET_STATS_MISSING_BLOCKS_IDX];
}
/**
* Returns count of blocks with one of more replica missing.
* @throws IOException
*/
public long getUnderReplicatedBlocksCount() throws IOException {
return namenode.getStats()[ClientProtocol.GET_STATS_UNDER_REPLICATED_IDX];
}
/**
* Returns count of blocks with at least one replica marked corrupt.
* @throws IOException
*/
public long getCorruptBlocksCount() throws IOException {
return namenode.getStats()[ClientProtocol.GET_STATS_CORRUPT_BLOCKS_IDX];
}
/**
* @return a list in which each entry describes a corrupt file/block
* @throws IOException
*/
public CorruptFileBlocks listCorruptFileBlocks(String path,
String cookie)
throws IOException {
return namenode.listCorruptFileBlocks(path, cookie);
}
public DatanodeInfo[] datanodeReport(DatanodeReportType type)
throws IOException {
return namenode.getDatanodeReport(type);
}
/**
* Enter, leave or get safe mode.
*
* @see ClientProtocol#setSafeMode(HdfsConstants.SafeModeAction,boolean)
*/
public boolean setSafeMode(SafeModeAction action) throws IOException {
return setSafeMode(action, false);
}
/**
* Enter, leave or get safe mode.
*
* @param action
* One of SafeModeAction.GET, SafeModeAction.ENTER and
* SafeModeActiob.LEAVE
* @param isChecked
* If true, then check only active namenode's safemode status, else
* check first namenode's status.
* @see ClientProtocol#setSafeMode(HdfsConstants.SafeModeAction, boolean)
*/
public boolean setSafeMode(SafeModeAction action, boolean isChecked) throws IOException{
return namenode.setSafeMode(action, isChecked);
}
/**
* Create one snapshot.
*
* @param snapshotRoot The directory where the snapshot is to be taken
* @param snapshotName Name of the snapshot
* @return the snapshot path.
* @see ClientProtocol#createSnapshot(String, String)
*/
public String createSnapshot(String snapshotRoot, String snapshotName)
throws IOException {
checkOpen();
try {
return namenode.createSnapshot(snapshotRoot, snapshotName);
} catch(RemoteException re) {
throw re.unwrapRemoteException();
}
}
/**
* Delete a snapshot of a snapshottable directory.
*
* @param snapshotRoot The snapshottable directory that the
* to-be-deleted snapshot belongs to
* @param snapshotName The name of the to-be-deleted snapshot
* @throws IOException
* @see ClientProtocol#deleteSnapshot(String, String)
*/
public void deleteSnapshot(String snapshotRoot, String snapshotName)
throws IOException {
try {
namenode.deleteSnapshot(snapshotRoot, snapshotName);
} catch(RemoteException re) {
throw re.unwrapRemoteException();
}
}
/**
* Rename a snapshot.
* @param snapshotDir The directory path where the snapshot was taken
* @param snapshotOldName Old name of the snapshot
* @param snapshotNewName New name of the snapshot
* @throws IOException
* @see ClientProtocol#renameSnapshot(String, String, String)
*/
public void renameSnapshot(String snapshotDir, String snapshotOldName,
String snapshotNewName) throws IOException {
checkOpen();
try {
namenode.renameSnapshot(snapshotDir, snapshotOldName, snapshotNewName);
} catch(RemoteException re) {
throw re.unwrapRemoteException();
}
}
/**
* Get all the current snapshottable directories.
* @return All the current snapshottable directories
* @throws IOException
* @see ClientProtocol#getSnapshottableDirListing()
*/
public SnapshottableDirectoryStatus[] getSnapshottableDirListing()
throws IOException {
checkOpen();
try {
return namenode.getSnapshottableDirListing();
} catch(RemoteException re) {
throw re.unwrapRemoteException();
}
}
/**
* Allow snapshot on a directory.
*
* @see ClientProtocol#allowSnapshot(String snapshotRoot)
*/
public void allowSnapshot(String snapshotRoot) throws IOException {
checkOpen();
try {
namenode.allowSnapshot(snapshotRoot);
} catch (RemoteException re) {
throw re.unwrapRemoteException();
}
}
/**
* Disallow snapshot on a directory.
*
* @see ClientProtocol#disallowSnapshot(String snapshotRoot)
*/
public void disallowSnapshot(String snapshotRoot) throws IOException {
checkOpen();
try {
namenode.disallowSnapshot(snapshotRoot);
} catch (RemoteException re) {
throw re.unwrapRemoteException();
}
}
/**
* Get the difference between two snapshots, or between a snapshot and the
* current tree of a directory.
* @see ClientProtocol#getSnapshotDiffReport(String, String, String)
*/
public SnapshotDiffReport getSnapshotDiffReport(String snapshotDir,
String fromSnapshot, String toSnapshot) throws IOException {
checkOpen();
try {
return namenode.getSnapshotDiffReport(snapshotDir,
fromSnapshot, toSnapshot);
} catch(RemoteException re) {
throw re.unwrapRemoteException();
}
}
/**
* Save namespace image.
*
* @see ClientProtocol#saveNamespace()
*/
void saveNamespace() throws AccessControlException, IOException {
try {
namenode.saveNamespace();
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class);
}
}
/**
* Rolls the edit log on the active NameNode.
* @return the txid of the new log segment
*
* @see ClientProtocol#rollEdits()
*/
long rollEdits() throws AccessControlException, IOException {
try {
return namenode.rollEdits();
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class);
}
}
/**
* enable/disable restore failed storage.
*
* @see ClientProtocol#restoreFailedStorage(String arg)
*/
boolean restoreFailedStorage(String arg)
throws AccessControlException, IOException{
return namenode.restoreFailedStorage(arg);
}
/**
* Refresh the hosts and exclude files. (Rereads them.)
* See {@link ClientProtocol#refreshNodes()}
* for more details.
*
* @see ClientProtocol#refreshNodes()
*/
public void refreshNodes() throws IOException {
namenode.refreshNodes();
}
/**
* Dumps DFS data structures into specified file.
*
* @see ClientProtocol#metaSave(String)
*/
public void metaSave(String pathname) throws IOException {
namenode.metaSave(pathname);
}
/**
* Requests the namenode to tell all datanodes to use a new, non-persistent
* bandwidth value for dfs.balance.bandwidthPerSec.
* See {@link ClientProtocol#setBalancerBandwidth(long)}
* for more details.
*
* @see ClientProtocol#setBalancerBandwidth(long)
*/
public void setBalancerBandwidth(long bandwidth) throws IOException {
namenode.setBalancerBandwidth(bandwidth);
}
/**
* @see ClientProtocol#finalizeUpgrade()
*/
public void finalizeUpgrade() throws IOException {
namenode.finalizeUpgrade();
}
/**
*/
@Deprecated
public boolean mkdirs(String src) throws IOException {
return mkdirs(src, null, true);
}
/**
* Create a directory (or hierarchy of directories) with the given
* name and permission.
*
* @param src The path of the directory being created
* @param permission The permission of the directory being created.
* If permission == null, use {@link FsPermission#getDefault()}.
* @param createParent create missing parent directory if true
*
* @return True if the operation success.
*
* @see ClientProtocol#mkdirs(String, FsPermission, boolean)
*/
public boolean mkdirs(String src, FsPermission permission,
boolean createParent) throws IOException {
if (permission == null) {
permission = FsPermission.getDefault();
}
FsPermission masked = permission.applyUMask(dfsClientConf.uMask);
return primitiveMkdir(src, masked, createParent);
}
/**
* Same {{@link #mkdirs(String, FsPermission, boolean)} except
* that the permissions has already been masked against umask.
*/
public boolean primitiveMkdir(String src, FsPermission absPermission)
throws IOException {
return primitiveMkdir(src, absPermission, true);
}
/**
* Same {{@link #mkdirs(String, FsPermission, boolean)} except
* that the permissions has already been masked against umask.
*/
public boolean primitiveMkdir(String src, FsPermission absPermission,
boolean createParent)
throws IOException {
checkOpen();
if (absPermission == null) {
absPermission =
FsPermission.getDefault().applyUMask(dfsClientConf.uMask);
}
if(LOG.isDebugEnabled()) {
LOG.debug(src + ": masked=" + absPermission);
}
try {
return namenode.mkdirs(src, absPermission, createParent);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
InvalidPathException.class,
FileAlreadyExistsException.class,
FileNotFoundException.class,
ParentNotDirectoryException.class,
SafeModeException.class,
NSQuotaExceededException.class,
DSQuotaExceededException.class,
UnresolvedPathException.class,
SnapshotAccessControlException.class);
}
}
/**
* Get {@link ContentSummary} rooted at the specified directory.
* @param path The string representation of the path
*
* @see ClientProtocol#getContentSummary(String)
*/
ContentSummary getContentSummary(String src) throws IOException {
try {
return namenode.getContentSummary(src);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
FileNotFoundException.class,
UnresolvedPathException.class);
}
}
/**
* Sets or resets quotas for a directory.
* @see ClientProtocol#setQuota(String, long, long)
*/
void setQuota(String src, long namespaceQuota, long diskspaceQuota)
throws IOException {
// sanity check
if ((namespaceQuota <= 0 && namespaceQuota != HdfsConstants.QUOTA_DONT_SET &&
namespaceQuota != HdfsConstants.QUOTA_RESET) ||
(diskspaceQuota <= 0 && diskspaceQuota != HdfsConstants.QUOTA_DONT_SET &&
diskspaceQuota != HdfsConstants.QUOTA_RESET)) {
throw new IllegalArgumentException("Invalid values for quota : " +
namespaceQuota + " and " +
diskspaceQuota);
}
try {
namenode.setQuota(src, namespaceQuota, diskspaceQuota);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
FileNotFoundException.class,
NSQuotaExceededException.class,
DSQuotaExceededException.class,
UnresolvedPathException.class,
SnapshotAccessControlException.class);
}
}
/**
* set the modification and access time of a file
*
* @see ClientProtocol#setTimes(String, long, long)
*/
public void setTimes(String src, long mtime, long atime) throws IOException {
checkOpen();
try {
namenode.setTimes(src, mtime, atime);
} catch(RemoteException re) {
throw re.unwrapRemoteException(AccessControlException.class,
FileNotFoundException.class,
UnresolvedPathException.class,
SnapshotAccessControlException.class);
}
}
/**
* @deprecated use {@link HdfsDataInputStream} instead.
*/
@Deprecated
public static class DFSDataInputStream extends HdfsDataInputStream {
public DFSDataInputStream(DFSInputStream in) throws IOException {
super(in);
}
}
void reportChecksumFailure(String file, ExtendedBlock blk, DatanodeInfo dn) {
DatanodeInfo [] dnArr = { dn };
LocatedBlock [] lblocks = { new LocatedBlock(blk, dnArr) };
reportChecksumFailure(file, lblocks);
}
// just reports checksum failure and ignores any exception during the report.
void reportChecksumFailure(String file, LocatedBlock lblocks[]) {
try {
reportBadBlocks(lblocks);
} catch (IOException ie) {
LOG.info("Found corruption while reading " + file
+ ". Error repairing corrupt blocks. Bad blocks remain.", ie);
}
}
@Override
public String toString() {
return getClass().getSimpleName() + "[clientName=" + clientName
+ ", ugi=" + ugi + "]";
}
public DomainSocketFactory getDomainSocketFactory() {
return domainSocketFactory;
}
public void disableLegacyBlockReaderLocal() {
shouldUseLegacyBlockReaderLocal = false;
}
public boolean useLegacyBlockReaderLocal() {
return shouldUseLegacyBlockReaderLocal;
}
public CachingStrategy getDefaultReadCachingStrategy() {
return defaultReadCachingStrategy;
}
public CachingStrategy getDefaultWriteCachingStrategy() {
return defaultWriteCachingStrategy;
}
}
| apache-2.0 |
stoksey69/googleads-java-lib | modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201506/cm/SoapResponseHeader.java | 4033 |
package com.google.api.ads.adwords.jaxws.v201506.cm;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
*
* Defines the elements within the header of a SOAP response.
*
*
* <p>Java class for SoapResponseHeader complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="SoapResponseHeader">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="requestId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="serviceName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="methodName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="operations" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
* <element name="responseTime" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SoapResponseHeader", propOrder = {
"requestId",
"serviceName",
"methodName",
"operations",
"responseTime"
})
public class SoapResponseHeader {
protected String requestId;
protected String serviceName;
protected String methodName;
protected Long operations;
protected Long responseTime;
/**
* Gets the value of the requestId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRequestId() {
return requestId;
}
/**
* Sets the value of the requestId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRequestId(String value) {
this.requestId = value;
}
/**
* Gets the value of the serviceName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getServiceName() {
return serviceName;
}
/**
* Sets the value of the serviceName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setServiceName(String value) {
this.serviceName = value;
}
/**
* Gets the value of the methodName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMethodName() {
return methodName;
}
/**
* Sets the value of the methodName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMethodName(String value) {
this.methodName = value;
}
/**
* Gets the value of the operations property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getOperations() {
return operations;
}
/**
* Sets the value of the operations property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setOperations(Long value) {
this.operations = value;
}
/**
* Gets the value of the responseTime property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getResponseTime() {
return responseTime;
}
/**
* Sets the value of the responseTime property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setResponseTime(Long value) {
this.responseTime = value;
}
}
| apache-2.0 |
kay-kim/mongo-java-driver | driver-core/src/main/com/mongodb/event/package-info.java | 700 | /*
* Copyright 2015 MongoDB, 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.
*/
/**
* This package contains cluster and connection event related classes
*/
package com.mongodb.event;
| apache-2.0 |
shun634501730/java_source_cn | src_en/com/sun/corba/se/spi/protocol/LocalClientRequestDispatcher.java | 2154 | /*
* Copyright (c) 2002, 2003, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package com.sun.corba.se.spi.protocol;
import org.omg.CORBA.portable.ServantObject;
/**
* @author Harold Carr
*/
public interface LocalClientRequestDispatcher
{
public boolean useLocalInvocation(org.omg.CORBA.Object self);
public boolean is_local(org.omg.CORBA.Object self);
/**
* Returns a Java reference to the servant which should be used for this
* request. servant_preinvoke() is invoked by a local stub.
* If a ServantObject object is returned, then its servant field
* has been set to an object of the expected type (Note: the object may
* or may not be the actual servant instance). The local stub may cast
* the servant field to the expected type, and then invoke the operation
* directly.
*
* @param self The object reference which delegated to this delegate.
*
* @param operation a string containing the operation name.
* The operation name corresponds to the operation name as it would be
* encoded in a GIOP request.
*
* @param expectedType a Class object representing the expected type of the servant.
* The expected type is the Class object associated with the operations
* class of the stub's interface (e.g. A stub for an interface Foo,
* would pass the Class object for the FooOperations interface).
*
* @return a ServantObject object.
* The method may return a null value if it does not wish to support
* this optimization (e.g. due to security, transactions, etc).
* The method must return null if the servant is not of the expected type.
*/
public ServantObject servant_preinvoke(org.omg.CORBA.Object self,
String operation,
Class expectedType);
public void servant_postinvoke(org.omg.CORBA.Object self,
ServantObject servant);
}
// End of file.
| apache-2.0 |
codeaudit/OG-Platform | projects/OG-Financial/src/main/java/com/opengamma/financial/analytics/volatility/surface/ConfigDBFuturePriceCurveDefinitionSource.java | 2270 | /**
* Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.financial.analytics.volatility.surface;
import com.opengamma.core.config.ConfigSource;
import com.opengamma.engine.function.FunctionCompilationContext;
import com.opengamma.engine.function.FunctionDefinition;
import com.opengamma.financial.config.ConfigSourceQuery;
import com.opengamma.id.VersionCorrection;
/**
*
*/
public class ConfigDBFuturePriceCurveDefinitionSource implements FuturePriceCurveDefinitionSource {
@SuppressWarnings("rawtypes")
private final ConfigSourceQuery<FuturePriceCurveDefinition> _query;
/**
* @param configSource the config source, not null
* @deprecated Use {@link #ConfigDBFuturePriceCurveDefinitionSource(ConfigSource,VersionCorrection)} or {@link #init} instead
*/
@Deprecated
public ConfigDBFuturePriceCurveDefinitionSource(final ConfigSource configSource) {
this(configSource, VersionCorrection.LATEST);
}
@SuppressWarnings("rawtypes")
public ConfigDBFuturePriceCurveDefinitionSource(final ConfigSource configSource, final VersionCorrection versionCorrection) {
this(new ConfigSourceQuery<FuturePriceCurveDefinition>(configSource, FuturePriceCurveDefinition.class, versionCorrection));
}
@SuppressWarnings("rawtypes")
private ConfigDBFuturePriceCurveDefinitionSource(final ConfigSourceQuery<FuturePriceCurveDefinition> query) {
_query = query;
}
public static ConfigDBFuturePriceCurveDefinitionSource init(final FunctionCompilationContext context, final FunctionDefinition function) {
return new ConfigDBFuturePriceCurveDefinitionSource(ConfigSourceQuery.init(context, function, FuturePriceCurveDefinition.class));
}
protected ConfigSource getConfigSource() {
return _query.getConfigSource();
}
@Override
public FuturePriceCurveDefinition<?> getDefinition(final String name, final String instrumentType) {
return _query.get(name + "_" + instrumentType);
}
@Override
public FuturePriceCurveDefinition<?> getDefinition(final String name, final String instrumentType, final VersionCorrection versionCorrection) {
return _query.get(name + "_" + instrumentType, versionCorrection);
}
}
| apache-2.0 |
googleapis/discovery-artifact-manager | toolkit/src/main/java/com/google/api/codegen/config/ResourceNameMessageConfig.java | 1961 | /* Copyright 2016 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.api.codegen.config;
import com.google.api.codegen.ResourceNameMessageConfigProto;
import com.google.api.tools.framework.model.DiagCollector;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableMap;
import javax.annotation.Nullable;
/** Configuration of the resource name types for fields of a single message. */
@AutoValue
public abstract class ResourceNameMessageConfig {
public abstract String messageName();
abstract ImmutableMap<String, String> fieldEntityMap();
@Nullable
public static ResourceNameMessageConfig createResourceNameMessageConfig(
DiagCollector diagCollector,
ResourceNameMessageConfigProto messageResourceTypesProto,
String defaultPackage) {
String messageName = messageResourceTypesProto.getMessageName();
String fullyQualifiedMessageName;
if (messageName.contains(".")) {
fullyQualifiedMessageName = messageName;
} else {
fullyQualifiedMessageName = defaultPackage + "." + messageName;
}
ImmutableMap<String, String> fieldEntityMap =
ImmutableMap.copyOf(messageResourceTypesProto.getFieldEntityMap());
return new AutoValue_ResourceNameMessageConfig(fullyQualifiedMessageName, fieldEntityMap);
}
public String getEntityNameForField(String fieldSimpleName) {
return fieldEntityMap().get(fieldSimpleName);
}
}
| apache-2.0 |
goodwinnk/intellij-community | jvm/jvm-analysis-impl/src/com/intellij/codeInspection/StringToUpperWithoutLocale2Inspection.java | 3686 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInspection;
import com.intellij.analysis.JvmAnalysisBundle;
import com.intellij.psi.CommonClassNames;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.PsiIdentifier;
import com.siyeh.HardcodedMethodConstants;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.uast.UCallExpression;
import org.jetbrains.uast.UCallableReferenceExpression;
import org.jetbrains.uast.UElement;
import org.jetbrains.uast.UastContextKt;
public class StringToUpperWithoutLocale2Inspection extends AbstractBaseUastLocalInspectionTool {
@Nls
@NotNull
@Override
public String getDisplayName() { //TODO remove once inspection is registered in JvmAnalysisPlugin.xml
return "StringToUpperWithoutLocale2Inspection";
}
private static final UastCallMatcher MATCHER = UastCallMatcher.anyOf(
UastCallMatcher.builder()
.withMethodName(HardcodedMethodConstants.TO_UPPER_CASE)
.withClassFqn(CommonClassNames.JAVA_LANG_STRING)
.withArgumentsCount(0).build(),
UastCallMatcher.builder()
.withMethodName(HardcodedMethodConstants.TO_LOWER_CASE)
.withClassFqn(CommonClassNames.JAVA_LANG_STRING)
.withArgumentsCount(0).build()
);
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly) {
return new PsiElementVisitor() {
@Override
public void visitElement(PsiElement element) {
UCallExpression callExpression = AnalysisUastUtil.getUCallExpression(element);
if (callExpression != null) {
handleCallExpression(callExpression, holder);
return;
}
if (!(element instanceof PsiIdentifier)) return;
PsiElement parent = element.getParent();
UElement parentUElement = UastContextKt.toUElement(parent);
if (parentUElement instanceof UCallableReferenceExpression) {
handleCallableReferenceExpression((UCallableReferenceExpression)parentUElement, element, holder);
}
}
};
}
private static void handleCallExpression(@NotNull UCallExpression callExpression, @NotNull ProblemsHolder holder) {
if (!MATCHER.testCallExpression(callExpression)) return;
if (NonNlsUastUtil.isCallExpressionWithNonNlsReceiver(callExpression)) return;
PsiElement methodIdentifierPsi = AnalysisUastUtil.getMethodIdentifierSourcePsi(callExpression);
if (methodIdentifierPsi == null) return;
String methodName = callExpression.getMethodName();
if (methodName == null) return; // shouldn't happen
holder.registerProblem(methodIdentifierPsi, getErrorDescription(methodName));
}
private static void handleCallableReferenceExpression(@NotNull UCallableReferenceExpression expression,
@NotNull PsiElement identifier,
@NotNull ProblemsHolder holder) {
if (!MATCHER.testCallableReferenceExpression(expression)) return;
if (NonNlsUastUtil.isCallableReferenceExpressionWithNonNlsQualifier(expression)) return;
holder.registerProblem(identifier, getErrorDescription(expression.getCallableName()));
}
@NotNull
private static String getErrorDescription(@NotNull String methodName) {
return JvmAnalysisBundle.message("jvm.inspections.string.touppercase.tolowercase.without.locale.description", methodName);
}
}
| apache-2.0 |
glimpseio/incubator-calcite | core/src/main/java/org/apache/calcite/interpreter/Sink.java | 1077 | /*
* 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.calcite.interpreter;
/**
* Sink to which to send rows.
*
* <p>Corresponds to an output of a relational expression.
*/
public interface Sink {
void send(Row row) throws InterruptedException;
void end() throws InterruptedException;
}
// End Sink.java
| apache-2.0 |
WangTaoTheTonic/flink | flink-runtime/src/main/java/org/apache/flink/runtime/metrics/scope/ScopeFormats.java | 5532 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.runtime.metrics.scope;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.MetricOptions;
import static org.apache.flink.util.Preconditions.checkNotNull;
/**
* A container for component scope formats.
*/
public class ScopeFormats {
private final JobManagerScopeFormat jobManagerFormat;
private final JobManagerJobScopeFormat jobManagerJobFormat;
private final TaskManagerScopeFormat taskManagerFormat;
private final TaskManagerJobScopeFormat taskManagerJobFormat;
private final TaskScopeFormat taskFormat;
private final OperatorScopeFormat operatorFormat;
// ------------------------------------------------------------------------
/**
* Creates all default scope formats.
*/
public ScopeFormats() {
this.jobManagerFormat = new JobManagerScopeFormat(MetricOptions.SCOPE_NAMING_JM.defaultValue());
this.jobManagerJobFormat = new JobManagerJobScopeFormat(
MetricOptions.SCOPE_NAMING_JM_JOB.defaultValue(), this.jobManagerFormat);
this.taskManagerFormat = new TaskManagerScopeFormat(MetricOptions.SCOPE_NAMING_TM.defaultValue());
this.taskManagerJobFormat = new TaskManagerJobScopeFormat(
MetricOptions.SCOPE_NAMING_TM_JOB.defaultValue(), this.taskManagerFormat);
this.taskFormat = new TaskScopeFormat(
MetricOptions.SCOPE_NAMING_TASK.defaultValue(), this.taskManagerJobFormat);
this.operatorFormat = new OperatorScopeFormat(
MetricOptions.SCOPE_NAMING_OPERATOR.defaultValue(), this.taskFormat);
}
/**
* Creates all scope formats, based on the given scope format strings.
*/
public ScopeFormats(
String jobManagerFormat,
String jobManagerJobFormat,
String taskManagerFormat,
String taskManagerJobFormat,
String taskFormat,
String operatorFormat)
{
this.jobManagerFormat = new JobManagerScopeFormat(jobManagerFormat);
this.jobManagerJobFormat = new JobManagerJobScopeFormat(jobManagerJobFormat, this.jobManagerFormat);
this.taskManagerFormat = new TaskManagerScopeFormat(taskManagerFormat);
this.taskManagerJobFormat = new TaskManagerJobScopeFormat(taskManagerJobFormat, this.taskManagerFormat);
this.taskFormat = new TaskScopeFormat(taskFormat, this.taskManagerJobFormat);
this.operatorFormat = new OperatorScopeFormat(operatorFormat, this.taskFormat);
}
/**
* Creates a {@code ScopeFormats} with the given scope formats.
*/
public ScopeFormats(
JobManagerScopeFormat jobManagerFormat,
JobManagerJobScopeFormat jobManagerJobFormat,
TaskManagerScopeFormat taskManagerFormat,
TaskManagerJobScopeFormat taskManagerJobFormat,
TaskScopeFormat taskFormat,
OperatorScopeFormat operatorFormat)
{
this.jobManagerFormat = checkNotNull(jobManagerFormat);
this.jobManagerJobFormat = checkNotNull(jobManagerJobFormat);
this.taskManagerFormat = checkNotNull(taskManagerFormat);
this.taskManagerJobFormat = checkNotNull(taskManagerJobFormat);
this.taskFormat = checkNotNull(taskFormat);
this.operatorFormat = checkNotNull(operatorFormat);
}
// ------------------------------------------------------------------------
// Accessors
// ------------------------------------------------------------------------
public JobManagerScopeFormat getJobManagerFormat() {
return this.jobManagerFormat;
}
public TaskManagerScopeFormat getTaskManagerFormat() {
return this.taskManagerFormat;
}
public TaskManagerJobScopeFormat getTaskManagerJobFormat() {
return this.taskManagerJobFormat;
}
public JobManagerJobScopeFormat getJobManagerJobFormat() {
return this.jobManagerJobFormat;
}
public TaskScopeFormat getTaskFormat() {
return this.taskFormat;
}
public OperatorScopeFormat getOperatorFormat() {
return this.operatorFormat;
}
// ------------------------------------------------------------------------
// Parsing from Config
// ------------------------------------------------------------------------
/**
* Creates the scope formats as defined in the given configuration
*
* @param config The configuration that defines the formats
* @return The ScopeFormats parsed from the configuration
*/
public static ScopeFormats fromConfig(Configuration config) {
String jmFormat = config.getString(MetricOptions.SCOPE_NAMING_JM);
String jmJobFormat = config.getString(MetricOptions.SCOPE_NAMING_JM_JOB);
String tmFormat = config.getString(MetricOptions.SCOPE_NAMING_TM);
String tmJobFormat = config.getString(MetricOptions.SCOPE_NAMING_TM_JOB);
String taskFormat = config.getString(MetricOptions.SCOPE_NAMING_TASK);
String operatorFormat = config.getString(MetricOptions.SCOPE_NAMING_OPERATOR);
return new ScopeFormats(jmFormat, jmJobFormat, tmFormat, tmJobFormat, taskFormat, operatorFormat);
}
}
| apache-2.0 |
shakamunyi/hadoop-20 | src/core/org/apache/hadoop/util/NativeCrc32.java | 5310 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.util;
import java.nio.ByteBuffer;
import java.util.zip.Checksum;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.ChecksumException;
/**
* Wrapper around JNI support code to do checksum computation
* natively.
*/
public class NativeCrc32 implements Checksum {
static {
NativeCodeLoader.isNativeCodeLoaded();
}
/** the current CRC value, bit-flipped */
private int crc;
private final PureJavaCrc32 pureJavaCrc32 = new PureJavaCrc32();
private final PureJavaCrc32C pureJavaCrc32C = new PureJavaCrc32C();
private int checksumType = CHECKSUM_CRC32;
private boolean isAvailable = true;
// Local benchmarks show that for >= 128 bytes, NativeCrc32 performs
// better than PureJavaCrc32.
private static final int SMALL_CHECKSUM = 128;
private static final Log LOG = LogFactory.getLog(NativeCrc32.class);
public NativeCrc32(int checksumType) {
this();
if (checksumType != CHECKSUM_CRC32 && checksumType != CHECKSUM_CRC32C) {
throw new IllegalArgumentException("Invalid checksum type");
}
this.checksumType = checksumType;
}
public NativeCrc32() {
isAvailable = isAvailable();
reset();
}
/** {@inheritDoc} */
public long getValue() {
return (~crc) & 0xffffffffL;
}
public void setValue(int crc) {
this.crc = ~crc;
}
/** {@inheritDoc} */
public void reset() {
crc = 0xffffffff;
}
/**
* Return true if the JNI-based native CRC extensions are available.
*/
public static boolean isAvailable() {
return NativeCodeLoader.isNativeCodeLoaded();
}
/**
* Verify the given buffers of data and checksums, and throw an exception
* if any checksum is invalid. The buffers given to this function should
* have their position initially at the start of the data, and their limit
* set at the end of the data. The position, limit, and mark are not
* modified.
*
* @param bytesPerSum the chunk size (eg 512 bytes)
* @param checksumType the DataChecksum type constant
* @param sums the DirectByteBuffer pointing at the beginning of the
* stored checksums
* @param data the DirectByteBuffer pointing at the beginning of the
* data to check
* @param basePos the position in the file where the data buffer starts
* @param fileName the name of the file being verified
* @throws ChecksumException if there is an invalid checksum
*/
public static void verifyChunkedSums(int bytesPerSum, int checksumType,
ByteBuffer sums, ByteBuffer data, String fileName, long basePos)
throws ChecksumException {
nativeVerifyChunkedSums(bytesPerSum, checksumType,
sums, sums.position(),
data, data.position(), data.remaining(),
fileName, basePos);
}
public void update(int b) {
byte[] buf = new byte[1];
buf[0] = (byte)b;
update(buf, 0, buf.length);
}
private void updatePureJava(byte[] buf, int offset, int len) {
if (checksumType == CHECKSUM_CRC32) {
pureJavaCrc32.setValueInternal(crc);
pureJavaCrc32.update(buf, offset, len);
crc = pureJavaCrc32.getCrcValue();
} else {
pureJavaCrc32C.setValueInternal(crc);
pureJavaCrc32C.update(buf, offset, len);
crc = pureJavaCrc32C.getCrcValue();
}
}
public void update(byte[] buf, int offset, int len) {
// To avoid JNI overhead, use native methods only for large checksum chunks.
if (isAvailable && len >= SMALL_CHECKSUM) {
try {
crc = update(crc, buf, offset, len, checksumType);
} catch (UnsatisfiedLinkError ule) {
isAvailable = false;
LOG.warn("Could not find native crc32 libraries," +
" falling back to pure java", ule);
updatePureJava(buf, offset, len);
}
} else {
updatePureJava(buf, offset, len);
}
}
public native int update(int crc, byte[] buf, int offset, int len, int checksumType);
private static native void nativeVerifyChunkedSums(
int bytesPerSum, int checksumType,
ByteBuffer sums, int sumsOffset,
ByteBuffer data, int dataOffset, int dataLength,
String fileName, long basePos);
// Copy the constants over from DataChecksum so that javah will pick them up
// and make them available in the native code header.
public static final int CHECKSUM_CRC32 = DataChecksum.CHECKSUM_CRC32;
public static final int CHECKSUM_CRC32C = DataChecksum.CHECKSUM_CRC32C;
}
| apache-2.0 |
minudika/carbon-analytics | components/org.wso2.carbon.editor.log.appender/src/main/java/org/wso2/carbon/editor/log/appender/EditorConsoleAppender.java | 6241 | /*
* Copyright 2017 WSO2, Inc. (http://wso2.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 org.wso2.carbon.editor.log.appender;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.Core;
import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.appender.AbstractAppender;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginElement;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import org.apache.logging.log4j.core.layout.PatternLayout;
import org.apache.logging.log4j.core.util.Booleans;
import org.owasp.encoder.Encode;
import org.wso2.carbon.editor.log.appender.internal.CircularBuffer;
import org.wso2.carbon.editor.log.appender.internal.ConsoleLogEvent;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
/**
* This appender will be used to capture the logs and later send to clients, if requested via the
* logging web service.
* This maintains a circular buffer, of some fixed amount {@value #BUFFER_SIZE}.
*/
@Plugin(name = "EditorConsole", category = Core.CATEGORY_NAME, elementType = Appender.ELEMENT_TYPE, printObject = true)
public final class EditorConsoleAppender extends AbstractAppender {
/**
* Fixed size of the circular buffer {@value #BUFFER_SIZE}
*/
private static final int BUFFER_SIZE = 10;
/**
* Date Formatter to decode timestamp
*/
private final SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss_SSS");
/**
* CircularBuffer to hold the log events
*/
private CircularBuffer<ConsoleLogEvent> circularBuffer;
/**
* Creates an instance of EditorConsoleAppender.
*
* @param name appender name
* @param filter null if not specified
* @param layout pattern of log messages
* @param ignoreExceptions default is true
* <p>
* Called by {@link #createAppender(String, Filter, Layout, String, String)}
*/
private EditorConsoleAppender(final String name, final Filter filter,
final Layout<? extends Serializable> layout, final boolean ignoreExceptions) {
super(name, filter, layout, ignoreExceptions);
activateOptions();
}
/**
* Taken from the previous EditorConsoleAppender
*/
public void activateOptions() {
this.circularBuffer = DataHolder.getBuffer(BUFFER_SIZE);
}
/**
* Creates a EditorConsoleAppender instance with
* attributes configured in log4j2.properties.
*
* @param name appender name
* @param filter null if not specified
* @param layout pattern of log messages
* @param ignore default is true
* @return intance of EditorConsoleAppender
*/
@PluginFactory
public static EditorConsoleAppender createAppender(@PluginAttribute("name") final String name,
@PluginElement("Filters") final Filter filter,
@PluginElement("Layout") Layout<? extends Serializable> layout,
@PluginAttribute("ignoreExceptions") final String ignore,
@PluginAttribute("buffSize") final String buffSize) {
if (name == null) {
LOGGER.error("No name provided for EditorConsoleAppender");
return null;
} else {
if (layout == null) {
layout = PatternLayout.createDefaultLayout();
}
final boolean ignoreExceptions = Booleans.parseBoolean(ignore, true);
return new EditorConsoleAppender(name, filter, layout, ignoreExceptions);
}
}
/**
* This is the overridden method from the Appender interface. {@link Appender}
* This allows to write log events to preferred destination.
* <p>
* Converts the default log events to tenant aware log events and writes to a CircularBuffer
*
* @param logEvent the LogEvent object
*/
@Override
public void append(LogEvent logEvent) {
if (circularBuffer != null) {
circularBuffer.append(populateConsoleLogEvent(logEvent));
}
}
private ConsoleLogEvent populateConsoleLogEvent(LogEvent logEvent) {
ConsoleLogEvent consoleLogEvent = new ConsoleLogEvent();
consoleLogEvent.setFqcn(logEvent.getLoggerName());
consoleLogEvent.setLevel(logEvent.getLevel().name());
consoleLogEvent.setMessage(getEncodedString(logEvent.getMessage().getFormattedMessage()));
String dateString = dateFormatter.format(logEvent.getTimeMillis());
consoleLogEvent.setTimeStamp(dateString);
if (logEvent.getThrown() != null) {
consoleLogEvent.setStacktrace(getStacktrace(logEvent.getThrown()));
}
return consoleLogEvent;
}
private String getStacktrace(Throwable e) {
StringWriter stringWriter = new StringWriter();
e.printStackTrace(new PrintWriter(stringWriter));
return stringWriter.toString().trim();
}
private static String getEncodedString(String str) {
String cleanedString = Encode.forHtml(str);
if (!cleanedString.equals(str)) {
cleanedString += " (Encoded)";
}
return cleanedString;
}
}
| apache-2.0 |
tsegismont/hawkular-metrics | core/metrics-core-service/src/main/java/org/hawkular/metrics/core/service/transformers/TaggedDataPointCollector.java | 3340 | /*
* Copyright 2014-2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.hawkular.metrics.core.service.transformers;
import static org.hawkular.metrics.core.service.transformers.NumericDataPointCollector.createPercentile;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.math3.stat.descriptive.moment.Mean;
import org.apache.commons.math3.stat.descriptive.rank.Max;
import org.apache.commons.math3.stat.descriptive.rank.Min;
import org.apache.commons.math3.stat.descriptive.summary.Sum;
import org.hawkular.metrics.core.service.PercentileWrapper;
import org.hawkular.metrics.model.DataPoint;
import org.hawkular.metrics.model.Percentile;
import org.hawkular.metrics.model.TaggedBucketPoint;
/**
* @author jsanda
*/
public class TaggedDataPointCollector {
// These are the tags that define this bucket.
private Map<String, String> tags;
private int samples = 0;
private Min min = new Min();
private Mean average = new Mean();
private Max max = new Max();
private Sum sum = new Sum();
private List<PercentileWrapper> percentiles;
private List<Percentile> percentileList;
public TaggedDataPointCollector(Map<String, String> tags, List<Percentile> percentilesList) {
this.tags = tags;
this.percentiles = new ArrayList<>(percentilesList.size() + 1);
this.percentileList = percentilesList;
percentilesList.stream().forEach(d -> percentiles.add(createPercentile.apply(d.getQuantile())));
percentiles.add(createPercentile.apply(50.0)); // Important to be the last one
}
public void increment(DataPoint<? extends Number> dataPoint) {
Number value = dataPoint.getValue();
min.increment(value.doubleValue());
average.increment(value.doubleValue());
max.increment(value.doubleValue());
sum.increment(value.doubleValue());
samples++;
percentiles.stream().forEach(p -> p.addValue(value.doubleValue()));
}
public TaggedBucketPoint toBucketPoint() {
List<Percentile> percentileReturns = new ArrayList<>(percentileList.size());
if(percentileList.size() > 0) {
for(int i = 0; i < percentileList.size(); i++) {
Percentile p = percentileList.get(i);
PercentileWrapper pw = percentiles.get(i);
percentileReturns.add(new Percentile(p.getOriginalQuantile(), pw.getResult()));
}
}
return new TaggedBucketPoint(tags, min.getResult(), average.getResult(),
this.percentiles.get(this.percentiles.size() - 1).getResult(), max.getResult(), sum.getResult(),
samples, percentileReturns);
}
}
| apache-2.0 |
Potass/ConnectBot | app/src/main/java/org/connectbot/util/VolumePreference.java | 2105 | /*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* 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.connectbot.util;
import android.content.Context;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import org.connectbot.R;
/**
* @author kenny
*
*/
public class VolumePreference extends DialogPreference implements OnSeekBarChangeListener {
/**
* @param context
* @param attrs
*/
public VolumePreference(Context context, AttributeSet attrs) {
super(context, attrs);
setupLayout(context, attrs);
}
public VolumePreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setupLayout(context, attrs);
}
private void setupLayout(Context context, AttributeSet attrs) {
setDialogLayoutResource(R.layout.volume_preference_dialog_layout);
setPersistent(true);
}
@Override
protected void onBindDialogView(View view) {
super.onBindDialogView(view);
SeekBar volumeBar = (SeekBar) view.findViewById(R.id.volume_bar);
volumeBar.setProgress((int) (getPersistedFloat(
PreferenceConstants.DEFAULT_BELL_VOLUME) * 100));
volumeBar.setOnSeekBarChangeListener(this);
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
persistFloat(progress / 100f);
}
public void onStartTrackingTouch(SeekBar seekBar) { }
public void onStopTrackingTouch(SeekBar seekBar) { }
}
| apache-2.0 |
uaraven/nano | sample/webservice/HelloAmazonProductAdvertising/src/com/amazon/webservices/awsecommerceservice/_2011_08_01/EditorialReview.java | 663 | // Generated by xsd compiler for android/java
// DO NOT CHANGE!
package com.amazon.webservices.awsecommerceservice._2011_08_01;
import java.io.Serializable;
import com.leansoft.nano.annotation.*;
@RootElement(name = "EditorialReview", namespace = "http://webservices.amazon.com/AWSECommerceService/2011-08-01")
public class EditorialReview implements Serializable {
private static final long serialVersionUID = -1L;
@Element(name = "Source")
@Order(value=0)
public String source;
@Element(name = "Content")
@Order(value=1)
public String content;
@Element(name = "IsLinkSuppressed")
@Order(value=2)
public Boolean isLinkSuppressed;
} | apache-2.0 |
BigData-Lab-Frankfurt/HiBench-DSE | common/mahout-distribution-0.7-hadoop1/math/target/generated-test-sources/org/apache/mahout/math/map/OpenIntLongHashMapTest.java | 11143 | /**
* 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.mahout.math.map;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.mahout.math.function.IntLongProcedure;
import org.apache.mahout.math.function.IntProcedure;
import org.apache.mahout.math.list.IntArrayList;
import org.apache.mahout.math.list.LongArrayList;
import org.apache.mahout.math.set.AbstractSet;
import org.junit.Assert;
import org.junit.Test;
public class OpenIntLongHashMapTest extends Assert {
@Test
public void testConstructors() {
OpenIntLongHashMap map = new OpenIntLongHashMap();
int[] capacity = new int[1];
double[] minLoadFactor = new double[1];
double[] maxLoadFactor = new double[1];
map.getInternalFactors(capacity, minLoadFactor, maxLoadFactor);
assertEquals(AbstractSet.defaultCapacity, capacity[0]);
assertEquals(AbstractSet.defaultMaxLoadFactor, maxLoadFactor[0], 0.001);
assertEquals(AbstractSet.defaultMinLoadFactor, minLoadFactor[0], 0.001);
int prime = PrimeFinder.nextPrime(907);
map = new OpenIntLongHashMap(prime);
map.getInternalFactors(capacity, minLoadFactor, maxLoadFactor);
assertEquals(prime, capacity[0]);
assertEquals(AbstractSet.defaultMaxLoadFactor, maxLoadFactor[0], 0.001);
assertEquals(AbstractSet.defaultMinLoadFactor, minLoadFactor[0], 0.001);
map = new OpenIntLongHashMap(prime, 0.4, 0.8);
map.getInternalFactors(capacity, minLoadFactor, maxLoadFactor);
assertEquals(prime, capacity[0]);
assertEquals(0.4, minLoadFactor[0], 0.001);
assertEquals(0.8, maxLoadFactor[0], 0.001);
}
@Test
public void testEnsureCapacity() {
OpenIntLongHashMap map = new OpenIntLongHashMap();
int prime = PrimeFinder.nextPrime(907);
map.ensureCapacity(prime);
int[] capacity = new int[1];
double[] minLoadFactor = new double[1];
double[] maxLoadFactor = new double[1];
map.getInternalFactors(capacity, minLoadFactor, maxLoadFactor);
assertEquals(prime, capacity[0]);
}
@Test
public void testClear() {
OpenIntLongHashMap map = new OpenIntLongHashMap();
map.put((int) 11, (long) 22);
assertEquals(1, map.size());
map.clear();
assertEquals(0, map.size());
assertEquals(0, map.get((int) 11), 0.0000001);
}
@Test
public void testClone() {
OpenIntLongHashMap map = new OpenIntLongHashMap();
map.put((int) 11, (long) 22);
OpenIntLongHashMap map2 = (OpenIntLongHashMap) map.clone();
map.clear();
assertEquals(1, map2.size());
}
@Test
public void testContainsKey() {
OpenIntLongHashMap map = new OpenIntLongHashMap();
map.put((int) 11, (long) 22);
assertTrue(map.containsKey((int) 11));
assertFalse(map.containsKey((int) 12));
}
@Test
public void testContainValue() {
OpenIntLongHashMap map = new OpenIntLongHashMap();
map.put((int) 11, (long) 22);
assertTrue(map.containsValue((long) 22));
assertFalse(map.containsValue((long) 23));
}
@Test
public void testForEachKey() {
final IntArrayList keys = new IntArrayList();
OpenIntLongHashMap map = new OpenIntLongHashMap();
map.put((int) 11, (long) 22);
map.put((int) 12, (long) 23);
map.put((int) 13, (long) 24);
map.put((int) 14, (long) 25);
map.removeKey((int) 13);
map.forEachKey(new IntProcedure() {
@Override
public boolean apply(int element) {
keys.add(element);
return true;
}
});
int[] keysArray = keys.toArray(new int[keys.size()]);
Arrays.sort(keysArray);
assertArrayEquals(new int[] {11, 12, 14}, keysArray );
}
private static class Pair implements Comparable<Pair> {
int k;
long v;
Pair(int k, long v) {
this.k = k;
this.v = v;
}
@Override
public int compareTo(Pair o) {
if (k < o.k) {
return -1;
} else if (k == o.k) {
return 0;
} else {
return 1;
}
}
}
@Test
public void testForEachPair() {
final List<Pair> pairs = new ArrayList<Pair>();
OpenIntLongHashMap map = new OpenIntLongHashMap();
map.put((int) 11, (long) 22);
map.put((int) 12, (long) 23);
map.put((int) 13, (long) 24);
map.put((int) 14, (long) 25);
map.removeKey((int) 13);
map.forEachPair(new IntLongProcedure() {
@Override
public boolean apply(int first, long second) {
pairs.add(new Pair(first, second));
return true;
}
});
Collections.sort(pairs);
assertEquals(3, pairs.size());
assertEquals((int) 11, pairs.get(0).k );
assertEquals((long) 22, pairs.get(0).v );
assertEquals((int) 12, pairs.get(1).k );
assertEquals((long) 23, pairs.get(1).v );
assertEquals((int) 14, pairs.get(2).k );
assertEquals((long) 25, pairs.get(2).v );
pairs.clear();
map.forEachPair(new IntLongProcedure() {
int count = 0;
@Override
public boolean apply(int first, long second) {
pairs.add(new Pair(first, second));
count++;
return count < 2;
}
});
assertEquals(2, pairs.size());
}
@Test
public void testGet() {
OpenIntLongHashMap map = new OpenIntLongHashMap();
map.put((int) 11, (long) 22);
map.put((int) 12, (long) 23);
assertEquals(22, map.get((int)11) );
assertEquals(0, map.get((int)0) );
}
@Test
public void testAdjustOrPutValue() {
OpenIntLongHashMap map = new OpenIntLongHashMap();
map.put((int) 11, (long) 22);
map.put((int) 12, (long) 23);
map.put((int) 13, (long) 24);
map.put((int) 14, (long) 25);
map.adjustOrPutValue((int)11, (long)1, (long)3);
assertEquals(25, map.get((int)11) );
map.adjustOrPutValue((int)15, (long)1, (long)3);
assertEquals(1, map.get((int)15) );
}
@Test
public void testKeys() {
OpenIntLongHashMap map = new OpenIntLongHashMap();
map.put((int) 11, (long) 22);
map.put((int) 12, (long) 22);
IntArrayList keys = new IntArrayList();
map.keys(keys);
keys.sort();
assertEquals(11, keys.get(0) );
assertEquals(12, keys.get(1) );
IntArrayList k2 = map.keys();
k2.sort();
assertEquals(keys, k2);
}
@Test
public void testPairsMatching() {
IntArrayList keyList = new IntArrayList();
LongArrayList valueList = new LongArrayList();
OpenIntLongHashMap map = new OpenIntLongHashMap();
map.put((int) 11, (long) 22);
map.put((int) 12, (long) 23);
map.put((int) 13, (long) 24);
map.put((int) 14, (long) 25);
map.removeKey((int) 13);
map.pairsMatching(new IntLongProcedure() {
@Override
public boolean apply(int first, long second) {
return (first % 2) == 0;
}},
keyList, valueList);
keyList.sort();
valueList.sort();
assertEquals(2, keyList.size());
assertEquals(2, valueList.size());
assertEquals(12, keyList.get(0) );
assertEquals(14, keyList.get(1) );
assertEquals(23, valueList.get(0) );
assertEquals(25, valueList.get(1) );
}
@Test
public void testValues() {
OpenIntLongHashMap map = new OpenIntLongHashMap();
map.put((int) 11, (long) 22);
map.put((int) 12, (long) 23);
map.put((int) 13, (long) 24);
map.put((int) 14, (long) 25);
map.removeKey((int) 13);
LongArrayList values = new LongArrayList(100);
map.values(values);
assertEquals(3, values.size());
values.sort();
assertEquals(22, values.get(0) );
assertEquals(23, values.get(1) );
assertEquals(25, values.get(2) );
}
// tests of the code in the abstract class
@Test
public void testCopy() {
OpenIntLongHashMap map = new OpenIntLongHashMap();
map.put((int) 11, (long) 22);
OpenIntLongHashMap map2 = (OpenIntLongHashMap) map.copy();
map.clear();
assertEquals(1, map2.size());
}
@Test
public void testEquals() {
// since there are no other subclasses of
// Abstractxxx available, we have to just test the
// obvious.
OpenIntLongHashMap map = new OpenIntLongHashMap();
map.put((int) 11, (long) 22);
map.put((int) 12, (long) 23);
map.put((int) 13, (long) 24);
map.put((int) 14, (long) 25);
map.removeKey((int) 13);
OpenIntLongHashMap map2 = (OpenIntLongHashMap) map.copy();
assertEquals(map, map2);
assertTrue(map2.equals(map));
assertFalse("Hello Sailor".equals(map));
assertFalse(map.equals("hello sailor"));
map2.removeKey((int) 11);
assertFalse(map.equals(map2));
assertFalse(map2.equals(map));
}
// keys() tested in testKeys
@Test
public void testKeysSortedByValue() {
OpenIntLongHashMap map = new OpenIntLongHashMap();
map.put((int) 11, (long) 22);
map.put((int) 12, (long) 23);
map.put((int) 13, (long) 24);
map.put((int) 14, (long) 25);
map.removeKey((int) 13);
IntArrayList keys = new IntArrayList();
map.keysSortedByValue(keys);
int[] keysArray = keys.toArray(new int[keys.size()]);
assertArrayEquals(new int[] {11, 12, 14},
keysArray );
}
@Test
public void testPairsSortedByKey() {
OpenIntLongHashMap map = new OpenIntLongHashMap();
map.put((int) 11, (long) 100);
map.put((int) 12, (long) 70);
map.put((int) 13, (long) 30);
map.put((int) 14, (long) 3);
IntArrayList keys = new IntArrayList();
LongArrayList values = new LongArrayList();
map.pairsSortedByKey(keys, values);
assertEquals(4, keys.size());
assertEquals(4, values.size());
assertEquals((int) 11, keys.get(0) );
assertEquals((long) 100, values.get(0) );
assertEquals((int) 12, keys.get(1) );
assertEquals((long) 70, values.get(1) );
assertEquals((int) 13, keys.get(2) );
assertEquals((long) 30, values.get(2) );
assertEquals((int) 14, keys.get(3) );
assertEquals((long) 3, values.get(3) );
keys.clear();
values.clear();
map.pairsSortedByValue(keys, values);
assertEquals((int) 11, keys.get(3) );
assertEquals((long) 100, values.get(3) );
assertEquals((int) 12, keys.get(2) );
assertEquals((long) 70, values.get(2) );
assertEquals((int) 13, keys.get(1) );
assertEquals((long) 30, values.get(1) );
assertEquals((int) 14, keys.get(0) );
assertEquals((long) 3, values.get(0) );
}
}
| apache-2.0 |
ydai1124/gobblin-1 | gobblin-restli/gobblin-throttling-service/gobblin-throttling-service-client/src/main/java/gobblin/util/limiter/stressTest/FixedOperationsStressor.java | 1650 | /*
* 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 gobblin.util.limiter.stressTest;
import org.apache.hadoop.conf.Configuration;
import gobblin.util.limiter.Limiter;
/**
* A {@link Stressor} that performs a fixed number of permit requests to the {@link Limiter} without pausing.
*/
public class FixedOperationsStressor extends RandomDelayStartStressor {
public static final String OPS_TO_RUN = "fixedOperationsStressor.opsToRun";
public static final int DEFAULT_OPS_TARGET = 200;
private int opsTarget;
@Override
public void configure(Configuration configuration) {
super.configure(configuration);
this.opsTarget = configuration.getInt(OPS_TO_RUN, DEFAULT_OPS_TARGET);
}
@Override
public void doRun(Limiter limiter) throws InterruptedException {
int ops = 0;
while (ops < this.opsTarget) {
limiter.acquirePermits(1);
ops++;
}
}
}
| apache-2.0 |
troyel/dhis2-core | dhis-2/dhis-support/dhis-support-system/src/main/java/org/hisp/dhis/system/collection/TaskLocalMap.java | 2264 | package org.hisp.dhis.system.collection;
/*
* Copyright (c) 2004-2017, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.util.HashMap;
import java.util.Map;
import org.hisp.dhis.scheduling.TaskId;
/**
* @author Lars Helge Overland
*/
public class TaskLocalMap<T, V>
{
private final Map<TaskId, Map<T, V>> internalMap;
public TaskLocalMap()
{
this.internalMap = new HashMap<>();
}
public Map<T, V> get( TaskId id )
{
Map<T, V> map = internalMap.get( id );
if ( map == null )
{
map = new HashMap<>();
internalMap.put( id, map );
}
return map;
}
public boolean clear( TaskId id )
{
return internalMap.remove( id ) != null;
}
}
| bsd-3-clause |
ric2b/Vivaldi-browser | chromium/chrome/android/javatests/src/org/chromium/chrome/browser/bookmarks/BookmarkBridgeTest.java | 18666 | // Copyright 2014 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.chrome.browser.bookmarks;
import androidx.test.filters.SmallTest;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.chromium.base.test.BaseJUnit4ClassRunner;
import org.chromium.base.test.UiThreadTest;
import org.chromium.base.test.util.Batch;
import org.chromium.base.test.util.DisabledTest;
import org.chromium.base.test.util.Feature;
import org.chromium.base.test.util.RequiresRestart;
import org.chromium.chrome.browser.bookmarks.BookmarkBridge.BookmarkItem;
import org.chromium.chrome.browser.flags.ChromeFeatureList;
import org.chromium.chrome.browser.power_bookmarks.PowerBookmarkMeta;
import org.chromium.chrome.browser.power_bookmarks.PowerBookmarkType;
import org.chromium.chrome.browser.power_bookmarks.ShoppingSpecifics;
import org.chromium.chrome.browser.profiles.Profile;
import org.chromium.chrome.browser.subscriptions.CommerceSubscription;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.test.ChromeBrowserTestRule;
import org.chromium.chrome.test.util.BookmarkTestUtil;
import org.chromium.chrome.test.util.browser.Features;
import org.chromium.components.bookmarks.BookmarkId;
import org.chromium.components.bookmarks.BookmarkType;
import org.chromium.content_public.browser.test.util.TestThreadUtils;
import org.chromium.url.GURL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
/**
* Tests for bookmark bridge
*/
@RunWith(BaseJUnit4ClassRunner.class)
@Batch(Batch.PER_CLASS)
public class BookmarkBridgeTest {
@Rule
public final ChromeBrowserTestRule mChromeBrowserTestRule = new ChromeBrowserTestRule();
private BookmarkBridge mBookmarkBridge;
private BookmarkBridge mDestroyedBookmarkBridge;
private BookmarkId mMobileNode;
private BookmarkId mOtherNode;
private BookmarkId mDesktopNode;
@Before
public void setUp() {
TestThreadUtils.runOnUiThreadBlocking(() -> {
Profile profile = Profile.getLastUsedRegularProfile();
mBookmarkBridge = new BookmarkBridge(profile);
mBookmarkBridge.loadFakePartnerBookmarkShimForTesting();
mDestroyedBookmarkBridge = new BookmarkBridge(profile);
mDestroyedBookmarkBridge.loadFakePartnerBookmarkShimForTesting();
mDestroyedBookmarkBridge.destroy();
});
BookmarkTestUtil.waitForBookmarkModelLoaded();
TestThreadUtils.runOnUiThreadBlocking(() -> {
mMobileNode = mBookmarkBridge.getMobileFolderId();
mDesktopNode = mBookmarkBridge.getDesktopFolderId();
mOtherNode = mBookmarkBridge.getOtherFolderId();
});
}
@After
public void tearDown() {
TestThreadUtils.runOnUiThreadBlocking(() -> mBookmarkBridge.removeAllUserBookmarks());
}
@Test
@SmallTest
@UiThreadTest
@Feature({"Bookmark"})
public void testAddBookmarksAndFolders() {
BookmarkId bookmarkA =
mBookmarkBridge.addBookmark(mDesktopNode, 0, "a", new GURL("http://a.com"));
verifyBookmark(bookmarkA, "a", "http://a.com/", false, mDesktopNode);
BookmarkId bookmarkB =
mBookmarkBridge.addBookmark(mOtherNode, 0, "b", new GURL("http://b.com"));
verifyBookmark(bookmarkB, "b", "http://b.com/", false, mOtherNode);
BookmarkId bookmarkC =
mBookmarkBridge.addBookmark(mMobileNode, 0, "c", new GURL("http://c.com"));
verifyBookmark(bookmarkC, "c", "http://c.com/", false, mMobileNode);
BookmarkId folderA = mBookmarkBridge.addFolder(mOtherNode, 0, "fa");
verifyBookmark(folderA, "fa", null, true, mOtherNode);
BookmarkId folderB = mBookmarkBridge.addFolder(mDesktopNode, 0, "fb");
verifyBookmark(folderB, "fb", null, true, mDesktopNode);
BookmarkId folderC = mBookmarkBridge.addFolder(mMobileNode, 0, "fc");
verifyBookmark(folderC, "fc", null, true, mMobileNode);
BookmarkId bookmarkAA =
mBookmarkBridge.addBookmark(folderA, 0, "aa", new GURL("http://aa.com"));
verifyBookmark(bookmarkAA, "aa", "http://aa.com/", false, folderA);
BookmarkId folderAA = mBookmarkBridge.addFolder(folderA, 0, "faa");
verifyBookmark(folderAA, "faa", null, true, folderA);
}
private void verifyBookmark(BookmarkId idToVerify, String expectedTitle,
String expectedUrl, boolean isFolder, BookmarkId expectedParent) {
Assert.assertNotNull(idToVerify);
BookmarkItem item = mBookmarkBridge.getBookmarkById(idToVerify);
Assert.assertEquals(expectedTitle, item.getTitle());
Assert.assertEquals(item.isFolder(), isFolder);
if (!isFolder) Assert.assertEquals(expectedUrl, item.getUrl().getSpec());
Assert.assertEquals(item.getParentId(), expectedParent);
}
@Test
@SmallTest
@UiThreadTest
@Feature({"Bookmark"})
public void testGetAllFoldersWithDepths() {
BookmarkId folderA = mBookmarkBridge.addFolder(mMobileNode, 0, "a");
BookmarkId folderB = mBookmarkBridge.addFolder(mDesktopNode, 0, "b");
BookmarkId folderC = mBookmarkBridge.addFolder(mOtherNode, 0, "c");
BookmarkId folderAA = mBookmarkBridge.addFolder(folderA, 0, "aa");
BookmarkId folderBA = mBookmarkBridge.addFolder(folderB, 0, "ba");
BookmarkId folderAAA = mBookmarkBridge.addFolder(folderAA, 0, "aaa");
BookmarkId folderAAAA = mBookmarkBridge.addFolder(folderAAA, 0, "aaaa");
mBookmarkBridge.addBookmark(mMobileNode, 0, "ua", new GURL("http://www.google.com"));
mBookmarkBridge.addBookmark(mDesktopNode, 0, "ua", new GURL("http://www.google.com"));
mBookmarkBridge.addBookmark(mOtherNode, 0, "ua", new GURL("http://www.google.com"));
mBookmarkBridge.addBookmark(folderA, 0, "ua", new GURL("http://www.medium.com"));
// Map folders to depths as expected results
HashMap<BookmarkId, Integer> idToDepth = new HashMap<BookmarkId, Integer>();
idToDepth.put(mMobileNode, 0);
idToDepth.put(folderA, 1);
idToDepth.put(folderAA, 2);
idToDepth.put(folderAAA, 3);
idToDepth.put(folderAAAA, 4);
idToDepth.put(mDesktopNode, 0);
idToDepth.put(folderB, 1);
idToDepth.put(folderBA, 2);
idToDepth.put(mOtherNode, 0);
idToDepth.put(folderC, 1);
List<BookmarkId> folderList = new ArrayList<BookmarkId>();
List<Integer> depthList = new ArrayList<Integer>();
mBookmarkBridge.getAllFoldersWithDepths(folderList, depthList);
verifyFolderDepths(folderList, depthList, idToDepth);
}
@Test
@SmallTest
@UiThreadTest
@Feature({"Bookmark"})
public void testGetMoveDestinations() {
BookmarkId folderA = mBookmarkBridge.addFolder(mMobileNode, 0, "a");
BookmarkId folderB = mBookmarkBridge.addFolder(mDesktopNode, 0, "b");
BookmarkId folderC = mBookmarkBridge.addFolder(mOtherNode, 0, "c");
BookmarkId folderAA = mBookmarkBridge.addFolder(folderA, 0, "aa");
BookmarkId folderBA = mBookmarkBridge.addFolder(folderB, 0, "ba");
BookmarkId folderAAA = mBookmarkBridge.addFolder(folderAA, 0, "aaa");
mBookmarkBridge.addBookmark(mMobileNode, 0, "ua", new GURL("http://www.google.com"));
mBookmarkBridge.addBookmark(mDesktopNode, 0, "ua", new GURL("http://www.google.com"));
mBookmarkBridge.addBookmark(mOtherNode, 0, "ua", new GURL("http://www.google.com"));
mBookmarkBridge.addBookmark(folderA, 0, "ua", new GURL("http://www.medium.com"));
// Map folders to depths as expected results
HashMap<BookmarkId, Integer> idToDepth = new HashMap<BookmarkId, Integer>();
List<BookmarkId> folderList = new ArrayList<BookmarkId>();
List<Integer> depthList = new ArrayList<Integer>();
mBookmarkBridge.getMoveDestinations(folderList, depthList, Arrays.asList(folderA));
idToDepth.put(mMobileNode, 0);
idToDepth.put(mDesktopNode, 0);
idToDepth.put(folderB, 1);
idToDepth.put(folderBA, 2);
idToDepth.put(mOtherNode, 0);
idToDepth.put(folderC, 1);
verifyFolderDepths(folderList, depthList, idToDepth);
mBookmarkBridge.getMoveDestinations(folderList, depthList, Arrays.asList(folderB));
idToDepth.put(mMobileNode, 0);
idToDepth.put(folderA, 1);
idToDepth.put(folderAA, 2);
idToDepth.put(folderAAA, 3);
idToDepth.put(mDesktopNode, 0);
idToDepth.put(mOtherNode, 0);
idToDepth.put(folderC, 1);
verifyFolderDepths(folderList, depthList, idToDepth);
mBookmarkBridge.getMoveDestinations(folderList, depthList, Arrays.asList(folderC));
idToDepth.put(mMobileNode, 0);
idToDepth.put(folderA, 1);
idToDepth.put(folderAA, 2);
idToDepth.put(folderAAA, 3);
idToDepth.put(mDesktopNode, 0);
idToDepth.put(folderB, 1);
idToDepth.put(folderBA, 2);
idToDepth.put(mOtherNode, 0);
verifyFolderDepths(folderList, depthList, idToDepth);
mBookmarkBridge.getMoveDestinations(folderList, depthList, Arrays.asList(folderBA));
idToDepth.put(mMobileNode, 0);
idToDepth.put(folderA, 1);
idToDepth.put(folderAA, 2);
idToDepth.put(folderAAA, 3);
idToDepth.put(mDesktopNode, 0);
idToDepth.put(folderB, 1);
idToDepth.put(mOtherNode, 0);
idToDepth.put(folderC, 1);
verifyFolderDepths(folderList, depthList, idToDepth);
mBookmarkBridge.getMoveDestinations(
folderList, depthList, Arrays.asList(folderAA, folderC));
idToDepth.put(mMobileNode, 0);
idToDepth.put(folderA, 1);
idToDepth.put(mDesktopNode, 0);
idToDepth.put(folderB, 1);
idToDepth.put(folderBA, 2);
idToDepth.put(mOtherNode, 0);
verifyFolderDepths(folderList, depthList, idToDepth);
}
private void verifyFolderDepths(List<BookmarkId> folderList, List<Integer> depthList,
HashMap<BookmarkId, Integer> idToDepth) {
Assert.assertEquals(folderList.size(), depthList.size());
Assert.assertEquals(folderList.size(), idToDepth.size());
for (int i = 0; i < folderList.size(); i++) {
BookmarkId folder = folderList.get(i);
Integer depth = depthList.get(i);
Assert.assertNotNull(folder);
Assert.assertNotNull(depthList.get(i));
Assert.assertTrue("Folder list contains non-folder elements: ",
mBookmarkBridge.getBookmarkById(folder).isFolder());
Assert.assertTrue(
"Returned list contained unexpected key: ", idToDepth.containsKey(folder));
Assert.assertEquals(idToDepth.get(folder), depth);
idToDepth.remove(folder);
}
Assert.assertEquals(idToDepth.size(), 0);
folderList.clear();
depthList.clear();
}
@Test
@SmallTest
@UiThreadTest
@Feature({"Bookmark"})
public void testReorderBookmarks() {
long kAFolder = mBookmarkBridge.addFolder(mMobileNode, 0, "a").getId();
long kBFolder = mBookmarkBridge.addFolder(mMobileNode, 0, "b").getId();
long kAUrl =
mBookmarkBridge.addBookmark(mMobileNode, 0, "a", new GURL("http://a.com")).getId();
long kBUrl =
mBookmarkBridge.addBookmark(mMobileNode, 0, "b", new GURL("http://b.com")).getId();
// Magic folder for partner bookmarks. See fake loading of partner bookmarks in setUp.
long kPartnerBookmarks = 0;
long[] startingIdsArray = new long[] {kBUrl, kAUrl, kBFolder, kAFolder, kPartnerBookmarks};
Assert.assertArrayEquals(
startingIdsArray, getIdArray(mBookmarkBridge.getChildIDs(mMobileNode)));
long[] reorderedIdsArray = new long[] {kAUrl, kBFolder, kBUrl, kAFolder};
mBookmarkBridge.reorderBookmarks(mMobileNode, reorderedIdsArray);
long[] endingIdsArray = new long[] {kAUrl, kBFolder, kBUrl, kAFolder, kPartnerBookmarks};
Assert.assertArrayEquals(
endingIdsArray, getIdArray(mBookmarkBridge.getChildIDs(mMobileNode)));
}
/**
* Given a list of BookmarkIds, returns an array full of the (long) ID numbers.
*
* @param bIds The BookmarkIds of interest.
* @return An array containing the (long) ID numbers.
*/
private long[] getIdArray(List<BookmarkId> bIds) {
// Get the new order for the IDs.
long[] newOrder = new long[bIds.size()];
for (int i = 0; i <= bIds.size() - 1; i++) {
newOrder[i] = bIds.get(i).getId();
}
return newOrder;
}
@Test
@SmallTest
@UiThreadTest
@Feature({"Bookmark"})
public void testSearchPartner() {
List<BookmarkId> expectedSearchResults = new ArrayList<>();
expectedSearchResults.add(new BookmarkId(
1, 1)); // Partner bookmark with ID 1: "Partner Bookmark A", http://a.com
expectedSearchResults.add(new BookmarkId(
2, 1)); // Partner bookmark with ID 2: "Partner Bookmark B", http://b.com
List<BookmarkId> searchResults = mBookmarkBridge.searchBookmarks("pArTnER BookMARK", 100);
Assert.assertEquals("Expected search results would yield partner bookmark with "
+ "case-insensitive title match",
expectedSearchResults, searchResults);
}
@Test
@SmallTest
@UiThreadTest
@Feature({"Bookmark"})
public void testSearchFolder() {
List<BookmarkId> expectedSearchResults = new ArrayList<>();
expectedSearchResults.add(mBookmarkBridge.addFolder(mMobileNode, 0, "FooBar"));
List<BookmarkId> searchResults = mBookmarkBridge.searchBookmarks("oba", 100);
Assert.assertEquals("Expected search results would yield case-insensitive match of "
+ "part of title",
expectedSearchResults, searchResults);
}
@Test
@SmallTest
@UiThreadTest
@Feature({"Bookmark"})
public void testSearch_MaxResults() {
List<BookmarkId> expectedSearchResults = new ArrayList<>();
expectedSearchResults.add(mBookmarkBridge.addFolder(mMobileNode, 0, "FooBar"));
expectedSearchResults.add(mBookmarkBridge.addFolder(mMobileNode, 1, "BazQuux"));
expectedSearchResults.add(new BookmarkId(
1, 1)); // Partner bookmark with ID 1: "Partner Bookmark A", http://a.com
List<BookmarkId> searchResults = mBookmarkBridge.searchBookmarks("a", 3);
Assert.assertEquals(
"Expected search results size to be 3 (maximum size)", 3, searchResults.size());
Assert.assertEquals("Expected that user (non-partner) bookmarks would get priority "
+ "over partner bookmarks",
expectedSearchResults, searchResults);
}
@Test
@SmallTest
@UiThreadTest
@Feature({"Bookmark"})
public void testGetUserBookmarkIdForTab() {
Assert.assertNull(mBookmarkBridge.getUserBookmarkIdForTab(null));
Assert.assertNull(
mDestroyedBookmarkBridge.getUserBookmarkIdForTab(Mockito.mock(Tab.class)));
}
@Test
@SmallTest
@UiThreadTest
@RequiresRestart
@Features.EnableFeatures({ChromeFeatureList.READ_LATER})
@DisabledTest(message = "Broken on official bot, crbug.com/1165869")
public void testAddToReadingList() {
Assert.assertTrue("Read later feature is not loaded properly.",
ChromeFeatureList.isEnabled(ChromeFeatureList.READ_LATER));
Assert.assertNull("Should return null for non http/https URLs.",
mBookmarkBridge.addToReadingList("a", new GURL("chrome://flags")));
BookmarkId readingListId =
mBookmarkBridge.addToReadingList("a", new GURL("https://www.google.com/"));
Assert.assertNotNull("Failed to add to reading list", readingListId);
Assert.assertEquals(BookmarkType.READING_LIST, readingListId.getType());
BookmarkItem readingListItem =
mBookmarkBridge.getReadingListItem(new GURL("https://www.google.com/"));
Assert.assertNotNull("Failed to find the reading list", readingListItem);
Assert.assertEquals(
"https://www.google.com/", readingListItem.getUrl().getValidSpecOrEmpty());
Assert.assertEquals("a", readingListItem.getTitle());
}
@Test
@SmallTest
@UiThreadTest
@Feature({"Bookmark"})
@Features.EnableFeatures({ChromeFeatureList.SHOPPING_LIST})
public void testProductUnsubscribeUpdatesBookmark() {
BookmarkId bookmark =
mBookmarkBridge.addBookmark(mMobileNode, 0, "a", new GURL("http://a.com"));
verifyBookmark(bookmark, "a", "http://a.com/", false, mMobileNode);
long offerId = 12345L;
ShoppingSpecifics specifics =
ShoppingSpecifics.newBuilder().setIsPriceTracked(true).setOfferId(offerId).build();
PowerBookmarkMeta meta = PowerBookmarkMeta.newBuilder()
.setType(PowerBookmarkType.SHOPPING)
.setShoppingSpecifics(specifics)
.build();
mBookmarkBridge.setPowerBookmarkMeta(bookmark, meta);
// Check that the price is tracked prior to sending an unsubscribe event.
PowerBookmarkMeta originalMeta = mBookmarkBridge.getPowerBookmarkMeta(bookmark);
Assert.assertTrue(originalMeta.getShoppingSpecifics().getIsPriceTracked());
ArrayList<CommerceSubscription> subscriptions = new ArrayList<>();
subscriptions.add(new CommerceSubscription(
CommerceSubscription.CommerceSubscriptionType.PRICE_TRACK, Long.toString(offerId),
CommerceSubscription.SubscriptionManagementType.USER_MANAGED,
CommerceSubscription.TrackingIdType.OFFER_ID));
mBookmarkBridge.getSubscriptionObserver().onUnsubscribe(subscriptions);
// The product with the unsubscribed ID should no longer be price tracked.
PowerBookmarkMeta updatedMeta = mBookmarkBridge.getPowerBookmarkMeta(bookmark);
Assert.assertFalse(updatedMeta.getShoppingSpecifics().getIsPriceTracked());
}
}
| bsd-3-clause |
DealerNextDoor/ApolloDev | src/org/apollo/game/model/inter/bank/package-info.java | 83 | /**
* Contains bank-related classes.
*/
package org.apollo.game.model.inter.bank; | isc |
OrangGeeGee/jsondoc | jsondoc-core/src/main/java/org/jsondoc/core/scanner/builder/JSONDocApiDocBuilder.java | 494 | package org.jsondoc.core.scanner.builder;
import org.jsondoc.core.annotation.Api;
import org.jsondoc.core.pojo.ApiDoc;
public class JSONDocApiDocBuilder {
public static ApiDoc build(Class<?> controller) {
Api api = controller.getAnnotation(Api.class);
ApiDoc apiDoc = new ApiDoc();
apiDoc.setDescription(api.description());
apiDoc.setName(api.name());
apiDoc.setGroup(api.group());
apiDoc.setVisibility(api.visibility());
apiDoc.setStage(api.stage());
return apiDoc;
}
}
| mit |
erguotou520/weex-uikit | platforms/android/WeexSDK/src/main/java/com/taobao/weex/ui/view/listview/WXRecyclerView.java | 14865 | /**
*
* Apache License
* Version 2.0, January 2004
* http://www.apache.org/licenses/
*
* TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
*
* 1. Definitions.
*
* "License" shall mean the terms and conditions for use, reproduction,
* and distribution as defined by Sections 1 through 9 of this document.
*
* "Licensor" shall mean the copyright owner or entity authorized by
* the copyright owner that is granting the License.
*
* "Legal Entity" shall mean the union of the acting entity and all
* other entities that control, are controlled by, or are under common
* control with that entity. For the purposes of this definition,
* "control" means (i) the power, direct or indirect, to cause the
* direction or management of such entity, whether by contract or
* otherwise, or (ii) ownership of fifty percent (50%) or more of the
* outstanding shares, or (iii) beneficial ownership of such entity.
*
* "You" (or "Your") shall mean an individual or Legal Entity
* exercising permissions granted by this License.
*
* "Source" form shall mean the preferred form for making modifications,
* including but not limited to software source code, documentation
* source, and configuration files.
*
* "Object" form shall mean any form resulting from mechanical
* transformation or translation of a Source form, including but
* not limited to compiled object code, generated documentation,
* and conversions to other media types.
*
* "Work" shall mean the work of authorship, whether in Source or
* Object form, made available under the License, as indicated by a
* copyright notice that is included in or attached to the work
* (an example is provided in the Appendix below).
*
* "Derivative Works" shall mean any work, whether in Source or Object
* form, that is based on (or derived from) the Work and for which the
* editorial revisions, annotations, elaborations, or other modifications
* represent, as a whole, an original work of authorship. For the purposes
* of this License, Derivative Works shall not include works that remain
* separable from, or merely link (or bind by name) to the interfaces of,
* the Work and Derivative Works thereof.
*
* "Contribution" shall mean any work of authorship, including
* the original version of the Work and any modifications or additions
* to that Work or Derivative Works thereof, that is intentionally
* submitted to Licensor for inclusion in the Work by the copyright owner
* or by an individual or Legal Entity authorized to submit on behalf of
* the copyright owner. For the purposes of this definition, "submitted"
* means any form of electronic, verbal, or written communication sent
* to the Licensor or its representatives, including but not limited to
* communication on electronic mailing lists, source code control systems,
* and issue tracking systems that are managed by, or on behalf of, the
* Licensor for the purpose of discussing and improving the Work, but
* excluding communication that is conspicuously marked or otherwise
* designated in writing by the copyright owner as "Not a Contribution."
*
* "Contributor" shall mean Licensor and any individual or Legal Entity
* on behalf of whom a Contribution has been received by Licensor and
* subsequently incorporated within the Work.
*
* 2. Grant of Copyright License. Subject to the terms and conditions of
* this License, each Contributor hereby grants to You a perpetual,
* worldwide, non-exclusive, no-charge, royalty-free, irrevocable
* copyright license to reproduce, prepare Derivative Works of,
* publicly display, publicly perform, sublicense, and distribute the
* Work and such Derivative Works in Source or Object form.
*
* 3. Grant of Patent License. Subject to the terms and conditions of
* this License, each Contributor hereby grants to You a perpetual,
* worldwide, non-exclusive, no-charge, royalty-free, irrevocable
* (except as stated in this section) patent license to make, have made,
* use, offer to sell, sell, import, and otherwise transfer the Work,
* where such license applies only to those patent claims licensable
* by such Contributor that are necessarily infringed by their
* Contribution(s) alone or by combination of their Contribution(s)
* with the Work to which such Contribution(s) was submitted. If You
* institute patent litigation against any entity (including a
* cross-claim or counterclaim in a lawsuit) alleging that the Work
* or a Contribution incorporated within the Work constitutes direct
* or contributory patent infringement, then any patent licenses
* granted to You under this License for that Work shall terminate
* as of the date such litigation is filed.
*
* 4. Redistribution. You may reproduce and distribute copies of the
* Work or Derivative Works thereof in any medium, with or without
* modifications, and in Source or Object form, provided that You
* meet the following conditions:
*
* (a) You must give any other recipients of the Work or
* Derivative Works a copy of this License; and
*
* (b) You must cause any modified files to carry prominent notices
* stating that You changed the files; and
*
* (c) You must retain, in the Source form of any Derivative Works
* that You distribute, all copyright, patent, trademark, and
* attribution notices from the Source form of the Work,
* excluding those notices that do not pertain to any part of
* the Derivative Works; and
*
* (d) If the Work includes a "NOTICE" text file as part of its
* distribution, then any Derivative Works that You distribute must
* include a readable copy of the attribution notices contained
* within such NOTICE file, excluding those notices that do not
* pertain to any part of the Derivative Works, in at least one
* of the following places: within a NOTICE text file distributed
* as part of the Derivative Works; within the Source form or
* documentation, if provided along with the Derivative Works; or,
* within a display generated by the Derivative Works, if and
* wherever such third-party notices normally appear. The contents
* of the NOTICE file are for informational purposes only and
* do not modify the License. You may add Your own attribution
* notices within Derivative Works that You distribute, alongside
* or as an addendum to the NOTICE text from the Work, provided
* that such additional attribution notices cannot be construed
* as modifying the License.
*
* You may add Your own copyright statement to Your modifications and
* may provide additional or different license terms and conditions
* for use, reproduction, or distribution of Your modifications, or
* for any such Derivative Works as a whole, provided Your use,
* reproduction, and distribution of the Work otherwise complies with
* the conditions stated in this License.
*
* 5. Submission of Contributions. Unless You explicitly state otherwise,
* any Contribution intentionally submitted for inclusion in the Work
* by You to the Licensor shall be under the terms and conditions of
* this License, without any additional terms or conditions.
* Notwithstanding the above, nothing herein shall supersede or modify
* the terms of any separate license agreement you may have executed
* with Licensor regarding such Contributions.
*
* 6. Trademarks. This License does not grant permission to use the trade
* names, trademarks, service marks, or product names of the Licensor,
* except as required for reasonable and customary use in describing the
* origin of the Work and reproducing the content of the NOTICE file.
*
* 7. Disclaimer of Warranty. Unless required by applicable law or
* agreed to in writing, Licensor provides the Work (and each
* Contributor provides its Contributions) on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied, including, without limitation, any warranties or conditions
* of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
* PARTICULAR PURPOSE. You are solely responsible for determining the
* appropriateness of using or redistributing the Work and assume any
* risks associated with Your exercise of permissions under this License.
*
* 8. Limitation of Liability. In no event and under no legal theory,
* whether in tort (including negligence), contract, or otherwise,
* unless required by applicable law (such as deliberate and grossly
* negligent acts) or agreed to in writing, shall any Contributor be
* liable to You for damages, including any direct, indirect, special,
* incidental, or consequential damages of any character arising as a
* result of this License or out of the use or inability to use the
* Work (including but not limited to damages for loss of goodwill,
* work stoppage, computer failure or malfunction, or any and all
* other commercial damages or losses), even if such Contributor
* has been advised of the possibility of such damages.
*
* 9. Accepting Warranty or Additional Liability. While redistributing
* the Work or Derivative Works thereof, You may choose to offer,
* and charge a fee for, acceptance of support, warranty, indemnity,
* or other liability obligations and/or rights consistent with this
* License. However, in accepting such obligations, You may act only
* on Your own behalf and on Your sole responsibility, not on behalf
* of any other Contributor, and only if You agree to indemnify,
* defend, and hold each Contributor harmless for any liability
* incurred by, or claims asserted against, such Contributor by reason
* of your accepting any such warranty or additional liability.
*
* END OF TERMS AND CONDITIONS
*
* APPENDIX: How to apply the Apache License to your work.
*
* To apply the Apache License to your work, attach the following
* boilerplate notice, with the fields enclosed by brackets "[]"
* replaced with your own identifying information. (Don't include
* the brackets!) The text should be enclosed in the appropriate
* comment syntax for the file format. We also recommend that a
* file or class name and description of purpose be included on the
* same "printed page" as the copyright notice for easier
* identification within third-party archives.
*
* Copyright 2016 Alibaba Group
*
* 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.taobao.weex.ui.view.listview;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.MotionEvent;
import com.taobao.weex.common.WXThread;
import com.taobao.weex.ui.view.gesture.WXGesture;
import com.taobao.weex.ui.view.gesture.WXGestureObservable;
public class WXRecyclerView extends RecyclerView implements WXGestureObservable {
public static final int TYPE_LINEAR_LAYOUT = 1;
public static final int TYPE_GRID_LAYOUT = 2;
public static final int TYPE_STAGGERED_GRID_LAYOUT = 3;
private WXGesture mGesture;
private boolean scrollable = true;
public WXRecyclerView(Context context) {
super(context);
}
public boolean isScrollable() {
return scrollable;
}
public void setScrollable(boolean scrollable) {
this.scrollable = scrollable;
}
@Override
public boolean postDelayed(Runnable action, long delayMillis) {
return super.postDelayed(WXThread.secure(action), delayMillis);
}
/**
*
* @param context
* @param type
* @param orientation should be {@link OrientationHelper#HORIZONTAL} or {@link OrientationHelper#VERTICAL}
*/
public void initView(Context context, int type,int orientation) {
if (type == TYPE_GRID_LAYOUT) {
setLayoutManager(new GridLayoutManager(context, 2,orientation,false));
} else if (type == TYPE_STAGGERED_GRID_LAYOUT) {
setLayoutManager(new StaggeredGridLayoutManager(2, orientation));
} else if (type == TYPE_LINEAR_LAYOUT) {
setLayoutManager(new LinearLayoutManager(context,orientation,false){
@Override
public boolean supportsPredictiveItemAnimations() {
return false;
}
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
try {
super.onLayoutChildren(recycler, state);
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
@Override
public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
try {
return super.scrollVerticallyBy(dy, recycler, state);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
});
}
}
@Override
public void registerGestureListener(@Nullable WXGesture wxGesture) {
mGesture = wxGesture;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if(!scrollable) {
return true;
}
boolean result = super.onTouchEvent(event);
if (mGesture != null) {
result |= mGesture.onTouch(this, event);
}
return result;
}
}
| mit |
gazarenkov/che-sketch | ide/che-core-ide-app/src/test/java/org/eclipse/che/ide/editor/macro/EditorCurrentProjectNameMacroTest.java | 1916 | /*******************************************************************************
* Copyright (c) 2012-2017 Codenvy, S.A.
* 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:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.ide.editor.macro;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.assertSame;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
/**
* Unit tests for the {@link EditorCurrentProjectNameMacro}
*
* @author Vlad Zhukovskyi
*/
@RunWith(MockitoJUnitRunner.class)
public class EditorCurrentProjectNameMacroTest extends AbstractEditorMacroTest {
private EditorCurrentProjectNameMacro provider;
@Override
protected AbstractEditorMacro getProvider() {
return provider;
}
@Before
public void init() throws Exception {
provider = new EditorCurrentProjectNameMacro(editorAgent, promiseProvider, localizationConstants);
}
@Test
public void testGetKey() throws Exception {
assertSame(provider.getName(), EditorCurrentProjectNameMacro.KEY);
}
@Test
public void getValue() throws Exception {
initEditorWithTestFile();
provider.expand();
verify(editorAgent).getActiveEditor();
verify(promiseProvider).resolve(eq(PROJECT_NAME));
}
@Test
public void getEmptyValue() throws Exception {
provider.expand();
verify(editorAgent).getActiveEditor();
verify(promiseProvider).resolve(eq(""));
}
} | epl-1.0 |
gazarenkov/che-sketch | plugins/plugin-svn/che-plugin-svn-ext-shared/src/main/java/org/eclipse/che/plugin/svn/shared/InfoResponse.java | 2096 | /*******************************************************************************
* Copyright (c) 2012-2017 Codenvy, S.A.
* 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:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.plugin.svn.shared;
import org.eclipse.che.dto.shared.DTO;
import javax.validation.constraints.NotNull;
import java.util.List;
@DTO
public interface InfoResponse {
/**************************************************************************
*
* Subversion command
*
**************************************************************************/
String getCommand();
void setCommand(@NotNull final String command);
InfoResponse withCommand(@NotNull final String command);
/**************************************************************************
*
* Execution output
*
**************************************************************************/
List<String> getOutput();
void setOutput(@NotNull final List<String> output);
InfoResponse withOutput(@NotNull final List<String> output);
/**************************************************************************
*
* Error output
*
**************************************************************************/
List<String> getErrorOutput();
void setErrorOutput(List<String> errorOutput);
InfoResponse withErrorOutput(List<String> errorOutput);
/**************************************************************************
*
* Item list
*
**************************************************************************/
List<SubversionItem> getItems();
void setItems(List<SubversionItem> items);
InfoResponse withItems(List<SubversionItem> items);
}
| epl-1.0 |
shakalaca/ASUS_ZenFone_A450CG | external/proguard/src/proguard/classfile/util/DynamicMemberReferenceInitializer.java | 27311 | /*
* ProGuard -- shrinking, optimization, obfuscation, and preverification
* of Java bytecode.
*
* Copyright (c) 2002-2009 Eric Lafortune (eric@graphics.cornell.edu)
*
* This program 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 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package proguard.classfile.util;
import proguard.classfile.*;
import proguard.classfile.attribute.CodeAttribute;
import proguard.classfile.attribute.visitor.AttributeVisitor;
import proguard.classfile.constant.*;
import proguard.classfile.constant.visitor.ConstantVisitor;
import proguard.classfile.instruction.*;
import proguard.classfile.instruction.visitor.InstructionVisitor;
import proguard.classfile.visitor.*;
import proguard.util.StringMatcher;
/**
* This InstructionVisitor initializes any constant
* <code>Class.get[Declared]{Field,Method}</code> references of all instructions
* it visits. More specifically, it fills out the references of string constant
* pool entries that refer to a class member in the program class pool or in the
* library class pool.
* <p>
* It optionally prints notes if on usage of
* <code>(SomeClass)Class.forName(variable).newInstance()</code>.
* <p>
* The class hierarchy and references must be initialized before using this
* visitor.
*
* @see ClassSuperHierarchyInitializer
* @see ClassReferenceInitializer
*
* @author Eric Lafortune
*/
public class DynamicMemberReferenceInitializer
extends SimplifiedVisitor
implements InstructionVisitor,
ConstantVisitor,
AttributeVisitor,
MemberVisitor
{
public static final int X = InstructionSequenceMatcher.X;
public static final int Y = InstructionSequenceMatcher.Y;
public static final int Z = InstructionSequenceMatcher.Z;
public static final int A = InstructionSequenceMatcher.A;
public static final int B = InstructionSequenceMatcher.B;
public static final int C = InstructionSequenceMatcher.C;
public static final int D = InstructionSequenceMatcher.D;
private final Constant[] GET_FIELD_CONSTANTS = new Constant[]
{
new MethodrefConstant(1, 2, null, null),
new ClassConstant(3, null),
new NameAndTypeConstant(4, 5),
new Utf8Constant(ClassConstants.INTERNAL_NAME_JAVA_LANG_CLASS),
new Utf8Constant(ClassConstants.INTERNAL_METHOD_NAME_CLASS_GET_FIELD),
new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_CLASS_GET_FIELD),
};
private final Constant[] GET_DECLARED_FIELD_CONSTANTS = new Constant[]
{
new MethodrefConstant(1, 2, null, null),
new ClassConstant(3, null),
new NameAndTypeConstant(4, 5),
new Utf8Constant(ClassConstants.INTERNAL_NAME_JAVA_LANG_CLASS),
new Utf8Constant(ClassConstants.INTERNAL_METHOD_NAME_CLASS_GET_DECLARED_FIELD),
new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_CLASS_GET_DECLARED_FIELD),
};
private final Constant[] GET_METHOD_CONSTANTS = new Constant[]
{
new MethodrefConstant(1, 2, null, null),
new ClassConstant(3, null),
new NameAndTypeConstant(4, 5),
new Utf8Constant(ClassConstants.INTERNAL_NAME_JAVA_LANG_CLASS),
new Utf8Constant(ClassConstants.INTERNAL_METHOD_NAME_CLASS_GET_METHOD),
new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_CLASS_GET_METHOD),
};
private final Constant[] GET_DECLARED_METHOD_CONSTANTS = new Constant[]
{
new MethodrefConstant(1, 2, null, null),
new ClassConstant(3, null),
new NameAndTypeConstant(4, 5),
new Utf8Constant(ClassConstants.INTERNAL_NAME_JAVA_LANG_CLASS),
new Utf8Constant(ClassConstants.INTERNAL_METHOD_NAME_CLASS_GET_DECLARED_METHOD),
new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_CLASS_GET_DECLARED_METHOD),
};
// SomeClass.class.get[Declared]Field("someField").
private final Instruction[] CONSTANT_GET_FIELD_INSTRUCTIONS = new Instruction[]
{
new ConstantInstruction(InstructionConstants.OP_LDC, X),
new ConstantInstruction(InstructionConstants.OP_LDC, Y),
new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, 0),
};
// SomeClass.class.get[Declared]Method("someMethod", new Class[] {}).
private final Instruction[] CONSTANT_GET_METHOD_INSTRUCTIONS0 = new Instruction[]
{
new ConstantInstruction(InstructionConstants.OP_LDC, X),
new ConstantInstruction(InstructionConstants.OP_LDC, Y),
new SimpleInstruction(InstructionConstants.OP_ICONST_0),
new ConstantInstruction(InstructionConstants.OP_ANEWARRAY, 1),
new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, 0),
};
// SomeClass.class.get[Declared]Method("someMethod", new Class[] { A.class }).
private final Instruction[] CONSTANT_GET_METHOD_INSTRUCTIONS1 = new Instruction[]
{
new ConstantInstruction(InstructionConstants.OP_LDC, X),
new ConstantInstruction(InstructionConstants.OP_LDC, Y),
new SimpleInstruction(InstructionConstants.OP_ICONST_1),
new ConstantInstruction(InstructionConstants.OP_ANEWARRAY, 1),
new SimpleInstruction(InstructionConstants.OP_DUP),
new SimpleInstruction(InstructionConstants.OP_ICONST_0),
new ConstantInstruction(InstructionConstants.OP_LDC, A),
new SimpleInstruction(InstructionConstants.OP_AASTORE),
new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, 0),
};
// SomeClass.class.get[Declared]Method("someMethod", new Class[] { A.class, B.class }).
private final Instruction[] CONSTANT_GET_METHOD_INSTRUCTIONS2 = new Instruction[]
{
new ConstantInstruction(InstructionConstants.OP_LDC, X),
new ConstantInstruction(InstructionConstants.OP_LDC, Y),
new SimpleInstruction(InstructionConstants.OP_ICONST_2),
new ConstantInstruction(InstructionConstants.OP_ANEWARRAY, 1),
new SimpleInstruction(InstructionConstants.OP_DUP),
new SimpleInstruction(InstructionConstants.OP_ICONST_0),
new ConstantInstruction(InstructionConstants.OP_LDC, A),
new SimpleInstruction(InstructionConstants.OP_AASTORE),
new SimpleInstruction(InstructionConstants.OP_DUP),
new SimpleInstruction(InstructionConstants.OP_ICONST_1),
new ConstantInstruction(InstructionConstants.OP_LDC, B),
new SimpleInstruction(InstructionConstants.OP_AASTORE),
new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, 0),
};
// get[Declared]Field("someField").
private final Instruction[] GET_FIELD_INSTRUCTIONS = new Instruction[]
{
new ConstantInstruction(InstructionConstants.OP_LDC, Y),
new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, 0),
};
// get[Declared]Method("someMethod", new Class[] {}).
private final Instruction[] GET_METHOD_INSTRUCTIONS0 = new Instruction[]
{
new ConstantInstruction(InstructionConstants.OP_LDC, Y),
new SimpleInstruction(InstructionConstants.OP_ICONST_0),
new ConstantInstruction(InstructionConstants.OP_ANEWARRAY, 1),
new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, 0),
};
// get[Declared]Method("someMethod", new Class[] { A.class }).
private final Instruction[] GET_METHOD_INSTRUCTIONS1 = new Instruction[]
{
new ConstantInstruction(InstructionConstants.OP_LDC, Y),
new SimpleInstruction(InstructionConstants.OP_ICONST_1),
new ConstantInstruction(InstructionConstants.OP_ANEWARRAY, 1),
new SimpleInstruction(InstructionConstants.OP_DUP),
new SimpleInstruction(InstructionConstants.OP_ICONST_0),
new ConstantInstruction(InstructionConstants.OP_LDC, A),
new SimpleInstruction(InstructionConstants.OP_AASTORE),
new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, 0),
};
// get[Declared]Method("someMethod", new Class[] { A.class, B.class }).
private final Instruction[] GET_METHOD_INSTRUCTIONS2 = new Instruction[]
{
new ConstantInstruction(InstructionConstants.OP_LDC, Y),
new SimpleInstruction(InstructionConstants.OP_ICONST_2),
new ConstantInstruction(InstructionConstants.OP_ANEWARRAY, 1),
new SimpleInstruction(InstructionConstants.OP_DUP),
new SimpleInstruction(InstructionConstants.OP_ICONST_0),
new ConstantInstruction(InstructionConstants.OP_LDC, A),
new SimpleInstruction(InstructionConstants.OP_AASTORE),
new SimpleInstruction(InstructionConstants.OP_DUP),
new SimpleInstruction(InstructionConstants.OP_ICONST_1),
new ConstantInstruction(InstructionConstants.OP_LDC, B),
new SimpleInstruction(InstructionConstants.OP_AASTORE),
new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, 0),
};
private final ClassPool programClassPool;
private final ClassPool libraryClassPool;
private final WarningPrinter notePrinter;
private final StringMatcher noteFieldExceptionMatcher;
private final StringMatcher noteMethodExceptionMatcher;
private final InstructionSequenceMatcher constantGetFieldMatcher =
new InstructionSequenceMatcher(GET_FIELD_CONSTANTS,
CONSTANT_GET_FIELD_INSTRUCTIONS);
private final InstructionSequenceMatcher constantGetDeclaredFieldMatcher =
new InstructionSequenceMatcher(GET_DECLARED_FIELD_CONSTANTS,
CONSTANT_GET_FIELD_INSTRUCTIONS);
private final InstructionSequenceMatcher constantGetMethodMatcher0 =
new InstructionSequenceMatcher(GET_METHOD_CONSTANTS,
CONSTANT_GET_METHOD_INSTRUCTIONS0);
private final InstructionSequenceMatcher constantGetDeclaredMethodMatcher0 =
new InstructionSequenceMatcher(GET_DECLARED_METHOD_CONSTANTS,
CONSTANT_GET_METHOD_INSTRUCTIONS0);
private final InstructionSequenceMatcher constantGetMethodMatcher1 =
new InstructionSequenceMatcher(GET_METHOD_CONSTANTS,
CONSTANT_GET_METHOD_INSTRUCTIONS1);
private final InstructionSequenceMatcher constantGetDeclaredMethodMatcher1 =
new InstructionSequenceMatcher(GET_DECLARED_METHOD_CONSTANTS,
CONSTANT_GET_METHOD_INSTRUCTIONS1);
private final InstructionSequenceMatcher constantGetMethodMatcher2 =
new InstructionSequenceMatcher(GET_METHOD_CONSTANTS,
CONSTANT_GET_METHOD_INSTRUCTIONS2);
private final InstructionSequenceMatcher constantGetDeclaredMethodMatcher2 =
new InstructionSequenceMatcher(GET_DECLARED_METHOD_CONSTANTS,
CONSTANT_GET_METHOD_INSTRUCTIONS2);
private final InstructionSequenceMatcher getFieldMatcher =
new InstructionSequenceMatcher(GET_FIELD_CONSTANTS,
GET_FIELD_INSTRUCTIONS);
private final InstructionSequenceMatcher getDeclaredFieldMatcher =
new InstructionSequenceMatcher(GET_DECLARED_FIELD_CONSTANTS,
GET_FIELD_INSTRUCTIONS);
private final InstructionSequenceMatcher getMethodMatcher0 =
new InstructionSequenceMatcher(GET_METHOD_CONSTANTS,
GET_METHOD_INSTRUCTIONS0);
private final InstructionSequenceMatcher getDeclaredMethodMatcher0 =
new InstructionSequenceMatcher(GET_DECLARED_METHOD_CONSTANTS,
GET_METHOD_INSTRUCTIONS0);
private final InstructionSequenceMatcher getMethodMatcher1 =
new InstructionSequenceMatcher(GET_METHOD_CONSTANTS,
GET_METHOD_INSTRUCTIONS1);
private final InstructionSequenceMatcher getDeclaredMethodMatcher1 =
new InstructionSequenceMatcher(GET_DECLARED_METHOD_CONSTANTS,
GET_METHOD_INSTRUCTIONS1);
private final InstructionSequenceMatcher getMethodMatcher2 =
new InstructionSequenceMatcher(GET_METHOD_CONSTANTS,
GET_METHOD_INSTRUCTIONS2);
private final InstructionSequenceMatcher getDeclaredMethodMatcher2 =
new InstructionSequenceMatcher(GET_DECLARED_METHOD_CONSTANTS,
GET_METHOD_INSTRUCTIONS2);
private final MemberFinder memberFinder = new MemberFinder();
// Fields acting as parameters for the visitors.
private Clazz referencedClass;
private boolean isDeclared;
private boolean isField;
/**
* Creates a new DynamicMemberReferenceInitializer.
*/
public DynamicMemberReferenceInitializer(ClassPool programClassPool,
ClassPool libraryClassPool,
WarningPrinter notePrinter,
StringMatcher noteFieldExceptionMatcher,
StringMatcher noteMethodExceptionMatcher)
{
this.programClassPool = programClassPool;
this.libraryClassPool = libraryClassPool;
this.notePrinter = notePrinter;
this.noteFieldExceptionMatcher = noteFieldExceptionMatcher;
this.noteMethodExceptionMatcher = noteMethodExceptionMatcher;
}
// Implementations for InstructionVisitor.
public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction)
{
// Try to match the SomeClass.class.getField("someField") construct.
matchGetMember(clazz, method, codeAttribute, offset, instruction,
constantGetFieldMatcher,
getFieldMatcher, true, false);
// Try to match the SomeClass.class.getDeclaredField("someField") construct.
matchGetMember(clazz, method, codeAttribute, offset, instruction,
constantGetDeclaredFieldMatcher,
getDeclaredFieldMatcher, true, true);
// Try to match the SomeClass.class.getMethod("someMethod", new Class[]
// {}) construct.
matchGetMember(clazz, method, codeAttribute, offset, instruction,
constantGetMethodMatcher0,
getMethodMatcher0, false, false);
// Try to match the SomeClass.class.getDeclaredMethod("someMethod",
// new Class[] {}) construct.
matchGetMember(clazz, method, codeAttribute, offset, instruction,
constantGetDeclaredMethodMatcher0,
getDeclaredMethodMatcher0, false, true);
// Try to match the SomeClass.class.getMethod("someMethod", new Class[]
// { A.class }) construct.
matchGetMember(clazz, method, codeAttribute, offset, instruction,
constantGetMethodMatcher1,
getMethodMatcher1, false, false);
// Try to match the SomeClass.class.getDeclaredMethod("someMethod",
// new Class[] { A.class }) construct.
matchGetMember(clazz, method, codeAttribute, offset, instruction,
constantGetDeclaredMethodMatcher1,
getDeclaredMethodMatcher1, false, true);
// Try to match the SomeClass.class.getMethod("someMethod", new Class[]
// { A.class, B.class }) construct.
matchGetMember(clazz, method, codeAttribute, offset, instruction,
constantGetMethodMatcher2,
getMethodMatcher2, false, false);
// Try to match the SomeClass.class.getDeclaredMethod("someMethod",
// new Class[] { A.class, B.class }) construct.
matchGetMember(clazz, method, codeAttribute, offset, instruction,
constantGetDeclaredMethodMatcher2,
getDeclaredMethodMatcher2, false, true);
}
/**
* Tries to match the next instruction and fills out the string constant
* or prints out a note accordingly.
*/
private void matchGetMember(Clazz clazz,
Method method,
CodeAttribute codeAttribute,
int offset,
Instruction instruction,
InstructionSequenceMatcher constantSequenceMatcher,
InstructionSequenceMatcher variableSequenceMatcher,
boolean isField,
boolean isDeclared)
{
// Try to match the next instruction in the constant sequence.
instruction.accept(clazz, method, codeAttribute, offset,
constantSequenceMatcher);
// Did we find a match to fill out the string constant?
if (constantSequenceMatcher.isMatching())
{
this.isField = isField;
this.isDeclared = isDeclared;
// Get the member's class.
clazz.constantPoolEntryAccept(constantSequenceMatcher.matchedConstantIndex(X), this);
// Fill out the matched string constant.
clazz.constantPoolEntryAccept(constantSequenceMatcher.matchedConstantIndex(Y), this);
// Don't look for the dynamic construct.
variableSequenceMatcher.reset();
}
// Try to match the next instruction in the variable sequence.
instruction.accept(clazz, method, codeAttribute, offset,
variableSequenceMatcher);
// Did we find a match to print out a note?
if (variableSequenceMatcher.isMatching())
{
// Print out a note about the dynamic invocation.
printDynamicInvocationNote(clazz,
variableSequenceMatcher,
isField,
isDeclared);
}
}
// Implementations for ConstantVisitor.
/**
* Remembers the referenced class.
*/
public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
{
// Remember the referenced class.
referencedClass = ClassUtil.isInternalArrayType(classConstant.getName(clazz)) ?
null :
classConstant.referencedClass;
}
/**
* Fills out the link to the referenced class member.
*/
public void visitStringConstant(Clazz clazz, StringConstant stringConstant)
{
if (referencedClass != null)
{
String name = stringConstant.getString(clazz);
// See if we can find the referenced class member locally, or
// somewhere in the hierarchy.
Member referencedMember = isDeclared ? isField ?
(Member)referencedClass.findField(name, null) :
(Member)referencedClass.findMethod(name, null) :
(Member)memberFinder.findMember(clazz,
referencedClass,
name,
null,
isField);
if (referencedMember != null)
{
stringConstant.referencedMember = referencedMember;
stringConstant.referencedClass = isDeclared ?
referencedClass :
memberFinder.correspondingClass();
}
}
}
// Small utility methods.
/**
* Prints out a note on the matched dynamic invocation, if necessary.
*/
private void printDynamicInvocationNote(Clazz clazz,
InstructionSequenceMatcher noteSequenceMatcher,
boolean isField,
boolean isDeclared)
{
// Print out a note about the dynamic invocation.
if (notePrinter != null &&
notePrinter.accepts(clazz.getName()))
{
// Is the class member name in the list of exceptions?
StringMatcher noteExceptionMatcher = isField ?
noteFieldExceptionMatcher :
noteMethodExceptionMatcher;
int memberNameIndex = noteSequenceMatcher.matchedConstantIndex(Y);
String memberName = clazz.getStringString(memberNameIndex);
if (noteExceptionMatcher == null ||
!noteExceptionMatcher.matches(memberName))
{
// Compose the external member name and partial descriptor.
String externalMemberDescription = memberName;
if (!isField)
{
externalMemberDescription += '(';
for (int count = 0; count < 2; count++)
{
int memberArgumentIndex = noteSequenceMatcher.matchedConstantIndex(A + count);
if (memberArgumentIndex > 0)
{
if (count > 0)
{
externalMemberDescription += ',';
}
String className = clazz.getClassName(memberArgumentIndex);
externalMemberDescription += ClassUtil.isInternalArrayType(className) ?
ClassUtil.externalType(className) :
ClassUtil.externalClassName(className);
}
}
externalMemberDescription += ')';
}
// Print out the actual note.
notePrinter.print(clazz.getName(),
"Note: " +
ClassUtil.externalClassName(clazz.getName()) +
" accesses a " +
(isDeclared ? "declared " : "") +
(isField ? "field" : "method") +
" '" +
externalMemberDescription +
"' dynamically");
// Print out notes about potential candidates.
ClassVisitor classVisitor;
if (isField)
{
classVisitor =
new AllFieldVisitor(
new MemberNameFilter(memberName, this));
}
else
{
// Compose the partial method descriptor.
String methodDescriptor = "(";
for (int count = 0; count < 2; count++)
{
int memberArgumentIndex = noteSequenceMatcher.matchedConstantIndex(A + count);
if (memberArgumentIndex > 0)
{
if (count > 0)
{
methodDescriptor += ',';
}
String className = clazz.getClassName(memberArgumentIndex);
methodDescriptor += ClassUtil.isInternalArrayType(className) ?
className :
ClassUtil.internalTypeFromClassName(className);
}
}
methodDescriptor += ")L///;";
classVisitor =
new AllMethodVisitor(
new MemberNameFilter(memberName,
new MemberDescriptorFilter(methodDescriptor, this)));
}
programClassPool.classesAcceptAlphabetically(classVisitor);
libraryClassPool.classesAcceptAlphabetically(classVisitor);
}
}
}
// Implementations for MemberVisitor.
public void visitProgramField(ProgramClass programClass, ProgramField programField)
{
if (notePrinter.accepts(programClass.getName()))
{
System.out.println(" Maybe this is program field '" +
ClassUtil.externalFullClassDescription(0, programClass.getName()) +
" { " +
ClassUtil.externalFullFieldDescription(0, programField.getName(programClass), programField.getDescriptor(programClass)) +
"; }'");
}
}
public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
{
if (notePrinter.accepts(programClass.getName()))
{
System.out.println(" Maybe this is program method '" +
ClassUtil.externalFullClassDescription(0, programClass.getName()) +
" { " +
ClassUtil.externalFullMethodDescription(null, 0, programMethod.getName(programClass), programMethod.getDescriptor(programClass)) +
"; }'");
}
}
public void visitLibraryField(LibraryClass libraryClass, LibraryField libraryField)
{
if (notePrinter.accepts(libraryClass.getName()))
{
System.out.println(" Maybe this is library field '" +
ClassUtil.externalFullClassDescription(0, libraryClass.getName()) +
" { " +
ClassUtil.externalFullFieldDescription(0, libraryField.getName(libraryClass), libraryField.getDescriptor(libraryClass)) +
"; }'");
}
}
public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
{
if (notePrinter.accepts(libraryClass.getName()))
{
System.out.println(" Maybe this is library method '" +
ClassUtil.externalFullClassDescription(0, libraryClass.getName()) +
" { " +
ClassUtil.externalFullMethodDescription(null, 0, libraryMethod.getName(libraryClass), libraryMethod.getDescriptor(libraryClass)) +
"; }'");
}
}
} | gpl-2.0 |
ahinz/postgis | java/jdbc/src/org/postgis/binary/ByteGetter.java | 2315 | /*
* ByteGetter.java
*
* PostGIS extension for PostgreSQL JDBC driver - Binary Parser
*
* (C) 2005 Markus Schaber, markus.schaber@logix-tt.com
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA or visit the web at
* http://www.gnu.org.
*
* $Id$
*/
package org.postgis.binary;
public abstract class ByteGetter {
/**
* Get a byte.
*
* @return The result is returned as Int to eliminate sign problems when
* or'ing several values together.
*/
public abstract int get(int index);
public static class BinaryByteGetter extends ByteGetter {
private byte[] array;
public BinaryByteGetter(byte[] array) {
this.array = array;
}
public int get(int index) {
return array[index] & 0xFF; // mask out sign-extended bits.
}
}
public static class StringByteGetter extends ByteGetter {
private String rep;
public StringByteGetter(String rep) {
this.rep = rep;
}
public int get(int index) {
index *= 2;
int high = unhex(rep.charAt(index));
int low = unhex(rep.charAt(index + 1));
return (high << 4) + low;
}
public static byte unhex(char c) {
if (c >= '0' && c <= '9') {
return (byte) (c - '0');
} else if (c >= 'A' && c <= 'F') {
return (byte) (c - 'A' + 10);
} else if (c >= 'a' && c <= 'f') {
return (byte) (c - 'a' + 10);
} else {
throw new IllegalArgumentException("No valid Hex char " + c);
}
}
}
}
| gpl-2.0 |
YouDiSN/OpenJDK-Research | jdk9/hotspot/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.phases/src/org/graalvm/compiler/phases/tiers/CompilerConfiguration.java | 1924 | /*
* 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.
*
* 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 org.graalvm.compiler.phases.tiers;
import org.graalvm.compiler.lir.phases.AllocationPhase.AllocationContext;
import org.graalvm.compiler.lir.phases.LIRPhaseSuite;
import org.graalvm.compiler.lir.phases.PostAllocationOptimizationPhase.PostAllocationOptimizationContext;
import org.graalvm.compiler.lir.phases.PreAllocationOptimizationPhase.PreAllocationOptimizationContext;
import org.graalvm.compiler.phases.PhaseSuite;
public interface CompilerConfiguration {
PhaseSuite<HighTierContext> createHighTier();
PhaseSuite<MidTierContext> createMidTier();
PhaseSuite<LowTierContext> createLowTier();
LIRPhaseSuite<PreAllocationOptimizationContext> createPreAllocationOptimizationStage();
LIRPhaseSuite<AllocationContext> createAllocationStage();
LIRPhaseSuite<PostAllocationOptimizationContext> createPostAllocationOptimizationStage();
}
| gpl-2.0 |
mateor/pdroid | android-2.3.4_r1/tags/1.32/frameworks/base/graphics/java/android/graphics/ColorFilter.java | 1155 | /*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// This file was generated from the C++ include file: SkColorFilter.h
// Any changes made to this file will be discarded by the build.
// To change this file, either edit the include, or device/tools/gluemaker/main.cpp,
// or one of the auxilary file specifications in device/tools/gluemaker.
package android.graphics;
public class ColorFilter {
protected void finalize() throws Throwable {
finalizer(native_instance);
}
private static native void finalizer(int native_instance);
int native_instance;
}
| gpl-3.0 |
dentmaged/Bukkit | src/main/java/org/bukkit/command/defaults/TeleportCommand.java | 4538 | package org.bukkit.command.defaults;
import java.util.List;
import org.apache.commons.lang.Validate;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import com.google.common.collect.ImmutableList;
@Deprecated
public class TeleportCommand extends VanillaCommand {
public TeleportCommand() {
super("tp");
this.description = "Teleports the given player (or yourself) to another player or coordinates";
this.usageMessage = "/tp [player] <target> and/or <x> <y> <z>";
this.setPermission("bukkit.command.teleport");
}
@Override
public boolean execute(CommandSender sender, String currentAlias, String[] args) {
if (!testPermission(sender)) return true;
if (args.length < 1 || args.length > 4) {
sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage);
return false;
}
Player player;
if (args.length == 1 || args.length == 3) {
if (sender instanceof Player) {
player = (Player) sender;
} else {
sender.sendMessage("Please provide a player!");
return true;
}
} else {
player = Bukkit.getPlayerExact(args[0]);
}
if (player == null) {
sender.sendMessage("Player not found: " + args[0]);
return true;
}
if (args.length < 3) {
Player target = Bukkit.getPlayerExact(args[args.length - 1]);
if (target == null) {
sender.sendMessage("Can't find player " + args[args.length - 1] + ". No tp.");
return true;
}
player.teleport(target, TeleportCause.COMMAND);
Command.broadcastCommandMessage(sender, "Teleported " + player.getDisplayName() + " to " + target.getDisplayName());
} else if (player.getWorld() != null) {
Location playerLocation = player.getLocation();
double x = getCoordinate(sender, playerLocation.getX(), args[args.length - 3]);
double y = getCoordinate(sender, playerLocation.getY(), args[args.length - 2], 0, 0);
double z = getCoordinate(sender, playerLocation.getZ(), args[args.length - 1]);
if (x == MIN_COORD_MINUS_ONE || y == MIN_COORD_MINUS_ONE || z == MIN_COORD_MINUS_ONE) {
sender.sendMessage("Please provide a valid location!");
return true;
}
playerLocation.setX(x);
playerLocation.setY(y);
playerLocation.setZ(z);
player.teleport(playerLocation, TeleportCause.COMMAND);
Command.broadcastCommandMessage(sender, String.format("Teleported %s to %.2f, %.2f, %.2f", player.getDisplayName(), x, y, z));
}
return true;
}
private double getCoordinate(CommandSender sender, double current, String input) {
return getCoordinate(sender, current, input, MIN_COORD, MAX_COORD);
}
private double getCoordinate(CommandSender sender, double current, String input, int min, int max) {
boolean relative = input.startsWith("~");
double result = relative ? current : 0;
if (!relative || input.length() > 1) {
boolean exact = input.contains(".");
if (relative) input = input.substring(1);
double testResult = getDouble(sender, input);
if (testResult == MIN_COORD_MINUS_ONE) {
return MIN_COORD_MINUS_ONE;
}
result += testResult;
if (!exact && !relative) result += 0.5f;
}
if (min != 0 || max != 0) {
if (result < min) {
result = MIN_COORD_MINUS_ONE;
}
if (result > max) {
result = MIN_COORD_MINUS_ONE;
}
}
return result;
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException {
Validate.notNull(sender, "Sender cannot be null");
Validate.notNull(args, "Arguments cannot be null");
Validate.notNull(alias, "Alias cannot be null");
if (args.length == 1 || args.length == 2) {
return super.tabComplete(sender, alias, args);
}
return ImmutableList.of();
}
}
| gpl-3.0 |
kumarrus/voltdb | src/frontend/org/voltdb/jdbc/Driver.java | 8523 | /* This file is part of VoltDB.
* Copyright (C) 2008-2015 VoltDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb.jdbc;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.logging.Logger;
import java.util.regex.Pattern;
public class Driver implements java.sql.Driver
{
public static final String JDBC_PROP_FILE_ENV = "VOLTDB_JDBC_PROPERTIES";
public static final String JDBC_PROP_FILE_PROP = "voltdb.jdbcproperties";
public static final String DEFAULT_PROP_FILENAME = "voltdb.properties";
//Driver URL prefix.
private static final String URL_PREFIX = "jdbc:voltdb:";
// Static so it's unit-testable, yes, lazy me
static String[] getServersFromURL(String url) {
// get everything between the prefix and the ?
String prefix = URL_PREFIX + "//";
int end = url.length();
if (url.indexOf("?") > 0) {
end = url.indexOf("?");
}
String servstring = url.substring(prefix.length(), end);
return servstring.split(",");
}
static Map<String, String> getPropsFromURL(String url) {
Map<String, String> results = new HashMap<String, String>();
if (url.indexOf("?") > 0) {
String propstring = url.substring(url.indexOf("?") + 1);
String[] props = propstring.split("&");
for (String prop : props) {
if (prop.indexOf("=") > 0) {
String[] comps = prop.split("=");
results.put(comps[0], comps[1]);
}
}
}
return results;
}
private static final int MAJOR_VERSION = 1;
private static final int MINOR_VERSION = 0;
static
{
try
{
DriverManager.registerDriver(new Driver());
}
catch (Exception e)
{}
}
public Driver() throws SQLException
{
// Required for Class.forName().newInstance()
}
@Override
public Connection connect(String url, Properties props) throws SQLException
{
if (acceptsURL(url))
{
try
{
// Properties favored order:
// 1) property file specified by env variable
// 2) property file specified by system property
// 3) property file with default name in same path as driver jar
// 4) Properties specified in the URL
// 5) Properties specified to getConnection() arg
//
Properties fileprops = tryToFindPropsFile();
// Copy the provided properties so we don't muck with
// the object the caller gave us.
Properties info = (Properties) props.clone();
String prefix = URL_PREFIX + "//";
if (!url.startsWith(prefix)) {
throw SQLError.get(SQLError.ILLEGAL_ARGUMENT);
}
// get the server strings
String[] servers = Driver.getServersFromURL(url);
// get the props from the URL
Map<String, String> urlprops = Driver.getPropsFromURL(url);
for (Entry<String, String> e : urlprops.entrySet()) {
// Favor the URL over the provided props
info.setProperty(e.getKey(), e.getValue());
}
// Favor the file-specified properties over the other props
for (Enumeration<?> e = fileprops.propertyNames(); e.hasMoreElements();)
{
String key = (String) e.nextElement();
info.setProperty(key, fileprops.getProperty(key));
}
String user = "";
String password = "";
boolean heavyweight = false;
int maxoutstandingtxns = 0;
for (Enumeration<?> e = info.propertyNames(); e.hasMoreElements();)
{
String key = (String) e.nextElement();
String value = info.getProperty(key);
if (key.toLowerCase().equals("user"))
user = value;
else if (key.toLowerCase().equals("password"))
password = value;
else if (key.toLowerCase().equals("heavyweight"))
heavyweight = (value.toLowerCase().equals("true") || value.toLowerCase().equals("yes") ||
value.toLowerCase().equals("1"));
else if (key.toLowerCase().equals("maxoutstandingtxns"))
maxoutstandingtxns = Integer.parseInt(value);
// else - unknown; ignore
}
// Return JDBC connection wrapper for the client
return new JDBC4Connection(JDBC4ClientConnectionPool.get(servers, user, password,
heavyweight, maxoutstandingtxns),
info);
} catch (Exception x) {
throw SQLError.get(x, SQLError.CONNECTION_UNSUCCESSFUL);
}
}
return null;
}
@Override
public boolean acceptsURL(String url) throws SQLException
{
return Pattern.compile("^jdbc:voltdb://.+", Pattern.CASE_INSENSITIVE).matcher(url).matches();
}
@Override
public int getMajorVersion()
{
return MAJOR_VERSION;
}
@Override
public int getMinorVersion()
{
return MINOR_VERSION;
}
@Override
public DriverPropertyInfo[] getPropertyInfo(String url, Properties loginProps) throws SQLException
{
return new DriverPropertyInfo[0];
}
@Override
public boolean jdbcCompliant()
{
return false;
}
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
throw new SQLFeatureNotSupportedException();
}
private Properties tryToFindPropsFile() {
Properties fileprops = new Properties();
String filename = null;
// Check the env first
filename = System.getenv(Driver.JDBC_PROP_FILE_ENV);
if (filename == null) {
filename = System.getProperty(Driver.JDBC_PROP_FILE_PROP);
}
if (filename == null) {
// see if we can find a file in the default location
URL pathToJar = this.getClass().getProtectionDomain()
.getCodeSource().getLocation();
String tmp = null;
try {
tmp = new File(pathToJar.toURI()).getParent() + File.separator + DEFAULT_PROP_FILENAME;
} catch (Exception e) {
tmp = null;
}
filename = tmp;
}
if (filename != null) {
File propfile = new File(filename);
if (propfile.exists() && propfile.isFile()) {
FileInputStream in = null;
try {
in = new FileInputStream(propfile);
fileprops.load(in);
}
catch (FileNotFoundException fnfe) {}
catch (IOException ioe) {}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {}
}
}
}
}
return fileprops;
}
}
| agpl-3.0 |
ilyessou/jfreechart | source/org/jfree/data/category/CategoryDatasetSelectionState.java | 3804 | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2009, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* ----------------------------------
* CategoryDatasetSelectionState.java
* ----------------------------------
* (C) Copyright 2009, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 30-Jun-2009 : Version 1 (DG);
*
*/
package org.jfree.data.category;
import java.io.Serializable;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.data.general.DatasetSelectionState;
/**
* Returns information about the selection state of items in an
* {@link CategoryDataset}. Classes that implement this interface must also
* implement {@link PublicCloneable} to ensure that charts and datasets can be
* correctly cloned. Likewise, classes implementing this interface must also
* implement {@link Serializable}.
* <br><br>
* The selection state might be part of a dataset implementation, or it could
* be maintained in parallel with a dataset implementation that doesn't
* directly support selection state.
*
* @since 1.2.0
*/
public interface CategoryDatasetSelectionState extends DatasetSelectionState {
/**
* Returns the number of rows in the dataset.
*
* @return The number of rows.
*/
public int getRowCount();
/**
* Returns the number of columns in the dataset.
*
*
* @return The number of columns.
*/
public int getColumnCount();
/**
* Returns <code>true</code> if the specified item is selected, and
* <code>false</code> otherwise.
*
* @param row the row index.
* @param column the column index.
*
* @return A boolean.
*/
public boolean isSelected(int row, int column);
/**
* Sets the selection state for an item in the dataset.
*
* @param row the row index.
* @param column the column index.
* @param selected the selection state.
*/
public void setSelected(int row, int column, boolean selected);
/**
* Sets the selection state for the specified item and, if requested,
* fires a change event.
*
* @param row the row index.
* @param column the column index.
* @param selected the selection state.
* @param notify notify listeners?
*/
public void setSelected(int row, int column, boolean selected,
boolean notify);
/**
* Clears all selected items.
*/
public void clearSelection();
/**
* Send an event to registered listeners to indicate that the selection
* has changed.
*/
public void fireSelectionEvent();
}
| lgpl-2.1 |
ljo/exist | src/org/exist/security/internal/AccountImpl.java | 11934 | /*
* eXist Open Source Native XML Database
* Copyright (C) 2015 The eXist Project
* http://exist-db.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.exist.security.internal;
import org.exist.security.AbstractRealm;
import org.exist.security.AbstractAccount;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.exist.config.Configuration;
import org.exist.config.ConfigurationException;
import org.exist.config.Configurator;
import org.exist.config.annotation.ConfigurationClass;
import org.exist.config.annotation.ConfigurationFieldAsElement;
import org.exist.security.Group;
import org.exist.security.PermissionDeniedException;
import org.exist.security.SchemaType;
import org.exist.security.SecurityManager;
import org.exist.security.Account;
import org.exist.security.internal.aider.UserAider;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Optional;
import java.util.Properties;
import org.exist.security.Credential;
import org.exist.storage.DBBroker;
/**
* Represents a user within the database.
*
* @author Wolfgang Meier <wolfgang@exist-db.org>
* @author {Marco.Tampucci, Massimo.Martinelli} @isti.cnr.it
* @author Adam retter <adam@exist-db.org>
*/
@ConfigurationClass("account")
public class AccountImpl extends AbstractAccount {
private final static Logger LOG = LogManager.getLogger(AccountImpl.class);
public static boolean CHECK_PASSWORDS = true;
private final static SecurityProperties securityProperties = new SecurityProperties();
public static SecurityProperties getSecurityProperties() {
return securityProperties;
}
/*
static {
Properties props = new Properties();
try {
props.load(AccountImpl.class.getClassLoader().getResourceAsStream(
"org/exist/security/security.properties"));
} catch(IOException e) {
}
String option = props.getProperty("passwords.encoding", "md5");
setPasswordEncoding(option);
option = props.getProperty("passwords.check", "yes");
CHECK_PASSWORDS = option.equalsIgnoreCase("yes")
|| option.equalsIgnoreCase("true");
}
static public void enablePasswordChecks(boolean check) {
CHECK_PASSWORDS = check;
}
static public void setPasswordEncoding(String encoding) {
if(encoding != null) {
LOG.equals("Setting password encoding to " + encoding);
if(encoding.equalsIgnoreCase("plain")) {
PASSWORD_ENCODING = PLAIN_ENCODING;
} else if(encoding.equalsIgnoreCase("md5")) {
PASSWORD_ENCODING = MD5_ENCODING;
} else {
PASSWORD_ENCODING = SIMPLE_MD5_ENCODING;
}
}
}*/
@ConfigurationFieldAsElement("password")
private String password = null;
@ConfigurationFieldAsElement("digestPassword")
private String digestPassword = null;
/**
* Create a new user with name and password
*
* @param realm
* @param id
* @param name
* @param password
* @throws ConfigurationException
*/
public AccountImpl(final DBBroker broker, final AbstractRealm realm, final int id, final String name,final String password) throws ConfigurationException {
super(broker, realm, id, name);
setPassword(password);
}
public AccountImpl(final DBBroker broker, final AbstractRealm realm, final int id, final String name, final String password, final Group group, final boolean hasDbaRole) throws ConfigurationException {
super(broker, realm, id, name);
setPassword(password);
this.groups.add(group);
this.hasDbaRole = hasDbaRole;
}
public AccountImpl(final DBBroker broker, final AbstractRealm realm, final int id, final String name, final String password, final Group group) throws ConfigurationException {
super(broker, realm, id, name);
setPassword(password);
this.groups.add(group);
}
/**
* Create a new user with name
*
* @param realm
* @param name
* The account name
* @throws ConfigurationException
*/
public AccountImpl(final DBBroker broker, final AbstractRealm realm, final String name) throws ConfigurationException {
super(broker, realm, Account.UNDEFINED_ID, name);
}
// /**
// * Create a new user with name, password and primary group
// *
// * @param name
// * @param password
// * @param primaryGroup
// * @throws ConfigurationException
// * @throws PermissionDeniedException
// */
// public AccountImpl(AbstractRealm realm, int id, String name, String password, String primaryGroup) throws ConfigurationException {
// this(realm, id, name, password);
// addGroup(primaryGroup);
// }
public AccountImpl(final DBBroker broker, final AbstractRealm realm, final int id, final Account from_user) throws ConfigurationException, PermissionDeniedException {
super(broker, realm, id, from_user.getName());
instantiate(from_user);
}
private void instantiate(final Account from_user) throws PermissionDeniedException {
//copy metadata
for(final SchemaType metadataKey : from_user.getMetadataKeys()) {
final String metadataValue = from_user.getMetadataValue(metadataKey);
setMetadataValue(metadataKey, metadataValue);
}
//copy umask
setUserMask(from_user.getUserMask());
if(from_user instanceof AccountImpl) {
final AccountImpl user = (AccountImpl) from_user;
groups = new ArrayList<>(user.groups);
password = user.password;
digestPassword = user.digestPassword;
hasDbaRole = user.hasDbaRole;
_cred = user._cred;
} else if(from_user instanceof UserAider) {
final UserAider user = (UserAider) from_user;
final String[] groups = user.getGroups();
for (final String group : groups) {
addGroup(group);
}
setPassword(user.getPassword());
digestPassword = user.getDigestPassword();
} else {
addGroup(from_user.getDefaultGroup());
//TODO: groups
}
}
public AccountImpl(final DBBroker broker, final AbstractRealm realm, final AccountImpl from_user) throws ConfigurationException {
super(broker, realm, from_user.id, from_user.name);
//copy metadata
for(final SchemaType metadataKey : from_user.getMetadataKeys()) {
final String metadataValue = from_user.getMetadataValue(metadataKey);
setMetadataValue(metadataKey, metadataValue);
}
groups = from_user.groups;
password = from_user.password;
digestPassword = from_user.digestPassword;
hasDbaRole = from_user.hasDbaRole;
_cred = from_user._cred;
//this.realm = realm; //set via super()
}
public AccountImpl(final AbstractRealm realm, final Configuration configuration) throws ConfigurationException {
super(realm, configuration);
//this is required because the classes fields are initialized after the super constructor
if(this.configuration != null) {
this.configuration = Configurator.configure(this, this.configuration);
}
this.hasDbaRole = this.hasGroup(SecurityManager.DBA_GROUP);
}
public AccountImpl(final AbstractRealm realm, final Configuration configuration, final boolean removed) throws ConfigurationException {
this(realm, configuration);
this.removed = removed;
}
/**
* Get the user's password
*
* @return Description of the Return Value
* @deprecated
*/
@Override
public final String getPassword() {
return password;
}
@Override
public final String getDigestPassword() {
return digestPassword;
}
@Override
public final void setPassword(final String passwd) {
_cred = new Password(this, passwd);
if(passwd == null) {
this.password = null;
this.digestPassword = null;
} else {
this.password = _cred.toString();
this.digestPassword = _cred.getDigest();
}
}
@Override
public void setCredential(final Credential credential) {
this._cred = credential;
this.password = _cred.toString();
this.digestPassword = _cred.getDigest();
}
public final static class SecurityProperties {
private final static boolean DEFAULT_CHECK_PASSWORDS = true;
private final static String PROP_CHECK_PASSWORDS = "passwords.check";
private Properties loadedSecurityProperties = null;
private Boolean checkPasswords = null;
public synchronized boolean isCheckPasswords() {
if(checkPasswords == null) {
final String property = getProperty(PROP_CHECK_PASSWORDS);
if(property == null || property.length() == 0) {
checkPasswords = DEFAULT_CHECK_PASSWORDS;
} else {
checkPasswords = property.equalsIgnoreCase("yes") || property.equalsIgnoreCase("true");
}
}
return checkPasswords;
}
public synchronized void enableCheckPasswords(final boolean enable) {
this.checkPasswords = enable;
}
private synchronized String getProperty(final String propertyName) {
if(loadedSecurityProperties == null) {
loadedSecurityProperties = new Properties();
try(final InputStream is = AccountImpl.class.getResourceAsStream("security.properties")) {
if(is != null) {
loadedSecurityProperties.load(is);
}
} catch(final IOException ioe) {
LOG.error("Unable to load security.properties, using defaults. " + ioe.getMessage(), ioe);
}
}
return loadedSecurityProperties.getProperty(propertyName);
}
}
//this method is used by Configurator
public final Group insertGroup(final int index, final String name) throws PermissionDeniedException {
//if we cant find the group in our own realm, try other realms
final Group group = Optional.ofNullable(getRealm().getGroup(name))
.orElse(getRealm().getSecurityManager().getGroup(name));
return insertGroup(index, group);
}
private Group insertGroup(final int index, final Group group) throws PermissionDeniedException {
if(group == null){
return null;
}
final Account user = getDatabase().getActiveBroker().getCurrentSubject();
group.assertCanModifyGroup(user);
if(!groups.contains(group)) {
groups.add(index, group);
if(SecurityManager.DBA_GROUP.equals(group.getName())) {
hasDbaRole = true;
}
}
return group;
}
}
| lgpl-2.1 |
jamesmowens/hit-automaton | src/edu/usfca/vas/window/fa/WindowMachineFASettings.java | 10270 | /*
[The "BSD licence"]
Copyright (c) 2004 Jean Bovet
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package edu.usfca.vas.window.fa;
import com.jgoodies.forms.factories.Borders;
import com.jgoodies.forms.factories.DefaultComponentFactory;
import com.jgoodies.forms.factories.FormFactory;
import com.jgoodies.forms.layout.*;
import edu.usfca.xj.appkit.frame.XJDialog;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class WindowMachineFASettings extends XJDialog {
private WindowMachineFA wm = null;
public WindowMachineFASettings(WindowMachineFA wm) {
super(wm.getWindow().getJavaContainer(), true);
this.wm = wm;
initComponents();
setResizable(false);
resize();
setDefaultButton(okButton);
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
close();
}
});
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
popValues();
close();
}
});
}
public void resize() {
Dimension d = dialogPane.getPreferredSize();
d.height += 30;
setSize(d);
}
public void pushValues() {
nameField.setText(wm.getTitle());
nameField.selectAll();
widthField.setText(String.valueOf(wm.getGraphicSize().width));
heightField.setText(String.valueOf(wm.getGraphicSize().height));
verticalSpinner.setValue(new Integer(wm.getVerticalMagnetics()));
horizontalSpinner.setValue(new Integer(wm.getHorizontalMagnetics()));
}
public void popValues() {
wm.setGraphicsSize(Integer.parseInt(widthField.getText()), Integer.parseInt(heightField.getText()));
wm.setTitle(nameField.getText());
Integer horizontal = (Integer)horizontalSpinner.getValue();
Integer vertical = (Integer)horizontalSpinner.getValue();
wm.setMagnetics(horizontal.intValue(), vertical.intValue());
}
public void display() {
pushValues();
center();
runModal();
}
private void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
DefaultComponentFactory compFactory = DefaultComponentFactory.getInstance();
dialogPane = new JPanel();
contentPane = new JPanel();
label1 = new JLabel();
nameField = new JTextField();
goodiesFormsSeparator2 = compFactory.createSeparator("Machine Size");
label2 = new JLabel();
widthField = new JTextField();
label3 = new JLabel();
heightField = new JTextField();
goodiesFormsSeparator1 = compFactory.createSeparator("Magnetic Layout Grid");
label6 = new JLabel();
verticalSpinner = new JSpinner();
label4 = new JLabel();
horizontalSpinner = new JSpinner();
buttonBar = new JPanel();
okButton = new JButton();
cancelButton = new JButton();
CellConstraints cc = new CellConstraints();
//======== this ========
setTitle("Machine Settings");
Container contentPane2 = getContentPane();
contentPane2.setLayout(new BorderLayout());
//======== dialogPane ========
{
dialogPane.setBorder(Borders.DIALOG_BORDER);
dialogPane.setPreferredSize(new Dimension(350, 300));
dialogPane.setLayout(new BorderLayout());
//======== contentPane ========
{
contentPane.setLayout(new FormLayout(
new ColumnSpec[] {
new ColumnSpec(Sizes.dluX(10)),
FormFactory.LABEL_COMPONENT_GAP_COLSPEC,
FormFactory.DEFAULT_COLSPEC,
FormFactory.LABEL_COMPONENT_GAP_COLSPEC,
new ColumnSpec(Sizes.dluX(30)),
FormFactory.LABEL_COMPONENT_GAP_COLSPEC,
new ColumnSpec(ColumnSpec.FILL, Sizes.DEFAULT, FormSpec.DEFAULT_GROW),
FormFactory.LABEL_COMPONENT_GAP_COLSPEC,
new ColumnSpec("10px")
},
new RowSpec[] {
FormFactory.DEFAULT_ROWSPEC,
FormFactory.LINE_GAP_ROWSPEC,
new RowSpec(Sizes.dluY(10)),
FormFactory.LINE_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.LINE_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.LINE_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.LINE_GAP_ROWSPEC,
new RowSpec(Sizes.dluY(10)),
FormFactory.LINE_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.LINE_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.LINE_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC
}));
//---- label1 ----
label1.setHorizontalAlignment(SwingConstants.RIGHT);
label1.setText("Name:");
contentPane.add(label1, cc.xy(3, 1));
contentPane.add(nameField, cc.xywh(5, 1, 3, 1));
contentPane.add(goodiesFormsSeparator2, cc.xywh(3, 5, 5, 1));
//---- label2 ----
label2.setHorizontalAlignment(SwingConstants.RIGHT);
label2.setText("Width:");
contentPane.add(label2, cc.xy(3, 7));
contentPane.add(widthField, cc.xywh(5, 7, 3, 1));
//---- label3 ----
label3.setHorizontalAlignment(SwingConstants.RIGHT);
label3.setText("Height:");
contentPane.add(label3, cc.xy(3, 9));
contentPane.add(heightField, cc.xywh(5, 9, 3, 1));
contentPane.add(goodiesFormsSeparator1, cc.xywh(3, 13, 5, 1));
//---- label6 ----
label6.setHorizontalAlignment(SwingConstants.RIGHT);
label6.setText("Vertical:");
contentPane.add(label6, cc.xy(3, 15));
//---- verticalSpinner ----
verticalSpinner.setModel(new SpinnerNumberModel(new Integer(0), new Integer(0), null, new Integer(1)));
contentPane.add(verticalSpinner, cc.xy(5, 15));
//---- label4 ----
label4.setHorizontalAlignment(SwingConstants.RIGHT);
label4.setText("Horizontal:");
contentPane.add(label4, cc.xy(3, 17));
//---- horizontalSpinner ----
horizontalSpinner.setModel(new SpinnerNumberModel(new Integer(1), new Integer(0), null, new Integer(1)));
contentPane.add(horizontalSpinner, cc.xy(5, 17));
}
dialogPane.add(contentPane, BorderLayout.CENTER);
//======== buttonBar ========
{
buttonBar.setBorder(Borders.BUTTON_BAR_GAP_BORDER);
buttonBar.setLayout(new FormLayout(
new ColumnSpec[] {
FormFactory.GLUE_COLSPEC,
FormFactory.BUTTON_COLSPEC,
FormFactory.RELATED_GAP_COLSPEC,
FormFactory.BUTTON_COLSPEC
},
RowSpec.decodeSpecs("pref")));
//---- okButton ----
okButton.setText("OK");
buttonBar.add(okButton, cc.xy(2, 1));
//---- cancelButton ----
cancelButton.setText("Cancel");
buttonBar.add(cancelButton, cc.xy(4, 1));
}
dialogPane.add(buttonBar, BorderLayout.SOUTH);
}
contentPane2.add(dialogPane, BorderLayout.CENTER);
// JFormDesigner - End of component initialization //GEN-END:initComponents
}
// JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables
private JPanel dialogPane;
private JPanel contentPane;
private JLabel label1;
private JTextField nameField;
private JComponent goodiesFormsSeparator2;
private JLabel label2;
private JTextField widthField;
private JLabel label3;
private JTextField heightField;
private JComponent goodiesFormsSeparator1;
private JLabel label6;
private JSpinner verticalSpinner;
private JLabel label4;
private JSpinner horizontalSpinner;
private JPanel buttonBar;
private JButton okButton;
private JButton cancelButton;
// JFormDesigner - End of variables declaration //GEN-END:variables
}
| lgpl-2.1 |
xasx/wildfly | undertow/src/main/java/org/wildfly/extension/undertow/sso/elytron/SingleSignOnIdentifierFactory.java | 1767 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2018, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.undertow.sso.elytron;
import java.util.function.Supplier;
import io.undertow.server.session.SecureRandomSessionIdGenerator;
import io.undertow.server.session.SessionIdGenerator;
/**
* Adapts a {@link SessionIdGenerator} to {@link Supplier}.
* @author Paul Ferraro
*/
public class SingleSignOnIdentifierFactory implements Supplier<String> {
private final SessionIdGenerator generator;
public SingleSignOnIdentifierFactory() {
this(new SecureRandomSessionIdGenerator());
}
public SingleSignOnIdentifierFactory(SessionIdGenerator generator) {
this.generator = generator;
}
@Override
public String get() {
return this.generator.createSessionId();
}
}
| lgpl-2.1 |
jinified/HubTurbo | src/main/java/util/events/UsedReposChangedEvent.java | 75 | package util.events;
public class UsedReposChangedEvent extends Event {
}
| lgpl-3.0 |
archeng504/yammp | src/org/yammp/dialog/PlaylistDialog.java | 9445 | /*
* Copyright (C) 2011 The MusicMod Project
*
* 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.yammp.dialog;
import org.yammp.Constants;
import org.yammp.R;
import org.yammp.YAMMPApplication;
import org.yammp.util.MediaUtils;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnShowListener;
import android.database.Cursor;
import android.media.AudioManager;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
public class PlaylistDialog extends FragmentActivity implements Constants, TextWatcher,
OnCancelListener, OnShowListener {
private AlertDialog mPlaylistDialog;
private String action;
private EditText mPlaylist;
private String mDefaultName, mOriginalName;
private long mRenameId;
private long[] mList = new long[] {};
private OnClickListener mRenamePlaylistListener = new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String name = mPlaylist.getText().toString();
mUtils.renamePlaylist(mRenameId, name);
finish();
}
};
private OnClickListener mCreatePlaylistListener = new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String name = mPlaylist.getText().toString();
if (name != null && name.length() > 0) {
int id = idForplaylist(name);
if (id >= 0) {
mUtils.clearPlaylist(id);
mUtils.addToPlaylist(mList, id);
} else {
long new_id = mUtils.createPlaylist(name);
if (new_id >= 0) {
mUtils.addToPlaylist(mList, new_id);
}
}
finish();
}
}
};
private MediaUtils mUtils;
@Override
public void afterTextChanged(Editable s) {
// don't care about this one
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// don't care about this one
}
@Override
public void onCancel(DialogInterface dialog) {
if (dialog == mPlaylistDialog) {
finish();
}
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mUtils = ((YAMMPApplication) getApplication()).getMediaUtils();
setContentView(new LinearLayout(this));
action = getIntent().getAction();
mRenameId = icicle != null ? icicle.getLong(INTENT_KEY_RENAME) : getIntent().getLongExtra(
INTENT_KEY_RENAME, -1);
mList = icicle != null ? icicle.getLongArray(INTENT_KEY_LIST) : getIntent()
.getLongArrayExtra(INTENT_KEY_LIST);
if (INTENT_RENAME_PLAYLIST.equals(action)) {
mOriginalName = nameForId(mRenameId);
mDefaultName = icicle != null ? icicle.getString(INTENT_KEY_DEFAULT_NAME)
: mOriginalName;
} else if (INTENT_CREATE_PLAYLIST.equals(action)) {
mDefaultName = icicle != null ? icicle.getString(INTENT_KEY_DEFAULT_NAME)
: makePlaylistName();
mOriginalName = mDefaultName;
}
DisplayMetrics dm = new DisplayMetrics();
dm = getResources().getDisplayMetrics();
mPlaylistDialog = new AlertDialog.Builder(this).create();
mPlaylistDialog.setVolumeControlStream(AudioManager.STREAM_MUSIC);
if (action != null && mRenameId >= 0 && mOriginalName != null || mDefaultName != null) {
mPlaylist = new EditText(this);
mPlaylist.setSingleLine(true);
mPlaylist.setText(mDefaultName);
mPlaylist.setSelection(mDefaultName.length());
mPlaylist.addTextChangedListener(this);
mPlaylistDialog.setIcon(android.R.drawable.ic_dialog_info);
String promptformat;
String prompt = "";
if (INTENT_RENAME_PLAYLIST.equals(action)) {
promptformat = getString(R.string.rename_playlist_prompt);
prompt = String.format(promptformat, mOriginalName, mDefaultName);
} else if (INTENT_CREATE_PLAYLIST.equals(action)) {
promptformat = getString(R.string.create_playlist_prompt);
prompt = String.format(promptformat, mDefaultName);
}
mPlaylistDialog.setTitle(prompt);
mPlaylistDialog.setView(mPlaylist, (int) (8 * dm.density), (int) (8 * dm.density),
(int) (8 * dm.density), (int) (4 * dm.density));
if (INTENT_RENAME_PLAYLIST.equals(action)) {
mPlaylistDialog.setButton(Dialog.BUTTON_POSITIVE, getString(R.string.save),
mRenamePlaylistListener);
mPlaylistDialog.setOnShowListener(this);
} else if (INTENT_CREATE_PLAYLIST.equals(action)) {
mPlaylistDialog.setButton(Dialog.BUTTON_POSITIVE, getString(R.string.save),
mCreatePlaylistListener);
}
mPlaylistDialog.setButton(Dialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
mPlaylistDialog.setOnCancelListener(this);
mPlaylistDialog.show();
} else {
Toast.makeText(this, R.string.error_bad_parameters, Toast.LENGTH_SHORT).show();
finish();
}
}
@Override
public void onPause() {
if (mPlaylistDialog != null && mPlaylistDialog.isShowing()) {
mPlaylistDialog.dismiss();
}
super.onPause();
}
@Override
public void onSaveInstanceState(Bundle outcicle) {
if (INTENT_RENAME_PLAYLIST.equals(action)) {
outcicle.putString(INTENT_KEY_DEFAULT_NAME, mPlaylist.getText().toString());
outcicle.putLong(INTENT_KEY_RENAME, mRenameId);
} else if (INTENT_CREATE_PLAYLIST.equals(action)) {
outcicle.putString(INTENT_KEY_DEFAULT_NAME, mPlaylist.getText().toString());
}
}
@Override
public void onShow(DialogInterface dialog) {
if (dialog == mPlaylistDialog) {
setSaveButton();
}
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
setSaveButton();
}
private int idForplaylist(String name) {
Cursor cursor = mUtils.query(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Audio.Playlists._ID }, MediaStore.Audio.Playlists.NAME
+ "=?", new String[] { name }, MediaStore.Audio.Playlists.NAME);
int id = -1;
if (cursor != null) {
cursor.moveToFirst();
if (!cursor.isAfterLast()) {
id = cursor.getInt(0);
}
cursor.close();
}
return id;
}
private String makePlaylistName() {
String template = getString(R.string.new_playlist_name_template);
int num = 1;
String[] cols = new String[] { MediaStore.Audio.Playlists.NAME };
ContentResolver resolver = getContentResolver();
String whereclause = MediaStore.Audio.Playlists.NAME + " != ''";
Cursor cursor = resolver.query(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, cols,
whereclause, null, MediaStore.Audio.Playlists.NAME);
if (cursor == null) return null;
String suggestedname;
suggestedname = String.format(template, num++);
// Need to loop until we've made 1 full pass through without finding a
// match. Looping more than once shouldn't happen very often, but will
// happen if you have playlists named
// "New Playlist 1"/10/2/3/4/5/6/7/8/9, where making only one pass would
// result in "New Playlist 10" being erroneously picked for the new
// name.
boolean done = false;
while (!done) {
done = true;
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
String playlistname = cursor.getString(0);
if (playlistname.compareToIgnoreCase(suggestedname) == 0) {
suggestedname = String.format(template, num++);
done = false;
}
cursor.moveToNext();
}
}
cursor.close();
return suggestedname;
};
private String nameForId(long id) {
Cursor cursor = mUtils.query(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Audio.Playlists.NAME }, MediaStore.Audio.Playlists._ID
+ "=?", new String[] { Long.valueOf(id).toString() },
MediaStore.Audio.Playlists.NAME);
String name = null;
if (cursor != null) {
cursor.moveToFirst();
if (!cursor.isAfterLast()) {
name = cursor.getString(0);
}
cursor.close();
}
return name;
}
private void setSaveButton() {
String typedname = mPlaylist.getText().toString();
Button button = mPlaylistDialog.getButton(Dialog.BUTTON_POSITIVE);
if (button == null) return;
if (typedname.trim().length() == 0 || PLAYLIST_NAME_FAVORITES.equals(typedname)) {
button.setEnabled(false);
} else {
button.setEnabled(true);
if (idForplaylist(typedname) >= 0 && !mOriginalName.equals(typedname)) {
button.setText(R.string.overwrite);
} else {
button.setText(R.string.save);
}
}
button.invalidate();
}
@Override
protected void onResume() {
super.onResume();
if (mPlaylistDialog != null) {
mPlaylistDialog.show();
}
}
}
| lgpl-3.0 |
apurtell/hadoop | hadoop-hdfs-project/hadoop-hdfs-rbf/src/test/java/org/apache/hadoop/hdfs/server/federation/store/TestStateStoreMembershipState.java | 24181 | /**
* 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.federation.store;
import static org.apache.hadoop.hdfs.server.federation.FederationTestUtils.NAMENODES;
import static org.apache.hadoop.hdfs.server.federation.FederationTestUtils.NAMESERVICES;
import static org.apache.hadoop.hdfs.server.federation.FederationTestUtils.ROUTERS;
import static org.apache.hadoop.hdfs.server.federation.FederationTestUtils.verifyException;
import static org.apache.hadoop.hdfs.server.federation.store.FederationStateStoreTestUtils.clearRecords;
import static org.apache.hadoop.hdfs.server.federation.store.FederationStateStoreTestUtils.createMockRegistrationForNamenode;
import static org.apache.hadoop.hdfs.server.federation.store.FederationStateStoreTestUtils.synchronizeRecords;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.hadoop.hdfs.server.federation.resolver.FederationNamenodeServiceState;
import org.apache.hadoop.hdfs.server.federation.resolver.FederationNamespaceInfo;
import org.apache.hadoop.hdfs.server.federation.router.RBFConfigKeys;
import org.apache.hadoop.hdfs.server.federation.store.protocol.GetNamenodeRegistrationsRequest;
import org.apache.hadoop.hdfs.server.federation.store.protocol.GetNamenodeRegistrationsResponse;
import org.apache.hadoop.hdfs.server.federation.store.protocol.GetNamespaceInfoRequest;
import org.apache.hadoop.hdfs.server.federation.store.protocol.GetNamespaceInfoResponse;
import org.apache.hadoop.hdfs.server.federation.store.protocol.NamenodeHeartbeatRequest;
import org.apache.hadoop.hdfs.server.federation.store.protocol.NamenodeHeartbeatResponse;
import org.apache.hadoop.hdfs.server.federation.store.protocol.UpdateNamenodeRegistrationRequest;
import org.apache.hadoop.hdfs.server.federation.store.records.MembershipState;
import org.apache.hadoop.test.GenericTestUtils;
import org.apache.hadoop.util.Time;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Test the basic {@link MembershipStore} membership functionality.
*/
public class TestStateStoreMembershipState extends TestStateStoreBase {
private static MembershipStore membershipStore;
@BeforeClass
public static void create() {
// Reduce expirations to 2 seconds
getConf().setLong(
RBFConfigKeys.FEDERATION_STORE_MEMBERSHIP_EXPIRATION_MS,
TimeUnit.SECONDS.toMillis(2));
// Set deletion time to 2 seconds
getConf().setLong(
RBFConfigKeys.FEDERATION_STORE_MEMBERSHIP_EXPIRATION_DELETION_MS,
TimeUnit.SECONDS.toMillis(2));
}
@Before
public void setup() throws IOException, InterruptedException {
membershipStore =
getStateStore().getRegisteredRecordStore(MembershipStore.class);
// Clear NN registrations
assertTrue(clearRecords(getStateStore(), MembershipState.class));
}
@Test
public void testNamenodeStateOverride() throws Exception {
// Populate the state store
// 1) ns0:nn0 - Standby
String ns = "ns0";
String nn = "nn0";
MembershipState report = createRegistration(
ns, nn, ROUTERS[1], FederationNamenodeServiceState.STANDBY);
assertTrue(namenodeHeartbeat(report));
// Load data into cache and calculate quorum
assertTrue(getStateStore().loadCache(MembershipStore.class, true));
MembershipState existingState = getNamenodeRegistration(ns, nn);
assertEquals(
FederationNamenodeServiceState.STANDBY, existingState.getState());
// Override cache
UpdateNamenodeRegistrationRequest request =
UpdateNamenodeRegistrationRequest.newInstance(
ns, nn, FederationNamenodeServiceState.ACTIVE);
assertTrue(membershipStore.updateNamenodeRegistration(request).getResult());
MembershipState newState = getNamenodeRegistration(ns, nn);
assertEquals(FederationNamenodeServiceState.ACTIVE, newState.getState());
// Override cache
UpdateNamenodeRegistrationRequest request1 =
UpdateNamenodeRegistrationRequest.newInstance(ns, nn,
FederationNamenodeServiceState.OBSERVER);
assertTrue(
membershipStore.updateNamenodeRegistration(request1).getResult());
MembershipState newState1 = getNamenodeRegistration(ns, nn);
assertEquals(FederationNamenodeServiceState.OBSERVER, newState1.getState());
}
@Test
public void testStateStoreDisconnected() throws Exception {
// Close the data store driver
getStateStore().closeDriver();
assertFalse(getStateStore().isDriverReady());
NamenodeHeartbeatRequest hbRequest = NamenodeHeartbeatRequest.newInstance();
hbRequest.setNamenodeMembership(
createMockRegistrationForNamenode(
"test", "test", FederationNamenodeServiceState.UNAVAILABLE));
verifyException(membershipStore, "namenodeHeartbeat",
StateStoreUnavailableException.class,
new Class[] {NamenodeHeartbeatRequest.class},
new Object[] {hbRequest });
// Information from cache, no exception should be triggered for these
// TODO - should cached info expire at some point?
GetNamenodeRegistrationsRequest getRequest =
GetNamenodeRegistrationsRequest.newInstance();
verifyException(membershipStore,
"getNamenodeRegistrations", null,
new Class[] {GetNamenodeRegistrationsRequest.class},
new Object[] {getRequest});
verifyException(membershipStore,
"getExpiredNamenodeRegistrations", null,
new Class[] {GetNamenodeRegistrationsRequest.class},
new Object[] {getRequest});
UpdateNamenodeRegistrationRequest overrideRequest =
UpdateNamenodeRegistrationRequest.newInstance();
verifyException(membershipStore,
"updateNamenodeRegistration", null,
new Class[] {UpdateNamenodeRegistrationRequest.class},
new Object[] {overrideRequest});
}
private void registerAndLoadRegistrations(
List<MembershipState> registrationList) throws IOException {
// Populate
assertTrue(synchronizeRecords(
getStateStore(), registrationList, MembershipState.class));
// Load into cache
assertTrue(getStateStore().loadCache(MembershipStore.class, true));
}
private MembershipState createRegistration(String ns, String nn,
String router, FederationNamenodeServiceState state) throws IOException {
MembershipState record = MembershipState.newInstance(
router, ns,
nn, "testcluster", "testblock-" + ns, "testrpc-"+ ns + nn,
"testservice-"+ ns + nn, "testlifeline-"+ ns + nn,
"http", "testweb-" + ns + nn, state, false);
return record;
}
@Test
public void testRegistrationMajorityQuorum()
throws InterruptedException, IOException {
// Populate the state store with a set of non-matching elements
// 1) ns0:nn0 - Standby (newest)
// 2) ns0:nn0 - Active (oldest)
// 3) ns0:nn0 - Active (2nd oldest)
// 4) ns0:nn0 - Active (3nd oldest element, newest active element)
// Verify the selected entry is the newest majority opinion (4)
String ns = "ns0";
String nn = "nn0";
// Active - oldest
MembershipState report = createRegistration(
ns, nn, ROUTERS[1], FederationNamenodeServiceState.ACTIVE);
assertTrue(namenodeHeartbeat(report));
Thread.sleep(1000);
// Active - 2nd oldest
report = createRegistration(
ns, nn, ROUTERS[2], FederationNamenodeServiceState.ACTIVE);
assertTrue(namenodeHeartbeat(report));
Thread.sleep(1000);
// Active - 3rd oldest, newest active element
report = createRegistration(
ns, nn, ROUTERS[3], FederationNamenodeServiceState.ACTIVE);
assertTrue(namenodeHeartbeat(report));
// standby - newest overall
report = createRegistration(
ns, nn, ROUTERS[0], FederationNamenodeServiceState.STANDBY);
assertTrue(namenodeHeartbeat(report));
// Load and calculate quorum
assertTrue(getStateStore().loadCache(MembershipStore.class, true));
// Verify quorum entry
MembershipState quorumEntry = getNamenodeRegistration(
report.getNameserviceId(), report.getNamenodeId());
assertNotNull(quorumEntry);
assertEquals(quorumEntry.getRouterId(), ROUTERS[3]);
}
@Test
public void testRegistrationQuorumExcludesExpired()
throws InterruptedException, IOException {
// Populate the state store with some expired entries and verify the expired
// entries are ignored.
// 1) ns0:nn0 - Active
// 2) ns0:nn0 - Expired
// 3) ns0:nn0 - Expired
// 4) ns0:nn0 - Expired
// Verify the selected entry is the active entry
List<MembershipState> registrationList = new ArrayList<>();
String ns = "ns0";
String nn = "nn0";
String rpcAddress = "testrpcaddress";
String serviceAddress = "testserviceaddress";
String lifelineAddress = "testlifelineaddress";
String blockPoolId = "testblockpool";
String clusterId = "testcluster";
String webScheme = "http";
String webAddress = "testwebaddress";
boolean safemode = false;
// Active
MembershipState record = MembershipState.newInstance(
ROUTERS[0], ns, nn, clusterId, blockPoolId,
rpcAddress, serviceAddress, lifelineAddress, webScheme,
webAddress, FederationNamenodeServiceState.ACTIVE, safemode);
registrationList.add(record);
// Expired
record = MembershipState.newInstance(
ROUTERS[1], ns, nn, clusterId, blockPoolId,
rpcAddress, serviceAddress, lifelineAddress, webScheme,
webAddress, FederationNamenodeServiceState.EXPIRED, safemode);
registrationList.add(record);
// Expired
record = MembershipState.newInstance(
ROUTERS[2], ns, nn, clusterId, blockPoolId,
rpcAddress, serviceAddress, lifelineAddress, webScheme, webAddress,
FederationNamenodeServiceState.EXPIRED, safemode);
registrationList.add(record);
// Expired
record = MembershipState.newInstance(
ROUTERS[3], ns, nn, clusterId, blockPoolId,
rpcAddress, serviceAddress, lifelineAddress, webScheme, webAddress,
FederationNamenodeServiceState.EXPIRED, safemode);
registrationList.add(record);
registerAndLoadRegistrations(registrationList);
// Verify quorum entry chooses active membership
MembershipState quorumEntry = getNamenodeRegistration(
record.getNameserviceId(), record.getNamenodeId());
assertNotNull(quorumEntry);
assertEquals(ROUTERS[0], quorumEntry.getRouterId());
}
@Test
public void testRegistrationQuorumAllExpired() throws IOException {
// 1) ns0:nn0 - Expired (oldest)
// 2) ns0:nn0 - Expired
// 3) ns0:nn0 - Expired
// 4) ns0:nn0 - Expired
// Verify no entry is either selected or cached
List<MembershipState> registrationList = new ArrayList<>();
String ns = NAMESERVICES[0];
String nn = NAMENODES[0];
String rpcAddress = "testrpcaddress";
String serviceAddress = "testserviceaddress";
String lifelineAddress = "testlifelineaddress";
String blockPoolId = "testblockpool";
String clusterId = "testcluster";
String webScheme = "http";
String webAddress = "testwebaddress";
boolean safemode = false;
long startingTime = Time.now();
// Expired
MembershipState record = MembershipState.newInstance(
ROUTERS[0], ns, nn, clusterId, blockPoolId,
rpcAddress, webAddress, lifelineAddress, webScheme, webAddress,
FederationNamenodeServiceState.EXPIRED, safemode);
record.setDateModified(startingTime - 10000);
registrationList.add(record);
// Expired
record = MembershipState.newInstance(
ROUTERS[1], ns, nn, clusterId, blockPoolId,
rpcAddress, serviceAddress, lifelineAddress, webScheme, webAddress,
FederationNamenodeServiceState.EXPIRED, safemode);
record.setDateModified(startingTime);
registrationList.add(record);
// Expired
record = MembershipState.newInstance(
ROUTERS[2], ns, nn, clusterId, blockPoolId,
rpcAddress, serviceAddress, lifelineAddress, webScheme, webAddress,
FederationNamenodeServiceState.EXPIRED, safemode);
record.setDateModified(startingTime);
registrationList.add(record);
// Expired
record = MembershipState.newInstance(
ROUTERS[3], ns, nn, clusterId, blockPoolId,
rpcAddress, serviceAddress, lifelineAddress, webScheme, webAddress,
FederationNamenodeServiceState.EXPIRED, safemode);
record.setDateModified(startingTime);
registrationList.add(record);
registerAndLoadRegistrations(registrationList);
// Verify no entry is found for this nameservice
assertNull(getNamenodeRegistration(
record.getNameserviceId(), record.getNamenodeId()));
}
@Test
public void testRegistrationNoQuorum()
throws InterruptedException, IOException {
// Populate the state store with a set of non-matching elements
// 1) ns0:nn0 - Standby (newest)
// 2) ns0:nn0 - Standby (oldest)
// 3) ns0:nn0 - Active (2nd oldest)
// 4) ns0:nn0 - Active (3nd oldest element, newest active element)
// Verify the selected entry is the newest entry (1)
MembershipState report1 = createRegistration(
NAMESERVICES[0], NAMENODES[0], ROUTERS[1],
FederationNamenodeServiceState.STANDBY);
assertTrue(namenodeHeartbeat(report1));
Thread.sleep(100);
MembershipState report2 = createRegistration(
NAMESERVICES[0], NAMENODES[0], ROUTERS[2],
FederationNamenodeServiceState.ACTIVE);
assertTrue(namenodeHeartbeat(report2));
Thread.sleep(100);
MembershipState report3 = createRegistration(
NAMESERVICES[0], NAMENODES[0], ROUTERS[3],
FederationNamenodeServiceState.ACTIVE);
assertTrue(namenodeHeartbeat(report3));
Thread.sleep(100);
MembershipState report4 = createRegistration(
NAMESERVICES[0], NAMENODES[0], ROUTERS[0],
FederationNamenodeServiceState.STANDBY);
assertTrue(namenodeHeartbeat(report4));
// Load and calculate quorum
assertTrue(getStateStore().loadCache(MembershipStore.class, true));
// Verify quorum entry uses the newest data, even though it is standby
MembershipState quorumEntry = getNamenodeRegistration(
report1.getNameserviceId(), report1.getNamenodeId());
assertNotNull(quorumEntry);
assertEquals(ROUTERS[0], quorumEntry.getRouterId());
assertEquals(
FederationNamenodeServiceState.STANDBY, quorumEntry.getState());
}
@Test
public void testRegistrationExpiredAndDeletion()
throws InterruptedException, IOException, TimeoutException {
// Populate the state store with a single NN element
// 1) ns0:nn0 - Active
// Wait for the entry to expire without heartbeating
// Verify the NN entry is populated as EXPIRED internally in the state store
MembershipState report = createRegistration(
NAMESERVICES[0], NAMENODES[0], ROUTERS[0],
FederationNamenodeServiceState.ACTIVE);
assertTrue(namenodeHeartbeat(report));
// Load cache
assertTrue(getStateStore().loadCache(MembershipStore.class, true));
// Verify quorum and entry
MembershipState quorumEntry = getNamenodeRegistration(
report.getNameserviceId(), report.getNamenodeId());
assertNotNull(quorumEntry);
assertEquals(ROUTERS[0], quorumEntry.getRouterId());
assertEquals(FederationNamenodeServiceState.ACTIVE, quorumEntry.getState());
quorumEntry = getExpiredNamenodeRegistration(report.getNameserviceId(),
report.getNamenodeId());
assertNull(quorumEntry);
// Wait past expiration (set in conf to 2 seconds)
GenericTestUtils.waitFor(() -> {
try {
assertTrue(getStateStore().loadCache(MembershipStore.class, true));
// Verify entry is expired and is no longer in the cache
return getNamenodeRegistration(NAMESERVICES[0], NAMENODES[0]) == null;
} catch (IOException e) {
return false;
}
}, 100, 3000);
// Verify entry is in expired membership records
quorumEntry = getExpiredNamenodeRegistration(NAMESERVICES[0], NAMENODES[0]);
assertNotNull(quorumEntry);
// Verify entry is now expired and can't be used by RPC service
quorumEntry = getNamenodeRegistration(
report.getNameserviceId(), report.getNamenodeId());
assertNull(quorumEntry);
quorumEntry = getExpiredNamenodeRegistration(
report.getNameserviceId(), report.getNamenodeId());
assertNotNull(quorumEntry);
// Heartbeat again, updates dateModified
assertTrue(namenodeHeartbeat(report));
// Reload cache
assertTrue(getStateStore().loadCache(MembershipStore.class, true));
// Verify updated entry marked as active and is accessible to RPC server
quorumEntry = getNamenodeRegistration(
report.getNameserviceId(), report.getNamenodeId());
assertNotNull(quorumEntry);
assertEquals(ROUTERS[0], quorumEntry.getRouterId());
assertEquals(FederationNamenodeServiceState.ACTIVE, quorumEntry.getState());
quorumEntry = getExpiredNamenodeRegistration(
report.getNameserviceId(), report.getNamenodeId());
assertNull(quorumEntry);
// Wait past expiration (set in conf to 2 seconds)
GenericTestUtils.waitFor(() -> {
try {
assertTrue(getStateStore().loadCache(MembershipStore.class, true));
// Verify entry is expired and is no longer in the cache
return getNamenodeRegistration(NAMESERVICES[0], NAMENODES[0]) == null;
} catch (IOException e) {
return false;
}
}, 100, 3000);
// Verify entry is in expired membership records
quorumEntry = getExpiredNamenodeRegistration(NAMESERVICES[0], NAMENODES[0]);
assertNotNull(quorumEntry);
// Wait past deletion (set in conf to 2 seconds)
GenericTestUtils.waitFor(() -> {
try {
assertTrue(getStateStore().loadCache(MembershipStore.class, true));
// Verify entry is deleted from even the expired membership records
return getExpiredNamenodeRegistration(NAMESERVICES[0], NAMENODES[0])
== null;
} catch (IOException e) {
return false;
}
}, 100, 3000);
}
@Test
public void testNamespaceInfoWithUnavailableNameNodeRegistration()
throws IOException {
// Populate the state store with one ACTIVE NameNode entry
// and one UNAVAILABLE NameNode entry
// 1) ns0:nn0 - ACTIVE
// 2) ns0:nn1 - UNAVAILABLE
List<MembershipState> registrationList = new ArrayList<>();
String router = ROUTERS[0];
String ns = NAMESERVICES[0];
String rpcAddress = "testrpcaddress";
String serviceAddress = "testserviceaddress";
String lifelineAddress = "testlifelineaddress";
String blockPoolId = "testblockpool";
String clusterId = "testcluster";
String webScheme = "http";
String webAddress = "testwebaddress";
boolean safemode = false;
MembershipState record = MembershipState.newInstance(
router, ns, NAMENODES[0], clusterId, blockPoolId,
rpcAddress, serviceAddress, lifelineAddress, webScheme,
webAddress, FederationNamenodeServiceState.ACTIVE, safemode);
registrationList.add(record);
// Set empty clusterId and blockPoolId for UNAVAILABLE NameNode
record = MembershipState.newInstance(
router, ns, NAMENODES[1], "", "",
rpcAddress, serviceAddress, lifelineAddress, webScheme,
webAddress, FederationNamenodeServiceState.UNAVAILABLE, safemode);
registrationList.add(record);
registerAndLoadRegistrations(registrationList);
GetNamespaceInfoRequest request = GetNamespaceInfoRequest.newInstance();
GetNamespaceInfoResponse response
= membershipStore.getNamespaceInfo(request);
Set<FederationNamespaceInfo> namespaces = response.getNamespaceInfo();
// Verify only one namespace is registered
assertEquals(1, namespaces.size());
// Verify the registered namespace has a valid pair of clusterId
// and blockPoolId derived from ACTIVE NameNode
FederationNamespaceInfo namespace = namespaces.iterator().next();
assertEquals(ns, namespace.getNameserviceId());
assertEquals(clusterId, namespace.getClusterId());
assertEquals(blockPoolId, namespace.getBlockPoolId());
}
/**
* Get a single namenode membership record from the store.
*
* @param nsId The HDFS nameservice ID to search for
* @param nnId The HDFS namenode ID to search for
* @return The single NamenodeMembershipRecord that matches the query or null
* if not found.
* @throws IOException if the query could not be executed.
*/
private MembershipState getNamenodeRegistration(
final String nsId, final String nnId) throws IOException {
MembershipState partial = MembershipState.newInstance();
partial.setNameserviceId(nsId);
partial.setNamenodeId(nnId);
GetNamenodeRegistrationsRequest request =
GetNamenodeRegistrationsRequest.newInstance(partial);
GetNamenodeRegistrationsResponse response =
membershipStore.getNamenodeRegistrations(request);
List<MembershipState> results = response.getNamenodeMemberships();
if (results != null && results.size() == 1) {
MembershipState record = results.get(0);
return record;
}
return null;
}
/**
* Get a single expired namenode membership record from the store.
*
* @param nsId The HDFS nameservice ID to search for
* @param nnId The HDFS namenode ID to search for
* @return The single expired NamenodeMembershipRecord that matches the query
* or null if not found.
* @throws IOException if the query could not be executed.
*/
private MembershipState getExpiredNamenodeRegistration(
final String nsId, final String nnId) throws IOException {
MembershipState partial = MembershipState.newInstance();
partial.setNameserviceId(nsId);
partial.setNamenodeId(nnId);
GetNamenodeRegistrationsRequest request =
GetNamenodeRegistrationsRequest.newInstance(partial);
GetNamenodeRegistrationsResponse response =
membershipStore.getExpiredNamenodeRegistrations(request);
List<MembershipState> results = response.getNamenodeMemberships();
if (results != null && results.size() == 1) {
MembershipState record = results.get(0);
return record;
}
return null;
}
/**
* Register a namenode heartbeat with the state store.
*
* @param store FederationMembershipStateStore instance to retrieve the
* membership data records.
* @param namenode A fully populated namenode membership record to be
* committed to the data store.
* @return True if successful, false otherwise.
* @throws IOException if the state store query could not be performed.
*/
private boolean namenodeHeartbeat(MembershipState namenode)
throws IOException {
NamenodeHeartbeatRequest request =
NamenodeHeartbeatRequest.newInstance(namenode);
NamenodeHeartbeatResponse response =
membershipStore.namenodeHeartbeat(request);
return response.getResult();
}
} | apache-2.0 |
haipeng-ssy/openfire_src | src/java/org/jivesoftware/openfire/handler/IQvCardHandler.java | 6967 | /**
* $RCSfile$
* $Revision: 1653 $
* $Date: 2005-07-20 00:21:40 -0300 (Wed, 20 Jul 2005) $
*
* Copyright (C) 2004-2008 Jive Software. 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 org.jivesoftware.openfire.handler;
import java.util.Iterator;
import org.dom4j.Element;
import org.dom4j.QName;
import org.jivesoftware.openfire.IQHandlerInfo;
import org.jivesoftware.openfire.PacketException;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.user.User;
import org.jivesoftware.openfire.user.UserManager;
import org.jivesoftware.openfire.user.UserNotFoundException;
import org.jivesoftware.openfire.vcard.VCardManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;
import org.xmpp.packet.PacketError;
/**
* Implements the TYPE_IQ vcard-temp protocol. Clients
* use this protocol to set and retrieve the vCard information
* associated with someone's account.
* <p>
* A 'get' query retrieves the vcard for the addressee.
* A 'set' query sets the vcard information for the sender's account.
* </p>
* <p>
* Currently an empty implementation to allow usage with normal
* clients. Future implementation needed.
* </p>
* <h2>Assumptions</h2>
* This handler assumes that the request is addressed to the server.
* An appropriate TYPE_IQ tag matcher should be placed in front of this
* one to route TYPE_IQ requests not addressed to the server to
* another channel (probably for direct delivery to the recipient).
* <h2>Warning</h2>
* There should be a way of determining whether a session has
* authorization to access this feature. I'm not sure it is a good
* idea to do authorization in each handler. It would be nice if
* the framework could assert authorization policies across channels.
* <h2>Warning</h2>
* I have noticed incompatibility between vCard XML used by Exodus and Psi.
* There is a new vCard standard going through the JSF JEP process. We might
* want to start either standardizing on clients (probably the most practical),
* sending notices for non-conformance (useful),
* or attempting to translate between client versions (not likely).
*
* @author Iain Shigeoka
*/
public class IQvCardHandler extends IQHandler {
private static final Logger Log = LoggerFactory.getLogger(IQvCardHandler.class);
private IQHandlerInfo info;
private XMPPServer server;
private UserManager userManager;
public IQvCardHandler() {
super("XMPP vCard Handler");
info = new IQHandlerInfo("vCard", "vcard-temp");
}
@Override
public IQ handleIQ(IQ packet) throws UnauthorizedException, PacketException {
IQ result = IQ.createResultIQ(packet);
IQ.Type type = packet.getType();
if (type.equals(IQ.Type.set)) {
try {
User user = userManager.getUser(packet.getFrom().getNode());
Element vcard = packet.getChildElement();
if (vcard != null) {
VCardManager.getInstance().setVCard(user.getUsername(), vcard);
}
}
catch (UserNotFoundException e) {
result = IQ.createResultIQ(packet);
result.setChildElement(packet.getChildElement().createCopy());
result.setError(PacketError.Condition.item_not_found);
}
catch (Exception e) {
Log.error(e.getMessage(), e);
result.setError(PacketError.Condition.internal_server_error);
}
}
else if (type.equals(IQ.Type.get)) {
JID recipient = packet.getTo();
// If no TO was specified then get the vCard of the sender of the packet
if (recipient == null) {
recipient = packet.getFrom();
}
// By default return an empty vCard
result.setChildElement("vCard", "vcard-temp");
// Only try to get the vCard values of non-anonymous users
if (recipient != null) {
if (recipient.getNode() != null && server.isLocal(recipient)) {
VCardManager vManager = VCardManager.getInstance();
Element userVCard = vManager.getVCard(recipient.getNode());
if (userVCard != null) {
// Check if the requester wants to ignore some vCard's fields
Element filter = packet.getChildElement()
.element(QName.get("filter", "vcard-temp-filter"));
if (filter != null) {
// Create a copy so we don't modify the original vCard
userVCard = userVCard.createCopy();
// Ignore fields requested by the user
for (Iterator toFilter = filter.elementIterator(); toFilter.hasNext();)
{
Element field = (Element) toFilter.next();
Element fieldToRemove = userVCard.element(field.getName());
if (fieldToRemove != null) {
fieldToRemove.detach();
}
}
}
result.setChildElement(userVCard);
}
}
else {
result = IQ.createResultIQ(packet);
result.setChildElement(packet.getChildElement().createCopy());
result.setError(PacketError.Condition.item_not_found);
}
} else {
result = IQ.createResultIQ(packet);
result.setChildElement(packet.getChildElement().createCopy());
result.setError(PacketError.Condition.item_not_found);
}
}
else {
result.setChildElement(packet.getChildElement().createCopy());
result.setError(PacketError.Condition.not_acceptable);
}
return result;
}
@Override
public void initialize(XMPPServer server) {
super.initialize(server);
this.server = server;
userManager = server.getUserManager();
}
@Override
public IQHandlerInfo getInfo() {
return info;
}
}
| apache-2.0 |
psakar/pnc | maven-repository-manager/src/test/java/org/jboss/pnc/mavenrepositorymanager/AbstractImportTest.java | 3478 | /**
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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.jboss.pnc.mavenrepositorymanager;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.commonjava.aprox.client.core.Aprox;
import org.commonjava.aprox.model.core.Group;
import org.commonjava.aprox.model.core.RemoteRepository;
import org.commonjava.aprox.model.core.StoreKey;
import org.commonjava.aprox.model.core.StoreType;
import org.jboss.pnc.mavenrepositorymanager.fixture.TestHttpServer;
import org.junit.Before;
import org.junit.Rule;
import java.io.InputStream;
import java.util.Collections;
public class AbstractImportTest extends AbstractRepositoryManagerDriverTest {
protected static final String STORE = "test";
protected static final String PUBLIC = "public";
protected static final String SHARED_IMPORTS = "shared-imports";
@Rule
public TestHttpServer server = new TestHttpServer("repos");
protected Aprox aprox;
@Before
public void before() throws Exception
{
aprox = driver.getAprox();
// create a remote repo pointing at our server fixture's 'repo/test' directory.
aprox.stores().create(new RemoteRepository(STORE, server.formatUrl(STORE)), "Creating test remote repo",
RemoteRepository.class);
Group publicGroup = aprox.stores().load(StoreType.group, PUBLIC, Group.class);
if (publicGroup == null) {
publicGroup = new Group(PUBLIC, new StoreKey(StoreType.remote, STORE));
aprox.stores().create(publicGroup, "creating public group", Group.class);
} else {
publicGroup.setConstituents(Collections.singletonList(new StoreKey(StoreType.remote, STORE)));
aprox.stores().update(publicGroup, "adding test remote to public group");
}
}
protected String download(String url) throws Exception {
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
String content = null;
InputStream stream = null;
try {
client = HttpClientBuilder.create().build();
response = client.execute(new HttpGet(url));
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
stream = response.getEntity().getContent();
content = IOUtils.toString(stream);
} finally {
IOUtils.closeQuietly(stream);
IOUtils.closeQuietly(response);
IOUtils.closeQuietly(client);
}
return content;
}
}
| apache-2.0 |
goodwinnk/intellij-community | platform/projectModel-api/src/com/intellij/openapi/project/ProjectTypeService.java | 1426 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.project;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.components.State;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* @author Dmitry Avdeev
*/
@State(name = "ProjectType")
public class ProjectTypeService implements PersistentStateComponent<ProjectType> {
private ProjectType myProjectType;
@Nullable
public static ProjectType getProjectType(@Nullable Project project) {
ProjectType projectType;
if (project != null) {
projectType = getInstance(project).myProjectType;
if (projectType != null) return projectType;
}
return DefaultProjectTypeEP.getDefaultProjectType();
}
public static void setProjectType(@NotNull Project project, @Nullable ProjectType projectType) {
getInstance(project).loadState(projectType);
}
private static ProjectTypeService getInstance(@NotNull Project project) {
return ServiceManager.getService(project, ProjectTypeService.class);
}
@Nullable
@Override
public ProjectType getState() {
return myProjectType;
}
@Override
public void loadState(@Nullable ProjectType state) {
myProjectType = state;
}
}
| apache-2.0 |
jk1/intellij-community | plugins/ui-designer/src/com/intellij/uiDesigner/wizard/BindToExistingBeanStep.java | 9877 | /*
* 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.uiDesigner.wizard;
import com.intellij.ide.wizard.StepAdapter;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.PsiType;
import com.intellij.psi.util.PropertyUtil;
import com.intellij.psi.util.PropertyUtilBase;
import com.intellij.uiDesigner.UIDesignerBundle;
import com.intellij.util.ArrayUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.util.ArrayList;
import java.util.Collections;
/**
* @author Anton Katilin
* @author Vladimir Kondratyev
*/
final class BindToExistingBeanStep extends StepAdapter{
private static final Logger LOG = Logger.getInstance("#com.intellij.uiDesigner.wizard.BindToExistingBeanStep");
private JScrollPane myScrollPane;
private JTable myTable;
private final WizardData myData;
private final MyTableModel myTableModel;
private JCheckBox myChkIsModified;
private JCheckBox myChkGetData;
private JCheckBox myChkSetData;
private JPanel myPanel;
BindToExistingBeanStep(@NotNull final WizardData data) {
myData = data;
myTableModel = new MyTableModel();
myTable.setModel(myTableModel);
myTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
myTable.getColumnModel().setColumnSelectionAllowed(true);
myScrollPane.getViewport().setBackground(myTable.getBackground());
myTable.setSurrendersFocusOnKeystroke(true);
// Customize "Form Property" column
{
final TableColumn column = myTable.getColumnModel().getColumn(0/*Form Property*/);
column.setCellRenderer(new FormPropertyTableCellRenderer(myData.myProject));
}
// Customize "Bean Property" column
{
final TableColumn column = myTable.getColumnModel().getColumn(1/*Bean Property*/);
column.setCellRenderer(new BeanPropertyTableCellRenderer());
final MyTableCellEditor cellEditor = new MyTableCellEditor();
column.setCellEditor(cellEditor);
final DefaultCellEditor editor = (DefaultCellEditor)myTable.getDefaultEditor(Object.class);
editor.setClickCountToStart(1);
myTable.setRowHeight(cellEditor.myCbx.getPreferredSize().height);
}
myChkGetData.setSelected(true);
myChkGetData.setEnabled(false);
myChkSetData.setSelected(true);
myChkSetData.setEnabled(false);
myChkIsModified.setSelected(myData.myGenerateIsModified);
}
public JComponent getComponent() {
return myPanel;
}
public void _init() {
// Check that data is correct
LOG.assertTrue(!myData.myBindToNewBean);
LOG.assertTrue(myData.myBeanClass != null);
myTableModel.fireTableDataChanged();
}
public void _commit(boolean finishChosen) {
// Stop editing if any
final TableCellEditor cellEditor = myTable.getCellEditor();
if(cellEditor != null){
cellEditor.stopCellEditing();
}
myData.myGenerateIsModified = myChkIsModified.isSelected();
// TODO[vova] check that at least one binding field exists
}
private final class MyTableModel extends AbstractTableModel{
private final String[] myColumnNames;
public MyTableModel() {
myColumnNames = new String[]{
UIDesignerBundle.message("column.form.field"),
UIDesignerBundle.message("column.bean.property")};
}
public int getColumnCount() {
return myColumnNames.length;
}
public String getColumnName(final int column) {
return myColumnNames[column];
}
public int getRowCount() {
return myData.myBindings.length;
}
public boolean isCellEditable(final int row, final int column) {
return column == 1/*Bean Property*/;
}
public Object getValueAt(final int row, final int column) {
if(column == 0/*Form Property*/){
return myData.myBindings[row].myFormProperty;
}
else if(column == 1/*Bean Property*/){
return myData.myBindings[row].myBeanProperty;
}
else{
throw new IllegalArgumentException("unknown column: " + column);
}
}
public void setValueAt(final Object value, final int row, final int column) {
LOG.assertTrue(column == 1/*Bean Property*/);
final FormProperty2BeanProperty binding = myData.myBindings[row];
binding.myBeanProperty = (BeanProperty)value;
}
}
private final class MyTableCellEditor extends AbstractCellEditor implements TableCellEditor{
private final ComboBox myCbx;
/* -1 if not defined*/
private int myEditingRow;
public MyTableCellEditor() {
myCbx = new ComboBox();
myCbx.setEditable(true);
myCbx.setRenderer(new BeanPropertyListCellRenderer());
myCbx.registerTableCellEditor(this);
final JComponent editorComponent = (JComponent)myCbx.getEditor().getEditorComponent();
editorComponent.setBorder(null);
myEditingRow = -1;
}
/**
* @return whether it's possible to convert {@code type1} into {@code type2}
* and vice versa.
*/
private boolean canConvert(@NonNls final String type1, @NonNls final String type2){
if("boolean".equals(type1) || "boolean".equals(type2)){
return type1.equals(type2);
}
else{
return true;
}
}
public Component getTableCellEditorComponent(
final JTable table,
final Object value,
final boolean isSelected,
final int row,
final int column
) {
myEditingRow = row;
final DefaultComboBoxModel model = (DefaultComboBoxModel)myCbx.getModel();
model.removeAllElements();
model.addElement(null/*<not defined>*/);
// Fill combobox with available bean's properties
final String[] rProps = PropertyUtilBase.getReadableProperties(myData.myBeanClass, true);
final String[] wProps = PropertyUtilBase.getWritableProperties(myData.myBeanClass, true);
final ArrayList<BeanProperty> rwProps = new ArrayList<>();
outer: for(int i = rProps.length - 1; i >= 0; i--){
final String propName = rProps[i];
if(ArrayUtil.find(wProps, propName) != -1){
LOG.assertTrue(!rwProps.contains(propName));
final PsiMethod getter = PropertyUtilBase.findPropertyGetter(myData.myBeanClass, propName, false, true);
if (getter == null) {
// possible if the getter is static: getReadableProperties() does not filter out static methods, and
// findPropertyGetter() checks for static/non-static
continue;
}
final PsiType returnType = getter.getReturnType();
LOG.assertTrue(returnType != null);
// There are two possible types: boolean and java.lang.String
@NonNls final String typeName = returnType.getCanonicalText();
LOG.assertTrue(typeName != null);
if(!"boolean".equals(typeName) && !"java.lang.String".equals(typeName)){
continue;
}
// Check that the property is not in use yet
for(int j = myData.myBindings.length - 1; j >= 0; j--){
final BeanProperty _property = myData.myBindings[j].myBeanProperty;
if(j != row && _property != null && propName.equals(_property.myName)){
continue outer;
}
}
// Check that we conver types
if(
!canConvert(
myData.myBindings[row].myFormProperty.getComponentPropertyClassName(),
typeName
)
){
continue;
}
rwProps.add(new BeanProperty(propName, typeName));
}
}
Collections.sort(rwProps);
for (BeanProperty rwProp : rwProps) {
model.addElement(rwProp);
}
// Set initially selected item
if(myData.myBindings[row].myBeanProperty != null){
myCbx.setSelectedItem(myData.myBindings[row].myBeanProperty);
}
else{
myCbx.setSelectedIndex(0/*<not defined>*/);
}
return myCbx;
}
public Object getCellEditorValue() {
LOG.assertTrue(myEditingRow != -1);
try {
// our ComboBox is editable so its editor can contain:
// 1) BeanProperty object (it user just selected something from ComboBox)
// 2) java.lang.String if user type something into ComboBox
final Object selectedItem = myCbx.getEditor().getItem();
if(selectedItem instanceof BeanProperty){
return selectedItem;
}
else if(selectedItem instanceof String){
final String fieldName = ((String)selectedItem).trim();
if(fieldName.length() == 0){
return null; // binding is not defined
}
final String fieldType = myData.myBindings[myEditingRow].myFormProperty.getComponentPropertyClassName();
return new BeanProperty(fieldName, fieldType);
}
else{
throw new IllegalArgumentException("unknown selectedItem: " + selectedItem);
}
}
finally {
myEditingRow = -1; // unset editing row. So it's possible to invoke this method only once per editing
}
}
}
}
| apache-2.0 |
DariusX/camel | components/camel-spring-redis/src/test/java/org/apache/camel/component/redis/RedisComponentSpringIntegrationTest.java | 3342 | /*
* 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.redis;
import org.apache.camel.EndpointInject;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.spring.CamelSpringTestSupport;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
@Ignore ("IntegrationTest")
public class RedisComponentSpringIntegrationTest extends CamelSpringTestSupport {
@EndpointInject("direct:start")
private ProducerTemplate template;
@EndpointInject("mock:result")
private MockEndpoint result;
@Test
public void shouldFilterDuplicateMessagesUsingIdempotentRepository() throws Exception {
result.expectedMessageCount(2);
template.send("direct:start", new Processor() {
public void process(Exchange exchange) throws Exception {
exchange.getIn().setHeader(RedisConstants.COMMAND, "PUBLISH");
exchange.getIn().setHeader(RedisConstants.CHANNEL, "testChannel");
exchange.getIn().setHeader(RedisConstants.MESSAGE, "Message one");
}
});
template.send("direct:start", new Processor() {
public void process(Exchange exchange) throws Exception {
exchange.getIn().setHeader(RedisConstants.COMMAND, "PUBLISH");
exchange.getIn().setHeader(RedisConstants.CHANNEL, "testChannel");
exchange.getIn().setHeader(RedisConstants.MESSAGE, "Message one");
}
});
template.send("direct:start", new Processor() {
public void process(Exchange exchange) throws Exception {
exchange.getIn().setHeader(RedisConstants.COMMAND, "PUBLISH");
exchange.getIn().setHeader(RedisConstants.CHANNEL, "testChannel");
exchange.getIn().setHeader(RedisConstants.MESSAGE, "Message two");
}
});
assertMockEndpointsSatisfied();
Exchange resultExchangeOne = result.getExchanges().get(0);
Exchange resultExchangeTwo = result.getExchanges().get(1);
assertEquals("Message one", resultExchangeOne.getIn().getBody());
assertEquals("Message two", resultExchangeTwo.getIn().getBody());
}
@Override
protected ClassPathXmlApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext("RedisComponentSpringTest-context.xml");
}
} | apache-2.0 |
charles-cooper/idylfin | src/com/opengamma/analytics/financial/model/option/definition/BinomialOptionModelDefinition.java | 695 | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.analytics.financial.model.option.definition;
import com.opengamma.analytics.financial.model.tree.RecombiningBinomialTree;
/**
*
* @param <T>
* @param <U>
*/
public abstract class BinomialOptionModelDefinition<T extends OptionDefinition, U extends StandardOptionDataBundle> {
public abstract double getUpFactor(T option, U data, int n, int j);
public abstract double getDownFactor(T option, U data, int n, int j);
public abstract RecombiningBinomialTree<Double> getUpProbabilityTree(T option, U data, int n, int j);
}
| apache-2.0 |
OSBI/saiku | saiku-bi-platform-plugin-p7.1/src/main/java/org/saiku/plugin/util/packager/JSMin.java | 7334 |
/*
*
* JSMin.java 2006-02-13
*
* Updated 2007-08-20 with updates from jsmin.c (2007-05-22)
*
* Copyright (c) 2006 John Reilly (www.inconspicuous.org)
*
* This work is a translation from C to Java of jsmin.c published by
* Douglas Crockford. Permission is hereby granted to use the Java
* version under the same conditions as the jsmin.c on which it is
* based.
*
*
*
*
* jsmin.c 2003-04-21
*
* Copyright (c) 2002 Douglas Crockford (www.crockford.com)
*
* 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.
*/
package org.saiku.plugin.util.packager;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PushbackInputStream;
class JSMin {
private static final int EOF = -1;
private final PushbackInputStream in;
private final OutputStream out;
private int theA;
private int theB;
public JSMin(InputStream in, OutputStream out) {
this.in = new PushbackInputStream(in);
this.out = out;
}
/**
* isAlphanum -- return true if the character is a letter, digit,
* underscore, dollar sign, or non-ASCII character.
*/
private static boolean isAlphanum(int c) {
return ( (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') ||
(c >= 'A' && c <= 'Z') || c == '_' || c == '$' || c == '\\' ||
c > 126);
}
/**
* get -- return the next character from stdin. Watch out for lookahead. If
* the character is a control character, translate it to a space or
* linefeed.
*/
private int get() throws IOException {
int c = in.read();
if (c >= ' ' || c == '\n' || c == EOF) {
return c;
}
if (c == '\r') {
return '\n';
}
return ' ';
}
/**
* Get the next character without getting it.
*/
private int peek() throws IOException {
int lookaheadChar = in.read();
in.unread(lookaheadChar);
return lookaheadChar;
}
/**
* next -- get the next character, excluding comments. peek() is used to see
* if a '/' is followed by a '/' or '*'.
*/
private int next() throws IOException, UnterminatedCommentException {
int c = get();
if (c == '/') {
switch (peek()) {
case '/':
for (;;) {
c = get();
if (c <= '\n') {
return c;
}
}
case '*':
get();
for (;;) {
switch (get()) {
case '*':
if (peek() == '/') {
get();
return ' ';
}
break;
case EOF:
throw new UnterminatedCommentException();
}
}
default:
return c;
}
}
return c;
}
/**
* action -- do something! What you do is determined by the argument: 1
* Output A. Copy B to A. Get the next B. 2 Copy B to A. Get the next B.
* (Delete A). 3 Get the next B. (Delete B). action treats a string as a
* single character. Wow! action recognizes a regular expression if it is
* preceded by ( or , or =.
*/
private void action(int d) throws IOException, UnterminatedRegExpLiteralException,
UnterminatedCommentException, UnterminatedStringLiteralException {
switch (d) {
case 1:
out.write(theA);
case 2:
theA = theB;
if (theA == '\'' || theA == '"') {
for (;;) {
out.write(theA);
theA = get();
if (theA == theB) {
break;
}
if (theA <= '\n') {
throw new UnterminatedStringLiteralException();
}
if (theA == '\\') {
out.write(theA);
theA = get();
}
}
}
case 3:
theB = next();
if (theB == '/' && (theA == '(' || theA == ',' || theA == '=' ||
theA == ':' || theA == '[' || theA == '!' ||
theA == '&' || theA == '|' || theA == '?' ||
theA == '{' || theA == '}' || theA == ';' ||
theA == '\n')) {
out.write(theA);
out.write(theB);
for (;;) {
theA = get();
if (theA == '/') {
break;
} else if (theA == '\\') {
out.write(theA);
theA = get();
} else if (theA <= '\n') {
throw new UnterminatedRegExpLiteralException();
}
out.write(theA);
}
theB = next();
}
}
}
/**
* jsmin -- Copy the input to the output, deleting the characters which are
* insignificant to JavaScript. Comments will be removed. Tabs will be
* replaced with spaces. Carriage returns will be replaced with linefeeds.
* Most spaces and linefeeds will be removed.
*/
public void jsmin() throws IOException, UnterminatedRegExpLiteralException, UnterminatedCommentException, UnterminatedStringLiteralException{
theA = '\n';
action(3);
while (theA != EOF) {
switch (theA) {
case ' ':
if (isAlphanum(theB)) {
action(1);
} else {
action(2);
}
break;
case '\n':
switch (theB) {
case '{':
case '[':
case '(':
case '+':
case '-':
action(1);
break;
case ' ':
action(3);
break;
default:
if (isAlphanum(theB)) {
action(1);
} else {
action(2);
}
}
break;
default:
switch (theB) {
case ' ':
if (isAlphanum(theA)) {
action(1);
break;
}
action(3);
break;
case '\n':
switch (theA) {
case '}':
case ']':
case ')':
case '+':
case '-':
case '"':
case '\'':
action(1);
break;
default:
if (isAlphanum(theA)) {
action(1);
} else {
action(3);
}
}
break;
default:
action(1);
break;
}
}
}
out.flush();
}
private class UnterminatedCommentException extends Exception {
}
private class UnterminatedStringLiteralException extends Exception {
}
private class UnterminatedRegExpLiteralException extends Exception {
}
public static void main(String arg[]) {
try {
JSMin jsmin = new JSMin(new FileInputStream(arg[0]), System.out);
jsmin.jsmin();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (UnterminatedRegExpLiteralException e) {
e.printStackTrace();
} catch (UnterminatedCommentException e) {
e.printStackTrace();
} catch (UnterminatedStringLiteralException e) {
e.printStackTrace();
}
}
} | apache-2.0 |
robin13/elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/dataframe/stats/outlierdetection/Parameters.java | 5618 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.core.ml.dataframe.stats.outlierdetection;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException;
import java.util.Objects;
import static org.elasticsearch.common.xcontent.ConstructingObjectParser.constructorArg;
public class Parameters implements Writeable, ToXContentObject {
public static final ParseField N_NEIGHBORS = new ParseField("n_neighbors");
public static final ParseField METHOD = new ParseField("method");
public static final ParseField FEATURE_INFLUENCE_THRESHOLD = new ParseField("feature_influence_threshold");
public static final ParseField COMPUTE_FEATURE_INFLUENCE = new ParseField("compute_feature_influence");
public static final ParseField OUTLIER_FRACTION = new ParseField("outlier_fraction");
public static final ParseField STANDARDIZATION_ENABLED = new ParseField("standardization_enabled");
public static Parameters fromXContent(XContentParser parser, boolean ignoreUnknownFields) {
return createParser(ignoreUnknownFields).apply(parser, null);
}
private static ConstructingObjectParser<Parameters, Void> createParser(boolean ignoreUnknownFields) {
ConstructingObjectParser<Parameters, Void> parser = new ConstructingObjectParser<>("outlier_detection_parameters",
ignoreUnknownFields,
a -> new Parameters(
(int) a[0],
(String) a[1],
(boolean) a[2],
(double) a[3],
(double) a[4],
(boolean) a[5]
));
parser.declareInt(constructorArg(), N_NEIGHBORS);
parser.declareString(constructorArg(), METHOD);
parser.declareBoolean(constructorArg(), COMPUTE_FEATURE_INFLUENCE);
parser.declareDouble(constructorArg(), FEATURE_INFLUENCE_THRESHOLD);
parser.declareDouble(constructorArg(), OUTLIER_FRACTION);
parser.declareBoolean(constructorArg(), STANDARDIZATION_ENABLED);
return parser;
}
private final int nNeighbors;
private final String method;
private final boolean computeFeatureInfluence;
private final double featureInfluenceThreshold;
private final double outlierFraction;
private final boolean standardizationEnabled;
public Parameters(int nNeighbors, String method, boolean computeFeatureInfluence, double featureInfluenceThreshold,
double outlierFraction, boolean standardizationEnabled) {
this.nNeighbors = nNeighbors;
this.method = method;
this.computeFeatureInfluence = computeFeatureInfluence;
this.featureInfluenceThreshold = featureInfluenceThreshold;
this.outlierFraction = outlierFraction;
this.standardizationEnabled = standardizationEnabled;
}
public Parameters(StreamInput in) throws IOException {
this.nNeighbors = in.readVInt();
this.method = in.readString();
this.computeFeatureInfluence = in.readBoolean();
this.featureInfluenceThreshold = in.readDouble();
this.outlierFraction = in.readDouble();
this.standardizationEnabled = in.readBoolean();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVInt(nNeighbors);
out.writeString(method);
out.writeBoolean(computeFeatureInfluence);
out.writeDouble(featureInfluenceThreshold);
out.writeDouble(outlierFraction);
out.writeBoolean(standardizationEnabled);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(N_NEIGHBORS.getPreferredName(), nNeighbors);
builder.field(METHOD.getPreferredName(), method);
builder.field(COMPUTE_FEATURE_INFLUENCE.getPreferredName(), computeFeatureInfluence);
builder.field(FEATURE_INFLUENCE_THRESHOLD.getPreferredName(), featureInfluenceThreshold);
builder.field(OUTLIER_FRACTION.getPreferredName(), outlierFraction);
builder.field(STANDARDIZATION_ENABLED.getPreferredName(), standardizationEnabled);
builder.endObject();
return builder;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Parameters that = (Parameters) o;
return nNeighbors == that.nNeighbors
&& Objects.equals(method, that.method)
&& computeFeatureInfluence == that.computeFeatureInfluence
&& featureInfluenceThreshold == that.featureInfluenceThreshold
&& outlierFraction == that.outlierFraction
&& standardizationEnabled == that.standardizationEnabled;
}
@Override
public int hashCode() {
return Objects.hash(nNeighbors, method, computeFeatureInfluence, featureInfluenceThreshold, outlierFraction,
standardizationEnabled);
}
}
| apache-2.0 |
akuhtz/izpack | izpack-api/src/main/java/com/izforge/izpack/api/config/BasicProfile.java | 10403 | /*
* IzPack - Copyright 2001-2010 Julien Ponge, All Rights Reserved.
*
* http://izpack.org/
* http://izpack.codehaus.org/
*
* Copyright 2005,2009 Ivan SZKIBA
* Copyright 2010,2011 Rene Krell
*
* 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.izforge.izpack.api.config;
import java.lang.reflect.Array;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.izforge.izpack.api.config.spi.AbstractBeanInvocationHandler;
import com.izforge.izpack.api.config.spi.BeanTool;
import com.izforge.izpack.api.config.spi.IniHandler;
public class BasicProfile extends CommonMultiMap<String, Profile.Section> implements Profile
{
private static final String SECTION_SYSTEM_PROPERTIES = "@prop";
private static final String SECTION_ENVIRONMENT = "@env";
private static final Pattern EXPRESSION = Pattern.compile(
"(?<!\\\\)\\$\\{(([^\\[\\}]+)(\\[([0-9]+)\\])?/)?([^\\[^/\\}]+)(\\[(([0-9]+))\\])?\\}");
private static final int G_SECTION = 2;
private static final int G_SECTION_IDX = 4;
private static final int G_OPTION = 5;
private static final int G_OPTION_IDX = 7;
private static final long serialVersionUID = -1817521505004015256L;
private List<String> _comment;
private List<String> _footerComment;
private final boolean _propertyFirstUpper;
private final boolean _treeMode;
public BasicProfile()
{
this(false, false);
}
public BasicProfile(boolean treeMode, boolean propertyFirstUpper)
{
_treeMode = treeMode;
_propertyFirstUpper = propertyFirstUpper;
}
@Override public List<String> getHeaderComment()
{
return _comment;
}
@Override public void setHeaderComment(List<String> value)
{
_comment = value;
}
@Override public List<String> getFooterComment()
{
return _footerComment;
}
@Override public void setFooterComment(List<String> value)
{
_footerComment = value;
}
@Override public Section add(String name)
{
if (isTreeMode())
{
int idx = name.lastIndexOf(getPathSeparator());
if (idx > 0)
{
String parent = name.substring(0, idx);
if (!containsKey(parent))
{
add(parent);
}
}
}
Section section = newSection(name);
add(name, section);
return section;
}
@Override public void add(String section, String option, Object value)
{
getOrAdd(section).add(option, value);
}
@Override public <T> T as(Class<T> clazz)
{
return as(clazz, null);
}
@Override public <T> T as(Class<T> clazz, String prefix)
{
return clazz.cast(Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] { clazz },
new BeanInvocationHandler(prefix)));
}
@Override public String fetch(Object sectionName, Object optionName)
{
Section sec = get(sectionName);
return (sec == null) ? null : sec.fetch(optionName);
}
@Override public <T> T fetch(Object sectionName, Object optionName, Class<T> clazz)
{
Section sec = get(sectionName);
return (sec == null) ? BeanTool.getInstance().zero(clazz) : sec.fetch(optionName, clazz);
}
@Override public String get(Object sectionName, Object optionName)
{
Section sec = get(sectionName);
return (sec == null) ? null : sec.get(optionName);
}
@Override public <T> T get(Object sectionName, Object optionName, Class<T> clazz)
{
Section sec = get(sectionName);
return (sec == null) ? BeanTool.getInstance().zero(clazz) : sec.get(optionName, clazz);
}
@Override public String put(String sectionName, String optionName, Object value)
{
return getOrAdd(sectionName).put(optionName, value);
}
@Override public Section remove(Section section)
{
return remove((Object) section.getName());
}
@Override public String removeOptionFromSection(Object sectionName, Object optionName)
{
Section sec = get(sectionName);
return (sec == null) ? null : sec.remove(optionName);
}
boolean isTreeMode()
{
return _treeMode;
}
char getPathSeparator()
{
return PATH_SEPARATOR;
}
boolean isPropertyFirstUpper()
{
return _propertyFirstUpper;
}
Section newSection(String name)
{
return new BasicProfileSection(this, name);
}
void resolve(StringBuilder buffer, Section owner)
{
Matcher m = EXPRESSION.matcher(buffer);
while (m.find())
{
String sectionName = m.group(G_SECTION);
String optionName = m.group(G_OPTION);
int optionIndex = parseOptionIndex(m);
Section section = parseSection(m, owner);
String value = null;
if (SECTION_ENVIRONMENT.equals(sectionName))
{
value = Config.getEnvironment(optionName);
}
else if (SECTION_SYSTEM_PROPERTIES.equals(sectionName))
{
value = Config.getSystemProperty(optionName);
}
else if (section != null)
{
value = (optionIndex == -1) ? section.fetch(optionName) : section.fetch(optionName, optionIndex);
}
if (value != null)
{
buffer.replace(m.start(), m.end(), value);
m.reset(buffer);
}
}
}
void store(IniHandler formatter)
{
formatter.startIni();
store(formatter, getHeaderComment());
for (Ini.Section s : values())
{
store(formatter, s);
}
if (_footerComment != null)
{
store(formatter, _footerComment);
}
formatter.endIni();
}
void store(IniHandler formatter, Section s)
{
store(formatter, getComment(s.getName()));
formatter.startSection(s.getName());
for (String name : s.keySet())
{
store(formatter, s, name);
}
formatter.endSection();
}
void store(IniHandler formatter, List<String> comment)
{
formatter.handleComment(comment);
}
void store(IniHandler formatter, Section section, String option)
{
store(formatter, section.getComment(option));
int n = section.length(option);
for (int i = 0; i < n; i++)
{
store(formatter, section, option, i);
}
}
void store(IniHandler formatter, Section section, String option, int index)
{
formatter.handleOption(option, section.get(option, index));
}
private Section getOrAdd(String sectionName)
{
Section section = get(sectionName);
return ((section == null)) ? add(sectionName) : section;
}
private int parseOptionIndex(Matcher m)
{
return (m.group(G_OPTION_IDX) == null) ? -1 : Integer.parseInt(m.group(G_OPTION_IDX));
}
private Section parseSection(Matcher m, Section owner)
{
String sectionName = m.group(G_SECTION);
int sectionIndex = parseSectionIndex(m);
return (sectionName == null) ? owner : ((sectionIndex == -1) ? get(sectionName) : get(sectionName, sectionIndex));
}
private int parseSectionIndex(Matcher m)
{
return (m.group(G_SECTION_IDX) == null) ? -1 : Integer.parseInt(m.group(G_SECTION_IDX));
}
private final class BeanInvocationHandler extends AbstractBeanInvocationHandler
{
private final String _prefix;
private BeanInvocationHandler(String prefix)
{
_prefix = prefix;
}
@Override protected Object getPropertySpi(String property, Class<?> clazz)
{
String key = transform(property);
Object o = null;
if (containsKey(key))
{
if (clazz.isArray())
{
o = Array.newInstance(clazz.getComponentType(), length(key));
for (int i = 0; i < length(key); i++)
{
Array.set(o, i, get(key, i).as(clazz.getComponentType()));
}
}
else
{
o = get(key).as(clazz);
}
}
return o;
}
@Override protected void setPropertySpi(String property, Object value, Class<?> clazz)
{
String key = transform(property);
remove(key);
if (value != null)
{
if (clazz.isArray())
{
for (int i = 0; i < Array.getLength(value); i++)
{
Section sec = add(key);
sec.from(Array.get(value, i));
}
}
else
{
Section sec = add(key);
sec.from(value);
}
}
}
@Override protected boolean hasPropertySpi(String property)
{
return containsKey(transform(property));
}
String transform(String property)
{
String ret = (_prefix == null) ? property : (_prefix + property);
if (isPropertyFirstUpper())
{
StringBuilder buff = new StringBuilder();
buff.append(Character.toUpperCase(property.charAt(0)));
buff.append(property.substring(1));
ret = buff.toString();
}
return ret;
}
}
}
| apache-2.0 |
wlan0/cattle | code/implementation/docker/machine/src/main/java/io/cattle/platform/docker/machine/launch/MachineDriverLoaderLock.java | 416 | package io.cattle.platform.docker.machine.launch;
import io.cattle.platform.lock.definition.AbstractLockDefinition;
import io.cattle.platform.lock.definition.LockDefinition;
public class MachineDriverLoaderLock extends AbstractLockDefinition implements LockDefinition {
private static final String LOCK_NAME = "MACHINE.DRIVER.LOADER";
public MachineDriverLoaderLock() {
super(LOCK_NAME);
}
}
| apache-2.0 |
apixandru/intellij-community | xml/relaxng/src/org/intellij/plugins/relaxNG/validation/RngParser.java | 10006 | /*
* Copyright 2007 Sascha Weinreuter
*
* 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.intellij.plugins.relaxNG.validation;
import com.intellij.javaee.UriUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.util.AtomicNotNullLazyValue;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.NotNullLazyValue;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.intellij.psi.search.PsiElementProcessor;
import com.intellij.psi.util.CachedValue;
import com.intellij.psi.util.CachedValueProvider;
import com.intellij.psi.util.CachedValuesManager;
import com.intellij.psi.xml.XmlFile;
import com.intellij.util.containers.ContainerUtil;
import com.thaiopensource.datatype.xsd.DatatypeLibraryFactoryImpl;
import com.thaiopensource.relaxng.impl.SchemaReaderImpl;
import com.thaiopensource.util.PropertyMap;
import com.thaiopensource.util.PropertyMapBuilder;
import com.thaiopensource.validate.Schema;
import com.thaiopensource.xml.sax.Sax2XMLReaderCreator;
import com.thaiopensource.xml.sax.XMLReaderCreator;
import org.intellij.plugins.relaxNG.compact.RncFileType;
import org.intellij.plugins.relaxNG.model.resolve.RelaxIncludeIndex;
import org.jetbrains.annotations.NotNull;
import org.kohsuke.rngom.ast.builder.BuildException;
import org.kohsuke.rngom.ast.builder.IncludedGrammar;
import org.kohsuke.rngom.ast.builder.SchemaBuilder;
import org.kohsuke.rngom.ast.om.ParsedPattern;
import org.kohsuke.rngom.binary.SchemaBuilderImpl;
import org.kohsuke.rngom.binary.SchemaPatternBuilder;
import org.kohsuke.rngom.digested.DPattern;
import org.kohsuke.rngom.digested.DSchemaBuilderImpl;
import org.kohsuke.rngom.dt.CachedDatatypeLibraryFactory;
import org.kohsuke.rngom.dt.CascadingDatatypeLibraryFactory;
import org.kohsuke.rngom.dt.DoNothingDatatypeLibraryFactoryImpl;
import org.kohsuke.rngom.dt.builtin.BuiltinDatatypeLibraryFactory;
import org.kohsuke.rngom.parse.IllegalSchemaException;
import org.kohsuke.rngom.parse.Parseable;
import org.kohsuke.rngom.parse.compact.CompactParseable;
import org.kohsuke.rngom.parse.xml.SAXParseable;
import org.relaxng.datatype.DatatypeLibrary;
import org.relaxng.datatype.DatatypeLibraryFactory;
import org.relaxng.datatype.helpers.DatatypeLibraryLoader;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
import java.io.StringReader;
import java.util.concurrent.ConcurrentMap;
public class RngParser {
private static final Logger LOG = Logger.getInstance("#org.intellij.plugins.relaxNG.validation.RngParser");
private static final NotNullLazyValue<DatatypeLibraryFactory> DT_LIBRARY_FACTORY = new AtomicNotNullLazyValue<DatatypeLibraryFactory>() {
@NotNull
@Override
protected DatatypeLibraryFactory compute() {
return new BuiltinDatatypeLibraryFactory(new CachedDatatypeLibraryFactory(
new CascadingDatatypeLibraryFactory(createXsdDatatypeFactory(), new DatatypeLibraryLoader())) {
@Override
public synchronized DatatypeLibrary createDatatypeLibrary(String namespaceURI) {
return super.createDatatypeLibrary(namespaceURI);
}
});
}
};
private static final ConcurrentMap<String, DPattern> ourCache = ContainerUtil.createConcurrentSoftMap();
private static DatatypeLibraryFactory createXsdDatatypeFactory() {
try {
return new DatatypeLibraryFactoryImpl();
} catch (Throwable e) {
LOG.error("Could not create DT library implementation 'com.thaiopensource.datatype.xsd.DatatypeLibraryFactoryImpl'. Plugin's classpath seems to be broken.", e);
return new DoNothingDatatypeLibraryFactoryImpl();
}
}
static final Key<CachedValue<Schema>> SCHEMA_KEY = Key.create("SCHEMA");
public static final DefaultHandler DEFAULT_HANDLER = new DefaultHandler() {
@Override
public void error(SAXParseException e) throws SAXException {
LOG.info("e.getMessage() = " + e.getMessage() + " [" + e.getSystemId() + "]");
LOG.info(e);
}
};
static final PropertyMap EMPTY_PROPS = new PropertyMapBuilder().toPropertyMap();
public static DPattern getCachedPattern(final PsiFile descriptorFile, final ErrorHandler eh) {
final VirtualFile file = descriptorFile.getVirtualFile();
if (file == null) {
return parsePattern(descriptorFile, eh, false);
}
String url = file.getUrl();
DPattern pattern = ourCache.get(url);
if (pattern == null) {
pattern = parsePattern(descriptorFile, eh, false);
}
if (pattern != null) {
DPattern oldPattern = ourCache.putIfAbsent(url, pattern);
if (oldPattern != null) {
return oldPattern;
}
}
return pattern;
}
public static DPattern parsePattern(final PsiFile file, final ErrorHandler eh, boolean checking) {
try {
final Parseable p = createParsable(file, eh);
if (checking) {
p.parse(new SchemaBuilderImpl(eh, DT_LIBRARY_FACTORY.getValue(), new SchemaPatternBuilder()));
} else {
return p.parse(new DSchemaBuilderImpl());
}
} catch (BuildException e) {
LOG.info(e);
} catch (IllegalSchemaException e) {
final VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile != null) {
if (LOG.isDebugEnabled()) {
LOG.debug("invalid schema: " + virtualFile.getPresentableUrl(), e);
} else {
LOG.info("invalid schema: " + virtualFile.getPresentableUrl() + ". [" + e.getMessage() + "]");
}
}
}
return null;
}
private static Parseable createParsable(final PsiFile file, final ErrorHandler eh) {
final InputSource source = makeInputSource(file);
final VirtualFile virtualFile = file.getVirtualFile();
if (file.getFileType() == RncFileType.getInstance()) {
return new CompactParseable(source, eh) {
@Override
public ParsedPattern parseInclude(String uri, SchemaBuilder schemaBuilder, IncludedGrammar g, String inheritedNs)
throws BuildException, IllegalSchemaException
{
ProgressManager.checkCanceled();
return super.parseInclude(resolveURI(virtualFile, uri), schemaBuilder, g, inheritedNs);
}
};
} else {
return new SAXParseable(source, eh) {
@Override
public ParsedPattern parseInclude(String uri, SchemaBuilder schemaBuilder, IncludedGrammar g, String inheritedNs)
throws BuildException, IllegalSchemaException
{
ProgressManager.checkCanceled();
return super.parseInclude(resolveURI(virtualFile, uri), schemaBuilder, g, inheritedNs);
}
};
}
}
private static String resolveURI(VirtualFile descriptorFile, String s) {
final VirtualFile file = UriUtil.findRelativeFile(s, descriptorFile);
if (file != null) {
s = VfsUtilCore.fixIDEAUrl(file.getUrl());
}
return s;
}
public static Schema getCachedSchema(final XmlFile descriptorFile) {
CachedValue<Schema> value = descriptorFile.getUserData(SCHEMA_KEY);
if (value == null) {
final CachedValueProvider<Schema> provider = () -> {
final InputSource inputSource = makeInputSource(descriptorFile);
try {
final Schema schema = new MySchemaReader(descriptorFile).createSchema(inputSource, EMPTY_PROPS);
final PsiElementProcessor.CollectElements<XmlFile> processor = new PsiElementProcessor.CollectElements<>();
RelaxIncludeIndex.processForwardDependencies(descriptorFile, processor);
if (processor.getCollection().size() > 0) {
return CachedValueProvider.Result.create(schema, processor.toArray(), descriptorFile);
} else {
return CachedValueProvider.Result.createSingleDependency(schema, descriptorFile);
}
} catch (Exception e) {
LOG.info(e);
return CachedValueProvider.Result.createSingleDependency(null, descriptorFile);
}
};
final CachedValuesManager mgr = CachedValuesManager.getManager(descriptorFile.getProject());
value = mgr.createCachedValue(provider, false);
descriptorFile.putUserData(SCHEMA_KEY, value);
}
return value.getValue();
}
private static InputSource makeInputSource(PsiFile descriptorFile) {
final InputSource inputSource = new InputSource(new StringReader(descriptorFile.getText()));
final VirtualFile file = descriptorFile.getVirtualFile();
if (file != null) {
inputSource.setSystemId(VfsUtilCore.fixIDEAUrl(file.getUrl()));
}
return inputSource;
}
static class MySchemaReader extends SchemaReaderImpl {
private final PsiFile myDescriptorFile;
public MySchemaReader(PsiFile descriptorFile) {
myDescriptorFile = descriptorFile;
}
@Override
protected com.thaiopensource.relaxng.parse.Parseable createParseable(XMLReaderCreator xmlReaderCreator, InputSource inputSource, ErrorHandler errorHandler) {
if (myDescriptorFile.getFileType() == RncFileType.getInstance()) {
return new com.thaiopensource.relaxng.parse.compact.CompactParseable(inputSource, errorHandler);
} else {
return new com.thaiopensource.relaxng.parse.sax.SAXParseable(new Sax2XMLReaderCreator(), inputSource, errorHandler);
}
}
}
} | apache-2.0 |
MeRPG/EndHQ-Libraries | src/org/apache/commons/lang3/builder/DiffBuilder.java | 26079 | /**
* 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.commons.lang3.builder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
/**
* <p>
* Assists in implementing {@link Diffable#diff(Object)} methods.
* </p>
*
* <p>
* To use this class, write code as follows:
* </p>
*
* <pre>
* public class Person implements Diffable<Person> {
* String name;
* int age;
* boolean smoker;
*
* ...
*
* public DiffResult diff(Person obj) {
* // No need for null check, as NullPointerException correct if obj is null
* return new DiffBuilder(this, obj, ToStringStyle.SHORT_PREFIX_STYLE)
* .append("name", this.name, obj.name)
* .append("age", this.age, obj.age)
* .append("smoker", this.smoker, obj.smoker)
* .build();
* }
* }
* </pre>
*
* <p>
* The {@code ToStringStyle} passed to the constructor is embedded in the
* returned {@code DiffResult} and influences the style of the
* {@code DiffResult.toString()} method. This style choice can be overridden by
* calling {@link DiffResult#toString(ToStringStyle)}.
* </p>
*
* @since 3.3
* @version $Id: DiffBuilder.java 1565245 2014-02-06 13:39:50Z sebb $
* @see Diffable
* @see Diff
* @see DiffResult
* @see ToStringStyle
*/
public class DiffBuilder implements Builder<DiffResult> {
private final List<Diff<?>> diffs;
private final boolean objectsTriviallyEqual;
private final Object left;
private final Object right;
private final ToStringStyle style;
/**
* <p>
* Constructs a builder for the specified objects with the specified style.
* </p>
*
* <p>
* If {@code lhs == rhs} or {@code lhs.equals(rhs)} then the builder will
* not evaluate any calls to {@code append(...)} and will return an empty
* {@link DiffResult} when {@link #build()} is executed.
* </p>
*
* @param lhs
* {@code this} object
* @param rhs
* the object to diff against
* @param style
* the style will use when outputting the objects, {@code null}
* uses the default
* @throws IllegalArgumentException
* if {@code lhs} or {@code rhs} is {@code null}
*/
public DiffBuilder(final Object lhs, final Object rhs,
final ToStringStyle style) {
if (lhs == null) {
throw new IllegalArgumentException("lhs cannot be null");
}
if (rhs == null) {
throw new IllegalArgumentException("rhs cannot be null");
}
this.diffs = new ArrayList<Diff<?>>();
this.left = lhs;
this.right = rhs;
this.style = style;
// Don't compare any fields if objects equal
this.objectsTriviallyEqual = (lhs == rhs || lhs.equals(rhs));
}
/**
* <p>
* Test if two {@code boolean}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code boolean}
* @param rhs
* the right hand {@code boolean}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final boolean lhs,
final boolean rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (lhs != rhs) {
diffs.add(new Diff<Boolean>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Boolean getLeft() {
return Boolean.valueOf(lhs);
}
@Override
public Boolean getRight() {
return Boolean.valueOf(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code boolean[]}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code boolean[]}
* @param rhs
* the right hand {@code boolean[]}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final boolean[] lhs,
final boolean[] rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (!Arrays.equals(lhs, rhs)) {
diffs.add(new Diff<Boolean[]>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Boolean[] getLeft() {
return ArrayUtils.toObject(lhs);
}
@Override
public Boolean[] getRight() {
return ArrayUtils.toObject(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code byte}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code byte}
* @param rhs
* the right hand {@code byte}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final byte lhs,
final byte rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (lhs != rhs) {
diffs.add(new Diff<Byte>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Byte getLeft() {
return Byte.valueOf(lhs);
}
@Override
public Byte getRight() {
return Byte.valueOf(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code byte[]}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code byte[]}
* @param rhs
* the right hand {@code byte[]}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final byte[] lhs,
final byte[] rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (!Arrays.equals(lhs, rhs)) {
diffs.add(new Diff<Byte[]>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Byte[] getLeft() {
return ArrayUtils.toObject(lhs);
}
@Override
public Byte[] getRight() {
return ArrayUtils.toObject(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code char}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code char}
* @param rhs
* the right hand {@code char}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final char lhs,
final char rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (lhs != rhs) {
diffs.add(new Diff<Character>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Character getLeft() {
return Character.valueOf(lhs);
}
@Override
public Character getRight() {
return Character.valueOf(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code char[]}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code char[]}
* @param rhs
* the right hand {@code char[]}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final char[] lhs,
final char[] rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (!Arrays.equals(lhs, rhs)) {
diffs.add(new Diff<Character[]>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Character[] getLeft() {
return ArrayUtils.toObject(lhs);
}
@Override
public Character[] getRight() {
return ArrayUtils.toObject(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code double}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code double}
* @param rhs
* the right hand {@code double}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final double lhs,
final double rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (Double.doubleToLongBits(lhs) != Double.doubleToLongBits(rhs)) {
diffs.add(new Diff<Double>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Double getLeft() {
return Double.valueOf(lhs);
}
@Override
public Double getRight() {
return Double.valueOf(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code double[]}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code double[]}
* @param rhs
* the right hand {@code double[]}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final double[] lhs,
final double[] rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (!Arrays.equals(lhs, rhs)) {
diffs.add(new Diff<Double[]>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Double[] getLeft() {
return ArrayUtils.toObject(lhs);
}
@Override
public Double[] getRight() {
return ArrayUtils.toObject(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code float}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code float}
* @param rhs
* the right hand {@code float}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final float lhs,
final float rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (Float.floatToIntBits(lhs) != Float.floatToIntBits(rhs)) {
diffs.add(new Diff<Float>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Float getLeft() {
return Float.valueOf(lhs);
}
@Override
public Float getRight() {
return Float.valueOf(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code float[]}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code float[]}
* @param rhs
* the right hand {@code float[]}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final float[] lhs,
final float[] rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (!Arrays.equals(lhs, rhs)) {
diffs.add(new Diff<Float[]>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Float[] getLeft() {
return ArrayUtils.toObject(lhs);
}
@Override
public Float[] getRight() {
return ArrayUtils.toObject(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code int}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code int}
* @param rhs
* the right hand {@code int}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final int lhs,
final int rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (lhs != rhs) {
diffs.add(new Diff<Integer>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Integer getLeft() {
return Integer.valueOf(lhs);
}
@Override
public Integer getRight() {
return Integer.valueOf(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code int[]}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code int[]}
* @param rhs
* the right hand {@code int[]}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final int[] lhs,
final int[] rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (!Arrays.equals(lhs, rhs)) {
diffs.add(new Diff<Integer[]>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Integer[] getLeft() {
return ArrayUtils.toObject(lhs);
}
@Override
public Integer[] getRight() {
return ArrayUtils.toObject(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code long}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code long}
* @param rhs
* the right hand {@code long}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final long lhs,
final long rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (lhs != rhs) {
diffs.add(new Diff<Long>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Long getLeft() {
return Long.valueOf(lhs);
}
@Override
public Long getRight() {
return Long.valueOf(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code long[]}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code long[]}
* @param rhs
* the right hand {@code long[]}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final long[] lhs,
final long[] rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (!Arrays.equals(lhs, rhs)) {
diffs.add(new Diff<Long[]>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Long[] getLeft() {
return ArrayUtils.toObject(lhs);
}
@Override
public Long[] getRight() {
return ArrayUtils.toObject(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code short}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code short}
* @param rhs
* the right hand {@code short}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final short lhs,
final short rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (lhs != rhs) {
diffs.add(new Diff<Short>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Short getLeft() {
return Short.valueOf(lhs);
}
@Override
public Short getRight() {
return Short.valueOf(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code short[]}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code short[]}
* @param rhs
* the right hand {@code short[]}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final short[] lhs,
final short[] rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (!Arrays.equals(lhs, rhs)) {
diffs.add(new Diff<Short[]>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Short[] getLeft() {
return ArrayUtils.toObject(lhs);
}
@Override
public Short[] getRight() {
return ArrayUtils.toObject(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code Objects}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code Object}
* @param rhs
* the right hand {@code Object}
* @return this
*/
public DiffBuilder append(final String fieldName, final Object lhs,
final Object rhs) {
if (objectsTriviallyEqual) {
return this;
}
if (lhs == rhs) {
return this;
}
Object objectToTest;
if (lhs != null) {
objectToTest = lhs;
} else {
// rhs cannot be null, as lhs != rhs
objectToTest = rhs;
}
if (objectToTest.getClass().isArray()) {
if (objectToTest instanceof boolean[]) {
return append(fieldName, (boolean[]) lhs, (boolean[]) rhs);
}
if (objectToTest instanceof byte[]) {
return append(fieldName, (byte[]) lhs, (byte[]) rhs);
}
if (objectToTest instanceof char[]) {
return append(fieldName, (char[]) lhs, (char[]) rhs);
}
if (objectToTest instanceof double[]) {
return append(fieldName, (double[]) lhs, (double[]) rhs);
}
if (objectToTest instanceof float[]) {
return append(fieldName, (float[]) lhs, (float[]) rhs);
}
if (objectToTest instanceof int[]) {
return append(fieldName, (int[]) lhs, (int[]) rhs);
}
if (objectToTest instanceof long[]) {
return append(fieldName, (long[]) lhs, (long[]) rhs);
}
if (objectToTest instanceof short[]) {
return append(fieldName, (short[]) lhs, (short[]) rhs);
}
return append(fieldName, (Object[]) lhs, (Object[]) rhs);
}
// Not array type
diffs.add(new Diff<Object>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Object getLeft() {
return lhs;
}
@Override
public Object getRight() {
return rhs;
}
});
return this;
}
/**
* <p>
* Test if two {@code Object[]}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code Object[]}
* @param rhs
* the right hand {@code Object[]}
* @return this
*/
public DiffBuilder append(final String fieldName, final Object[] lhs,
final Object[] rhs) {
if (objectsTriviallyEqual) {
return this;
}
if (!Arrays.equals(lhs, rhs)) {
diffs.add(new Diff<Object[]>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Object[] getLeft() {
return lhs;
}
@Override
public Object[] getRight() {
return rhs;
}
});
}
return this;
}
/**
* <p>
* Builds a {@link DiffResult} based on the differences appended to this
* builder.
* </p>
*
* @return a {@code DiffResult} containing the differences between the two
* objects.
*/
@Override
public DiffResult build() {
return new DiffResult(left, right, diffs, style);
}
}
| apache-2.0 |