repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
cymcsg/UltimateAndroid | deprecated/UltimateAndroidNormal/UltimateAndroid/src/com/marshalchen/common/usefulModule/standuptimer/dao/TeamDAO.java | 4747 | /*
* Copyright (c) 2014. Marshal Chen.
*/
package com.marshalchen.common.usefulModule.standuptimer.dao;
import static android.provider.BaseColumns._ID;
import java.util.ArrayList;
import java.util.List;
import com.marshalchen.common.usefulModule.standuptimer.model.Team;
import com.marshalchen.common.usefulModule.standuptimer.utils.Logger;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class TeamDAO extends DAOHelper {
public TeamDAO(Context ctx) {
super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
}
public Team save(Team team) {
SQLiteDatabase db = getWritableDatabase();
if (team.getId() != null) {
return updateExistingTeam(db, team);
} else {
return createNewTeam(db, team);
}
}
public Team findById(Long id) {
Cursor cursor = null;
Team team = null;
try {
SQLiteDatabase db = getReadableDatabase();
cursor = db.query(TEAMS_TABLE_NAME, TEAMS_ALL_COLUMS, _ID + " = ?", new String[]{id.toString()}, null, null, null);
if (cursor.getCount() == 1) {
if (cursor.moveToFirst()) {
String name = cursor.getString(1);
team = new Team(id, name);
}
}
} finally {
closeCursor(cursor);
}
return team;
}
public Team findByName(String name) {
Cursor cursor = null;
Team team = null;
name = name.trim();
try {
SQLiteDatabase db = getReadableDatabase();
cursor = db.query(TEAMS_TABLE_NAME, TEAMS_ALL_COLUMS, TEAMS_NAME + " = ?", new String[]{name}, null, null, null);
if (cursor.getCount() == 1) {
if (cursor.moveToFirst()) {
long id = cursor.getLong(0);
name = cursor.getString(1);
team = new Team(id, name);
}
}
} finally {
closeCursor(cursor);
}
Logger.d((team == null ? "Unsuccessfully" : "Successfully") + " found team with a name of '" + name + "'");
return team;
}
public List<String> findAllTeamNames() {
List<String> teamNames = new ArrayList<String>();
Cursor cursor = null;
try {
SQLiteDatabase db = getReadableDatabase();
cursor = db.query(TEAMS_TABLE_NAME, new String[]{TEAMS_NAME}, null, null, null, null, TEAMS_NAME);
while (cursor.moveToNext()) {
teamNames.add(cursor.getString(0));
}
} finally {
closeCursor(cursor);
}
Logger.d("Found " + teamNames.size() + " teams");
return teamNames;
}
public void deleteAll() {
Logger.d("Deleting all teams");
SQLiteDatabase db = getWritableDatabase();
db.delete(TEAMS_TABLE_NAME, null, null);
}
public void delete(Team team) {
Logger.d("Deleting team with the name of '" + team.getName() + "'");
if (team.getId() != null) {
SQLiteDatabase db = getWritableDatabase();
db.delete(TEAMS_TABLE_NAME, _ID + " = ?", new String[]{team.getId().toString()});
}
}
private boolean attemptingToCreateDuplicateTeam(Team team) {
return team.getId() == null && findByName(team.getName()) != null;
}
private Team createNewTeam(SQLiteDatabase db, Team team) {
if (team.getName() == null || team.getName().trim().length() == 0) {
String msg = "Attempting to create a team with an empty name";
Logger.w(msg);
throw new InvalidTeamNameException(msg);
}
if (attemptingToCreateDuplicateTeam(team)) {
String msg = "Attempting to create duplicate team with the name " + team.getName();
Logger.w(msg);
throw new DuplicateTeamException(msg);
}
Logger.d("Creating new team with a name of '" + team.getName() + "'");
ContentValues values = new ContentValues();
values.put(TEAMS_NAME, team.getName());
long id = db.insertOrThrow(TEAMS_TABLE_NAME, null, values);
return new Team(id, team.getName());
}
private Team updateExistingTeam(SQLiteDatabase db, Team team) {
Logger.d("Updating team with the name of '" + team.getName() + "'");
ContentValues values = new ContentValues();
values.put(TEAMS_NAME, team.getName());
long id = db.update(TEAMS_TABLE_NAME, values, _ID + " = ?", new String[]{team.getId().toString()});
return new Team(id, team.getName());
}
}
| apache-2.0 |
mahaliachante/aws-sdk-java | aws-java-sdk-support/src/main/java/com/amazonaws/services/support/model/AddAttachmentsToSetResult.java | 7304 | /*
* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.support.model;
import java.io.Serializable;
/**
* <p>
* The ID and expiry time of the attachment set returned by the
* <a>AddAttachmentsToSet</a> operation.
* </p>
*/
public class AddAttachmentsToSetResult implements Serializable, Cloneable {
/**
* <p>
* The ID of the attachment set. If an <code>AttachmentSetId</code> was not
* specified, a new attachment set is created, and the ID of the set is
* returned in the response. If an <code>AttachmentSetId</code> was
* specified, the attachments are added to the specified set, if it exists.
* </p>
*/
private String attachmentSetId;
/**
* <p>
* The time and date when the attachment set expires.
* </p>
*/
private String expiryTime;
/**
* <p>
* The ID of the attachment set. If an <code>AttachmentSetId</code> was not
* specified, a new attachment set is created, and the ID of the set is
* returned in the response. If an <code>AttachmentSetId</code> was
* specified, the attachments are added to the specified set, if it exists.
* </p>
*
* @param attachmentSetId
* The ID of the attachment set. If an <code>AttachmentSetId</code>
* was not specified, a new attachment set is created, and the ID of
* the set is returned in the response. If an
* <code>AttachmentSetId</code> was specified, the attachments are
* added to the specified set, if it exists.
*/
public void setAttachmentSetId(String attachmentSetId) {
this.attachmentSetId = attachmentSetId;
}
/**
* <p>
* The ID of the attachment set. If an <code>AttachmentSetId</code> was not
* specified, a new attachment set is created, and the ID of the set is
* returned in the response. If an <code>AttachmentSetId</code> was
* specified, the attachments are added to the specified set, if it exists.
* </p>
*
* @return The ID of the attachment set. If an <code>AttachmentSetId</code>
* was not specified, a new attachment set is created, and the ID of
* the set is returned in the response. If an
* <code>AttachmentSetId</code> was specified, the attachments are
* added to the specified set, if it exists.
*/
public String getAttachmentSetId() {
return this.attachmentSetId;
}
/**
* <p>
* The ID of the attachment set. If an <code>AttachmentSetId</code> was not
* specified, a new attachment set is created, and the ID of the set is
* returned in the response. If an <code>AttachmentSetId</code> was
* specified, the attachments are added to the specified set, if it exists.
* </p>
*
* @param attachmentSetId
* The ID of the attachment set. If an <code>AttachmentSetId</code>
* was not specified, a new attachment set is created, and the ID of
* the set is returned in the response. If an
* <code>AttachmentSetId</code> was specified, the attachments are
* added to the specified set, if it exists.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public AddAttachmentsToSetResult withAttachmentSetId(String attachmentSetId) {
setAttachmentSetId(attachmentSetId);
return this;
}
/**
* <p>
* The time and date when the attachment set expires.
* </p>
*
* @param expiryTime
* The time and date when the attachment set expires.
*/
public void setExpiryTime(String expiryTime) {
this.expiryTime = expiryTime;
}
/**
* <p>
* The time and date when the attachment set expires.
* </p>
*
* @return The time and date when the attachment set expires.
*/
public String getExpiryTime() {
return this.expiryTime;
}
/**
* <p>
* The time and date when the attachment set expires.
* </p>
*
* @param expiryTime
* The time and date when the attachment set expires.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public AddAttachmentsToSetResult withExpiryTime(String expiryTime) {
setExpiryTime(expiryTime);
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 (getAttachmentSetId() != null)
sb.append("AttachmentSetId: " + getAttachmentSetId() + ",");
if (getExpiryTime() != null)
sb.append("ExpiryTime: " + getExpiryTime());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof AddAttachmentsToSetResult == false)
return false;
AddAttachmentsToSetResult other = (AddAttachmentsToSetResult) obj;
if (other.getAttachmentSetId() == null
^ this.getAttachmentSetId() == null)
return false;
if (other.getAttachmentSetId() != null
&& other.getAttachmentSetId().equals(this.getAttachmentSetId()) == false)
return false;
if (other.getExpiryTime() == null ^ this.getExpiryTime() == null)
return false;
if (other.getExpiryTime() != null
&& other.getExpiryTime().equals(this.getExpiryTime()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime
* hashCode
+ ((getAttachmentSetId() == null) ? 0 : getAttachmentSetId()
.hashCode());
hashCode = prime * hashCode
+ ((getExpiryTime() == null) ? 0 : getExpiryTime().hashCode());
return hashCode;
}
@Override
public AddAttachmentsToSetResult clone() {
try {
return (AddAttachmentsToSetResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(
"Got a CloneNotSupportedException from Object.clone() "
+ "even though we're Cloneable!", e);
}
}
} | apache-2.0 |
msmolens/VTK | Wrapping/Java/vtk/vtkReferenceInformation.java | 3930 | package vtk;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Information object return by the Garbage collector. This allow the user to
* monitor what kind of vtkObject and how many have been removed and kept during
* the Garbage collection call.
*
* @author sebastien jourdain - sebastien.jourdain@kitware.com
*/
public class vtkReferenceInformation {
private int numberOfObjectsToFree;
private int numberOfObjectsStillReferenced;
private HashMap<String, AtomicInteger> classesKept;
private HashMap<String, AtomicInteger> classesRemoved;
private boolean keepTrackOfClassNames;
public vtkReferenceInformation(int nbToFree, int nbToKeep, int totalSize) {
this.numberOfObjectsToFree = nbToFree;
this.numberOfObjectsStillReferenced = nbToKeep;
this.keepTrackOfClassNames = false;
}
public vtkReferenceInformation(boolean keepTrackOfClassNames) {
this.numberOfObjectsToFree = 0;
this.numberOfObjectsStillReferenced = 0;
this.keepTrackOfClassNames = keepTrackOfClassNames;
}
public int getTotalNumberOfObjects() {
return numberOfObjectsStillReferenced + numberOfObjectsToFree;
}
public int getNumberOfObjectsToFree() {
return numberOfObjectsToFree;
}
public int getTotalNumberOfObjectsStillReferenced() {
return numberOfObjectsStillReferenced;
}
public void setNumberOfObjectsStillReferenced(int numberOfObjectsStillReferenced) {
this.numberOfObjectsStillReferenced = numberOfObjectsStillReferenced;
}
public void setNumberOfObjectsToFree(int numberOfObjectsToFree) {
this.numberOfObjectsToFree = numberOfObjectsToFree;
}
public void addFreeObject(String className) {
this.numberOfObjectsToFree++;
if (keepTrackOfClassNames) {
if (classesRemoved == null && className != null) {
classesRemoved = new HashMap<String, AtomicInteger>();
}
AtomicInteger counter = classesRemoved.get(className);
if (counter == null) {
classesRemoved.put(className, new AtomicInteger(1));
} else {
counter.incrementAndGet();
}
}
}
public void addKeptObject(String className) {
this.numberOfObjectsStillReferenced++;
if (keepTrackOfClassNames && className != null) {
if (classesKept == null) {
classesKept = new HashMap<String, AtomicInteger>();
}
AtomicInteger counter = classesKept.get(className);
if (counter == null) {
classesKept.put(className, new AtomicInteger(1));
} else {
counter.incrementAndGet();
}
}
}
public String listKeptReferenceToString() {
if (classesKept == null) {
return "";
}
final StringBuilder builder = new StringBuilder(500);
builder.append("List of classes kept in Java layer:\n");
for (Entry<String, AtomicInteger> entry : classesKept.entrySet()) {
builder.append(" - ").append(entry.getKey()).append(": ").append(entry.getValue().toString()).append("\n");
}
return builder.toString();
}
public String listRemovedReferenceToString() {
if (classesRemoved == null) {
return "";
}
final StringBuilder builder = new StringBuilder(500);
builder.append("List of classes removed in Java layer:\n");
for (Entry<String, AtomicInteger> entry : classesRemoved.entrySet()) {
builder.append(" - ").append(entry.getKey()).append(": ").append(entry.getValue().toString()).append("\n");
}
return builder.toString();
}
public String toString() {
final StringBuilder builder = new StringBuilder(50);
builder.append("VTK Gabage Collection: free(");
builder.append(this.numberOfObjectsToFree);
builder.append(") - keep(");
builder.append(this.numberOfObjectsStillReferenced);
builder.append(") - total(");
builder.append(this.getTotalNumberOfObjects());
builder.append(")");
return builder.toString();
}
}
| bsd-3-clause |
google/error-prone-javac | test/tools/javac/NonAmbiguousField/Test.java | 1345 | /*
* Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4053724
* @summary Certain non-ambiguous field references were reported by the
* compiler as ambiguous.
* @author turnidge
*
* @compile one/Parent.java two/Child.java
* @compile/fail/ref=Test.out -XDrawDiagnostics one/Parent2.java two/Child2.java
*/
| gpl-2.0 |
thejeshgn/sl4a | android/ScriptingLayerForAndroid/src/com/googlecode/android_scripting/ScriptListAdapter.java | 2464 | /*
* Copyright (C) 2010 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.googlecode.android_scripting;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.io.File;
import java.util.List;
public abstract class ScriptListAdapter extends BaseAdapter {
protected final Context mContext;
protected final LayoutInflater mInflater;
public ScriptListAdapter(Context context) {
mContext = context;
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return getScriptList().size();
}
@Override
public Object getItem(int position) {
return getScriptList().get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout container;
File script = getScriptList().get(position);
if (convertView == null) {
container = (LinearLayout) mInflater.inflate(R.layout.list_item, null);
} else {
container = (LinearLayout) convertView;
}
ImageView icon = (ImageView) container.findViewById(R.id.list_item_icon);
int resourceId;
if (script.isDirectory()) {
resourceId = R.drawable.folder;
} else {
resourceId = FeaturedInterpreters.getInterpreterIcon(mContext, script.getName());
if (resourceId == 0) {
resourceId = R.drawable.sl4a_logo_32;
}
}
icon.setImageResource(resourceId);
TextView text = (TextView) container.findViewById(R.id.list_item_title);
text.setText(getScriptList().get(position).getName());
return container;
}
protected abstract List<File> getScriptList();
}
| apache-2.0 |
rajzz9/openid4java | src/org/openid4java/infocard/OpenIDToken.java | 5477 | /*
* Copyright 2006-2008 Sxip Identity Corporation
*/
package org.openid4java.infocard;
import org.openid4java.message.Message;
import org.openid4java.message.ParameterList;
import org.openid4java.OpenIDException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
/**
* Models the OpenID Infocard token used to transport OpenID messages.
* An OpenID token encapsulates an OpenID message in key-value form into
* an <openid:OpenIDToken> element.
* <p>
* Provides functionality for OPs / Servers to create OpenID tokens from
* OpenID messages, and for RPs / Consumers to parse received tokens into
* OpenID messages.
*/
public class OpenIDToken
{
private static Log _log = LogFactory.getLog(OpenIDToken.class);
private static final boolean DEBUG = _log.isDebugEnabled();
/**
* Token type data structure.
*/
private OpenIDTokenType _tokenType;
/**
* The encapsulated OpenID Message.
*/
private Message _openidMessage;
/**
* Constructs an OpenID token encapsulating the provided OpenID Message.
* Should be used on the OP/STS side to generate a RSTR.
*
* @param openidMessage The OpenID message obtained from
* ServerManager.authResponse().
*/
public OpenIDToken(Message openidMessage)
{
setOpenIDMessage(openidMessage);
if (DEBUG)
_log.debug("Created " + _tokenType +" token");
}
/**
* Parses the data posted by the selector into an OpenID token.
* Should be used on the RP side.
*
* @param xmlToken The "xmlToken" parameter posted by the selector.
* @return An OpenIDToken encapsulating the OpenID AuthResponse.
*/
public static OpenIDToken createFromXmlToken(String xmlToken)
throws InfocardException
{
if (xmlToken == null)
throw new InfocardException("Error processing xmlToken: null value");
if (DEBUG)
_log.debug("Processing xmlToken: " + xmlToken);
try
{
DocumentBuilderFactory documentBuilderFactory =
DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
DocumentBuilder documentBuilder =
documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(
new ByteArrayInputStream(xmlToken.getBytes("utf-8")));
String keyValueForm;
try
{
keyValueForm = document.getElementsByTagNameNS(
Message.OPENID2_NS, "OpenIDToken")
.item(0).getFirstChild().getNodeValue();
}
catch (Exception e)
{
throw new InfocardException(
"Error extracting OpenID message from the xmlToken", e);
}
Message message = Message.createMessage(
ParameterList.createFromKeyValueForm(keyValueForm));
return new OpenIDToken(message);
// DOM exceptions :
}
catch (ParserConfigurationException e)
{
throw new InfocardException("Parser configuration error", e);
}
catch (SAXException e)
{
throw new InfocardException("Error parsing XML token document", e);
}
catch (IOException e)
{
throw new InfocardException("Error reading xmlToken document", e);
}
catch (OpenIDException e)
{
throw new InfocardException("Error building OpenID message from xmlToken", e);
}
}
/**
* Gets the OpenID message contained in the OpenID token.
*/
public Message getOpenIDMessage()
{
return _openidMessage;
}
/**
* Gets the OpenID message as a ParameterList.
* @return ParameterList containing the OpenID message.
*/
public ParameterList getOpenIDParams()
{
return new ParameterList(_openidMessage.getParameterMap());
}
/**
* Sets the OpenID Message to encapsulate into the token.
*/
public void setOpenIDMessage(Message openidMessage)
{
this._openidMessage = openidMessage;
if (OpenIDTokenType.OPENID20_TOKEN.toString().equals(
openidMessage.getParameterValue("openid.ns")))
_tokenType = OpenIDTokenType.OPENID20_TOKEN;
else
_tokenType = OpenIDTokenType.OPENID11_TOKEN;
}
/**
* Gets the OpenID token type.
*
* @see org.openid4java.infocard.OpenIDTokenType
*/
public OpenIDTokenType getTokenType()
{
return _tokenType;
}
/**
* Generates the XML string representation of the OpenID token.
*/
public String getToken()
{
StringBuffer token = new StringBuffer();
token.append("<openid:OpenIDToken xmlns:openid=\"" +
Message.OPENID2_NS + "\">");
token.append(_openidMessage.keyValueFormEncoding());
token.append("</openid:OpenIDToken>");
return token.toString();
}
}
| apache-2.0 |
smartan/lucene | src/main/java/org/apache/lucene/store/IOContext.java | 4505 | package org.apache.lucene.store;
/*
* 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.
*/
/**
* IOContext holds additional details on the merge/search context. A IOContext
* object can never be initialized as null as passed as a parameter to either
* {@link org.apache.lucene.store.Directory#openInput(String, IOContext)} or
* {@link org.apache.lucene.store.Directory#createOutput(String, IOContext)}
*/
public class IOContext {
/**
* Context is a enumerator which specifies the context in which the Directory
* is being used for.
*/
public enum Context {
MERGE, READ, FLUSH, DEFAULT
};
/**
* An object of a enumerator Context type
*/
public final Context context;
public final MergeInfo mergeInfo;
public final FlushInfo flushInfo;
public final boolean readOnce;
public static final IOContext DEFAULT = new IOContext(Context.DEFAULT);
public static final IOContext READONCE = new IOContext(true);
public static final IOContext READ = new IOContext(false);
public IOContext() {
this(false);
}
public IOContext(FlushInfo flushInfo) {
assert flushInfo != null;
this.context = Context.FLUSH;
this.mergeInfo = null;
this.readOnce = false;
this.flushInfo = flushInfo;
}
public IOContext(Context context) {
this(context, null);
}
private IOContext(boolean readOnce) {
this.context = Context.READ;
this.mergeInfo = null;
this.readOnce = readOnce;
this.flushInfo = null;
}
public IOContext(MergeInfo mergeInfo) {
this(Context.MERGE, mergeInfo);
}
private IOContext(Context context, MergeInfo mergeInfo) {
assert context != Context.MERGE || mergeInfo != null : "MergeInfo must not be null if context is MERGE";
assert context != Context.FLUSH : "Use IOContext(FlushInfo) to create a FLUSH IOContext";
this.context = context;
this.readOnce = false;
this.mergeInfo = mergeInfo;
this.flushInfo = null;
}
/**
* This constructor is used to initialize a {@link IOContext} instance with a new value for the readOnce variable.
* @param ctxt {@link IOContext} object whose information is used to create the new instance except the readOnce variable.
* @param readOnce The new {@link IOContext} object will use this value for readOnce.
*/
public IOContext(IOContext ctxt, boolean readOnce) {
this.context = ctxt.context;
this.mergeInfo = ctxt.mergeInfo;
this.flushInfo = ctxt.flushInfo;
this.readOnce = readOnce;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((context == null) ? 0 : context.hashCode());
result = prime * result + ((flushInfo == null) ? 0 : flushInfo.hashCode());
result = prime * result + ((mergeInfo == null) ? 0 : mergeInfo.hashCode());
result = prime * result + (readOnce ? 1231 : 1237);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
IOContext other = (IOContext) obj;
if (context != other.context)
return false;
if (flushInfo == null) {
if (other.flushInfo != null)
return false;
} else if (!flushInfo.equals(other.flushInfo))
return false;
if (mergeInfo == null) {
if (other.mergeInfo != null)
return false;
} else if (!mergeInfo.equals(other.mergeInfo))
return false;
if (readOnce != other.readOnce)
return false;
return true;
}
@Override
public String toString() {
return "IOContext [context=" + context + ", mergeInfo=" + mergeInfo
+ ", flushInfo=" + flushInfo + ", readOnce=" + readOnce + "]";
}
} | apache-2.0 |
rabbitcount/jedis | src/main/java/redis/clients/jedis/Jedis.java | 121171 | package redis.clients.jedis;
import java.net.URI;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import redis.clients.jedis.BinaryClient.LIST_POSITION;
import redis.clients.jedis.JedisCluster.Reset;
import redis.clients.jedis.commands.*;
import redis.clients.jedis.params.set.SetParams;
import redis.clients.jedis.params.sortedset.ZAddParams;
import redis.clients.jedis.params.sortedset.ZIncrByParams;
import redis.clients.util.SafeEncoder;
import redis.clients.util.Slowlog;
public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommands,
AdvancedJedisCommands, ScriptingCommands, BasicCommands, ClusterCommands, SentinelCommands {
protected JedisPoolAbstract dataSource = null;
public Jedis() {
super();
}
public Jedis(final String host) {
super(host);
}
public Jedis(final String host, final int port) {
super(host, port);
}
public Jedis(final String host, final int port, final int timeout) {
super(host, port, timeout);
}
public Jedis(final String host, final int port, final int connectionTimeout, final int soTimeout) {
super(host, port, connectionTimeout, soTimeout);
}
public Jedis(JedisShardInfo shardInfo) {
super(shardInfo);
}
public Jedis(URI uri) {
super(uri);
}
public Jedis(final URI uri, final int timeout) {
super(uri, timeout);
}
public Jedis(final URI uri, final int connectionTimeout, final int soTimeout) {
super(uri, connectionTimeout, soTimeout);
}
/**
* Set the string value as value of the key. The string can't be longer than 1073741824 bytes (1
* GB).
* <p>
* Time complexity: O(1)
* @param key
* @param value
* @return Status code reply
*/
@Override
public String set(final String key, String value) {
checkIsInMultiOrPipeline();
client.set(key, value);
return client.getStatusCodeReply();
}
/**
* Set the string value as value of the key. The string can't be longer than 1073741824 bytes (1
* GB).
* @param key
* @param value
* @param params NX|XX, NX -- Only set the key if it does not already exist. XX -- Only set the
* key if it already exist. EX|PX, expire time units: EX = seconds; PX = milliseconds
* @return Status code reply
*/
public String set(final String key, final String value, final SetParams params) {
checkIsInMultiOrPipeline();
client.set(key, value, params);
return client.getStatusCodeReply();
}
/**
* Get the value of the specified key. If the key does not exist null is returned. If the value
* stored at key is not a string an error is returned because GET can only handle string values.
* <p>
* Time complexity: O(1)
* @param key
* @return Bulk reply
*/
@Override
public String get(final String key) {
checkIsInMultiOrPipeline();
client.sendCommand(Protocol.Command.GET, key);
return client.getBulkReply();
}
/**
* Test if the specified key exists. The command returns the number of keys existed
* Time complexity: O(N)
* @param keys
* @return Integer reply, specifically: an integer greater than 0 if one or more keys were removed
* 0 if none of the specified key existed
*/
public Long exists(final String... keys) {
checkIsInMultiOrPipeline();
client.exists(keys);
return client.getIntegerReply();
}
/**
* Test if the specified key exists. The command returns "1" if the key exists, otherwise "0" is
* returned. Note that even keys set with an empty string as value will return "1". Time
* complexity: O(1)
* @param key
* @return Boolean reply, true if the key exists, otherwise false
*/
@Override
public Boolean exists(final String key) {
checkIsInMultiOrPipeline();
client.exists(key);
return client.getIntegerReply() == 1;
}
/**
* Remove the specified keys. If a given key does not exist no operation is performed for this
* key. The command returns the number of keys removed. Time complexity: O(1)
* @param keys
* @return Integer reply, specifically: an integer greater than 0 if one or more keys were removed
* 0 if none of the specified key existed
*/
@Override
public Long del(final String... keys) {
checkIsInMultiOrPipeline();
client.del(keys);
return client.getIntegerReply();
}
@Override
public Long del(String key) {
client.del(key);
return client.getIntegerReply();
}
/**
* Return the type of the value stored at key in form of a string. The type can be one of "none",
* "string", "list", "set". "none" is returned if the key does not exist. Time complexity: O(1)
* @param key
* @return Status code reply, specifically: "none" if the key does not exist "string" if the key
* contains a String value "list" if the key contains a List value "set" if the key
* contains a Set value "zset" if the key contains a Sorted Set value "hash" if the key
* contains a Hash value
*/
@Override
public String type(final String key) {
checkIsInMultiOrPipeline();
client.type(key);
return client.getStatusCodeReply();
}
/**
* Returns all the keys matching the glob-style pattern as space separated strings. For example if
* you have in the database the keys "foo" and "foobar" the command "KEYS foo*" will return
* "foo foobar".
* <p>
* Note that while the time complexity for this operation is O(n) the constant times are pretty
* low. For example Redis running on an entry level laptop can scan a 1 million keys database in
* 40 milliseconds. <b>Still it's better to consider this one of the slow commands that may ruin
* the DB performance if not used with care.</b>
* <p>
* In other words this command is intended only for debugging and special operations like creating
* a script to change the DB schema. Don't use it in your normal code. Use Redis Sets in order to
* group together a subset of objects.
* <p>
* Glob style patterns examples:
* <ul>
* <li>h?llo will match hello hallo hhllo
* <li>h*llo will match hllo heeeello
* <li>h[ae]llo will match hello and hallo, but not hillo
* </ul>
* <p>
* Use \ to escape special chars if you want to match them verbatim.
* <p>
* Time complexity: O(n) (with n being the number of keys in the DB, and assuming keys and pattern
* of limited length)
* @param pattern
* @return Multi bulk reply
*/
@Override
public Set<String> keys(final String pattern) {
checkIsInMultiOrPipeline();
client.keys(pattern);
return BuilderFactory.STRING_SET.build(client.getBinaryMultiBulkReply());
}
/**
* Return a randomly selected key from the currently selected DB.
* <p>
* Time complexity: O(1)
* @return Singe line reply, specifically the randomly selected key or an empty string is the
* database is empty
*/
@Override
public String randomKey() {
checkIsInMultiOrPipeline();
client.randomKey();
return client.getBulkReply();
}
/**
* Atomically renames the key oldkey to newkey. If the source and destination name are the same an
* error is returned. If newkey already exists it is overwritten.
* <p>
* Time complexity: O(1)
* @param oldkey
* @param newkey
* @return Status code repy
*/
@Override
public String rename(final String oldkey, final String newkey) {
checkIsInMultiOrPipeline();
client.rename(oldkey, newkey);
return client.getStatusCodeReply();
}
/**
* Rename oldkey into newkey but fails if the destination key newkey already exists.
* <p>
* Time complexity: O(1)
* @param oldkey
* @param newkey
* @return Integer reply, specifically: 1 if the key was renamed 0 if the target key already exist
*/
@Override
public Long renamenx(final String oldkey, final String newkey) {
checkIsInMultiOrPipeline();
client.renamenx(oldkey, newkey);
return client.getIntegerReply();
}
/**
* Set a timeout on the specified key. After the timeout the key will be automatically deleted by
* the server. A key with an associated timeout is said to be volatile in Redis terminology.
* <p>
* Voltile keys are stored on disk like the other keys, the timeout is persistent too like all the
* other aspects of the dataset. Saving a dataset containing expires and stopping the server does
* not stop the flow of time as Redis stores on disk the time when the key will no longer be
* available as Unix time, and not the remaining seconds.
* <p>
* Since Redis 2.1.3 you can update the value of the timeout of a key already having an expire
* set. It is also possible to undo the expire at all turning the key into a normal key using the
* {@link #persist(String) PERSIST} command.
* <p>
* Time complexity: O(1)
* @see <a href="http://redis.io/commands/expire">Expire Command</a>
* @param key
* @param seconds
* @return Integer reply, specifically: 1: the timeout was set. 0: the timeout was not set since
* the key already has an associated timeout (this may happen only in Redis versions <
* 2.1.3, Redis >= 2.1.3 will happily update the timeout), or the key does not exist.
*/
@Override
public Long expire(final String key, final int seconds) {
checkIsInMultiOrPipeline();
client.expire(key, seconds);
return client.getIntegerReply();
}
/**
* EXPIREAT works exctly like {@link #expire(String, int) EXPIRE} but instead to get the number of
* seconds representing the Time To Live of the key as a second argument (that is a relative way
* of specifing the TTL), it takes an absolute one in the form of a UNIX timestamp (Number of
* seconds elapsed since 1 Gen 1970).
* <p>
* EXPIREAT was introduced in order to implement the Append Only File persistence mode so that
* EXPIRE commands are automatically translated into EXPIREAT commands for the append only file.
* Of course EXPIREAT can also used by programmers that need a way to simply specify that a given
* key should expire at a given time in the future.
* <p>
* Since Redis 2.1.3 you can update the value of the timeout of a key already having an expire
* set. It is also possible to undo the expire at all turning the key into a normal key using the
* {@link #persist(String) PERSIST} command.
* <p>
* Time complexity: O(1)
* @see <a href="http://redis.io/commands/expire">Expire Command</a>
* @param key
* @param unixTime
* @return Integer reply, specifically: 1: the timeout was set. 0: the timeout was not set since
* the key already has an associated timeout (this may happen only in Redis versions <
* 2.1.3, Redis >= 2.1.3 will happily update the timeout), or the key does not exist.
*/
@Override
public Long expireAt(final String key, final long unixTime) {
checkIsInMultiOrPipeline();
client.expireAt(key, unixTime);
return client.getIntegerReply();
}
/**
* The TTL command returns the remaining time to live in seconds of a key that has an
* {@link #expire(String, int) EXPIRE} set. This introspection capability allows a Redis client to
* check how many seconds a given key will continue to be part of the dataset.
* @param key
* @return Integer reply, returns the remaining time to live in seconds of a key that has an
* EXPIRE. In Redis 2.6 or older, if the Key does not exists or does not have an
* associated expire, -1 is returned. In Redis 2.8 or newer, if the Key does not have an
* associated expire, -1 is returned or if the Key does not exists, -2 is returned.
*/
@Override
public Long ttl(final String key) {
checkIsInMultiOrPipeline();
client.ttl(key);
return client.getIntegerReply();
}
/**
* Move the specified key from the currently selected DB to the specified destination DB. Note
* that this command returns 1 only if the key was successfully moved, and 0 if the target key was
* already there or if the source key was not found at all, so it is possible to use MOVE as a
* locking primitive.
* @param key
* @param dbIndex
* @return Integer reply, specifically: 1 if the key was moved 0 if the key was not moved because
* already present on the target DB or was not found in the current DB.
*/
@Override
public Long move(final String key, final int dbIndex) {
checkIsInMultiOrPipeline();
client.move(key, dbIndex);
return client.getIntegerReply();
}
/**
* GETSET is an atomic set this value and return the old value command. Set key to the string
* value and return the old value stored at key. The string can't be longer than 1073741824 bytes
* (1 GB).
* <p>
* Time complexity: O(1)
* @param key
* @param value
* @return Bulk reply
*/
@Override
public String getSet(final String key, final String value) {
checkIsInMultiOrPipeline();
client.getSet(key, value);
return client.getBulkReply();
}
/**
* Get the values of all the specified keys. If one or more keys dont exist or is not of type
* String, a 'nil' value is returned instead of the value of the specified key, but the operation
* never fails.
* <p>
* Time complexity: O(1) for every key
* @param keys
* @return Multi bulk reply
*/
@Override
public List<String> mget(final String... keys) {
checkIsInMultiOrPipeline();
client.mget(keys);
return client.getMultiBulkReply();
}
/**
* SETNX works exactly like {@link #set(String, String) SET} with the only difference that if the
* key already exists no operation is performed. SETNX actually means "SET if Not eXists".
* <p>
* Time complexity: O(1)
* @param key
* @param value
* @return Integer reply, specifically: 1 if the key was set 0 if the key was not set
*/
@Override
public Long setnx(final String key, final String value) {
checkIsInMultiOrPipeline();
client.setnx(key, value);
return client.getIntegerReply();
}
/**
* The command is exactly equivalent to the following group of commands:
* {@link #set(String, String) SET} + {@link #expire(String, int) EXPIRE}. The operation is
* atomic.
* <p>
* Time complexity: O(1)
* @param key
* @param seconds
* @param value
* @return Status code reply
*/
@Override
public String setex(final String key, final int seconds, final String value) {
checkIsInMultiOrPipeline();
client.setex(key, seconds, value);
return client.getStatusCodeReply();
}
/**
* Set the the respective keys to the respective values. MSET will replace old values with new
* values, while {@link #msetnx(String...) MSETNX} will not perform any operation at all even if
* just a single key already exists.
* <p>
* Because of this semantic MSETNX can be used in order to set different keys representing
* different fields of an unique logic object in a way that ensures that either all the fields or
* none at all are set.
* <p>
* Both MSET and MSETNX are atomic operations. This means that for instance if the keys A and B
* are modified, another client talking to Redis can either see the changes to both A and B at
* once, or no modification at all.
* @see #msetnx(String...)
* @param keysvalues
* @return Status code reply Basically +OK as MSET can't fail
*/
@Override
public String mset(final String... keysvalues) {
checkIsInMultiOrPipeline();
client.mset(keysvalues);
return client.getStatusCodeReply();
}
/**
* Set the the respective keys to the respective values. {@link #mset(String...) MSET} will
* replace old values with new values, while MSETNX will not perform any operation at all even if
* just a single key already exists.
* <p>
* Because of this semantic MSETNX can be used in order to set different keys representing
* different fields of an unique logic object in a way that ensures that either all the fields or
* none at all are set.
* <p>
* Both MSET and MSETNX are atomic operations. This means that for instance if the keys A and B
* are modified, another client talking to Redis can either see the changes to both A and B at
* once, or no modification at all.
* @see #mset(String...)
* @param keysvalues
* @return Integer reply, specifically: 1 if the all the keys were set 0 if no key was set (at
* least one key already existed)
*/
@Override
public Long msetnx(final String... keysvalues) {
checkIsInMultiOrPipeline();
client.msetnx(keysvalues);
return client.getIntegerReply();
}
/**
* IDECRBY work just like {@link #decr(String) INCR} but instead to decrement by 1 the decrement
* is integer.
* <p>
* INCR commands are limited to 64 bit signed integers.
* <p>
* Note: this is actually a string operation, that is, in Redis there are not "integer" types.
* Simply the string stored at the key is parsed as a base 10 64 bit signed integer, incremented,
* and then converted back as a string.
* <p>
* Time complexity: O(1)
* @see #incr(String)
* @see #decr(String)
* @see #incrBy(String, long)
* @param key
* @param integer
* @return Integer reply, this commands will reply with the new value of key after the increment.
*/
@Override
public Long decrBy(final String key, final long integer) {
checkIsInMultiOrPipeline();
client.decrBy(key, integer);
return client.getIntegerReply();
}
/**
* Decrement the number stored at key by one. If the key does not exist or contains a value of a
* wrong type, set the key to the value of "0" before to perform the decrement operation.
* <p>
* INCR commands are limited to 64 bit signed integers.
* <p>
* Note: this is actually a string operation, that is, in Redis there are not "integer" types.
* Simply the string stored at the key is parsed as a base 10 64 bit signed integer, incremented,
* and then converted back as a string.
* <p>
* Time complexity: O(1)
* @see #incr(String)
* @see #incrBy(String, long)
* @see #decrBy(String, long)
* @param key
* @return Integer reply, this commands will reply with the new value of key after the increment.
*/
@Override
public Long decr(final String key) {
checkIsInMultiOrPipeline();
client.decr(key);
return client.getIntegerReply();
}
/**
* INCRBY work just like {@link #incr(String) INCR} but instead to increment by 1 the increment is
* integer.
* <p>
* INCR commands are limited to 64 bit signed integers.
* <p>
* Note: this is actually a string operation, that is, in Redis there are not "integer" types.
* Simply the string stored at the key is parsed as a base 10 64 bit signed integer, incremented,
* and then converted back as a string.
* <p>
* Time complexity: O(1)
* @see #incr(String)
* @see #decr(String)
* @see #decrBy(String, long)
* @param key
* @param integer
* @return Integer reply, this commands will reply with the new value of key after the increment.
*/
@Override
public Long incrBy(final String key, final long integer) {
checkIsInMultiOrPipeline();
client.incrBy(key, integer);
return client.getIntegerReply();
}
/**
* INCRBYFLOAT
* <p>
* INCRBYFLOAT commands are limited to double precision floating point values.
* <p>
* Note: this is actually a string operation, that is, in Redis there are not "double" types.
* Simply the string stored at the key is parsed as a base double precision floating point value,
* incremented, and then converted back as a string. There is no DECRYBYFLOAT but providing a
* negative value will work as expected.
* <p>
* Time complexity: O(1)
* @param key
* @param value
* @return Double reply, this commands will reply with the new value of key after the increment.
*/
@Override
public Double incrByFloat(final String key, final double value) {
checkIsInMultiOrPipeline();
client.incrByFloat(key, value);
String dval = client.getBulkReply();
return (dval != null ? new Double(dval) : null);
}
/**
* Increment the number stored at key by one. If the key does not exist or contains a value of a
* wrong type, set the key to the value of "0" before to perform the increment operation.
* <p>
* INCR commands are limited to 64 bit signed integers.
* <p>
* Note: this is actually a string operation, that is, in Redis there are not "integer" types.
* Simply the string stored at the key is parsed as a base 10 64 bit signed integer, incremented,
* and then converted back as a string.
* <p>
* Time complexity: O(1)
* @see #incrBy(String, long)
* @see #decr(String)
* @see #decrBy(String, long)
* @param key
* @return Integer reply, this commands will reply with the new value of key after the increment.
*/
@Override
public Long incr(final String key) {
checkIsInMultiOrPipeline();
client.incr(key);
return client.getIntegerReply();
}
/**
* If the key already exists and is a string, this command appends the provided value at the end
* of the string. If the key does not exist it is created and set as an empty string, so APPEND
* will be very similar to SET in this special case.
* <p>
* Time complexity: O(1). The amortized time complexity is O(1) assuming the appended value is
* small and the already present value is of any size, since the dynamic string library used by
* Redis will double the free space available on every reallocation.
* @param key
* @param value
* @return Integer reply, specifically the total length of the string after the append operation.
*/
@Override
public Long append(final String key, final String value) {
checkIsInMultiOrPipeline();
client.append(key, value);
return client.getIntegerReply();
}
/**
* Return a subset of the string from offset start to offset end (both offsets are inclusive).
* Negative offsets can be used in order to provide an offset starting from the end of the string.
* So -1 means the last char, -2 the penultimate and so forth.
* <p>
* The function handles out of range requests without raising an error, but just limiting the
* resulting range to the actual length of the string.
* <p>
* Time complexity: O(start+n) (with start being the start index and n the total length of the
* requested range). Note that the lookup part of this command is O(1) so for small strings this
* is actually an O(1) command.
* @param key
* @param start
* @param end
* @return Bulk reply
*/
@Override
public String substr(final String key, final int start, final int end) {
checkIsInMultiOrPipeline();
client.substr(key, start, end);
return client.getBulkReply();
}
/**
* Set the specified hash field to the specified value.
* <p>
* If key does not exist, a new key holding a hash is created.
* <p>
* <b>Time complexity:</b> O(1)
* @param key
* @param field
* @param value
* @return If the field already exists, and the HSET just produced an update of the value, 0 is
* returned, otherwise if a new field is created 1 is returned.
*/
@Override
public Long hset(final String key, final String field, final String value) {
checkIsInMultiOrPipeline();
client.hset(key, field, value);
return client.getIntegerReply();
}
/**
* If key holds a hash, retrieve the value associated to the specified field.
* <p>
* If the field is not found or the key does not exist, a special 'nil' value is returned.
* <p>
* <b>Time complexity:</b> O(1)
* @param key
* @param field
* @return Bulk reply
*/
@Override
public String hget(final String key, final String field) {
checkIsInMultiOrPipeline();
client.hget(key, field);
return client.getBulkReply();
}
/**
* Set the specified hash field to the specified value if the field not exists. <b>Time
* complexity:</b> O(1)
* @param key
* @param field
* @param value
* @return If the field already exists, 0 is returned, otherwise if a new field is created 1 is
* returned.
*/
@Override
public Long hsetnx(final String key, final String field, final String value) {
checkIsInMultiOrPipeline();
client.hsetnx(key, field, value);
return client.getIntegerReply();
}
/**
* Set the respective fields to the respective values. HMSET replaces old values with new values.
* <p>
* If key does not exist, a new key holding a hash is created.
* <p>
* <b>Time complexity:</b> O(N) (with N being the number of fields)
* @param key
* @param hash
* @return Return OK or Exception if hash is empty
*/
@Override
public String hmset(final String key, final Map<String, String> hash) {
checkIsInMultiOrPipeline();
client.hmset(key, hash);
return client.getStatusCodeReply();
}
/**
* Retrieve the values associated to the specified fields.
* <p>
* If some of the specified fields do not exist, nil values are returned. Non existing keys are
* considered like empty hashes.
* <p>
* <b>Time complexity:</b> O(N) (with N being the number of fields)
* @param key
* @param fields
* @return Multi Bulk Reply specifically a list of all the values associated with the specified
* fields, in the same order of the request.
*/
@Override
public List<String> hmget(final String key, final String... fields) {
checkIsInMultiOrPipeline();
client.hmget(key, fields);
return client.getMultiBulkReply();
}
/**
* Increment the number stored at field in the hash at key by value. If key does not exist, a new
* key holding a hash is created. If field does not exist or holds a string, the value is set to 0
* before applying the operation. Since the value argument is signed you can use this command to
* perform both increments and decrements.
* <p>
* The range of values supported by HINCRBY is limited to 64 bit signed integers.
* <p>
* <b>Time complexity:</b> O(1)
* @param key
* @param field
* @param value
* @return Integer reply The new value at field after the increment operation.
*/
@Override
public Long hincrBy(final String key, final String field, final long value) {
checkIsInMultiOrPipeline();
client.hincrBy(key, field, value);
return client.getIntegerReply();
}
/**
* Increment the number stored at field in the hash at key by a double precision floating point
* value. If key does not exist, a new key holding a hash is created. If field does not exist or
* holds a string, the value is set to 0 before applying the operation. Since the value argument
* is signed you can use this command to perform both increments and decrements.
* <p>
* The range of values supported by HINCRBYFLOAT is limited to double precision floating point
* values.
* <p>
* <b>Time complexity:</b> O(1)
* @param key
* @param field
* @param value
* @return Double precision floating point reply The new value at field after the increment
* operation.
*/
@Override
public Double hincrByFloat(final String key, final String field, final double value) {
checkIsInMultiOrPipeline();
client.hincrByFloat(key, field, value);
final String dval = client.getBulkReply();
return (dval != null ? new Double(dval) : null);
}
/**
* Test for existence of a specified field in a hash. <b>Time complexity:</b> O(1)
* @param key
* @param field
* @return Return 1 if the hash stored at key contains the specified field. Return 0 if the key is
* not found or the field is not present.
*/
@Override
public Boolean hexists(final String key, final String field) {
checkIsInMultiOrPipeline();
client.hexists(key, field);
return client.getIntegerReply() == 1;
}
/**
* Remove the specified field from an hash stored at key.
* <p>
* <b>Time complexity:</b> O(1)
* @param key
* @param fields
* @return If the field was present in the hash it is deleted and 1 is returned, otherwise 0 is
* returned and no operation is performed.
*/
@Override
public Long hdel(final String key, final String... fields) {
checkIsInMultiOrPipeline();
client.hdel(key, fields);
return client.getIntegerReply();
}
/**
* Return the number of items in a hash.
* <p>
* <b>Time complexity:</b> O(1)
* @param key
* @return The number of entries (fields) contained in the hash stored at key. If the specified
* key does not exist, 0 is returned assuming an empty hash.
*/
@Override
public Long hlen(final String key) {
checkIsInMultiOrPipeline();
client.hlen(key);
return client.getIntegerReply();
}
/**
* Return all the fields in a hash.
* <p>
* <b>Time complexity:</b> O(N), where N is the total number of entries
* @param key
* @return All the fields names contained into a hash.
*/
@Override
public Set<String> hkeys(final String key) {
checkIsInMultiOrPipeline();
client.hkeys(key);
return BuilderFactory.STRING_SET.build(client.getBinaryMultiBulkReply());
}
/**
* Return all the values in a hash.
* <p>
* <b>Time complexity:</b> O(N), where N is the total number of entries
* @param key
* @return All the fields values contained into a hash.
*/
@Override
public List<String> hvals(final String key) {
checkIsInMultiOrPipeline();
client.hvals(key);
final List<String> lresult = client.getMultiBulkReply();
return lresult;
}
/**
* Return all the fields and associated values in a hash.
* <p>
* <b>Time complexity:</b> O(N), where N is the total number of entries
* @param key
* @return All the fields and values contained into a hash.
*/
@Override
public Map<String, String> hgetAll(final String key) {
checkIsInMultiOrPipeline();
client.hgetAll(key);
return BuilderFactory.STRING_MAP.build(client.getBinaryMultiBulkReply());
}
/**
* Add the string value to the head (LPUSH) or tail (RPUSH) of the list stored at key. If the key
* does not exist an empty list is created just before the append operation. If the key exists but
* is not a List an error is returned.
* <p>
* Time complexity: O(1)
* @param key
* @param strings
* @return Integer reply, specifically, the number of elements inside the list after the push
* operation.
*/
@Override
public Long rpush(final String key, final String... strings) {
checkIsInMultiOrPipeline();
client.rpush(key, strings);
return client.getIntegerReply();
}
/**
* Add the string value to the head (LPUSH) or tail (RPUSH) of the list stored at key. If the key
* does not exist an empty list is created just before the append operation. If the key exists but
* is not a List an error is returned.
* <p>
* Time complexity: O(1)
* @param key
* @param strings
* @return Integer reply, specifically, the number of elements inside the list after the push
* operation.
*/
@Override
public Long lpush(final String key, final String... strings) {
checkIsInMultiOrPipeline();
client.lpush(key, strings);
return client.getIntegerReply();
}
/**
* Return the length of the list stored at the specified key. If the key does not exist zero is
* returned (the same behaviour as for empty lists). If the value stored at key is not a list an
* error is returned.
* <p>
* Time complexity: O(1)
* @param key
* @return The length of the list.
*/
@Override
public Long llen(final String key) {
checkIsInMultiOrPipeline();
client.llen(key);
return client.getIntegerReply();
}
/**
* Return the specified elements of the list stored at the specified key. Start and end are
* zero-based indexes. 0 is the first element of the list (the list head), 1 the next element and
* so on.
* <p>
* For example LRANGE foobar 0 2 will return the first three elements of the list.
* <p>
* start and end can also be negative numbers indicating offsets from the end of the list. For
* example -1 is the last element of the list, -2 the penultimate element and so on.
* <p>
* <b>Consistency with range functions in various programming languages</b>
* <p>
* Note that if you have a list of numbers from 0 to 100, LRANGE 0 10 will return 11 elements,
* that is, rightmost item is included. This may or may not be consistent with behavior of
* range-related functions in your programming language of choice (think Ruby's Range.new,
* Array#slice or Python's range() function).
* <p>
* LRANGE behavior is consistent with one of Tcl.
* <p>
* <b>Out-of-range indexes</b>
* <p>
* Indexes out of range will not produce an error: if start is over the end of the list, or start
* > end, an empty list is returned. If end is over the end of the list Redis will threat it
* just like the last element of the list.
* <p>
* Time complexity: O(start+n) (with n being the length of the range and start being the start
* offset)
* @param key
* @param start
* @param end
* @return Multi bulk reply, specifically a list of elements in the specified range.
*/
@Override
public List<String> lrange(final String key, final long start, final long end) {
checkIsInMultiOrPipeline();
client.lrange(key, start, end);
return client.getMultiBulkReply();
}
/**
* Trim an existing list so that it will contain only the specified range of elements specified.
* Start and end are zero-based indexes. 0 is the first element of the list (the list head), 1 the
* next element and so on.
* <p>
* For example LTRIM foobar 0 2 will modify the list stored at foobar key so that only the first
* three elements of the list will remain.
* <p>
* start and end can also be negative numbers indicating offsets from the end of the list. For
* example -1 is the last element of the list, -2 the penultimate element and so on.
* <p>
* Indexes out of range will not produce an error: if start is over the end of the list, or start
* > end, an empty list is left as value. If end over the end of the list Redis will threat it
* just like the last element of the list.
* <p>
* Hint: the obvious use of LTRIM is together with LPUSH/RPUSH. For example:
* <p>
* {@code lpush("mylist", "someelement"); ltrim("mylist", 0, 99); * }
* <p>
* The above two commands will push elements in the list taking care that the list will not grow
* without limits. This is very useful when using Redis to store logs for example. It is important
* to note that when used in this way LTRIM is an O(1) operation because in the average case just
* one element is removed from the tail of the list.
* <p>
* Time complexity: O(n) (with n being len of list - len of range)
* @param key
* @param start
* @param end
* @return Status code reply
*/
@Override
public String ltrim(final String key, final long start, final long end) {
checkIsInMultiOrPipeline();
client.ltrim(key, start, end);
return client.getStatusCodeReply();
}
/**
* Return the specified element of the list stored at the specified key. 0 is the first element, 1
* the second and so on. Negative indexes are supported, for example -1 is the last element, -2
* the penultimate and so on.
* <p>
* If the value stored at key is not of list type an error is returned. If the index is out of
* range a 'nil' reply is returned.
* <p>
* Note that even if the average time complexity is O(n) asking for the first or the last element
* of the list is O(1).
* <p>
* Time complexity: O(n) (with n being the length of the list)
* @param key
* @param index
* @return Bulk reply, specifically the requested element
*/
@Override
public String lindex(final String key, final long index) {
checkIsInMultiOrPipeline();
client.lindex(key, index);
return client.getBulkReply();
}
/**
* Set a new value as the element at index position of the List at key.
* <p>
* Out of range indexes will generate an error.
* <p>
* Similarly to other list commands accepting indexes, the index can be negative to access
* elements starting from the end of the list. So -1 is the last element, -2 is the penultimate,
* and so forth.
* <p>
* <b>Time complexity:</b>
* <p>
* O(N) (with N being the length of the list), setting the first or last elements of the list is
* O(1).
* @see #lindex(String, long)
* @param key
* @param index
* @param value
* @return Status code reply
*/
@Override
public String lset(final String key, final long index, final String value) {
checkIsInMultiOrPipeline();
client.lset(key, index, value);
return client.getStatusCodeReply();
}
/**
* Remove the first count occurrences of the value element from the list. If count is zero all the
* elements are removed. If count is negative elements are removed from tail to head, instead to
* go from head to tail that is the normal behaviour. So for example LREM with count -2 and hello
* as value to remove against the list (a,b,c,hello,x,hello,hello) will lave the list
* (a,b,c,hello,x). The number of removed elements is returned as an integer, see below for more
* information about the returned value. Note that non existing keys are considered like empty
* lists by LREM, so LREM against non existing keys will always return 0.
* <p>
* Time complexity: O(N) (with N being the length of the list)
* @param key
* @param count
* @param value
* @return Integer Reply, specifically: The number of removed elements if the operation succeeded
*/
@Override
public Long lrem(final String key, final long count, final String value) {
checkIsInMultiOrPipeline();
client.lrem(key, count, value);
return client.getIntegerReply();
}
/**
* Atomically return and remove the first (LPOP) or last (RPOP) element of the list. For example
* if the list contains the elements "a","b","c" LPOP will return "a" and the list will become
* "b","c".
* <p>
* If the key does not exist or the list is already empty the special value 'nil' is returned.
* @see #rpop(String)
* @param key
* @return Bulk reply
*/
@Override
public String lpop(final String key) {
checkIsInMultiOrPipeline();
client.lpop(key);
return client.getBulkReply();
}
/**
* Atomically return and remove the first (LPOP) or last (RPOP) element of the list. For example
* if the list contains the elements "a","b","c" RPOP will return "c" and the list will become
* "a","b".
* <p>
* If the key does not exist or the list is already empty the special value 'nil' is returned.
* @see #lpop(String)
* @param key
* @return Bulk reply
*/
@Override
public String rpop(final String key) {
checkIsInMultiOrPipeline();
client.rpop(key);
return client.getBulkReply();
}
/**
* Atomically return and remove the last (tail) element of the srckey list, and push the element
* as the first (head) element of the dstkey list. For example if the source list contains the
* elements "a","b","c" and the destination list contains the elements "foo","bar" after an
* RPOPLPUSH command the content of the two lists will be "a","b" and "c","foo","bar".
* <p>
* If the key does not exist or the list is already empty the special value 'nil' is returned. If
* the srckey and dstkey are the same the operation is equivalent to removing the last element
* from the list and pusing it as first element of the list, so it's a "list rotation" command.
* <p>
* Time complexity: O(1)
* @param srckey
* @param dstkey
* @return Bulk reply
*/
@Override
public String rpoplpush(final String srckey, final String dstkey) {
checkIsInMultiOrPipeline();
client.rpoplpush(srckey, dstkey);
return client.getBulkReply();
}
/**
* Add the specified member to the set value stored at key. If member is already a member of the
* set no operation is performed. If key does not exist a new set with the specified member as
* sole member is created. If the key exists but does not hold a set value an error is returned.
* <p>
* Time complexity O(1)
* @param key
* @param members
* @return Integer reply, specifically: 1 if the new element was added 0 if the element was
* already a member of the set
*/
@Override
public Long sadd(final String key, final String... members) {
checkIsInMultiOrPipeline();
client.sadd(key, members);
return client.getIntegerReply();
}
/**
* Return all the members (elements) of the set value stored at key. This is just syntax glue for
* {@link #sinter(String...) SINTER}.
* <p>
* Time complexity O(N)
* @param key
* @return Multi bulk reply
*/
@Override
public Set<String> smembers(final String key) {
checkIsInMultiOrPipeline();
client.smembers(key);
final List<String> members = client.getMultiBulkReply();
if (members == null) {
return null;
}
return SetFromList.of(members);
}
/**
* Remove the specified member from the set value stored at key. If member was not a member of the
* set no operation is performed. If key does not hold a set value an error is returned.
* <p>
* Time complexity O(1)
* @param key
* @param members
* @return Integer reply, specifically: 1 if the new element was removed 0 if the new element was
* not a member of the set
*/
@Override
public Long srem(final String key, final String... members) {
checkIsInMultiOrPipeline();
client.srem(key, members);
return client.getIntegerReply();
}
/**
* Remove a random element from a Set returning it as return value. If the Set is empty or the key
* does not exist, a nil object is returned.
* <p>
* The {@link #srandmember(String)} command does a similar work but the returned element is not
* removed from the Set.
* <p>
* Time complexity O(1)
* @param key
* @return Bulk reply
*/
@Override
public String spop(final String key) {
checkIsInMultiOrPipeline();
client.spop(key);
return client.getBulkReply();
}
@Override
public Set<String> spop(final String key, final long count) {
checkIsInMultiOrPipeline();
client.spop(key, count);
final List<String> members = client.getMultiBulkReply();
if (members == null) {
return null;
}
return SetFromList.of(members);
}
/**
* Move the specifided member from the set at srckey to the set at dstkey. This operation is
* atomic, in every given moment the element will appear to be in the source or destination set
* for accessing clients.
* <p>
* If the source set does not exist or does not contain the specified element no operation is
* performed and zero is returned, otherwise the element is removed from the source set and added
* to the destination set. On success one is returned, even if the element was already present in
* the destination set.
* <p>
* An error is raised if the source or destination keys contain a non Set value.
* <p>
* Time complexity O(1)
* @param srckey
* @param dstkey
* @param member
* @return Integer reply, specifically: 1 if the element was moved 0 if the element was not found
* on the first set and no operation was performed
*/
@Override
public Long smove(final String srckey, final String dstkey, final String member) {
checkIsInMultiOrPipeline();
client.smove(srckey, dstkey, member);
return client.getIntegerReply();
}
/**
* Return the set cardinality (number of elements). If the key does not exist 0 is returned, like
* for empty sets.
* @param key
* @return Integer reply, specifically: the cardinality (number of elements) of the set as an
* integer.
*/
@Override
public Long scard(final String key) {
checkIsInMultiOrPipeline();
client.scard(key);
return client.getIntegerReply();
}
/**
* Return 1 if member is a member of the set stored at key, otherwise 0 is returned.
* <p>
* Time complexity O(1)
* @param key
* @param member
* @return Integer reply, specifically: 1 if the element is a member of the set 0 if the element
* is not a member of the set OR if the key does not exist
*/
@Override
public Boolean sismember(final String key, final String member) {
checkIsInMultiOrPipeline();
client.sismember(key, member);
return client.getIntegerReply() == 1;
}
/**
* Return the members of a set resulting from the intersection of all the sets hold at the
* specified keys. Like in {@link #lrange(String, long, long) LRANGE} the result is sent to the
* client as a multi-bulk reply (see the protocol specification for more information). If just a
* single key is specified, then this command produces the same result as
* {@link #smembers(String) SMEMBERS}. Actually SMEMBERS is just syntax sugar for SINTER.
* <p>
* Non existing keys are considered like empty sets, so if one of the keys is missing an empty set
* is returned (since the intersection with an empty set always is an empty set).
* <p>
* Time complexity O(N*M) worst case where N is the cardinality of the smallest set and M the
* number of sets
* @param keys
* @return Multi bulk reply, specifically the list of common elements.
*/
@Override
public Set<String> sinter(final String... keys) {
checkIsInMultiOrPipeline();
client.sinter(keys);
final List<String> members = client.getMultiBulkReply();
if (members == null) {
return null;
}
return SetFromList.of(members);
}
/**
* This commnad works exactly like {@link #sinter(String...) SINTER} but instead of being returned
* the resulting set is sotred as dstkey.
* <p>
* Time complexity O(N*M) worst case where N is the cardinality of the smallest set and M the
* number of sets
* @param dstkey
* @param keys
* @return Status code reply
*/
@Override
public Long sinterstore(final String dstkey, final String... keys) {
checkIsInMultiOrPipeline();
client.sinterstore(dstkey, keys);
return client.getIntegerReply();
}
/**
* Return the members of a set resulting from the union of all the sets hold at the specified
* keys. Like in {@link #lrange(String, long, long) LRANGE} the result is sent to the client as a
* multi-bulk reply (see the protocol specification for more information). If just a single key is
* specified, then this command produces the same result as {@link #smembers(String) SMEMBERS}.
* <p>
* Non existing keys are considered like empty sets.
* <p>
* Time complexity O(N) where N is the total number of elements in all the provided sets
* @param keys
* @return Multi bulk reply, specifically the list of common elements.
*/
@Override
public Set<String> sunion(final String... keys) {
checkIsInMultiOrPipeline();
client.sunion(keys);
final List<String> members = client.getMultiBulkReply();
if (members == null) {
return null;
}
return SetFromList.of(members);
}
/**
* This command works exactly like {@link #sunion(String...) SUNION} but instead of being returned
* the resulting set is stored as dstkey. Any existing value in dstkey will be over-written.
* <p>
* Time complexity O(N) where N is the total number of elements in all the provided sets
* @param dstkey
* @param keys
* @return Status code reply
*/
@Override
public Long sunionstore(final String dstkey, final String... keys) {
checkIsInMultiOrPipeline();
client.sunionstore(dstkey, keys);
return client.getIntegerReply();
}
/**
* Return the difference between the Set stored at key1 and all the Sets key2, ..., keyN
* <p>
* <b>Example:</b>
*
* <pre>
* key1 = [x, a, b, c]
* key2 = [c]
* key3 = [a, d]
* SDIFF key1,key2,key3 => [x, b]
* </pre>
*
* Non existing keys are considered like empty sets.
* <p>
* <b>Time complexity:</b>
* <p>
* O(N) with N being the total number of elements of all the sets
* @param keys
* @return Return the members of a set resulting from the difference between the first set
* provided and all the successive sets.
*/
@Override
public Set<String> sdiff(final String... keys) {
checkIsInMultiOrPipeline();
client.sdiff(keys);
return BuilderFactory.STRING_SET.build(client.getBinaryMultiBulkReply());
}
/**
* This command works exactly like {@link #sdiff(String...) SDIFF} but instead of being returned
* the resulting set is stored in dstkey.
* @param dstkey
* @param keys
* @return Status code reply
*/
@Override
public Long sdiffstore(final String dstkey, final String... keys) {
checkIsInMultiOrPipeline();
client.sdiffstore(dstkey, keys);
return client.getIntegerReply();
}
/**
* Return a random element from a Set, without removing the element. If the Set is empty or the
* key does not exist, a nil object is returned.
* <p>
* The SPOP command does a similar work but the returned element is popped (removed) from the Set.
* <p>
* Time complexity O(1)
* @param key
* @return Bulk reply
*/
@Override
public String srandmember(final String key) {
checkIsInMultiOrPipeline();
client.srandmember(key);
return client.getBulkReply();
}
@Override
public List<String> srandmember(final String key, final int count) {
checkIsInMultiOrPipeline();
client.srandmember(key, count);
return client.getMultiBulkReply();
}
/**
* Add the specified member having the specifeid score to the sorted set stored at key. If member
* is already a member of the sorted set the score is updated, and the element reinserted in the
* right position to ensure sorting. If key does not exist a new sorted set with the specified
* member as sole member is crated. If the key exists but does not hold a sorted set value an
* error is returned.
* <p>
* The score value can be the string representation of a double precision floating point number.
* <p>
* Time complexity O(log(N)) with N being the number of elements in the sorted set
* @param key
* @param score
* @param member
* @return Integer reply, specifically: 1 if the new element was added 0 if the element was
* already a member of the sorted set and the score was updated
*/
@Override
public Long zadd(final String key, final double score, final String member) {
checkIsInMultiOrPipeline();
client.zadd(key, score, member);
return client.getIntegerReply();
}
@Override
public Long zadd(final String key, final double score, final String member,
final ZAddParams params) {
checkIsInMultiOrPipeline();
client.zadd(key, score, member, params);
return client.getIntegerReply();
}
@Override
public Long zadd(final String key, final Map<String, Double> scoreMembers) {
checkIsInMultiOrPipeline();
client.zadd(key, scoreMembers);
return client.getIntegerReply();
}
@Override
public Long zadd(String key, Map<String, Double> scoreMembers, ZAddParams params) {
checkIsInMultiOrPipeline();
client.zadd(key, scoreMembers, params);
return client.getIntegerReply();
}
@Override
public Set<String> zrange(final String key, final long start, final long end) {
checkIsInMultiOrPipeline();
client.zrange(key, start, end);
final List<String> members = client.getMultiBulkReply();
if (members == null) {
return null;
}
return SetFromList.of(members);
}
/**
* Remove the specified member from the sorted set value stored at key. If member was not a member
* of the set no operation is performed. If key does not not hold a set value an error is
* returned.
* <p>
* Time complexity O(log(N)) with N being the number of elements in the sorted set
* @param key
* @param members
* @return Integer reply, specifically: 1 if the new element was removed 0 if the new element was
* not a member of the set
*/
@Override
public Long zrem(final String key, final String... members) {
checkIsInMultiOrPipeline();
client.zrem(key, members);
return client.getIntegerReply();
}
/**
* If member already exists in the sorted set adds the increment to its score and updates the
* position of the element in the sorted set accordingly. If member does not already exist in the
* sorted set it is added with increment as score (that is, like if the previous score was
* virtually zero). If key does not exist a new sorted set with the specified member as sole
* member is crated. If the key exists but does not hold a sorted set value an error is returned.
* <p>
* The score value can be the string representation of a double precision floating point number.
* It's possible to provide a negative value to perform a decrement.
* <p>
* For an introduction to sorted sets check the Introduction to Redis data types page.
* <p>
* Time complexity O(log(N)) with N being the number of elements in the sorted set
* @param key
* @param score
* @param member
* @return The new score
*/
@Override
public Double zincrby(final String key, final double score, final String member) {
checkIsInMultiOrPipeline();
client.zincrby(key, score, member);
String newscore = client.getBulkReply();
return Double.valueOf(newscore);
}
@Override
public Double zincrby(String key, double score, String member, ZIncrByParams params) {
checkIsInMultiOrPipeline();
client.zincrby(key, score, member, params);
String newscore = client.getBulkReply();
// with nx / xx options it could return null now
if (newscore == null) return null;
return Double.valueOf(newscore);
}
/**
* Return the rank (or index) or member in the sorted set at key, with scores being ordered from
* low to high.
* <p>
* When the given member does not exist in the sorted set, the special value 'nil' is returned.
* The returned rank (or index) of the member is 0-based for both commands.
* <p>
* <b>Time complexity:</b>
* <p>
* O(log(N))
* @see #zrevrank(String, String)
* @param key
* @param member
* @return Integer reply or a nil bulk reply, specifically: the rank of the element as an integer
* reply if the element exists. A nil bulk reply if there is no such element.
*/
@Override
public Long zrank(final String key, final String member) {
checkIsInMultiOrPipeline();
client.zrank(key, member);
return client.getIntegerReply();
}
/**
* Return the rank (or index) or member in the sorted set at key, with scores being ordered from
* high to low.
* <p>
* When the given member does not exist in the sorted set, the special value 'nil' is returned.
* The returned rank (or index) of the member is 0-based for both commands.
* <p>
* <b>Time complexity:</b>
* <p>
* O(log(N))
* @see #zrank(String, String)
* @param key
* @param member
* @return Integer reply or a nil bulk reply, specifically: the rank of the element as an integer
* reply if the element exists. A nil bulk reply if there is no such element.
*/
@Override
public Long zrevrank(final String key, final String member) {
checkIsInMultiOrPipeline();
client.zrevrank(key, member);
return client.getIntegerReply();
}
@Override
public Set<String> zrevrange(final String key, final long start, final long end) {
checkIsInMultiOrPipeline();
client.zrevrange(key, start, end);
final List<String> members = client.getMultiBulkReply();
if (members == null) {
return null;
}
return SetFromList.of(members);
}
@Override
public Set<Tuple> zrangeWithScores(final String key, final long start, final long end) {
checkIsInMultiOrPipeline();
client.zrangeWithScores(key, start, end);
return getTupledSet();
}
@Override
public Set<Tuple> zrevrangeWithScores(final String key, final long start, final long end) {
checkIsInMultiOrPipeline();
client.zrevrangeWithScores(key, start, end);
return getTupledSet();
}
/**
* Return the sorted set cardinality (number of elements). If the key does not exist 0 is
* returned, like for empty sorted sets.
* <p>
* Time complexity O(1)
* @param key
* @return the cardinality (number of elements) of the set as an integer.
*/
@Override
public Long zcard(final String key) {
checkIsInMultiOrPipeline();
client.zcard(key);
return client.getIntegerReply();
}
/**
* Return the score of the specified element of the sorted set at key. If the specified element
* does not exist in the sorted set, or the key does not exist at all, a special 'nil' value is
* returned.
* <p>
* <b>Time complexity:</b> O(1)
* @param key
* @param member
* @return the score
*/
@Override
public Double zscore(final String key, final String member) {
checkIsInMultiOrPipeline();
client.zscore(key, member);
final String score = client.getBulkReply();
return (score != null ? new Double(score) : null);
}
@Override
public String watch(final String... keys) {
client.watch(keys);
return client.getStatusCodeReply();
}
/**
* Sort a Set or a List.
* <p>
* Sort the elements contained in the List, Set, or Sorted Set value at key. By default sorting is
* numeric with elements being compared as double precision floating point numbers. This is the
* simplest form of SORT.
* @see #sort(String, String)
* @see #sort(String, SortingParams)
* @see #sort(String, SortingParams, String)
* @param key
* @return Assuming the Set/List at key contains a list of numbers, the return value will be the
* list of numbers ordered from the smallest to the biggest number.
*/
@Override
public List<String> sort(final String key) {
checkIsInMultiOrPipeline();
client.sort(key);
return client.getMultiBulkReply();
}
/**
* Sort a Set or a List accordingly to the specified parameters.
* <p>
* <b>examples:</b>
* <p>
* Given are the following sets and key/values:
*
* <pre>
* x = [1, 2, 3]
* y = [a, b, c]
*
* k1 = z
* k2 = y
* k3 = x
*
* w1 = 9
* w2 = 8
* w3 = 7
* </pre>
*
* Sort Order:
*
* <pre>
* sort(x) or sort(x, sp.asc())
* -> [1, 2, 3]
*
* sort(x, sp.desc())
* -> [3, 2, 1]
*
* sort(y)
* -> [c, a, b]
*
* sort(y, sp.alpha())
* -> [a, b, c]
*
* sort(y, sp.alpha().desc())
* -> [c, a, b]
* </pre>
*
* Limit (e.g. for Pagination):
*
* <pre>
* sort(x, sp.limit(0, 2))
* -> [1, 2]
*
* sort(y, sp.alpha().desc().limit(1, 2))
* -> [b, a]
* </pre>
*
* Sorting by external keys:
*
* <pre>
* sort(x, sb.by(w*))
* -> [3, 2, 1]
*
* sort(x, sb.by(w*).desc())
* -> [1, 2, 3]
* </pre>
*
* Getting external keys:
*
* <pre>
* sort(x, sp.by(w*).get(k*))
* -> [x, y, z]
*
* sort(x, sp.by(w*).get(#).get(k*))
* -> [3, x, 2, y, 1, z]
* </pre>
* @see #sort(String)
* @see #sort(String, SortingParams, String)
* @param key
* @param sortingParameters
* @return a list of sorted elements.
*/
@Override
public List<String> sort(final String key, final SortingParams sortingParameters) {
checkIsInMultiOrPipeline();
client.sort(key, sortingParameters);
return client.getMultiBulkReply();
}
/**
* BLPOP (and BRPOP) is a blocking list pop primitive. You can see this commands as blocking
* versions of LPOP and RPOP able to block if the specified keys don't exist or contain empty
* lists.
* <p>
* The following is a description of the exact semantic. We describe BLPOP but the two commands
* are identical, the only difference is that BLPOP pops the element from the left (head) of the
* list, and BRPOP pops from the right (tail).
* <p>
* <b>Non blocking behavior</b>
* <p>
* When BLPOP is called, if at least one of the specified keys contain a non empty list, an
* element is popped from the head of the list and returned to the caller together with the name
* of the key (BLPOP returns a two elements array, the first element is the key, the second the
* popped value).
* <p>
* Keys are scanned from left to right, so for instance if you issue BLPOP list1 list2 list3 0
* against a dataset where list1 does not exist but list2 and list3 contain non empty lists, BLPOP
* guarantees to return an element from the list stored at list2 (since it is the first non empty
* list starting from the left).
* <p>
* <b>Blocking behavior</b>
* <p>
* If none of the specified keys exist or contain non empty lists, BLPOP blocks until some other
* client performs a LPUSH or an RPUSH operation against one of the lists.
* <p>
* Once new data is present on one of the lists, the client finally returns with the name of the
* key unblocking it and the popped value.
* <p>
* When blocking, if a non-zero timeout is specified, the client will unblock returning a nil
* special value if the specified amount of seconds passed without a push operation against at
* least one of the specified keys.
* <p>
* The timeout argument is interpreted as an integer value. A timeout of zero means instead to
* block forever.
* <p>
* <b>Multiple clients blocking for the same keys</b>
* <p>
* Multiple clients can block for the same key. They are put into a queue, so the first to be
* served will be the one that started to wait earlier, in a first-blpopping first-served fashion.
* <p>
* <b>blocking POP inside a MULTI/EXEC transaction</b>
* <p>
* BLPOP and BRPOP can be used with pipelining (sending multiple commands and reading the replies
* in batch), but it does not make sense to use BLPOP or BRPOP inside a MULTI/EXEC block (a Redis
* transaction).
* <p>
* The behavior of BLPOP inside MULTI/EXEC when the list is empty is to return a multi-bulk nil
* reply, exactly what happens when the timeout is reached. If you like science fiction, think at
* it like if inside MULTI/EXEC the time will flow at infinite speed :)
* <p>
* Time complexity: O(1)
* @see #brpop(int, String...)
* @param timeout
* @param keys
* @return BLPOP returns a two-elements array via a multi bulk reply in order to return both the
* unblocking key and the popped value.
* <p>
* When a non-zero timeout is specified, and the BLPOP operation timed out, the return
* value is a nil multi bulk reply. Most client values will return false or nil
* accordingly to the programming language used.
*/
@Override
public List<String> blpop(final int timeout, final String... keys) {
return blpop(getArgsAddTimeout(timeout, keys));
}
private String[] getArgsAddTimeout(int timeout, String[] keys) {
final int keyCount = keys.length;
final String[] args = new String[keyCount + 1];
for (int at = 0; at != keyCount; ++at) {
args[at] = keys[at];
}
args[keyCount] = String.valueOf(timeout);
return args;
}
@Override
public List<String> blpop(String... args) {
checkIsInMultiOrPipeline();
client.blpop(args);
client.setTimeoutInfinite();
try {
return client.getMultiBulkReply();
} finally {
client.rollbackTimeout();
}
}
@Override
public List<String> brpop(String... args) {
checkIsInMultiOrPipeline();
client.brpop(args);
client.setTimeoutInfinite();
try {
return client.getMultiBulkReply();
} finally {
client.rollbackTimeout();
}
}
/**
* Sort a Set or a List accordingly to the specified parameters and store the result at dstkey.
* @see #sort(String, SortingParams)
* @see #sort(String)
* @see #sort(String, String)
* @param key
* @param sortingParameters
* @param dstkey
* @return The number of elements of the list at dstkey.
*/
@Override
public Long sort(final String key, final SortingParams sortingParameters, final String dstkey) {
checkIsInMultiOrPipeline();
client.sort(key, sortingParameters, dstkey);
return client.getIntegerReply();
}
/**
* Sort a Set or a List and Store the Result at dstkey.
* <p>
* Sort the elements contained in the List, Set, or Sorted Set value at key and store the result
* at dstkey. By default sorting is numeric with elements being compared as double precision
* floating point numbers. This is the simplest form of SORT.
* @see #sort(String)
* @see #sort(String, SortingParams)
* @see #sort(String, SortingParams, String)
* @param key
* @param dstkey
* @return The number of elements of the list at dstkey.
*/
@Override
public Long sort(final String key, final String dstkey) {
checkIsInMultiOrPipeline();
client.sort(key, dstkey);
return client.getIntegerReply();
}
/**
* BLPOP (and BRPOP) is a blocking list pop primitive. You can see this commands as blocking
* versions of LPOP and RPOP able to block if the specified keys don't exist or contain empty
* lists.
* <p>
* The following is a description of the exact semantic. We describe BLPOP but the two commands
* are identical, the only difference is that BLPOP pops the element from the left (head) of the
* list, and BRPOP pops from the right (tail).
* <p>
* <b>Non blocking behavior</b>
* <p>
* When BLPOP is called, if at least one of the specified keys contain a non empty list, an
* element is popped from the head of the list and returned to the caller together with the name
* of the key (BLPOP returns a two elements array, the first element is the key, the second the
* popped value).
* <p>
* Keys are scanned from left to right, so for instance if you issue BLPOP list1 list2 list3 0
* against a dataset where list1 does not exist but list2 and list3 contain non empty lists, BLPOP
* guarantees to return an element from the list stored at list2 (since it is the first non empty
* list starting from the left).
* <p>
* <b>Blocking behavior</b>
* <p>
* If none of the specified keys exist or contain non empty lists, BLPOP blocks until some other
* client performs a LPUSH or an RPUSH operation against one of the lists.
* <p>
* Once new data is present on one of the lists, the client finally returns with the name of the
* key unblocking it and the popped value.
* <p>
* When blocking, if a non-zero timeout is specified, the client will unblock returning a nil
* special value if the specified amount of seconds passed without a push operation against at
* least one of the specified keys.
* <p>
* The timeout argument is interpreted as an integer value. A timeout of zero means instead to
* block forever.
* <p>
* <b>Multiple clients blocking for the same keys</b>
* <p>
* Multiple clients can block for the same key. They are put into a queue, so the first to be
* served will be the one that started to wait earlier, in a first-blpopping first-served fashion.
* <p>
* <b>blocking POP inside a MULTI/EXEC transaction</b>
* <p>
* BLPOP and BRPOP can be used with pipelining (sending multiple commands and reading the replies
* in batch), but it does not make sense to use BLPOP or BRPOP inside a MULTI/EXEC block (a Redis
* transaction).
* <p>
* The behavior of BLPOP inside MULTI/EXEC when the list is empty is to return a multi-bulk nil
* reply, exactly what happens when the timeout is reached. If you like science fiction, think at
* it like if inside MULTI/EXEC the time will flow at infinite speed :)
* <p>
* Time complexity: O(1)
* @see #blpop(int, String...)
* @param timeout
* @param keys
* @return BLPOP returns a two-elements array via a multi bulk reply in order to return both the
* unblocking key and the popped value.
* <p>
* When a non-zero timeout is specified, and the BLPOP operation timed out, the return
* value is a nil multi bulk reply. Most client values will return false or nil
* accordingly to the programming language used.
*/
@Override
public List<String> brpop(final int timeout, final String... keys) {
return brpop(getArgsAddTimeout(timeout, keys));
}
@Override
public Long zcount(final String key, final double min, final double max) {
checkIsInMultiOrPipeline();
client.zcount(key, min, max);
return client.getIntegerReply();
}
@Override
public Long zcount(final String key, final String min, final String max) {
checkIsInMultiOrPipeline();
client.zcount(key, min, max);
return client.getIntegerReply();
}
/**
* Return the all the elements in the sorted set at key with a score between min and max
* (including elements with score equal to min or max).
* <p>
* The elements having the same score are returned sorted lexicographically as ASCII strings (this
* follows from a property of Redis sorted sets and does not involve further computation).
* <p>
* Using the optional {@link #zrangeByScore(String, double, double, int, int) LIMIT} it's possible
* to get only a range of the matching elements in an SQL-alike way. Note that if offset is large
* the commands needs to traverse the list for offset elements and this adds up to the O(M)
* figure.
* <p>
* The {@link #zcount(String, double, double) ZCOUNT} command is similar to
* {@link #zrangeByScore(String, double, double) ZRANGEBYSCORE} but instead of returning the
* actual elements in the specified interval, it just returns the number of matching elements.
* <p>
* <b>Exclusive intervals and infinity</b>
* <p>
* min and max can be -inf and +inf, so that you are not required to know what's the greatest or
* smallest element in order to take, for instance, elements "up to a given value".
* <p>
* Also while the interval is for default closed (inclusive) it's possible to specify open
* intervals prefixing the score with a "(" character, so for instance:
* <p>
* {@code ZRANGEBYSCORE zset (1.3 5}
* <p>
* Will return all the values with score > 1.3 and <= 5, while for instance:
* <p>
* {@code ZRANGEBYSCORE zset (5 (10}
* <p>
* Will return all the values with score > 5 and < 10 (5 and 10 excluded).
* <p>
* <b>Time complexity:</b>
* <p>
* O(log(N))+O(M) with N being the number of elements in the sorted set and M the number of
* elements returned by the command, so if M is constant (for instance you always ask for the
* first ten elements with LIMIT) you can consider it O(log(N))
* @see #zrangeByScore(String, double, double)
* @see #zrangeByScore(String, double, double, int, int)
* @see #zrangeByScoreWithScores(String, double, double)
* @see #zrangeByScoreWithScores(String, String, String)
* @see #zrangeByScoreWithScores(String, double, double, int, int)
* @see #zcount(String, double, double)
* @param key
* @param min a double or Double.MIN_VALUE for "-inf"
* @param max a double or Double.MAX_VALUE for "+inf"
* @return Multi bulk reply specifically a list of elements in the specified score range.
*/
@Override
public Set<String> zrangeByScore(final String key, final double min, final double max) {
checkIsInMultiOrPipeline();
client.zrangeByScore(key, min, max);
final List<String> members = client.getMultiBulkReply();
if (members == null) {
return null;
}
return SetFromList.of(members);
}
@Override
public Set<String> zrangeByScore(final String key, final String min, final String max) {
checkIsInMultiOrPipeline();
client.zrangeByScore(key, min, max);
final List<String> members = client.getMultiBulkReply();
if (members == null) {
return null;
}
return SetFromList.of(members);
}
/**
* Return the all the elements in the sorted set at key with a score between min and max
* (including elements with score equal to min or max).
* <p>
* The elements having the same score are returned sorted lexicographically as ASCII strings (this
* follows from a property of Redis sorted sets and does not involve further computation).
* <p>
* Using the optional {@link #zrangeByScore(String, double, double, int, int) LIMIT} it's possible
* to get only a range of the matching elements in an SQL-alike way. Note that if offset is large
* the commands needs to traverse the list for offset elements and this adds up to the O(M)
* figure.
* <p>
* The {@link #zcount(String, double, double) ZCOUNT} command is similar to
* {@link #zrangeByScore(String, double, double) ZRANGEBYSCORE} but instead of returning the
* actual elements in the specified interval, it just returns the number of matching elements.
* <p>
* <b>Exclusive intervals and infinity</b>
* <p>
* min and max can be -inf and +inf, so that you are not required to know what's the greatest or
* smallest element in order to take, for instance, elements "up to a given value".
* <p>
* Also while the interval is for default closed (inclusive) it's possible to specify open
* intervals prefixing the score with a "(" character, so for instance:
* <p>
* {@code ZRANGEBYSCORE zset (1.3 5}
* <p>
* Will return all the values with score > 1.3 and <= 5, while for instance:
* <p>
* {@code ZRANGEBYSCORE zset (5 (10}
* <p>
* Will return all the values with score > 5 and < 10 (5 and 10 excluded).
* <p>
* <b>Time complexity:</b>
* <p>
* O(log(N))+O(M) with N being the number of elements in the sorted set and M the number of
* elements returned by the command, so if M is constant (for instance you always ask for the
* first ten elements with LIMIT) you can consider it O(log(N))
* @see #zrangeByScore(String, double, double)
* @see #zrangeByScore(String, double, double, int, int)
* @see #zrangeByScoreWithScores(String, double, double)
* @see #zrangeByScoreWithScores(String, double, double, int, int)
* @see #zcount(String, double, double)
* @param key
* @param min
* @param max
* @return Multi bulk reply specifically a list of elements in the specified score range.
*/
@Override
public Set<String> zrangeByScore(final String key, final double min, final double max,
final int offset, final int count) {
checkIsInMultiOrPipeline();
client.zrangeByScore(key, min, max, offset, count);
final List<String> members = client.getMultiBulkReply();
if (members == null) {
return null;
}
return SetFromList.of(members);
}
@Override
public Set<String> zrangeByScore(final String key, final String min, final String max,
final int offset, final int count) {
checkIsInMultiOrPipeline();
client.zrangeByScore(key, min, max, offset, count);
final List<String> members = client.getMultiBulkReply();
if (members == null) {
return null;
}
return SetFromList.of(members);
}
/**
* Return the all the elements in the sorted set at key with a score between min and max
* (including elements with score equal to min or max).
* <p>
* The elements having the same score are returned sorted lexicographically as ASCII strings (this
* follows from a property of Redis sorted sets and does not involve further computation).
* <p>
* Using the optional {@link #zrangeByScore(String, double, double, int, int) LIMIT} it's possible
* to get only a range of the matching elements in an SQL-alike way. Note that if offset is large
* the commands needs to traverse the list for offset elements and this adds up to the O(M)
* figure.
* <p>
* The {@link #zcount(String, double, double) ZCOUNT} command is similar to
* {@link #zrangeByScore(String, double, double) ZRANGEBYSCORE} but instead of returning the
* actual elements in the specified interval, it just returns the number of matching elements.
* <p>
* <b>Exclusive intervals and infinity</b>
* <p>
* min and max can be -inf and +inf, so that you are not required to know what's the greatest or
* smallest element in order to take, for instance, elements "up to a given value".
* <p>
* Also while the interval is for default closed (inclusive) it's possible to specify open
* intervals prefixing the score with a "(" character, so for instance:
* <p>
* {@code ZRANGEBYSCORE zset (1.3 5}
* <p>
* Will return all the values with score > 1.3 and <= 5, while for instance:
* <p>
* {@code ZRANGEBYSCORE zset (5 (10}
* <p>
* Will return all the values with score > 5 and < 10 (5 and 10 excluded).
* <p>
* <b>Time complexity:</b>
* <p>
* O(log(N))+O(M) with N being the number of elements in the sorted set and M the number of
* elements returned by the command, so if M is constant (for instance you always ask for the
* first ten elements with LIMIT) you can consider it O(log(N))
* @see #zrangeByScore(String, double, double)
* @see #zrangeByScore(String, double, double, int, int)
* @see #zrangeByScoreWithScores(String, double, double)
* @see #zrangeByScoreWithScores(String, double, double, int, int)
* @see #zcount(String, double, double)
* @param key
* @param min
* @param max
* @return Multi bulk reply specifically a list of elements in the specified score range.
*/
@Override
public Set<Tuple> zrangeByScoreWithScores(final String key, final double min, final double max) {
checkIsInMultiOrPipeline();
client.zrangeByScoreWithScores(key, min, max);
return getTupledSet();
}
@Override
public Set<Tuple> zrangeByScoreWithScores(final String key, final String min, final String max) {
checkIsInMultiOrPipeline();
client.zrangeByScoreWithScores(key, min, max);
return getTupledSet();
}
/**
* Return the all the elements in the sorted set at key with a score between min and max
* (including elements with score equal to min or max).
* <p>
* The elements having the same score are returned sorted lexicographically as ASCII strings (this
* follows from a property of Redis sorted sets and does not involve further computation).
* <p>
* Using the optional {@link #zrangeByScore(String, double, double, int, int) LIMIT} it's possible
* to get only a range of the matching elements in an SQL-alike way. Note that if offset is large
* the commands needs to traverse the list for offset elements and this adds up to the O(M)
* figure.
* <p>
* The {@link #zcount(String, double, double) ZCOUNT} command is similar to
* {@link #zrangeByScore(String, double, double) ZRANGEBYSCORE} but instead of returning the
* actual elements in the specified interval, it just returns the number of matching elements.
* <p>
* <b>Exclusive intervals and infinity</b>
* <p>
* min and max can be -inf and +inf, so that you are not required to know what's the greatest or
* smallest element in order to take, for instance, elements "up to a given value".
* <p>
* Also while the interval is for default closed (inclusive) it's possible to specify open
* intervals prefixing the score with a "(" character, so for instance:
* <p>
* {@code ZRANGEBYSCORE zset (1.3 5}
* <p>
* Will return all the values with score > 1.3 and <= 5, while for instance:
* <p>
* {@code ZRANGEBYSCORE zset (5 (10}
* <p>
* Will return all the values with score > 5 and < 10 (5 and 10 excluded).
* <p>
* <b>Time complexity:</b>
* <p>
* O(log(N))+O(M) with N being the number of elements in the sorted set and M the number of
* elements returned by the command, so if M is constant (for instance you always ask for the
* first ten elements with LIMIT) you can consider it O(log(N))
* @see #zrangeByScore(String, double, double)
* @see #zrangeByScore(String, double, double, int, int)
* @see #zrangeByScoreWithScores(String, double, double)
* @see #zrangeByScoreWithScores(String, double, double, int, int)
* @see #zcount(String, double, double)
* @param key
* @param min
* @param max
* @return Multi bulk reply specifically a list of elements in the specified score range.
*/
@Override
public Set<Tuple> zrangeByScoreWithScores(final String key, final double min, final double max,
final int offset, final int count) {
checkIsInMultiOrPipeline();
client.zrangeByScoreWithScores(key, min, max, offset, count);
return getTupledSet();
}
@Override
public Set<Tuple> zrangeByScoreWithScores(final String key, final String min, final String max,
final int offset, final int count) {
checkIsInMultiOrPipeline();
client.zrangeByScoreWithScores(key, min, max, offset, count);
return getTupledSet();
}
private Set<Tuple> getTupledSet() {
checkIsInMultiOrPipeline();
List<String> membersWithScores = client.getMultiBulkReply();
if (membersWithScores == null) {
return null;
}
if (membersWithScores.size() == 0) {
return Collections.emptySet();
}
Set<Tuple> set = new LinkedHashSet<Tuple>(membersWithScores.size() / 2, 1.0f);
Iterator<String> iterator = membersWithScores.iterator();
while (iterator.hasNext()) {
set.add(new Tuple(iterator.next(), Double.valueOf(iterator.next())));
}
return set;
}
@Override
public Set<String> zrevrangeByScore(final String key, final double max, final double min) {
checkIsInMultiOrPipeline();
client.zrevrangeByScore(key, max, min);
final List<String> members = client.getMultiBulkReply();
if (members == null) {
return null;
}
return SetFromList.of(members);
}
@Override
public Set<String> zrevrangeByScore(final String key, final String max, final String min) {
checkIsInMultiOrPipeline();
client.zrevrangeByScore(key, max, min);
final List<String> members = client.getMultiBulkReply();
if (members == null) {
return null;
}
return SetFromList.of(members);
}
@Override
public Set<String> zrevrangeByScore(final String key, final double max, final double min,
final int offset, final int count) {
checkIsInMultiOrPipeline();
client.zrevrangeByScore(key, max, min, offset, count);
final List<String> members = client.getMultiBulkReply();
if (members == null) {
return null;
}
return SetFromList.of(members);
}
@Override
public Set<Tuple> zrevrangeByScoreWithScores(final String key, final double max, final double min) {
checkIsInMultiOrPipeline();
client.zrevrangeByScoreWithScores(key, max, min);
return getTupledSet();
}
@Override
public Set<Tuple> zrevrangeByScoreWithScores(final String key, final double max,
final double min, final int offset, final int count) {
checkIsInMultiOrPipeline();
client.zrevrangeByScoreWithScores(key, max, min, offset, count);
return getTupledSet();
}
@Override
public Set<Tuple> zrevrangeByScoreWithScores(final String key, final String max,
final String min, final int offset, final int count) {
checkIsInMultiOrPipeline();
client.zrevrangeByScoreWithScores(key, max, min, offset, count);
return getTupledSet();
}
@Override
public Set<String> zrevrangeByScore(final String key, final String max, final String min,
final int offset, final int count) {
checkIsInMultiOrPipeline();
client.zrevrangeByScore(key, max, min, offset, count);
final List<String> members = client.getMultiBulkReply();
if (members == null) {
return null;
}
return SetFromList.of(members);
}
@Override
public Set<Tuple> zrevrangeByScoreWithScores(final String key, final String max, final String min) {
checkIsInMultiOrPipeline();
client.zrevrangeByScoreWithScores(key, max, min);
return getTupledSet();
}
/**
* Remove all elements in the sorted set at key with rank between start and end. Start and end are
* 0-based with rank 0 being the element with the lowest score. Both start and end can be negative
* numbers, where they indicate offsets starting at the element with the highest rank. For
* example: -1 is the element with the highest score, -2 the element with the second highest score
* and so forth.
* <p>
* <b>Time complexity:</b> O(log(N))+O(M) with N being the number of elements in the sorted set
* and M the number of elements removed by the operation
*/
@Override
public Long zremrangeByRank(final String key, final long start, final long end) {
checkIsInMultiOrPipeline();
client.zremrangeByRank(key, start, end);
return client.getIntegerReply();
}
/**
* Remove all the elements in the sorted set at key with a score between min and max (including
* elements with score equal to min or max).
* <p>
* <b>Time complexity:</b>
* <p>
* O(log(N))+O(M) with N being the number of elements in the sorted set and M the number of
* elements removed by the operation
* @param key
* @param start
* @param end
* @return Integer reply, specifically the number of elements removed.
*/
@Override
public Long zremrangeByScore(final String key, final double start, final double end) {
checkIsInMultiOrPipeline();
client.zremrangeByScore(key, start, end);
return client.getIntegerReply();
}
@Override
public Long zremrangeByScore(final String key, final String start, final String end) {
checkIsInMultiOrPipeline();
client.zremrangeByScore(key, start, end);
return client.getIntegerReply();
}
/**
* Creates a union or intersection of N sorted sets given by keys k1 through kN, and stores it at
* dstkey. It is mandatory to provide the number of input keys N, before passing the input keys
* and the other (optional) arguments.
* <p>
* As the terms imply, the {@link #zinterstore(String, String...) ZINTERSTORE} command requires an
* element to be present in each of the given inputs to be inserted in the result. The
* {@link #zunionstore(String, String...) ZUNIONSTORE} command inserts all elements across all
* inputs.
* <p>
* Using the WEIGHTS option, it is possible to add weight to each input sorted set. This means
* that the score of each element in the sorted set is first multiplied by this weight before
* being passed to the aggregation. When this option is not given, all weights default to 1.
* <p>
* With the AGGREGATE option, it's possible to specify how the results of the union or
* intersection are aggregated. This option defaults to SUM, where the score of an element is
* summed across the inputs where it exists. When this option is set to be either MIN or MAX, the
* resulting set will contain the minimum or maximum score of an element across the inputs where
* it exists.
* <p>
* <b>Time complexity:</b> O(N) + O(M log(M)) with N being the sum of the sizes of the input
* sorted sets, and M being the number of elements in the resulting sorted set
* @see #zunionstore(String, String...)
* @see #zunionstore(String, ZParams, String...)
* @see #zinterstore(String, String...)
* @see #zinterstore(String, ZParams, String...)
* @param dstkey
* @param sets
* @return Integer reply, specifically the number of elements in the sorted set at dstkey
*/
@Override
public Long zunionstore(final String dstkey, final String... sets) {
checkIsInMultiOrPipeline();
client.zunionstore(dstkey, sets);
return client.getIntegerReply();
}
/**
* Creates a union or intersection of N sorted sets given by keys k1 through kN, and stores it at
* dstkey. It is mandatory to provide the number of input keys N, before passing the input keys
* and the other (optional) arguments.
* <p>
* As the terms imply, the {@link #zinterstore(String, String...) ZINTERSTORE} command requires an
* element to be present in each of the given inputs to be inserted in the result. The
* {@link #zunionstore(String, String...) ZUNIONSTORE} command inserts all elements across all
* inputs.
* <p>
* Using the WEIGHTS option, it is possible to add weight to each input sorted set. This means
* that the score of each element in the sorted set is first multiplied by this weight before
* being passed to the aggregation. When this option is not given, all weights default to 1.
* <p>
* With the AGGREGATE option, it's possible to specify how the results of the union or
* intersection are aggregated. This option defaults to SUM, where the score of an element is
* summed across the inputs where it exists. When this option is set to be either MIN or MAX, the
* resulting set will contain the minimum or maximum score of an element across the inputs where
* it exists.
* <p>
* <b>Time complexity:</b> O(N) + O(M log(M)) with N being the sum of the sizes of the input
* sorted sets, and M being the number of elements in the resulting sorted set
* @see #zunionstore(String, String...)
* @see #zunionstore(String, ZParams, String...)
* @see #zinterstore(String, String...)
* @see #zinterstore(String, ZParams, String...)
* @param dstkey
* @param sets
* @param params
* @return Integer reply, specifically the number of elements in the sorted set at dstkey
*/
@Override
public Long zunionstore(final String dstkey, final ZParams params, final String... sets) {
checkIsInMultiOrPipeline();
client.zunionstore(dstkey, params, sets);
return client.getIntegerReply();
}
/**
* Creates a union or intersection of N sorted sets given by keys k1 through kN, and stores it at
* dstkey. It is mandatory to provide the number of input keys N, before passing the input keys
* and the other (optional) arguments.
* <p>
* As the terms imply, the {@link #zinterstore(String, String...) ZINTERSTORE} command requires an
* element to be present in each of the given inputs to be inserted in the result. The
* {@link #zunionstore(String, String...) ZUNIONSTORE} command inserts all elements across all
* inputs.
* <p>
* Using the WEIGHTS option, it is possible to add weight to each input sorted set. This means
* that the score of each element in the sorted set is first multiplied by this weight before
* being passed to the aggregation. When this option is not given, all weights default to 1.
* <p>
* With the AGGREGATE option, it's possible to specify how the results of the union or
* intersection are aggregated. This option defaults to SUM, where the score of an element is
* summed across the inputs where it exists. When this option is set to be either MIN or MAX, the
* resulting set will contain the minimum or maximum score of an element across the inputs where
* it exists.
* <p>
* <b>Time complexity:</b> O(N) + O(M log(M)) with N being the sum of the sizes of the input
* sorted sets, and M being the number of elements in the resulting sorted set
* @see #zunionstore(String, String...)
* @see #zunionstore(String, ZParams, String...)
* @see #zinterstore(String, String...)
* @see #zinterstore(String, ZParams, String...)
* @param dstkey
* @param sets
* @return Integer reply, specifically the number of elements in the sorted set at dstkey
*/
@Override
public Long zinterstore(final String dstkey, final String... sets) {
checkIsInMultiOrPipeline();
client.zinterstore(dstkey, sets);
return client.getIntegerReply();
}
/**
* Creates a union or intersection of N sorted sets given by keys k1 through kN, and stores it at
* dstkey. It is mandatory to provide the number of input keys N, before passing the input keys
* and the other (optional) arguments.
* <p>
* As the terms imply, the {@link #zinterstore(String, String...) ZINTERSTORE} command requires an
* element to be present in each of the given inputs to be inserted in the result. The
* {@link #zunionstore(String, String...) ZUNIONSTORE} command inserts all elements across all
* inputs.
* <p>
* Using the WEIGHTS option, it is possible to add weight to each input sorted set. This means
* that the score of each element in the sorted set is first multiplied by this weight before
* being passed to the aggregation. When this option is not given, all weights default to 1.
* <p>
* With the AGGREGATE option, it's possible to specify how the results of the union or
* intersection are aggregated. This option defaults to SUM, where the score of an element is
* summed across the inputs where it exists. When this option is set to be either MIN or MAX, the
* resulting set will contain the minimum or maximum score of an element across the inputs where
* it exists.
* <p>
* <b>Time complexity:</b> O(N) + O(M log(M)) with N being the sum of the sizes of the input
* sorted sets, and M being the number of elements in the resulting sorted set
* @see #zunionstore(String, String...)
* @see #zunionstore(String, ZParams, String...)
* @see #zinterstore(String, String...)
* @see #zinterstore(String, ZParams, String...)
* @param dstkey
* @param sets
* @param params
* @return Integer reply, specifically the number of elements in the sorted set at dstkey
*/
@Override
public Long zinterstore(final String dstkey, final ZParams params, final String... sets) {
checkIsInMultiOrPipeline();
client.zinterstore(dstkey, params, sets);
return client.getIntegerReply();
}
@Override
public Long zlexcount(final String key, final String min, final String max) {
checkIsInMultiOrPipeline();
client.zlexcount(key, min, max);
return client.getIntegerReply();
}
@Override
public Set<String> zrangeByLex(final String key, final String min, final String max) {
checkIsInMultiOrPipeline();
client.zrangeByLex(key, min, max);
final List<String> members = client.getMultiBulkReply();
if (members == null) {
return null;
}
return SetFromList.of(members);
}
@Override
public Set<String> zrangeByLex(final String key, final String min, final String max,
final int offset, final int count) {
checkIsInMultiOrPipeline();
client.zrangeByLex(key, min, max, offset, count);
final List<String> members = client.getMultiBulkReply();
if (members == null) {
return null;
}
return SetFromList.of(members);
}
@Override
public Set<String> zrevrangeByLex(String key, String max, String min) {
checkIsInMultiOrPipeline();
client.zrevrangeByLex(key, max, min);
final List<String> members = client.getMultiBulkReply();
if (members == null) {
return null;
}
return SetFromList.of(members);
}
@Override
public Set<String> zrevrangeByLex(String key, String max, String min, int offset, int count) {
checkIsInMultiOrPipeline();
client.zrevrangeByLex(key, max, min, offset, count);
final List<String> members = client.getMultiBulkReply();
if (members == null) {
return null;
}
return SetFromList.of(members);
}
@Override
public Long zremrangeByLex(final String key, final String min, final String max) {
checkIsInMultiOrPipeline();
client.zremrangeByLex(key, min, max);
return client.getIntegerReply();
}
@Override
public Long strlen(final String key) {
client.strlen(key);
return client.getIntegerReply();
}
@Override
public Long lpushx(final String key, final String... string) {
client.lpushx(key, string);
return client.getIntegerReply();
}
/**
* Undo a {@link #expire(String, int) expire} at turning the expire key into a normal key.
* <p>
* Time complexity: O(1)
* @param key
* @return Integer reply, specifically: 1: the key is now persist. 0: the key is not persist (only
* happens when key not set).
*/
@Override
public Long persist(final String key) {
client.persist(key);
return client.getIntegerReply();
}
@Override
public Long rpushx(final String key, final String... string) {
client.rpushx(key, string);
return client.getIntegerReply();
}
@Override
public String echo(final String string) {
client.echo(string);
return client.getBulkReply();
}
@Override
public Long linsert(final String key, final LIST_POSITION where, final String pivot,
final String value) {
client.linsert(key, where, pivot, value);
return client.getIntegerReply();
}
/**
* Pop a value from a list, push it to another list and return it; or block until one is available
* @param source
* @param destination
* @param timeout
* @return the element
*/
@Override
public String brpoplpush(String source, String destination, int timeout) {
client.brpoplpush(source, destination, timeout);
client.setTimeoutInfinite();
try {
return client.getBulkReply();
} finally {
client.rollbackTimeout();
}
}
/**
* Sets or clears the bit at offset in the string value stored at key
* @param key
* @param offset
* @param value
* @return
*/
@Override
public Boolean setbit(String key, long offset, boolean value) {
client.setbit(key, offset, value);
return client.getIntegerReply() == 1;
}
@Override
public Boolean setbit(String key, long offset, String value) {
client.setbit(key, offset, value);
return client.getIntegerReply() == 1;
}
/**
* Returns the bit value at offset in the string value stored at key
* @param key
* @param offset
* @return
*/
@Override
public Boolean getbit(String key, long offset) {
client.getbit(key, offset);
return client.getIntegerReply() == 1;
}
@Override
public Long setrange(String key, long offset, String value) {
client.setrange(key, offset, value);
return client.getIntegerReply();
}
@Override
public String getrange(String key, long startOffset, long endOffset) {
client.getrange(key, startOffset, endOffset);
return client.getBulkReply();
}
@Override
public Long bitpos(final String key, final boolean value) {
return bitpos(key, value, new BitPosParams());
}
@Override
public Long bitpos(final String key, final boolean value, final BitPosParams params) {
client.bitpos(key, value, params);
return client.getIntegerReply();
}
/**
* Retrieve the configuration of a running Redis server. Not all the configuration parameters are
* supported.
* <p>
* CONFIG GET returns the current configuration parameters. This sub command only accepts a single
* argument, that is glob style pattern. All the configuration parameters matching this parameter
* are reported as a list of key-value pairs.
* <p>
* <b>Example:</b>
*
* <pre>
* $ redis-cli config get '*'
* 1. "dbfilename"
* 2. "dump.rdb"
* 3. "requirepass"
* 4. (nil)
* 5. "masterauth"
* 6. (nil)
* 7. "maxmemory"
* 8. "0\n"
* 9. "appendfsync"
* 10. "everysec"
* 11. "save"
* 12. "3600 1 300 100 60 10000"
*
* $ redis-cli config get 'm*'
* 1. "masterauth"
* 2. (nil)
* 3. "maxmemory"
* 4. "0\n"
* </pre>
* @param pattern
* @return Bulk reply.
*/
@Override
public List<String> configGet(final String pattern) {
client.configGet(pattern);
return client.getMultiBulkReply();
}
/**
* Alter the configuration of a running Redis server. Not all the configuration parameters are
* supported.
* <p>
* The list of configuration parameters supported by CONFIG SET can be obtained issuing a
* {@link #configGet(String) CONFIG GET *} command.
* <p>
* The configuration set using CONFIG SET is immediately loaded by the Redis server that will
* start acting as specified starting from the next command.
* <p>
* <b>Parameters value format</b>
* <p>
* The value of the configuration parameter is the same as the one of the same parameter in the
* Redis configuration file, with the following exceptions:
* <p>
* <ul>
* <li>The save paramter is a list of space-separated integers. Every pair of integers specify the
* time and number of changes limit to trigger a save. For instance the command CONFIG SET save
* "3600 10 60 10000" will configure the server to issue a background saving of the RDB file every
* 3600 seconds if there are at least 10 changes in the dataset, and every 60 seconds if there are
* at least 10000 changes. To completely disable automatic snapshots just set the parameter as an
* empty string.
* <li>All the integer parameters representing memory are returned and accepted only using bytes
* as unit.
* </ul>
* @param parameter
* @param value
* @return Status code reply
*/
@Override
public String configSet(final String parameter, final String value) {
client.configSet(parameter, value);
return client.getStatusCodeReply();
}
@Override
public Object eval(String script, int keyCount, String... params) {
client.setTimeoutInfinite();
try {
client.eval(script, keyCount, params);
return getEvalResult();
} finally {
client.rollbackTimeout();
}
}
@Override
public void subscribe(final JedisPubSub jedisPubSub, final String... channels) {
client.setTimeoutInfinite();
try {
jedisPubSub.proceed(client, channels);
} finally {
client.rollbackTimeout();
}
}
@Override
public Long publish(final String channel, final String message) {
checkIsInMultiOrPipeline();
connect();
client.publish(channel, message);
return client.getIntegerReply();
}
@Override
public void psubscribe(final JedisPubSub jedisPubSub, final String... patterns) {
checkIsInMultiOrPipeline();
client.setTimeoutInfinite();
try {
jedisPubSub.proceedWithPatterns(client, patterns);
} finally {
client.rollbackTimeout();
}
}
protected static String[] getParams(List<String> keys, List<String> args) {
int keyCount = keys.size();
int argCount = args.size();
String[] params = new String[keyCount + args.size()];
for (int i = 0; i < keyCount; i++)
params[i] = keys.get(i);
for (int i = 0; i < argCount; i++)
params[keyCount + i] = args.get(i);
return params;
}
@Override
public Object eval(String script, List<String> keys, List<String> args) {
return eval(script, keys.size(), getParams(keys, args));
}
@Override
public Object eval(String script) {
return eval(script, 0);
}
@Override
public Object evalsha(String script) {
return evalsha(script, 0);
}
private Object getEvalResult() {
return evalResult(client.getOne());
}
private Object evalResult(Object result) {
if (result instanceof byte[]) return SafeEncoder.encode((byte[]) result);
if (result instanceof List<?>) {
List<?> list = (List<?>) result;
List<Object> listResult = new ArrayList<Object>(list.size());
for (Object bin : list) {
listResult.add(evalResult(bin));
}
return listResult;
}
return result;
}
@Override
public Object evalsha(String sha1, List<String> keys, List<String> args) {
return evalsha(sha1, keys.size(), getParams(keys, args));
}
@Override
public Object evalsha(String sha1, int keyCount, String... params) {
checkIsInMultiOrPipeline();
client.evalsha(sha1, keyCount, params);
return getEvalResult();
}
@Override
public Boolean scriptExists(String sha1) {
String[] a = new String[1];
a[0] = sha1;
return scriptExists(a).get(0);
}
@Override
public List<Boolean> scriptExists(String... sha1) {
client.scriptExists(sha1);
List<Long> result = client.getIntegerMultiBulkReply();
List<Boolean> exists = new ArrayList<Boolean>();
for (Long value : result)
exists.add(value == 1);
return exists;
}
@Override
public String scriptLoad(String script) {
client.scriptLoad(script);
return client.getBulkReply();
}
@Override
public List<Slowlog> slowlogGet() {
client.slowlogGet();
return Slowlog.from(client.getObjectMultiBulkReply());
}
@Override
public List<Slowlog> slowlogGet(long entries) {
client.slowlogGet(entries);
return Slowlog.from(client.getObjectMultiBulkReply());
}
@Override
public Long objectRefcount(String string) {
client.objectRefcount(string);
return client.getIntegerReply();
}
@Override
public String objectEncoding(String string) {
client.objectEncoding(string);
return client.getBulkReply();
}
@Override
public Long objectIdletime(String string) {
client.objectIdletime(string);
return client.getIntegerReply();
}
@Override
public Long bitcount(final String key) {
client.bitcount(key);
return client.getIntegerReply();
}
@Override
public Long bitcount(final String key, long start, long end) {
client.bitcount(key, start, end);
return client.getIntegerReply();
}
@Override
public Long bitop(BitOP op, final String destKey, String... srcKeys) {
client.bitop(op, destKey, srcKeys);
return client.getIntegerReply();
}
/**
* <pre>
* redis 127.0.0.1:26381> sentinel masters
* 1) 1) "name"
* 2) "mymaster"
* 3) "ip"
* 4) "127.0.0.1"
* 5) "port"
* 6) "6379"
* 7) "runid"
* 8) "93d4d4e6e9c06d0eea36e27f31924ac26576081d"
* 9) "flags"
* 10) "master"
* 11) "pending-commands"
* 12) "0"
* 13) "last-ok-ping-reply"
* 14) "423"
* 15) "last-ping-reply"
* 16) "423"
* 17) "info-refresh"
* 18) "6107"
* 19) "num-slaves"
* 20) "1"
* 21) "num-other-sentinels"
* 22) "2"
* 23) "quorum"
* 24) "2"
*
* </pre>
* @return
*/
@Override
@SuppressWarnings("rawtypes")
public List<Map<String, String>> sentinelMasters() {
client.sentinel(Protocol.SENTINEL_MASTERS);
final List<Object> reply = client.getObjectMultiBulkReply();
final List<Map<String, String>> masters = new ArrayList<Map<String, String>>();
for (Object obj : reply) {
masters.add(BuilderFactory.STRING_MAP.build((List) obj));
}
return masters;
}
/**
* <pre>
* redis 127.0.0.1:26381> sentinel get-master-addr-by-name mymaster
* 1) "127.0.0.1"
* 2) "6379"
* </pre>
* @param masterName
* @return two elements list of strings : host and port.
*/
@Override
public List<String> sentinelGetMasterAddrByName(String masterName) {
client.sentinel(Protocol.SENTINEL_GET_MASTER_ADDR_BY_NAME, masterName);
final List<Object> reply = client.getObjectMultiBulkReply();
return BuilderFactory.STRING_LIST.build(reply);
}
/**
* <pre>
* redis 127.0.0.1:26381> sentinel reset mymaster
* (integer) 1
* </pre>
* @param pattern
* @return
*/
@Override
public Long sentinelReset(String pattern) {
client.sentinel(Protocol.SENTINEL_RESET, pattern);
return client.getIntegerReply();
}
/**
* <pre>
* redis 127.0.0.1:26381> sentinel slaves mymaster
* 1) 1) "name"
* 2) "127.0.0.1:6380"
* 3) "ip"
* 4) "127.0.0.1"
* 5) "port"
* 6) "6380"
* 7) "runid"
* 8) "d7f6c0ca7572df9d2f33713df0dbf8c72da7c039"
* 9) "flags"
* 10) "slave"
* 11) "pending-commands"
* 12) "0"
* 13) "last-ok-ping-reply"
* 14) "47"
* 15) "last-ping-reply"
* 16) "47"
* 17) "info-refresh"
* 18) "657"
* 19) "master-link-down-time"
* 20) "0"
* 21) "master-link-status"
* 22) "ok"
* 23) "master-host"
* 24) "localhost"
* 25) "master-port"
* 26) "6379"
* 27) "slave-priority"
* 28) "100"
* </pre>
* @param masterName
* @return
*/
@Override
@SuppressWarnings("rawtypes")
public List<Map<String, String>> sentinelSlaves(String masterName) {
client.sentinel(Protocol.SENTINEL_SLAVES, masterName);
final List<Object> reply = client.getObjectMultiBulkReply();
final List<Map<String, String>> slaves = new ArrayList<Map<String, String>>();
for (Object obj : reply) {
slaves.add(BuilderFactory.STRING_MAP.build((List) obj));
}
return slaves;
}
@Override
public String sentinelFailover(String masterName) {
client.sentinel(Protocol.SENTINEL_FAILOVER, masterName);
return client.getStatusCodeReply();
}
@Override
public String sentinelMonitor(String masterName, String ip, int port, int quorum) {
client.sentinel(Protocol.SENTINEL_MONITOR, masterName, ip, String.valueOf(port),
String.valueOf(quorum));
return client.getStatusCodeReply();
}
@Override
public String sentinelRemove(String masterName) {
client.sentinel(Protocol.SENTINEL_REMOVE, masterName);
return client.getStatusCodeReply();
}
@Override
public String sentinelSet(String masterName, Map<String, String> parameterMap) {
int index = 0;
int paramsLength = parameterMap.size() * 2 + 2;
String[] params = new String[paramsLength];
params[index++] = Protocol.SENTINEL_SET;
params[index++] = masterName;
for (Entry<String, String> entry : parameterMap.entrySet()) {
params[index++] = entry.getKey();
params[index++] = entry.getValue();
}
client.sentinel(params);
return client.getStatusCodeReply();
}
public byte[] dump(final String key) {
checkIsInMultiOrPipeline();
client.dump(key);
return client.getBinaryBulkReply();
}
public String restore(final String key, final int ttl, final byte[] serializedValue) {
checkIsInMultiOrPipeline();
client.restore(key, ttl, serializedValue);
return client.getStatusCodeReply();
}
@Override
public Long pexpire(final String key, final long milliseconds) {
checkIsInMultiOrPipeline();
client.pexpire(key, milliseconds);
return client.getIntegerReply();
}
@Override
public Long pexpireAt(final String key, final long millisecondsTimestamp) {
checkIsInMultiOrPipeline();
client.pexpireAt(key, millisecondsTimestamp);
return client.getIntegerReply();
}
@Override
public Long pttl(final String key) {
checkIsInMultiOrPipeline();
client.pttl(key);
return client.getIntegerReply();
}
/**
* PSETEX works exactly like {@link #setex(String, int, String)} with the sole difference that the
* expire time is specified in milliseconds instead of seconds. Time complexity: O(1)
* @param key
* @param milliseconds
* @param value
* @return Status code reply
*/
@Override
public String psetex(final String key, final long milliseconds, final String value) {
checkIsInMultiOrPipeline();
client.psetex(key, milliseconds, value);
return client.getStatusCodeReply();
}
public String clientKill(final String client) {
checkIsInMultiOrPipeline();
this.client.clientKill(client);
return this.client.getStatusCodeReply();
}
public String clientSetname(final String name) {
checkIsInMultiOrPipeline();
client.clientSetname(name);
return client.getStatusCodeReply();
}
public String migrate(final String host, final int port, final String key,
final int destinationDb, final int timeout) {
checkIsInMultiOrPipeline();
client.migrate(host, port, key, destinationDb, timeout);
return client.getStatusCodeReply();
}
@Override
public ScanResult<String> scan(final String cursor) {
return scan(cursor, new ScanParams());
}
@Override
public ScanResult<String> scan(final String cursor, final ScanParams params) {
checkIsInMultiOrPipeline();
client.scan(cursor, params);
List<Object> result = client.getObjectMultiBulkReply();
String newcursor = new String((byte[]) result.get(0));
List<String> results = new ArrayList<String>();
List<byte[]> rawResults = (List<byte[]>) result.get(1);
for (byte[] bs : rawResults) {
results.add(SafeEncoder.encode(bs));
}
return new ScanResult<String>(newcursor, results);
}
@Override
public ScanResult<Map.Entry<String, String>> hscan(final String key, final String cursor) {
return hscan(key, cursor, new ScanParams());
}
@Override
public ScanResult<Map.Entry<String, String>> hscan(final String key, final String cursor,
final ScanParams params) {
checkIsInMultiOrPipeline();
client.hscan(key, cursor, params);
List<Object> result = client.getObjectMultiBulkReply();
String newcursor = new String((byte[]) result.get(0));
List<Map.Entry<String, String>> results = new ArrayList<Map.Entry<String, String>>();
List<byte[]> rawResults = (List<byte[]>) result.get(1);
Iterator<byte[]> iterator = rawResults.iterator();
while (iterator.hasNext()) {
results.add(new AbstractMap.SimpleEntry<String, String>(SafeEncoder.encode(iterator.next()),
SafeEncoder.encode(iterator.next())));
}
return new ScanResult<Map.Entry<String, String>>(newcursor, results);
}
@Override
public ScanResult<String> sscan(final String key, final String cursor) {
return sscan(key, cursor, new ScanParams());
}
@Override
public ScanResult<String> sscan(final String key, final String cursor, final ScanParams params) {
checkIsInMultiOrPipeline();
client.sscan(key, cursor, params);
List<Object> result = client.getObjectMultiBulkReply();
String newcursor = new String((byte[]) result.get(0));
List<String> results = new ArrayList<String>();
List<byte[]> rawResults = (List<byte[]>) result.get(1);
for (byte[] bs : rawResults) {
results.add(SafeEncoder.encode(bs));
}
return new ScanResult<String>(newcursor, results);
}
@Override
public ScanResult<Tuple> zscan(final String key, final String cursor) {
return zscan(key, cursor, new ScanParams());
}
@Override
public ScanResult<Tuple> zscan(final String key, final String cursor, final ScanParams params) {
checkIsInMultiOrPipeline();
client.zscan(key, cursor, params);
List<Object> result = client.getObjectMultiBulkReply();
String newcursor = new String((byte[]) result.get(0));
List<Tuple> results = new ArrayList<Tuple>();
List<byte[]> rawResults = (List<byte[]>) result.get(1);
Iterator<byte[]> iterator = rawResults.iterator();
while (iterator.hasNext()) {
results.add(new Tuple(SafeEncoder.encode(iterator.next()), Double.valueOf(SafeEncoder
.encode(iterator.next()))));
}
return new ScanResult<Tuple>(newcursor, results);
}
@Override
public String clusterNodes() {
checkIsInMultiOrPipeline();
client.clusterNodes();
return client.getBulkReply();
}
@Override
public String readonly() {
client.readonly();
return client.getStatusCodeReply();
}
@Override
public String clusterMeet(final String ip, final int port) {
checkIsInMultiOrPipeline();
client.clusterMeet(ip, port);
return client.getStatusCodeReply();
}
@Override
public String clusterReset(final Reset resetType) {
checkIsInMultiOrPipeline();
client.clusterReset(resetType);
return client.getStatusCodeReply();
}
@Override
public String clusterAddSlots(final int... slots) {
checkIsInMultiOrPipeline();
client.clusterAddSlots(slots);
return client.getStatusCodeReply();
}
@Override
public String clusterDelSlots(final int... slots) {
checkIsInMultiOrPipeline();
client.clusterDelSlots(slots);
return client.getStatusCodeReply();
}
@Override
public String clusterInfo() {
checkIsInMultiOrPipeline();
client.clusterInfo();
return client.getStatusCodeReply();
}
@Override
public List<String> clusterGetKeysInSlot(final int slot, final int count) {
checkIsInMultiOrPipeline();
client.clusterGetKeysInSlot(slot, count);
return client.getMultiBulkReply();
}
@Override
public String clusterSetSlotNode(final int slot, final String nodeId) {
checkIsInMultiOrPipeline();
client.clusterSetSlotNode(slot, nodeId);
return client.getStatusCodeReply();
}
@Override
public String clusterSetSlotMigrating(final int slot, final String nodeId) {
checkIsInMultiOrPipeline();
client.clusterSetSlotMigrating(slot, nodeId);
return client.getStatusCodeReply();
}
@Override
public String clusterSetSlotImporting(final int slot, final String nodeId) {
checkIsInMultiOrPipeline();
client.clusterSetSlotImporting(slot, nodeId);
return client.getStatusCodeReply();
}
@Override
public String clusterSetSlotStable(final int slot) {
checkIsInMultiOrPipeline();
client.clusterSetSlotStable(slot);
return client.getStatusCodeReply();
}
@Override
public String clusterForget(final String nodeId) {
checkIsInMultiOrPipeline();
client.clusterForget(nodeId);
return client.getStatusCodeReply();
}
@Override
public String clusterFlushSlots() {
checkIsInMultiOrPipeline();
client.clusterFlushSlots();
return client.getStatusCodeReply();
}
@Override
public Long clusterKeySlot(final String key) {
checkIsInMultiOrPipeline();
client.clusterKeySlot(key);
return client.getIntegerReply();
}
@Override
public Long clusterCountKeysInSlot(final int slot) {
checkIsInMultiOrPipeline();
client.clusterCountKeysInSlot(slot);
return client.getIntegerReply();
}
@Override
public String clusterSaveConfig() {
checkIsInMultiOrPipeline();
client.clusterSaveConfig();
return client.getStatusCodeReply();
}
@Override
public String clusterReplicate(final String nodeId) {
checkIsInMultiOrPipeline();
client.clusterReplicate(nodeId);
return client.getStatusCodeReply();
}
@Override
public List<String> clusterSlaves(final String nodeId) {
checkIsInMultiOrPipeline();
client.clusterSlaves(nodeId);
return client.getMultiBulkReply();
}
@Override
public String clusterFailover() {
checkIsInMultiOrPipeline();
client.clusterFailover();
return client.getStatusCodeReply();
}
@Override
public List<Object> clusterSlots() {
checkIsInMultiOrPipeline();
client.clusterSlots();
return client.getObjectMultiBulkReply();
}
public String asking() {
checkIsInMultiOrPipeline();
client.asking();
return client.getStatusCodeReply();
}
public List<String> pubsubChannels(String pattern) {
checkIsInMultiOrPipeline();
client.pubsubChannels(pattern);
return client.getMultiBulkReply();
}
public Long pubsubNumPat() {
checkIsInMultiOrPipeline();
client.pubsubNumPat();
return client.getIntegerReply();
}
public Map<String, String> pubsubNumSub(String... channels) {
checkIsInMultiOrPipeline();
client.pubsubNumSub(channels);
return BuilderFactory.PUBSUB_NUMSUB_MAP.build(client.getBinaryMultiBulkReply());
}
@Override
public void close() {
if (dataSource != null) {
if (client.isBroken()) {
this.dataSource.returnBrokenResource(this);
} else {
this.dataSource.returnResource(this);
}
} else {
client.close();
}
}
public void setDataSource(JedisPoolAbstract jedisPool) {
this.dataSource = jedisPool;
}
@Override
public Long pfadd(final String key, final String... elements) {
checkIsInMultiOrPipeline();
client.pfadd(key, elements);
return client.getIntegerReply();
}
@Override
public long pfcount(final String key) {
checkIsInMultiOrPipeline();
client.pfcount(key);
return client.getIntegerReply();
}
@Override
public long pfcount(String... keys) {
checkIsInMultiOrPipeline();
client.pfcount(keys);
return client.getIntegerReply();
}
@Override
public String pfmerge(final String destkey, final String... sourcekeys) {
checkIsInMultiOrPipeline();
client.pfmerge(destkey, sourcekeys);
return client.getStatusCodeReply();
}
@Override
public List<String> blpop(int timeout, String key) {
return blpop(key, String.valueOf(timeout));
}
@Override
public List<String> brpop(int timeout, String key) {
return brpop(key, String.valueOf(timeout));
}
}
| mit |
lhanson/checkstyle | src/testinputs/com/puppycrawl/tools/checkstyle/annotation/package-info.java | 65 | @Deprecated
package com.puppycrawl.tools.checkstyle.annotation;
| lgpl-2.1 |
gunan/tensorflow | tensorflow/java/src/main/java/org/tensorflow/AbstractOperation.java | 2874 | /* Copyright 2019 The TensorFlow Authors. 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.tensorflow;
/**
* Base class for {@link Operation} implementations.
*
* <p>As opposed to {@link Operation} itself, this class is package private and therefore its usage
* is limited to internal purposes only.
*/
abstract class AbstractOperation implements Operation {
@Override
public Output<?>[] outputList(int idx, int length) {
Output<?>[] outputs = new Output<?>[length];
for (int i = 0; i < length; ++i) {
outputs[i] = output(idx + i);
}
return outputs;
}
@Override
@SuppressWarnings({"rawtypes", "unchecked"})
public <T> Output<T> output(int idx) {
return new Output(this, idx);
}
@Override
public String toString() {
return String.format("<%s '%s'>", type(), name());
}
/**
* Returns the native handle of the {@code outputIdx}th output of this operation.
*
* <p>The nature of the returned value varies depending on current the execution environment.
*
* <ul>
* <li>In eager mode, the value is a handle to the tensor returned at this output.
* <li>In graph mode, the value is a handle to the operation itself, which should be paired with
* the index of the output when calling the native layer.
* </ul>
*
* @param outputIdx index of the output in this operation
* @return a native handle, see method description for more details
*/
abstract long getUnsafeNativeHandle(int outputIdx);
/**
* Returns the shape of the tensor of the {@code outputIdx}th output of this operation.
*
* @param outputIdx index of the output of this operation
* @return output tensor shape
*/
abstract long[] shape(int outputIdx);
/**
* Returns the datatype of the tensor of the {@code outputIdx}th output of this operation.
*
* @param outputIdx index of the output of this operation
* @return output tensor datatype
*/
abstract DataType dtype(int outputIdx);
/**
* Returns the tensor of the {@code outputIdx}th output of this operation.
*
* <p>This is only supported in an eager execution environment.
*
* @param outputIdx index of the output of this operation
* @return output tensor
*/
abstract Tensor<?> tensor(int outputIdx);
}
| apache-2.0 |
amarouni/incubator-beam | sdks/java/core/src/main/java/org/apache/beam/sdk/util/BucketingFunction.java | 4168 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.sdk.util;
import static com.google.common.base.Preconditions.checkState;
import java.util.HashMap;
import java.util.Map;
import org.apache.beam.sdk.transforms.Combine;
/**
* Keep track of the minimum/maximum/sum of a set of timestamped long values.
* For efficiency, bucket values by their timestamp.
*/
public class BucketingFunction {
private static class Bucket {
private int numSamples;
private long combinedValue;
public Bucket(BucketingFunction outer) {
numSamples = 0;
combinedValue = outer.function.identity();
}
public void add(BucketingFunction outer, long value) {
combinedValue = outer.function.apply(combinedValue, value);
numSamples++;
}
public boolean remove() {
numSamples--;
checkState(numSamples >= 0, "Lost count of samples");
return numSamples == 0;
}
public long get() {
return combinedValue;
}
}
/**
* How large a time interval to fit within each bucket.
*/
private final long bucketWidthMs;
/**
* How many buckets are considered 'significant'?
*/
private final int numSignificantBuckets;
/**
* How many samples are considered 'significant'?
*/
private final int numSignificantSamples;
/**
* Function for combining sample values.
*/
private final Combine.BinaryCombineLongFn function;
/**
* Active buckets.
*/
private final Map<Long, Bucket> buckets;
public BucketingFunction(
long bucketWidthMs,
int numSignificantBuckets,
int numSignificantSamples,
Combine.BinaryCombineLongFn function) {
this.bucketWidthMs = bucketWidthMs;
this.numSignificantBuckets = numSignificantBuckets;
this.numSignificantSamples = numSignificantSamples;
this.function = function;
this.buckets = new HashMap<>();
}
/**
* Which bucket key corresponds to {@code timeMsSinceEpoch}.
*/
private long key(long timeMsSinceEpoch) {
return timeMsSinceEpoch - (timeMsSinceEpoch % bucketWidthMs);
}
/**
* Add one sample of {@code value} (to bucket) at {@code timeMsSinceEpoch}.
*/
public void add(long timeMsSinceEpoch, long value) {
long key = key(timeMsSinceEpoch);
Bucket bucket = buckets.get(key);
if (bucket == null) {
bucket = new Bucket(this);
buckets.put(key, bucket);
}
bucket.add(this, value);
}
/**
* Remove one sample (from bucket) at {@code timeMsSinceEpoch}.
*/
public void remove(long timeMsSinceEpoch) {
long key = key(timeMsSinceEpoch);
Bucket bucket = buckets.get(key);
if (bucket == null) {
return;
}
if (bucket.remove()) {
buckets.remove(key);
}
}
/**
* Return the (bucketized) combined value of all samples.
*/
public long get() {
long result = function.identity();
for (Bucket bucket : buckets.values()) {
result = function.apply(result, bucket.get());
}
return result;
}
/**
* Is the current result 'significant'? Ie is it drawn from enough buckets
* or from enough samples?
*/
public boolean isSignificant() {
if (buckets.size() >= numSignificantBuckets) {
return true;
}
int totalSamples = 0;
for (Bucket bucket : buckets.values()) {
totalSamples += bucket.numSamples;
}
return totalSamples >= numSignificantSamples;
}
}
| apache-2.0 |
mahaliachante/aws-sdk-java | aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/transform/DescribeVolumeStatusResultStaxUnmarshaller.java | 2769 | /*
* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.ec2.model.transform;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.stream.events.XMLEvent;
import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.transform.MapEntry;
import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;
/**
* Describe Volume Status Result StAX Unmarshaller
*/
public class DescribeVolumeStatusResultStaxUnmarshaller implements Unmarshaller<DescribeVolumeStatusResult, StaxUnmarshallerContext> {
public DescribeVolumeStatusResult unmarshall(StaxUnmarshallerContext context) throws Exception {
DescribeVolumeStatusResult describeVolumeStatusResult = new DescribeVolumeStatusResult();
int originalDepth = context.getCurrentDepth();
int targetDepth = originalDepth + 1;
if (context.isStartOfDocument()) targetDepth += 1;
while (true) {
XMLEvent xmlEvent = context.nextEvent();
if (xmlEvent.isEndDocument()) return describeVolumeStatusResult;
if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
if (context.testExpression("volumeStatusSet/item", targetDepth)) {
describeVolumeStatusResult.getVolumeStatuses().add(VolumeStatusItemStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
if (context.testExpression("nextToken", targetDepth)) {
describeVolumeStatusResult.setNextToken(StringStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
} else if (xmlEvent.isEndElement()) {
if (context.getCurrentDepth() < originalDepth) {
return describeVolumeStatusResult;
}
}
}
}
private static DescribeVolumeStatusResultStaxUnmarshaller instance;
public static DescribeVolumeStatusResultStaxUnmarshaller getInstance() {
if (instance == null) instance = new DescribeVolumeStatusResultStaxUnmarshaller();
return instance;
}
}
| apache-2.0 |
mahaliachante/aws-sdk-java | aws-java-sdk-elasticloadbalancing/src/main/java/com/amazonaws/services/elasticloadbalancing/model/transform/SetLoadBalancerPoliciesForBackendServerRequestMarshaller.java | 3102 | /*
* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.elasticloadbalancing.model.transform;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.internal.ListWithAutoConstructFlag;
import com.amazonaws.services.elasticloadbalancing.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;
/**
* Set Load Balancer Policies For Backend Server Request Marshaller
*/
public class SetLoadBalancerPoliciesForBackendServerRequestMarshaller implements Marshaller<Request<SetLoadBalancerPoliciesForBackendServerRequest>, SetLoadBalancerPoliciesForBackendServerRequest> {
public Request<SetLoadBalancerPoliciesForBackendServerRequest> marshall(SetLoadBalancerPoliciesForBackendServerRequest setLoadBalancerPoliciesForBackendServerRequest) {
if (setLoadBalancerPoliciesForBackendServerRequest == null) {
throw new AmazonClientException("Invalid argument passed to marshall(...)");
}
Request<SetLoadBalancerPoliciesForBackendServerRequest> request = new DefaultRequest<SetLoadBalancerPoliciesForBackendServerRequest>(setLoadBalancerPoliciesForBackendServerRequest, "AmazonElasticLoadBalancing");
request.addParameter("Action", "SetLoadBalancerPoliciesForBackendServer");
request.addParameter("Version", "2012-06-01");
if (setLoadBalancerPoliciesForBackendServerRequest.getLoadBalancerName() != null) {
request.addParameter("LoadBalancerName", StringUtils.fromString(setLoadBalancerPoliciesForBackendServerRequest.getLoadBalancerName()));
}
if (setLoadBalancerPoliciesForBackendServerRequest.getInstancePort() != null) {
request.addParameter("InstancePort", StringUtils.fromInteger(setLoadBalancerPoliciesForBackendServerRequest.getInstancePort()));
}
java.util.List<String> policyNamesList = setLoadBalancerPoliciesForBackendServerRequest.getPolicyNames();
int policyNamesListIndex = 1;
if (policyNamesList.isEmpty()) {
request.addParameter("PolicyNames", "");
}
for (String policyNamesListValue : policyNamesList) {
if (policyNamesListValue != null) {
request.addParameter("PolicyNames.member." + policyNamesListIndex, StringUtils.fromString(policyNamesListValue));
}
policyNamesListIndex++;
}
return request;
}
}
| apache-2.0 |
mahaliachante/aws-sdk-java | aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/RouteOrigin.java | 1816 | /*
* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.ec2.model;
/**
* Route Origin
*/
public enum RouteOrigin {
CreateRouteTable("CreateRouteTable"),
CreateRoute("CreateRoute"),
EnableVgwRoutePropagation("EnableVgwRoutePropagation");
private String value;
private RouteOrigin(String value) {
this.value = value;
}
@Override
public String toString() {
return this.value;
}
/**
* Use this in place of valueOf.
*
* @param value
* real value
* @return RouteOrigin corresponding to the value
*/
public static RouteOrigin fromValue(String value) {
if (value == null || "".equals(value)) {
throw new IllegalArgumentException("Value cannot be null or empty!");
} else if ("CreateRouteTable".equals(value)) {
return RouteOrigin.CreateRouteTable;
} else if ("CreateRoute".equals(value)) {
return RouteOrigin.CreateRoute;
} else if ("EnableVgwRoutePropagation".equals(value)) {
return RouteOrigin.EnableVgwRoutePropagation;
} else {
throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
}
}
}
| apache-2.0 |
antoaravinth/incubator-groovy | src/main/org/codehaus/groovy/ast/DynamicVariable.java | 2090 | /*
* 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.codehaus.groovy.ast;
import org.codehaus.groovy.ast.expr.Expression;
// An implicitly created variable, such as a variable in a script that's doesn't have an explicit
// declaration, or the "it" argument to a closure.
public class DynamicVariable implements Variable {
private String name;
private boolean closureShare = false;
private boolean staticContext = false;
public DynamicVariable(String name, boolean context) {
this.name = name;
staticContext = context;
}
public ClassNode getType() {
return ClassHelper.DYNAMIC_TYPE;
}
public String getName() {
return name;
}
public Expression getInitialExpression() {
return null;
}
public boolean hasInitialExpression() {
return false;
}
public boolean isInStaticContext() {
return staticContext;
}
public boolean isDynamicTyped() {
return true;
}
public boolean isClosureSharedVariable() {
return closureShare;
}
public void setClosureSharedVariable(boolean inClosure) {
closureShare = inClosure;
}
public int getModifiers() {
return 0;
}
public ClassNode getOriginType() {
return getType();
}
}
| apache-2.0 |
grgrzybek/camel | components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/FtpEndpoint.java | 8541 | /**
* 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.file.remote;
import java.util.HashMap;
import java.util.Map;
import org.apache.camel.FailedToCreateConsumerException;
import org.apache.camel.FailedToCreateProducerException;
import org.apache.camel.Processor;
import org.apache.camel.component.file.GenericFileConfiguration;
import org.apache.camel.component.file.GenericFileProducer;
import org.apache.camel.component.file.remote.RemoteFileConfiguration.PathSeparator;
import org.apache.camel.spi.UriEndpoint;
import org.apache.camel.spi.UriParam;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
/**
* FTP endpoint
*/
@UriEndpoint(scheme = "ftp", extendsScheme = "file", title = "FTP",
syntax = "ftp:host:port/directoryName", consumerClass = FtpConsumer.class, label = "file")
public class FtpEndpoint<T extends FTPFile> extends RemoteFileEndpoint<FTPFile> {
protected FTPClient ftpClient;
protected FTPClientConfig ftpClientConfig;
protected Map<String, Object> ftpClientParameters;
protected Map<String, Object> ftpClientConfigParameters;
@UriParam
protected FtpConfiguration configuration;
@UriParam
protected int soTimeout;
@UriParam
protected int dataTimeout;
public FtpEndpoint() {
}
public FtpEndpoint(String uri, RemoteFileComponent<FTPFile> component, FtpConfiguration configuration) {
super(uri, component, configuration);
this.configuration = configuration;
}
@Override
public String getScheme() {
return "ftp";
}
@Override
protected RemoteFileConsumer<FTPFile> buildConsumer(Processor processor) {
try {
return new FtpConsumer(this, processor, createRemoteFileOperations());
} catch (Exception e) {
throw new FailedToCreateConsumerException(this, e);
}
}
protected GenericFileProducer<FTPFile> buildProducer() {
try {
return new RemoteFileProducer<FTPFile>(this, createRemoteFileOperations());
} catch (Exception e) {
throw new FailedToCreateProducerException(this, e);
}
}
public RemoteFileOperations<FTPFile> createRemoteFileOperations() throws Exception {
// configure ftp client
FTPClient client = ftpClient;
if (client == null) {
// must use a new client if not explicit configured to use a custom client
client = createFtpClient();
}
// use configured buffer size which is larger and therefore faster (as the default is no buffer)
if (getConfiguration().getReceiveBufferSize() > 0) {
client.setBufferSize(getConfiguration().getReceiveBufferSize());
}
// set any endpoint configured timeouts
if (getConfiguration().getConnectTimeout() > -1) {
client.setConnectTimeout(getConfiguration().getConnectTimeout());
}
if (getConfiguration().getSoTimeout() > -1) {
soTimeout = getConfiguration().getSoTimeout();
}
dataTimeout = getConfiguration().getTimeout();
// then lookup ftp client parameters and set those
if (ftpClientParameters != null) {
Map<String, Object> localParameters = new HashMap<String, Object>(ftpClientParameters);
// setting soTimeout has to be done later on FTPClient (after it has connected)
Object timeout = localParameters.remove("soTimeout");
if (timeout != null) {
soTimeout = getCamelContext().getTypeConverter().convertTo(int.class, timeout);
}
// and we want to keep data timeout so we can log it later
timeout = localParameters.remove("dataTimeout");
if (timeout != null) {
dataTimeout = getCamelContext().getTypeConverter().convertTo(int.class, dataTimeout);
}
setProperties(client, localParameters);
}
if (ftpClientConfigParameters != null) {
// client config is optional so create a new one if we have parameter for it
if (ftpClientConfig == null) {
ftpClientConfig = new FTPClientConfig();
}
Map<String, Object> localConfigParameters = new HashMap<String, Object>(ftpClientConfigParameters);
setProperties(ftpClientConfig, localConfigParameters);
}
if (dataTimeout > 0) {
client.setDataTimeout(dataTimeout);
}
if (log.isDebugEnabled()) {
log.debug("Created FTPClient [connectTimeout: {}, soTimeout: {}, dataTimeout: {}, bufferSize: {}"
+ ", receiveDataSocketBufferSize: {}, sendDataSocketBufferSize: {}]: {}",
new Object[]{client.getConnectTimeout(), getSoTimeout(), dataTimeout, client.getBufferSize(),
client.getReceiveDataSocketBufferSize(), client.getSendDataSocketBufferSize(), client});
}
FtpOperations operations = new FtpOperations(client, getFtpClientConfig());
operations.setEndpoint(this);
return operations;
}
protected FTPClient createFtpClient() throws Exception {
return new FTPClient();
}
@Override
public FtpConfiguration getConfiguration() {
if (configuration == null) {
configuration = new FtpConfiguration();
}
return configuration;
}
@Override
public void setConfiguration(GenericFileConfiguration configuration) {
if (configuration == null) {
throw new IllegalArgumentException("FtpConfiguration expected");
}
// need to set on both
this.configuration = (FtpConfiguration) configuration;
super.setConfiguration(configuration);
}
public FTPClient getFtpClient() {
return ftpClient;
}
public void setFtpClient(FTPClient ftpClient) {
this.ftpClient = ftpClient;
}
public FTPClientConfig getFtpClientConfig() {
return ftpClientConfig;
}
public void setFtpClientConfig(FTPClientConfig ftpClientConfig) {
this.ftpClientConfig = ftpClientConfig;
}
/**
* Used by FtpComponent to provide additional parameters for the FTPClient
*/
void setFtpClientParameters(Map<String, Object> ftpClientParameters) {
this.ftpClientParameters = ftpClientParameters;
}
/**
* Used by FtpComponent to provide additional parameters for the FTPClientConfig
*/
void setFtpClientConfigParameters(Map<String, Object> ftpClientConfigParameters) {
this.ftpClientConfigParameters = new HashMap<String, Object>(ftpClientConfigParameters);
}
public int getSoTimeout() {
return soTimeout;
}
/**
* Sets the soTimeout on the FTP client.
*/
public void setSoTimeout(int soTimeout) {
this.soTimeout = soTimeout;
}
public int getDataTimeout() {
return dataTimeout;
}
/**
* Sets the data timeout on the FTP client.
*/
public void setDataTimeout(int dataTimeout) {
this.dataTimeout = dataTimeout;
}
@Override
public char getFileSeparator() {
// the regular ftp component should use the configured separator
// as FTP servers may require you to use windows or unix style
// and therefore you need to be able to control that
PathSeparator pathSeparator = getConfiguration().getSeparator();
switch (pathSeparator) {
case Windows:
return '\\';
case UNIX:
return '/';
default:
return super.getFileSeparator();
}
}
}
| apache-2.0 |
hdost/gerrit | gerrit-httpd/src/main/java/com/google/gerrit/httpd/rpc/RpcServletModule.java | 1805 | // Copyright (C) 2009 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 com.google.gerrit.httpd.rpc;
import com.google.gwtjsonrpc.common.RemoteJsonService;
import com.google.inject.Key;
import com.google.inject.Scopes;
import com.google.inject.internal.UniqueAnnotations;
import com.google.inject.servlet.ServletModule;
/** Binds {@link RemoteJsonService} implementations to a JSON servlet. */
public abstract class RpcServletModule extends ServletModule {
public static final String PREFIX = "/gerrit_ui/rpc/";
private final String prefix;
protected RpcServletModule(final String pathPrefix) {
prefix = pathPrefix;
}
protected void rpc(Class<? extends RemoteJsonService> clazz) {
String name = clazz.getSimpleName();
if (name.endsWith("Impl")) {
name = name.substring(0, name.length() - 4);
}
rpc(name, clazz);
}
protected void rpc(final String name, Class<? extends RemoteJsonService> clazz) {
final Key<GerritJsonServlet> srv =
Key.get(GerritJsonServlet.class, UniqueAnnotations.create());
final GerritJsonServletProvider provider =
new GerritJsonServletProvider(clazz);
bind(clazz);
serve(prefix + name).with(srv);
bind(srv).toProvider(provider).in(Scopes.SINGLETON);
}
}
| apache-2.0 |
panchenko/spring-security | test/src/main/java/org/springframework/security/test/context/support/WithUserDetailsSecurityContextFactory.java | 2223 | /*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.support;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.util.Assert;
/**
* A {@link WithUserDetailsSecurityContextFactory} that works with {@link WithUserDetails}
* .
*
* @see WithUserDetails
*
* @author Rob Winch
* @since 4.0
*/
final class WithUserDetailsSecurityContextFactory implements
WithSecurityContextFactory<WithUserDetails> {
private UserDetailsService userDetailsService;
@Autowired
public WithUserDetailsSecurityContextFactory(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
public SecurityContext createSecurityContext(WithUserDetails withUser) {
String username = withUser.value();
Assert.hasLength(username, "value() must be non empty String");
UserDetails principal = userDetailsService.loadUserByUsername(username);
Authentication authentication = new UsernamePasswordAuthenticationToken(
principal, principal.getPassword(), principal.getAuthorities());
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authentication);
return context;
}
} | apache-2.0 |
shaotuanchen/sunflower_exp | tools/source/gcc-4.2.4/libjava/classpath/gnu/CORBA/Poa/DynamicImpHandler.java | 3072 | /* DynamicImpHandler.java --
Copyright (C) 2005 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.CORBA.Poa;
import org.omg.CORBA.BAD_OPERATION;
import org.omg.CORBA.portable.InputStream;
import org.omg.CORBA.portable.InvokeHandler;
import org.omg.CORBA.portable.OutputStream;
import org.omg.CORBA.portable.ResponseHandler;
import org.omg.PortableServer.DynamicImplementation;
/**
* The InvokeHandler, indicating, that the target is a dynamic
* implementation rather than an invoke handler. These two
* types are not substitutable, but in some methods have possibility
* just to handle them differently.
*
* @author Audrius Meskauskas, Lithuania (AudriusA@Bioinformatics.org)
*/
public class DynamicImpHandler
implements InvokeHandler
{
/**
* The servant that is a dynamic implementation rather than
* invoke handler.
*/
public final DynamicImplementation servant;
/**
* Create a new instance, wrapping some dyn implementation.
* @param _servant
*/
public DynamicImpHandler(DynamicImplementation _servant)
{
servant = _servant;
}
/**
* We cannot invoke properly without having parameter info.
*
* @throws BAD_OPERATION, always.
*/
public OutputStream _invoke(String method, InputStream input,
ResponseHandler handler
)
{
throw new BAD_OPERATION(servant + " is not an InvokeHandler.");
}
} | bsd-3-clause |
shaotuanchen/sunflower_exp | tools/source/gcc-4.2.4/libjava/classpath/gnu/classpath/jdwp/event/ClassPrepareEvent.java | 4624 | /* ClassPrepareEvent.java -- An event specifying that a class has been
prepared by the virtual machine
Copyright (C) 2005 Free Software Foundation
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.classpath.jdwp.event;
import gnu.classpath.jdwp.JdwpConstants;
import gnu.classpath.jdwp.VMIdManager;
import gnu.classpath.jdwp.id.ReferenceTypeId;
import gnu.classpath.jdwp.id.ThreadId;
import gnu.classpath.jdwp.util.JdwpString;
import gnu.classpath.jdwp.util.Signature;
import java.io.DataOutputStream;
import java.io.IOException;
/**
* "Notification of a class prepare in the target VM. See the JVM
* specification for a definition of class preparation. Class prepare
* events are not generated for primtiive classes (for example,
* <code>java.lang.Integer.TYPE</code>)." -- JDWP 1.4.2
*
* @author Keith Seitz (keiths@redhat.com)
*/
public class ClassPrepareEvent
extends Event
{
// The thread in which this event occurred
private Thread _thread;
// The class that was prepared
private Class _class;
// Prepare flags
private int _status;
/**
* Class has been verified
*/
public static final int STATUS_VERIFIED
= JdwpConstants.ClassStatus.VERIFIED;
/**
* Class has been prepared
*/
public static final int STATUS_PREPARED
= JdwpConstants.ClassStatus.PREPARED;
/**
* Class has been initialized
*/
public static final int STATUS_INITIALIZED
= JdwpConstants.ClassStatus.INITIALIZED;
/**
* Error preparing class
*/
public static final int STATUS_ERROR
= JdwpConstants.ClassStatus.ERROR;
/**
* Constructs a new <code>ClassPrepareEvent</code>
*
* @param thread thread in which event occurred
* @param clazz class which was prepared
* @param flags prepare status flags
*/
public ClassPrepareEvent (Thread thread, Class clazz, int flags)
{
super (JdwpConstants.EventKind.CLASS_PREPARE);
_thread = thread;
_class = clazz;
_status = flags;
}
/**
* Returns a specific filtering parameter for this event.
* Valid types are thread and class.
*
* @param type the type of parameter desired
* @returns the desired parameter or <code>null</code>
*/
public Object getParameter (int type)
{
if (type == EVENT_THREAD)
return _thread;
else if (type == EVENT_CLASS)
return _class;
return null;
}
/**
* Writes the event to the given stream
*
* @param outStream the output stream to write the event to
*/
protected void _writeData (DataOutputStream outStream)
throws IOException
{
VMIdManager idm = VMIdManager.getDefault();
ThreadId tid = (ThreadId) idm.getObjectId (_thread);
ReferenceTypeId rid = idm.getReferenceTypeId (_class);
tid.write (outStream);
rid.writeTagged (outStream);
JdwpString.writeString (outStream,
Signature.computeClassSignature (_class));
outStream.writeInt (_status);
}
}
| bsd-3-clause |
ibaton/smarthome | bundles/core/org.eclipse.smarthome.core/src/main/java/org/eclipse/smarthome/core/library/items/DateTimeItem.java | 2055 | /**
* Copyright (c) 2014-2015 openHAB UG (haftungsbeschraenkt) 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.eclipse.smarthome.core.library.items;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.eclipse.smarthome.core.items.GenericItem;
import org.eclipse.smarthome.core.library.CoreItemFactory;
import org.eclipse.smarthome.core.library.types.DateTimeType;
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;
/**
* A DateTimeItem stores a timestamp including a valid time zone.
*
* @author Thomas.Eichstaedt-Engelen
* @author Kai Kreuzer - Initial contribution and API
*
*/
public class DateTimeItem extends GenericItem {
private static List<Class<? extends State>> acceptedDataTypes = new ArrayList<Class<? extends State>>();
private static List<Class<? extends Command>> acceptedCommandTypes = new ArrayList<Class<? extends Command>>();
static {
acceptedDataTypes.add((DateTimeType.class));
acceptedDataTypes.add(UnDefType.class);
acceptedCommandTypes.add(RefreshType.class);
acceptedCommandTypes.add(DateTimeType.class);
}
public DateTimeItem(String name) {
super(CoreItemFactory.DATETIME, name);
}
@Override
public List<Class<? extends State>> getAcceptedDataTypes() {
return Collections.unmodifiableList(acceptedDataTypes);
}
@Override
public List<Class<? extends Command>> getAcceptedCommandTypes() {
return Collections.unmodifiableList(acceptedCommandTypes);
}
public void send(DateTimeType command) {
internalSend(command);
}
}
| epl-1.0 |
belliottsmith/cassandra | test/unit/org/apache/cassandra/cql3/validation/entities/udfverify/UseOfSynchronizedWithWaitLI.java | 2059 | /*
* 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.cassandra.cql3.validation.entities.udfverify;
import java.nio.ByteBuffer;
import java.util.List;
import org.apache.cassandra.cql3.functions.types.TypeCodec;
import org.apache.cassandra.cql3.functions.JavaUDF;
import org.apache.cassandra.cql3.functions.UDFContext;
import org.apache.cassandra.transport.ProtocolVersion;
/**
* Used by {@link org.apache.cassandra.cql3.validation.entities.UFVerifierTest}.
*/
public final class UseOfSynchronizedWithWaitLI extends JavaUDF
{
public UseOfSynchronizedWithWaitLI(TypeCodec<Object> returnDataType, TypeCodec<Object>[] argDataTypes, UDFContext udfContext)
{
super(returnDataType, argDataTypes, udfContext);
}
protected Object executeAggregateImpl(ProtocolVersion protocolVersion, Object firstParam, List<ByteBuffer> params)
{
throw new UnsupportedOperationException();
}
protected ByteBuffer executeImpl(ProtocolVersion protocolVersion, List<ByteBuffer> params)
{
synchronized (this)
{
try
{
wait(1000L, 100);
}
catch (InterruptedException e)
{
throw new RuntimeException(e);
}
}
return null;
}
}
| apache-2.0 |
actorapp/droidkit-webrtc | webrtc/src/main/java/org/webrtc/MediaConstraints.java | 2814 | /*
* libjingle
* Copyright 2013, Google Inc.
*
* 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 org.webrtc;
import java.util.LinkedList;
import java.util.List;
/**
* Description of media constraints for {@code MediaStream} and
* {@code PeerConnection}.
*/
public class MediaConstraints {
/** Simple String key/value pair. */
public static class KeyValuePair {
private final String key;
private final String value;
public KeyValuePair(String key, String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public String getValue() {
return value;
}
public String toString() {
return key + ": " + value;
}
}
public final List<KeyValuePair> mandatory;
public final List<KeyValuePair> optional;
public MediaConstraints() {
mandatory = new LinkedList<KeyValuePair>();
optional = new LinkedList<KeyValuePair>();
}
private static String stringifyKeyValuePairList(List<KeyValuePair> list) {
StringBuilder builder = new StringBuilder("[");
for (KeyValuePair pair : list) {
if (builder.length() > 1) {
builder.append(", ");
}
builder.append(pair.toString());
}
return builder.append("]").toString();
}
public String toString() {
return "mandatory: " + stringifyKeyValuePairList(mandatory) +
", optional: " + stringifyKeyValuePairList(optional);
}
}
| bsd-3-clause |
marinmitev/smarthome | protocols/enocean/org.eclipse.smarthome.protocols.enocean.basedriver.impl/src/main/java/org/eclipse/smarthome/protocols/enocean/basedriver/impl/radio/Message4BS.java | 2363 | /*******************************************************************************
* Copyright (c) 2013, 2015 Orange.
* 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:
* Victor PERRON, Antonin CHAZALET, Andre BOTTARO.
*******************************************************************************/
package org.eclipse.smarthome.protocols.enocean.basedriver.impl.radio;
/**
* Message4BS: Prototype of a 4BS telegram
*
* Teach-in procedure:
*
* - if DB0.3 is 0, then it's a teach-in telegram.
*
* - if DB0.7 is also 0, no manufacturer info.
*
* - if DB0.7 is 1, manufacturer info is present.
*/
public class Message4BS extends Message {
/**
* @param data
* , i.e the data, and the optional data parts of an EnOcean
* packet/telegram (see, section "1.6.1 Packet description", page
* 13 of EnOceanSerialProtocol3.pdf). E.g. for a (full) 1BS
* telegram 55000707017ad500008a92390001ffffffff3000eb, then data
* is d500008a92390001ffffffff3000
*/
public Message4BS(byte[] data) {
super(data);
}
public boolean isTeachin() {
return (((getPayloadBytes()[3] & 0x08)) == 0);
}
/**
* @return true if the message teach-in embeds profile & manufacturer info.
*/
public boolean hasTeachInInfo() {
return (getPayloadBytes()[3] & 0x80) != 0;
}
/**
* @return the FUNC in the case of a teach-in message with information.
*/
public int teachInFunc() {
return (getPayloadBytes()[0] >> 2) & 0xff;
}
/**
* @return the TYPE in the case of a teach-in message with information.
*/
public int teachInType() {
byte b0 = getPayloadBytes()[0];
byte b1 = getPayloadBytes()[1];
return (((b0 & 0x03) << 5) & 0xff) | ((((b1 >> 3)) & 0xff));
}
/**
* @return the MANUF in the case of a teach-in message with information.
*/
public int teachInManuf() {
byte b0 = (byte) ((getPayloadBytes()[1]) & 0x07);
byte b1 = getPayloadBytes()[2];
return ((b0 & 0xff) << 8) + (b1 & 0xff);
}
}
| epl-1.0 |
GlenRSmith/elasticsearch | server/src/test/java/org/elasticsearch/index/suggest/stats/CompletionsStatsTests.java | 1435 | /*
* 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 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.index.suggest.stats;
import org.elasticsearch.common.FieldMemoryStats;
import org.elasticsearch.common.FieldMemoryStatsTests;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.search.suggest.completion.CompletionStats;
import org.elasticsearch.test.ESTestCase;
import java.io.IOException;
public class CompletionsStatsTests extends ESTestCase {
public void testSerialize() throws IOException {
FieldMemoryStats map = randomBoolean() ? null : FieldMemoryStatsTests.randomFieldMemoryStats();
CompletionStats stats = new CompletionStats(randomNonNegativeLong(), map);
BytesStreamOutput out = new BytesStreamOutput();
stats.writeTo(out);
StreamInput input = out.bytes().streamInput();
CompletionStats read = new CompletionStats(input);
assertEquals(-1, input.read());
assertEquals(stats.getSizeInBytes(), read.getSizeInBytes());
assertEquals(stats.getFields(), read.getFields());
}
}
| apache-2.0 |
s20121035/rk3288_android5.1_repo | external/chromium_org/android_webview/java/src/org/chromium/android_webview/AwContentsClient.java | 8483 | // Copyright 2012 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.android_webview;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Picture;
import android.net.http.SslError;
import android.os.Looper;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ConsoleMessage;
import android.webkit.GeolocationPermissions;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import org.chromium.android_webview.permission.AwPermissionRequest;
import java.security.Principal;
import java.util.HashMap;
/**
* Base-class that an AwContents embedder derives from to receive callbacks.
* This extends ContentViewClient, as in many cases we want to pass-thru ContentViewCore
* callbacks right to our embedder, and this setup facilities that.
* For any other callbacks we need to make transformations of (e.g. adapt parameters
* or perform filtering) we can provide final overrides for methods here, and then introduce
* new abstract methods that the our own client must implement.
* i.e.: all methods in this class should either be final, or abstract.
*/
public abstract class AwContentsClient {
private final AwContentsClientCallbackHelper mCallbackHelper;
// Last background color reported from the renderer. Holds the sentinal value INVALID_COLOR
// if not valid.
private int mCachedRendererBackgroundColor = INVALID_COLOR;
private static final int INVALID_COLOR = 0;
public AwContentsClient() {
this(Looper.myLooper());
}
// Alllow injection of the callback thread, for testing.
public AwContentsClient(Looper looper) {
mCallbackHelper = new AwContentsClientCallbackHelper(looper, this);
}
final AwContentsClientCallbackHelper getCallbackHelper() {
return mCallbackHelper;
}
final int getCachedRendererBackgroundColor() {
assert isCachedRendererBackgroundColorValid();
return mCachedRendererBackgroundColor;
}
final boolean isCachedRendererBackgroundColorValid() {
return mCachedRendererBackgroundColor != INVALID_COLOR;
}
final void onBackgroundColorChanged(int color) {
// Avoid storing the sentinal INVALID_COLOR (note that both 0 and 1 are both
// fully transparent so this transpose makes no visible difference).
mCachedRendererBackgroundColor = color == INVALID_COLOR ? 1 : color;
}
//--------------------------------------------------------------------------------------------
// WebView specific methods that map directly to WebViewClient / WebChromeClient
//--------------------------------------------------------------------------------------------
/**
* Parameters for the {@link AwContentsClient#showFileChooser} method.
*/
public static class FileChooserParams {
public int mode;
public String acceptTypes;
public String title;
public String defaultFilename;
public boolean capture;
}
/**
* Parameters for the {@link AwContentsClient#shouldInterceptRequest} method.
*/
public static class ShouldInterceptRequestParams {
// Url of the request.
public String url;
// Is this for the main frame or a child iframe?
public boolean isMainFrame;
// Was a gesture associated with the request? Don't trust can easily be spoofed.
public boolean hasUserGesture;
// Method used (GET/POST/OPTIONS)
public String method;
// Headers that would have been sent to server.
public HashMap<String, String> requestHeaders;
}
public abstract void getVisitedHistory(ValueCallback<String[]> callback);
public abstract void doUpdateVisitedHistory(String url, boolean isReload);
public abstract void onProgressChanged(int progress);
public abstract AwWebResourceResponse shouldInterceptRequest(
ShouldInterceptRequestParams params);
public abstract boolean shouldOverrideKeyEvent(KeyEvent event);
public abstract boolean shouldOverrideUrlLoading(String url);
public abstract void onLoadResource(String url);
public abstract void onUnhandledKeyEvent(KeyEvent event);
public abstract boolean onConsoleMessage(ConsoleMessage consoleMessage);
public abstract void onReceivedHttpAuthRequest(AwHttpAuthHandler handler,
String host, String realm);
public abstract void onReceivedSslError(ValueCallback<Boolean> callback, SslError error);
// TODO(sgurun): Make abstract once this has rolled in downstream.
public void onReceivedClientCertRequest(
final AwContentsClientBridge.ClientCertificateRequestCallback callback,
final String[] keyTypes, final Principal[] principals, final String host,
final int port) { }
public abstract void onReceivedLoginRequest(String realm, String account, String args);
public abstract void onFormResubmission(Message dontResend, Message resend);
public abstract void onDownloadStart(String url, String userAgent, String contentDisposition,
String mimeType, long contentLength);
// TODO(joth): Make abstract once this has rolled in downstream.
public /*abstract*/ void showFileChooser(ValueCallback<String[]> uploadFilePathsCallback,
FileChooserParams fileChooserParams) { }
public abstract void onGeolocationPermissionsShowPrompt(String origin,
GeolocationPermissions.Callback callback);
public abstract void onGeolocationPermissionsHidePrompt();
// TODO(michaelbai): Change the abstract once merged
public /*abstract*/ void onPermissionRequest(AwPermissionRequest awPermissionRequest) {}
// TODO(michaelbai): Change the abstract once merged
public /*abstract*/ void onPermissionRequestCanceled(
AwPermissionRequest awPermissionRequest) {}
public abstract void onScaleChangedScaled(float oldScale, float newScale);
protected abstract void handleJsAlert(String url, String message, JsResultReceiver receiver);
protected abstract void handleJsBeforeUnload(String url, String message,
JsResultReceiver receiver);
protected abstract void handleJsConfirm(String url, String message, JsResultReceiver receiver);
protected abstract void handleJsPrompt(String url, String message, String defaultValue,
JsPromptResultReceiver receiver);
protected abstract boolean onCreateWindow(boolean isDialog, boolean isUserGesture);
protected abstract void onCloseWindow();
public abstract void onReceivedTouchIconUrl(String url, boolean precomposed);
public abstract void onReceivedIcon(Bitmap bitmap);
public abstract void onReceivedTitle(String title);
protected abstract void onRequestFocus();
protected abstract View getVideoLoadingProgressView();
public abstract void onPageStarted(String url);
public abstract void onPageFinished(String url);
public abstract void onReceivedError(int errorCode, String description, String failingUrl);
// TODO (michaelbai): Remove this method once the same method remove from
// WebViewContentsClientAdapter.
public void onShowCustomView(View view,
int requestedOrientation, WebChromeClient.CustomViewCallback callback) {
}
// TODO (michaelbai): This method should be abstract, having empty body here
// makes the merge to the Android easy.
public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
onShowCustomView(view, ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED, callback);
}
public abstract void onHideCustomView();
public abstract Bitmap getDefaultVideoPoster();
//--------------------------------------------------------------------------------------------
// Other WebView-specific methods
//--------------------------------------------------------------------------------------------
//
public abstract void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches,
boolean isDoneCounting);
/**
* Called whenever there is a new content picture available.
* @param picture New picture.
*/
public abstract void onNewPicture(Picture picture);
}
| gpl-3.0 |
leogoing/spring_jeesite | src/main/java/com/thinkgem/jeesite/common/persistence/BaseDao.java | 269 | /**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.common.persistence;
/**
* DAO支持类实现
* @author ThinkGem
* @version 2014-05-16
*/
public interface BaseDao {
} | apache-2.0 |
sriharshanb/powermock | core/src/main/java/org/powermock/core/testlisteners/FieldDefaulter.java | 1629 | /*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.powermock.core.testlisteners;
import org.powermock.core.spi.support.AbstractPowerMockTestListenerBase;
import org.powermock.core.spi.testresult.TestMethodResult;
import org.powermock.reflect.Whitebox;
import org.powermock.reflect.internal.TypeUtils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Set;
/**
* A test listener that automatically set all instance fields to their default
* values after each test method. E.g. an object field is set to
* <code>null</code>, an <code>int</code> field is set to 0 and so on.
*/
public class FieldDefaulter extends AbstractPowerMockTestListenerBase {
@Override
public void afterTestMethod(Object testInstance, Method method, Object[] arguments, TestMethodResult testResult) throws Exception {
Set<Field> allFields = Whitebox.getAllInstanceFields(testInstance);
for (Field field : allFields) {
field.set(testInstance, TypeUtils.getDefaultValue(field.getType()));
}
}
}
| apache-2.0 |
roele/sling | samples/webloader/service/src/main/java/org/apache/sling/samples/webloader/Webloader.java | 1938 | /*
* 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.sling.samples.webloader;
/** Gets documents from the Web via a Google query, and stores them into the
* repository. The service interface is designed to be easy to use from Sling
* scripts.
*/
public interface Webloader {
/** Create a new job that loads documents in the repository, and start
* it immediately
* @return the job ID
* @param webQuery used to Google for documents to retrieve
* @param storagePath documents are stored under this path in the repository
* @param fileExtensions comma-separated list of extensions , each one
* is passed in turn to Google as a "filetype:" search option
* @param maxDocsToRetrieve up to this many documents are stored
* @param maxDocSizeInKb documents over this size are ignored, to speed up the process
*/
String createJob(String webQuery, String storagePath,
String fileExtensions, int maxDocsToRetrieve, int maxDocSizeInKb);
/** Get the status of a job given its ID
* @return null if the job doesn't exist
*/
WebloaderJobStatus getJobStatus(String jobId);
}
| apache-2.0 |
JuudeDemos/android-sdk-20 | src/java/lang/IllegalAccessException.java | 1618 | /*
* 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 java.lang;
/**
* Thrown when a program attempts to access a field or method which is not
* accessible from the location where the reference is made.
*/
public class IllegalAccessException extends ReflectiveOperationException {
private static final long serialVersionUID = 6616958222490762034L;
/**
* Constructs a new {@code IllegalAccessException} that includes the current
* stack trace.
*/
public IllegalAccessException() {
}
/**
* Constructs a new {@code IllegalAccessException} with the current stack
* trace and the specified detail message.
*
* @param detailMessage
* the detail message for this exception.
*/
public IllegalAccessException(String detailMessage) {
super(detailMessage);
}
}
| apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk/jdk/src/share/classes/javax/accessibility/AccessibleExtendedTable.java | 2976 | /*
* Copyright (c) 2001, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.accessibility;
/**
* Class AccessibleExtendedTable provides extended information about
* a user-interface component that presents data in a two-dimensional
* table format.
* Applications can determine if an object supports the
* AccessibleExtendedTable interface by first obtaining its
* AccessibleContext and then calling the
* {@link AccessibleContext#getAccessibleTable} method.
* If the return value is not null and the type of the return value is
* AccessibleExtendedTable, the object supports this interface.
*
* @author Lynn Monsanto
* @since 1.4
*/
public interface AccessibleExtendedTable extends AccessibleTable {
/**
* Returns the row number of an index in the table.
*
* @param index the zero-based index in the table. The index is
* the table cell offset from row == 0 and column == 0.
* @return the zero-based row of the table if one exists;
* otherwise -1.
*/
public int getAccessibleRow(int index);
/**
* Returns the column number of an index in the table.
*
* @param index the zero-based index in the table. The index is
* the table cell offset from row == 0 and column == 0.
* @return the zero-based column of the table if one exists;
* otherwise -1.
*/
public int getAccessibleColumn(int index);
/*
* Returns the index at a row and column in the table.
*
* @param r zero-based row of the table
* @param c zero-based column of the table
* @return the zero-based index in the table if one exists;
* otherwise -1. The index is the table cell offset from
* row == 0 and column == 0.
*/
public int getAccessibleIndex(int r, int c);
}
| mit |
iKrelve/DexHunter | dalvik/tests/083-jit-regressions/src/Main.java | 4427 | /*
* Copyright (C) 2009 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.
*/
import java.util.concurrent.*;
/**
* Test for Jit regressions.
*/
public class Main {
public static void main(String args[]) throws Exception {
b2296099Test();
b2302318Test();
b2487514Test();
b5884080Test();
zeroTest();
}
static void b2296099Test() throws Exception {
int x = -1190771042;
int dist = 360530809;
int xl = -1190771042;
int distl = 360530809;
for (int i = 0; i < 100000; i++) {
int b = rotateLeft(x, dist);
if (b != 1030884493)
throw new RuntimeException("Unexpected value: " + b
+ " after " + i + " iterations");
}
for (int i = 0; i < 100000; i++) {
long bl = rotateLeft(xl, distl);
if (bl != 1030884493)
throw new RuntimeException("Unexpected value: " + bl
+ " after " + i + " iterations");
}
System.out.println("b2296099 passes");
}
static int rotateLeft(int i, int distance) {
return ((i << distance) | (i >>> (-distance)));
}
static void b2302318Test() {
System.gc();
SpinThread slow = new SpinThread(Thread.MIN_PRIORITY);
SpinThread fast1 = new SpinThread(Thread.NORM_PRIORITY);
SpinThread fast2 = new SpinThread(Thread.MAX_PRIORITY);
slow.setDaemon(true);
fast1.setDaemon(true);
fast2.setDaemon(true);
fast2.start();
slow.start();
fast1.start();
try {
Thread.sleep(3000);
} catch (InterruptedException ie) {/*ignore */}
System.gc();
System.out.println("b2302318 passes");
}
static void b2487514Test() {
PriorityBlockingQueue q = new PriorityBlockingQueue(10);
int catchCount = 0;
q.offer(new Integer(0));
/*
* Warm up the code cache to have toArray() compiled. The key here is
* to pass a compatible type so that there are no exceptions when
* executing the method body (ie the APUT_OBJECT bytecode).
*/
for (int i = 0; i < 1000; i++) {
Integer[] ints = (Integer[]) q.toArray(new Integer[5]);
}
/* Now pass an incompatible type which is guaranteed to throw */
for (int i = 0; i < 1000; i++) {
try {
Object[] obj = q.toArray(new String[5]);
}
catch (ArrayStoreException success) {
catchCount++;
}
}
if (catchCount == 1000) {
System.out.println("b2487514 passes");
}
else {
System.out.println("b2487514 fails: catchCount is " + catchCount +
" (expecting 1000)");
}
}
static void b5884080Test() {
int vA = 1;
int l = 0;
do {
int k = 0;
do
vA += 1;
while(++k < 100);
} while (++l < 1000);
if (vA == 100001) {
System.out.println("b5884080 passes");
}
else {
System.out.println("b5884080 fails: vA is " + vA +
" (expecting 100001)");
}
}
static void zeroTest() throws Exception {
ZeroTests zt = new ZeroTests();
try {
zt.longDivTest();
} catch (Throwable th) {
th.printStackTrace();
}
try {
zt.longModTest();
} catch (Throwable th) {
th.printStackTrace();
}
}
}
class SpinThread extends Thread {
int mPriority;
SpinThread(int prio) {
super("Spin prio=" + prio);
mPriority = prio;
}
public void run() {
setPriority(mPriority);
while (true) {}
}
}
| apache-2.0 |
tseen/Federated-HDFS | tseenliu/FedHDFS-hadoop-src/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestDataNodeVolumeFailureReporting.java | 11522 | /**
* 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.datanode;
import static org.apache.hadoop.test.MetricsAsserts.assertCounter;
import static org.apache.hadoop.test.MetricsAsserts.getMetrics;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import java.io.File;
import java.util.ArrayList;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.impl.Log4JLogger;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.DFSTestUtil;
import org.apache.hadoop.hdfs.HdfsConfiguration;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeDescriptor;
import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeManager;
import org.apache.log4j.Level;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* Test reporting of DN volume failure counts and metrics.
*/
public class TestDataNodeVolumeFailureReporting {
private static final Log LOG = LogFactory.getLog(TestDataNodeVolumeFailureReporting.class);
{
((Log4JLogger)TestDataNodeVolumeFailureReporting.LOG).getLogger().setLevel(Level.ALL);
}
private FileSystem fs;
private MiniDFSCluster cluster;
private Configuration conf;
private String dataDir;
// Sleep at least 3 seconds (a 1s heartbeat plus padding) to allow
// for heartbeats to propagate from the datanodes to the namenode.
final int WAIT_FOR_HEARTBEATS = 3000;
// Wait at least (2 * re-check + 10 * heartbeat) seconds for
// a datanode to be considered dead by the namenode.
final int WAIT_FOR_DEATH = 15000;
@Before
public void setUp() throws Exception {
conf = new HdfsConfiguration();
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, 512L);
/*
* Lower the DN heartbeat, DF rate, and recheck interval to one second
* so state about failures and datanode death propagates faster.
*/
conf.setInt(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, 1);
conf.setInt(DFSConfigKeys.DFS_DF_INTERVAL_KEY, 1000);
conf.setInt(DFSConfigKeys.DFS_NAMENODE_HEARTBEAT_RECHECK_INTERVAL_KEY, 1000);
// Allow a single volume failure (there are two volumes)
conf.setInt(DFSConfigKeys.DFS_DATANODE_FAILED_VOLUMES_TOLERATED_KEY, 1);
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build();
cluster.waitActive();
fs = cluster.getFileSystem();
dataDir = cluster.getDataDirectory();
}
@After
public void tearDown() throws Exception {
for (int i = 0; i < 3; i++) {
FileUtil.setExecutable(new File(dataDir, "data"+(2*i+1)), true);
FileUtil.setExecutable(new File(dataDir, "data"+(2*i+2)), true);
}
cluster.shutdown();
}
/**
* Test that individual volume failures do not cause DNs to fail, that
* all volumes failed on a single datanode do cause it to fail, and
* that the capacities and liveliness is adjusted correctly in the NN.
*/
@Test
public void testSuccessiveVolumeFailures() throws Exception {
assumeTrue(!System.getProperty("os.name").startsWith("Windows"));
// Bring up two more datanodes
cluster.startDataNodes(conf, 2, true, null, null);
cluster.waitActive();
/*
* Calculate the total capacity of all the datanodes. Sleep for
* three seconds to be sure the datanodes have had a chance to
* heartbeat their capacities.
*/
Thread.sleep(WAIT_FOR_HEARTBEATS);
final DatanodeManager dm = cluster.getNamesystem().getBlockManager(
).getDatanodeManager();
final long origCapacity = DFSTestUtil.getLiveDatanodeCapacity(dm);
long dnCapacity = DFSTestUtil.getDatanodeCapacity(dm, 0);
File dn1Vol1 = new File(dataDir, "data"+(2*0+1));
File dn2Vol1 = new File(dataDir, "data"+(2*1+1));
File dn3Vol1 = new File(dataDir, "data"+(2*2+1));
File dn3Vol2 = new File(dataDir, "data"+(2*2+2));
/*
* Make the 1st volume directories on the first two datanodes
* non-accessible. We don't make all three 1st volume directories
* readonly since that would cause the entire pipeline to
* fail. The client does not retry failed nodes even though
* perhaps they could succeed because just a single volume failed.
*/
assertTrue("Couldn't chmod local vol", FileUtil.setExecutable(dn1Vol1, false));
assertTrue("Couldn't chmod local vol", FileUtil.setExecutable(dn2Vol1, false));
/*
* Create file1 and wait for 3 replicas (ie all DNs can still
* store a block). Then assert that all DNs are up, despite the
* volume failures.
*/
Path file1 = new Path("/test1");
DFSTestUtil.createFile(fs, file1, 1024, (short)3, 1L);
DFSTestUtil.waitReplication(fs, file1, (short)3);
ArrayList<DataNode> dns = cluster.getDataNodes();
assertTrue("DN1 should be up", dns.get(0).isDatanodeUp());
assertTrue("DN2 should be up", dns.get(1).isDatanodeUp());
assertTrue("DN3 should be up", dns.get(2).isDatanodeUp());
/*
* The metrics should confirm the volume failures.
*/
assertCounter("VolumeFailures", 1L,
getMetrics(dns.get(0).getMetrics().name()));
assertCounter("VolumeFailures", 1L,
getMetrics(dns.get(1).getMetrics().name()));
assertCounter("VolumeFailures", 0L,
getMetrics(dns.get(2).getMetrics().name()));
// Ensure we wait a sufficient amount of time
assert (WAIT_FOR_HEARTBEATS * 10) > WAIT_FOR_DEATH;
// Eventually the NN should report two volume failures
DFSTestUtil.waitForDatanodeStatus(dm, 3, 0, 2,
origCapacity - (1*dnCapacity), WAIT_FOR_HEARTBEATS);
/*
* Now fail a volume on the third datanode. We should be able to get
* three replicas since we've already identified the other failures.
*/
assertTrue("Couldn't chmod local vol", FileUtil.setExecutable(dn3Vol1, false));
Path file2 = new Path("/test2");
DFSTestUtil.createFile(fs, file2, 1024, (short)3, 1L);
DFSTestUtil.waitReplication(fs, file2, (short)3);
assertTrue("DN3 should still be up", dns.get(2).isDatanodeUp());
assertCounter("VolumeFailures", 1L,
getMetrics(dns.get(2).getMetrics().name()));
ArrayList<DatanodeDescriptor> live = new ArrayList<DatanodeDescriptor>();
ArrayList<DatanodeDescriptor> dead = new ArrayList<DatanodeDescriptor>();
dm.fetchDatanodes(live, dead, false);
live.clear();
dead.clear();
dm.fetchDatanodes(live, dead, false);
assertEquals("DN3 should have 1 failed volume",
1, live.get(2).getVolumeFailures());
/*
* Once the datanodes have a chance to heartbeat their new capacity the
* total capacity should be down by three volumes (assuming the host
* did not grow or shrink the data volume while the test was running).
*/
dnCapacity = DFSTestUtil.getDatanodeCapacity(dm, 0);
DFSTestUtil.waitForDatanodeStatus(dm, 3, 0, 3,
origCapacity - (3*dnCapacity), WAIT_FOR_HEARTBEATS);
/*
* Now fail the 2nd volume on the 3rd datanode. All its volumes
* are now failed and so it should report two volume failures
* and that it's no longer up. Only wait for two replicas since
* we'll never get a third.
*/
assertTrue("Couldn't chmod local vol", FileUtil.setExecutable(dn3Vol2, false));
Path file3 = new Path("/test3");
DFSTestUtil.createFile(fs, file3, 1024, (short)3, 1L);
DFSTestUtil.waitReplication(fs, file3, (short)2);
// The DN should consider itself dead
DFSTestUtil.waitForDatanodeDeath(dns.get(2));
// And report two failed volumes
assertCounter("VolumeFailures", 2L,
getMetrics(dns.get(2).getMetrics().name()));
// The NN considers the DN dead
DFSTestUtil.waitForDatanodeStatus(dm, 2, 1, 2,
origCapacity - (4*dnCapacity), WAIT_FOR_HEARTBEATS);
/*
* The datanode never tries to restore the failed volume, even if
* it's subsequently repaired, but it should see this volume on
* restart, so file creation should be able to succeed after
* restoring the data directories and restarting the datanodes.
*/
assertTrue("Couldn't chmod local vol", FileUtil.setExecutable(dn1Vol1, true));
assertTrue("Couldn't chmod local vol", FileUtil.setExecutable(dn2Vol1, true));
assertTrue("Couldn't chmod local vol", FileUtil.setExecutable(dn3Vol1, true));
assertTrue("Couldn't chmod local vol", FileUtil.setExecutable(dn3Vol2, true));
cluster.restartDataNodes();
cluster.waitActive();
Path file4 = new Path("/test4");
DFSTestUtil.createFile(fs, file4, 1024, (short)3, 1L);
DFSTestUtil.waitReplication(fs, file4, (short)3);
/*
* Eventually the capacity should be restored to its original value,
* and that the volume failure count should be reported as zero by
* both the metrics and the NN.
*/
DFSTestUtil.waitForDatanodeStatus(dm, 3, 0, 0, origCapacity,
WAIT_FOR_HEARTBEATS);
}
/**
* Test that the NN re-learns of volume failures after restart.
*/
@Test
public void testVolFailureStatsPreservedOnNNRestart() throws Exception {
assumeTrue(!System.getProperty("os.name").startsWith("Windows"));
// Bring up two more datanodes that can tolerate 1 failure
cluster.startDataNodes(conf, 2, true, null, null);
cluster.waitActive();
final DatanodeManager dm = cluster.getNamesystem().getBlockManager(
).getDatanodeManager();
long origCapacity = DFSTestUtil.getLiveDatanodeCapacity(dm);
long dnCapacity = DFSTestUtil.getDatanodeCapacity(dm, 0);
// Fail the first volume on both datanodes (we have to keep the
// third healthy so one node in the pipeline will not fail).
File dn1Vol1 = new File(dataDir, "data"+(2*0+1));
File dn2Vol1 = new File(dataDir, "data"+(2*1+1));
assertTrue("Couldn't chmod local vol", FileUtil.setExecutable(dn1Vol1, false));
assertTrue("Couldn't chmod local vol", FileUtil.setExecutable(dn2Vol1, false));
Path file1 = new Path("/test1");
DFSTestUtil.createFile(fs, file1, 1024, (short)2, 1L);
DFSTestUtil.waitReplication(fs, file1, (short)2);
// The NN reports two volumes failures
DFSTestUtil.waitForDatanodeStatus(dm, 3, 0, 2,
origCapacity - (1*dnCapacity), WAIT_FOR_HEARTBEATS);
// After restarting the NN it still see the two failures
cluster.restartNameNode(0);
cluster.waitActive();
DFSTestUtil.waitForDatanodeStatus(dm, 3, 0, 2,
origCapacity - (1*dnCapacity), WAIT_FOR_HEARTBEATS);
}
}
| apache-2.0 |
thomasdarimont/keycloak | model/jpa/src/main/java/org/keycloak/connections/jpa/entityprovider/JpaEntitySpi.java | 1430 | /*
* Copyright 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.keycloak.connections.jpa.entityprovider;
import org.keycloak.provider.Provider;
import org.keycloak.provider.ProviderFactory;
import org.keycloak.provider.Spi;
/**
* @author <a href="mailto:erik.mulder@docdatapayments.com">Erik Mulder</a>
*
* Spi that allows for adding extra JPA entity's to the Keycloak entity manager.
*/
public class JpaEntitySpi implements Spi {
@Override
public boolean isInternal() {
return true;
}
@Override
public String getName() {
return "jpa-entity-provider";
}
@Override
public Class<? extends Provider> getProviderClass() {
return JpaEntityProvider.class;
}
@Override
public Class<? extends ProviderFactory> getProviderFactoryClass() {
return JpaEntityProviderFactory.class;
}
}
| apache-2.0 |
zcwk/AndEngine | src/org/andengine/util/modifier/ease/EaseBounceInOut.java | 1822 | package org.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseBounceInOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseBounceInOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseBounceInOut() {
}
public static EaseBounceInOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseBounceInOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
final float percentage = pSecondsElapsed / pDuration;
if(percentage < 0.5f) {
return 0.5f * EaseBounceIn.getValue(2 * percentage);
} else {
return 0.5f + 0.5f * EaseBounceOut.getValue(percentage * 2 - 1);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| apache-2.0 |
zcwk/AndEngine | src/org/andengine/entity/modifier/ColorModifier.java | 4680 | package org.andengine.entity.modifier;
import org.andengine.entity.IEntity;
import org.andengine.util.color.Color;
import org.andengine.util.modifier.ease.EaseLinear;
import org.andengine.util.modifier.ease.IEaseFunction;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 15:39:50 - 29.06.2010
*/
public class ColorModifier extends TripleValueSpanEntityModifier {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
public ColorModifier(final float pDuration, final Color pFromColor, final Color pToColor) {
this(pDuration, pFromColor.getRed(), pToColor.getRed(), pFromColor.getGreen(), pToColor.getGreen(), pFromColor.getBlue(), pToColor.getBlue(), null, EaseLinear.getInstance());
}
public ColorModifier(final float pDuration, final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue) {
this(pDuration, pFromRed, pToRed, pFromGreen, pToGreen, pFromBlue, pToBlue, null, EaseLinear.getInstance());
}
public ColorModifier(final float pDuration, final Color pFromColor, final Color pToColor, final IEaseFunction pEaseFunction) {
this(pDuration, pFromColor.getRed(), pToColor.getRed(), pFromColor.getGreen(), pToColor.getGreen(), pFromColor.getBlue(), pToColor.getBlue(), null, pEaseFunction);
}
public ColorModifier(final float pDuration, final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue, final IEaseFunction pEaseFunction) {
this(pDuration, pFromRed, pToRed, pFromGreen, pToGreen, pFromBlue, pToBlue, null, pEaseFunction);
}
public ColorModifier(final float pDuration, final Color pFromColor, final Color pToColor, final IEntityModifierListener pEntityModifierListener) {
super(pDuration, pFromColor.getRed(), pToColor.getRed(), pFromColor.getGreen(), pToColor.getGreen(), pFromColor.getBlue(), pToColor.getBlue(), pEntityModifierListener, EaseLinear.getInstance());
}
public ColorModifier(final float pDuration, final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue, final IEntityModifierListener pEntityModifierListener) {
super(pDuration, pFromRed, pToRed, pFromGreen, pToGreen, pFromBlue, pToBlue, pEntityModifierListener, EaseLinear.getInstance());
}
public ColorModifier(final float pDuration, final Color pFromColor, final Color pToColor, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) {
super(pDuration, pFromColor.getRed(), pToColor.getRed(), pFromColor.getGreen(), pToColor.getGreen(), pFromColor.getBlue(), pToColor.getBlue(), pEntityModifierListener, pEaseFunction);
}
public ColorModifier(final float pDuration, final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) {
super(pDuration, pFromRed, pToRed, pFromGreen, pToGreen, pFromBlue, pToBlue, pEntityModifierListener, pEaseFunction);
}
protected ColorModifier(final ColorModifier pColorModifier) {
super(pColorModifier);
}
@Override
public ColorModifier deepCopy(){
return new ColorModifier(this);
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
protected void onSetInitialValues(final IEntity pEntity, final float pRed, final float pGreen, final float pBlue) {
pEntity.setColor(pRed, pGreen, pBlue);
}
@Override
protected void onSetValues(final IEntity pEntity, final float pPerctentageDone, final float pRed, final float pGreen, final float pBlue) {
pEntity.setColor(pRed, pGreen, pBlue);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| apache-2.0 |
caot/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/generation/CommentByBlockCommentHandler.java | 28839 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.generation;
import com.intellij.codeInsight.CodeInsightUtilBase;
import com.intellij.codeInsight.CommentUtil;
import com.intellij.codeInsight.actions.MultiCaretCodeInsightActionHandler;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.ide.highlighter.custom.CustomFileTypeLexer;
import com.intellij.lang.Commenter;
import com.intellij.lang.CustomUncommenter;
import com.intellij.lang.Language;
import com.intellij.lang.LanguageCommenters;
import com.intellij.lexer.Lexer;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.impl.AbstractFileType;
import com.intellij.openapi.fileTypes.impl.CustomSyntaxTableFileType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Couple;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import com.intellij.psi.codeStyle.Indent;
import com.intellij.psi.templateLanguages.MultipleLangCommentProvider;
import com.intellij.psi.templateLanguages.OuterLanguageElement;
import com.intellij.psi.templateLanguages.TemplateLanguageFileViewProvider;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtilBase;
import com.intellij.util.containers.IntArrayList;
import com.intellij.util.text.CharArrayUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
public class CommentByBlockCommentHandler extends MultiCaretCodeInsightActionHandler {
private Project myProject;
private Editor myEditor;
private Caret myCaret;
private @NotNull PsiFile myFile;
private Document myDocument;
private CommenterDataHolder mySelfManagedCommenterData;
@Override
public void invoke(@NotNull Project project, @NotNull Editor editor, @NotNull Caret caret, @NotNull PsiFile file) {
if (!CodeInsightUtilBase.prepareEditorForWrite(editor)) return;
myProject = project;
myEditor = editor;
myCaret = caret;
myFile = file;
myDocument = editor.getDocument();
if (!FileDocumentManager.getInstance().requestWriting(myDocument, project)) {
return;
}
FeatureUsageTracker.getInstance().triggerFeatureUsed("codeassists.comment.block");
final Commenter commenter = findCommenter(myFile, myEditor, caret);
if (commenter == null) return;
final String prefix;
final String suffix;
if (commenter instanceof SelfManagingCommenter) {
final SelfManagingCommenter selfManagingCommenter = (SelfManagingCommenter)commenter;
mySelfManagedCommenterData = selfManagingCommenter.createBlockCommentingState(
caret.getSelectionStart(),
caret.getSelectionEnd(),
myDocument,
myFile
);
if (mySelfManagedCommenterData == null) {
mySelfManagedCommenterData = SelfManagingCommenter.EMPTY_STATE;
}
prefix = selfManagingCommenter.getBlockCommentPrefix(
caret.getSelectionStart(),
myDocument,
mySelfManagedCommenterData
);
suffix = selfManagingCommenter.getBlockCommentSuffix(
caret.getSelectionEnd(),
myDocument,
mySelfManagedCommenterData
);
}
else {
prefix = commenter.getBlockCommentPrefix();
suffix = commenter.getBlockCommentSuffix();
}
if (prefix == null || suffix == null) return;
TextRange commentedRange = findCommentedRange(commenter);
if (commentedRange != null) {
final int commentStart = commentedRange.getStartOffset();
final int commentEnd = commentedRange.getEndOffset();
int selectionStart = commentStart;
int selectionEnd = commentEnd;
if (myCaret.hasSelection()) {
selectionStart = myCaret.getSelectionStart();
selectionEnd = myCaret.getSelectionEnd();
}
if ((commentStart < selectionStart || commentStart >= selectionEnd) && (commentEnd <= selectionStart || commentEnd > selectionEnd)) {
commentRange(selectionStart, selectionEnd, prefix, suffix, commenter);
}
else {
uncommentRange(commentedRange, trim(prefix), trim(suffix), commenter);
}
}
else {
if (myCaret.hasSelection()) {
int selectionStart = myCaret.getSelectionStart();
int selectionEnd = myCaret.getSelectionEnd();
if (commenter instanceof IndentedCommenter) {
final Boolean value = ((IndentedCommenter)commenter).forceIndentedLineComment();
if (value != null && value == Boolean.TRUE) {
selectionStart = myDocument.getLineStartOffset(myDocument.getLineNumber(selectionStart));
selectionEnd = myDocument.getLineEndOffset(myDocument.getLineNumber(selectionEnd));
}
}
commentRange(selectionStart, selectionEnd, prefix, suffix, commenter);
}
else {
EditorUtil.fillVirtualSpaceUntilCaret(editor);
int caretOffset = myCaret.getOffset();
if (commenter instanceof IndentedCommenter) {
final Boolean value = ((IndentedCommenter)commenter).forceIndentedLineComment();
if (value != null && value == Boolean.TRUE) {
final int lineNumber = myDocument.getLineNumber(caretOffset);
final int start = myDocument.getLineStartOffset(lineNumber);
final int end = myDocument.getLineEndOffset(lineNumber);
commentRange(start, end, prefix, suffix, commenter);
return;
}
}
myDocument.insertString(caretOffset, prefix + suffix);
myCaret.moveToOffset(caretOffset + prefix.length());
}
}
}
@Nullable
private static String trim(String s) {
return s == null ? null : s.trim();
}
private boolean testSelectionForNonComments() {
if (!myCaret.hasSelection()) {
return true;
}
TextRange range
= new TextRange(myCaret.getSelectionStart(), myCaret.getSelectionEnd() - 1);
for (PsiElement element = myFile.findElementAt(range.getStartOffset()); element != null && range.intersects(element.getTextRange());
element = element.getNextSibling()) {
if (element instanceof OuterLanguageElement) {
if (!isInjectedWhiteSpace(range, (OuterLanguageElement)element)) {
return false;
}
}
else {
if (!isWhiteSpaceOrComment(element, range)) {
return false;
}
}
}
return true;
}
private boolean isInjectedWhiteSpace(@NotNull TextRange range, @NotNull OuterLanguageElement element) {
PsiElement psi = element.getContainingFile().getViewProvider().getPsi(element.getLanguage());
if (psi == null) {
return false;
}
List<PsiElement> injectedElements = PsiTreeUtil.getInjectedElements(element);
for (PsiElement el : injectedElements) {
if (!isWhiteSpaceOrComment(el, range)) {
return false;
}
}
return true;
}
private boolean isWhiteSpaceOrComment(@NotNull PsiElement element, @NotNull TextRange range) {
final TextRange textRange = element.getTextRange();
TextRange intersection = range.intersection(textRange);
if (intersection == null) {
return false;
}
intersection = TextRange.create(Math.max(intersection.getStartOffset() - textRange.getStartOffset(), 0),
Math.min(intersection.getEndOffset() - textRange.getStartOffset(), textRange.getLength()));
return isWhiteSpaceOrComment(element) ||
intersection.substring(element.getText()).trim().length() == 0;
}
private static boolean isWhiteSpaceOrComment(PsiElement element) {
return element instanceof PsiWhiteSpace ||
PsiTreeUtil.getParentOfType(element, PsiComment.class, false) != null;
}
@Nullable
private TextRange findCommentedRange(final Commenter commenter) {
final CharSequence text = myDocument.getCharsSequence();
final FileType fileType = myFile.getFileType();
if (fileType instanceof CustomSyntaxTableFileType) {
Lexer lexer = new CustomFileTypeLexer(((CustomSyntaxTableFileType)fileType).getSyntaxTable());
final int caretOffset = myCaret.getOffset();
int commentStart = CharArrayUtil.lastIndexOf(text, commenter.getBlockCommentPrefix(), caretOffset);
if (commentStart == -1) return null;
lexer.start(text, commentStart, text.length());
if (lexer.getTokenType() == CustomHighlighterTokenType.MULTI_LINE_COMMENT && lexer.getTokenEnd() >= caretOffset) {
return new TextRange(commentStart, lexer.getTokenEnd());
}
return null;
}
final String prefix;
final String suffix;
// Custom uncommenter is able to find commented block inside of selected text
final String selectedText = myCaret.getSelectedText();
if ((commenter instanceof CustomUncommenter) && selectedText != null) {
final TextRange commentedRange = ((CustomUncommenter)commenter).findMaximumCommentedRange(selectedText);
if (commentedRange == null) {
return null;
}
// Uncommenter returns range relative to text start, so we need to shift it to make abosolute.
return commentedRange.shiftRight(myCaret.getSelectionStart());
}
if (commenter instanceof SelfManagingCommenter) {
SelfManagingCommenter selfManagingCommenter = (SelfManagingCommenter)commenter;
prefix = selfManagingCommenter.getBlockCommentPrefix(
myCaret.getSelectionStart(),
myDocument,
mySelfManagedCommenterData
);
suffix = selfManagingCommenter.getBlockCommentSuffix(
myCaret.getSelectionEnd(),
myDocument,
mySelfManagedCommenterData
);
}
else {
prefix = trim(commenter.getBlockCommentPrefix());
suffix = trim(commenter.getBlockCommentSuffix());
}
if (prefix == null || suffix == null) return null;
TextRange commentedRange;
if (commenter instanceof SelfManagingCommenter) {
commentedRange = ((SelfManagingCommenter)commenter).getBlockCommentRange(
myCaret.getSelectionStart(),
myCaret.getSelectionEnd(),
myDocument,
mySelfManagedCommenterData
);
}
else {
if (!testSelectionForNonComments()) {
return null;
}
commentedRange = getSelectedComments(text, prefix, suffix);
}
if (commentedRange == null) {
PsiElement comment = findCommentAtCaret();
if (comment != null) {
String commentText = comment.getText();
if (commentText.startsWith(prefix) && commentText.endsWith(suffix)) {
commentedRange = comment.getTextRange();
}
}
}
return commentedRange;
}
@Nullable
private TextRange getSelectedComments(CharSequence text, String prefix, String suffix) {
TextRange commentedRange = null;
if (myCaret.hasSelection()) {
int selectionStart = myCaret.getSelectionStart();
selectionStart = CharArrayUtil.shiftForward(text, selectionStart, " \t\n");
int selectionEnd = myCaret.getSelectionEnd() - 1;
selectionEnd = CharArrayUtil.shiftBackward(text, selectionEnd, " \t\n") + 1;
if (selectionEnd - selectionStart >= prefix.length() + suffix.length() &&
CharArrayUtil.regionMatches(text, selectionStart, prefix) &&
CharArrayUtil.regionMatches(text, selectionEnd - suffix.length(), suffix)) {
commentedRange = new TextRange(selectionStart, selectionEnd);
}
}
return commentedRange;
}
@Nullable
private static Commenter findCommenter(PsiFile file, Editor editor, Caret caret) {
final FileType fileType = file.getFileType();
if (fileType instanceof AbstractFileType) {
return ((AbstractFileType)fileType).getCommenter();
}
Language lang = PsiUtilBase.getLanguageInEditor(caret, file.getProject());
return getCommenter(file, editor, lang, lang);
}
@Nullable
public static Commenter getCommenter(final PsiFile file, final Editor editor,
final Language lineStartLanguage, final Language lineEndLanguage) {
final FileViewProvider viewProvider = file.getViewProvider();
for (MultipleLangCommentProvider provider : MultipleLangCommentProvider.EP_NAME.getExtensions()) {
if (provider.canProcess(file, viewProvider)) {
return provider.getLineCommenter(file, editor, lineStartLanguage, lineEndLanguage);
}
}
final Language fileLanguage = file.getLanguage();
Language lang = lineStartLanguage == null || LanguageCommenters.INSTANCE.forLanguage(lineStartLanguage) == null ||
fileLanguage.getBaseLanguage() == lineStartLanguage // file language is a more specific dialect of the line language
? fileLanguage
: lineStartLanguage;
if (viewProvider instanceof TemplateLanguageFileViewProvider &&
lang == ((TemplateLanguageFileViewProvider)viewProvider).getTemplateDataLanguage()) {
lang = viewProvider.getBaseLanguage();
}
return LanguageCommenters.INSTANCE.forLanguage(lang);
}
@Nullable
private PsiElement findCommentAtCaret() {
int offset = myCaret.getOffset();
TextRange range = new TextRange(myCaret.getSelectionStart(), myCaret.getSelectionEnd());
if (offset == range.getEndOffset()) {
offset--;
}
if (offset <= range.getStartOffset()) {
offset++;
}
PsiElement elt = myFile.getViewProvider().findElementAt(offset);
if (elt == null) return null;
PsiElement comment = PsiTreeUtil.getParentOfType(elt, PsiComment.class, false);
if (comment == null || myCaret.hasSelection() && !range.contains(comment.getTextRange())) {
return null;
}
return comment;
}
public void commentRange(int startOffset, int endOffset, String commentPrefix, String commentSuffix, Commenter commenter) {
final CharSequence chars = myDocument.getCharsSequence();
LogicalPosition caretPosition = myCaret.getLogicalPosition();
if (startOffset == 0 || chars.charAt(startOffset - 1) == '\n') {
if (endOffset == myDocument.getTextLength() || endOffset > 0 && chars.charAt(endOffset - 1) == '\n') {
CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(myProject);
CommonCodeStyleSettings settings = CodeStyleSettingsManager.getSettings(myProject).getCommonSettings(myFile.getLanguage());
String space;
if (!settings.BLOCK_COMMENT_AT_FIRST_COLUMN) {
final FileType fileType = myFile.getFileType();
int line1 = myEditor.offsetToLogicalPosition(startOffset).line;
int line2 = myEditor.offsetToLogicalPosition(endOffset - 1).line;
Indent minIndent = CommentUtil.getMinLineIndent(myProject, myDocument, line1, line2, fileType);
if (minIndent == null) {
minIndent = codeStyleManager.zeroIndent();
}
space = codeStyleManager.fillIndent(minIndent, fileType);
}
else {
space = "";
}
final StringBuilder nestingPrefix = new StringBuilder(space).append(commentPrefix);
if (!commentPrefix.endsWith("\n")) {
nestingPrefix.append("\n");
}
final StringBuilder nestingSuffix = new StringBuilder(space);
nestingSuffix.append(commentSuffix.startsWith("\n") ? commentSuffix.substring(1) : commentSuffix);
nestingSuffix.append("\n");
TextRange range =
insertNestedComments(startOffset, endOffset, nestingPrefix.toString(), nestingSuffix.toString(), commenter);
myCaret.setSelection(range.getStartOffset(), range.getEndOffset());
LogicalPosition pos = new LogicalPosition(caretPosition.line + 1, caretPosition.column);
myCaret.moveToLogicalPosition(pos);
return;
}
}
TextRange range = insertNestedComments(startOffset, endOffset, commentPrefix, commentSuffix, commenter);
myCaret.setSelection(range.getStartOffset(), range.getEndOffset());
LogicalPosition pos = new LogicalPosition(caretPosition.line, caretPosition.column + commentPrefix.length());
myCaret.moveToLogicalPosition(pos);
}
private int doBoundCommentingAndGetShift(int offset,
String commented,
int skipLength,
String toInsert,
boolean skipBrace,
TextRange selection) {
if (commented == null && (offset == selection.getStartOffset() || offset + (skipBrace ? skipLength : 0) == selection.getEndOffset())) {
return 0;
}
if (commented == null) {
myDocument.insertString(offset + (skipBrace ? skipLength : 0), toInsert);
return toInsert.length();
}
else {
myDocument.replaceString(offset, offset + skipLength, commented);
return commented.length() - skipLength;
}
}
private TextRange insertNestedComments(int startOffset,
int endOffset,
String commentPrefix,
String commentSuffix,
Commenter commenter) {
if (commenter instanceof SelfManagingCommenter) {
final SelfManagingCommenter selfManagingCommenter = (SelfManagingCommenter)commenter;
return selfManagingCommenter.insertBlockComment(
startOffset,
endOffset,
myDocument,
mySelfManagedCommenterData
);
}
String normalizedPrefix = commentPrefix.trim();
String normalizedSuffix = commentSuffix.trim();
IntArrayList nestedCommentPrefixes = new IntArrayList();
IntArrayList nestedCommentSuffixes = new IntArrayList();
String commentedPrefix = commenter.getCommentedBlockCommentPrefix();
String commentedSuffix = commenter.getCommentedBlockCommentSuffix();
CharSequence chars = myDocument.getCharsSequence();
for (int i = startOffset; i < endOffset; ++i) {
if (CharArrayUtil.regionMatches(chars, i, normalizedPrefix)) {
nestedCommentPrefixes.add(i);
}
else {
if (CharArrayUtil.regionMatches(chars, i, normalizedSuffix)) {
nestedCommentSuffixes.add(i);
}
}
}
int shift = 0;
if (!(commentedSuffix == null &&
!nestedCommentSuffixes.isEmpty() &&
nestedCommentSuffixes.get(nestedCommentSuffixes.size() - 1) + commentSuffix.length() == endOffset)) {
myDocument.insertString(endOffset, commentSuffix);
shift += commentSuffix.length();
}
// process nested comments in back order
int i = nestedCommentPrefixes.size() - 1;
int j = nestedCommentSuffixes.size() - 1;
final TextRange selection = new TextRange(startOffset, endOffset);
while (i >= 0 && j >= 0) {
final int prefixIndex = nestedCommentPrefixes.get(i);
final int suffixIndex = nestedCommentSuffixes.get(j);
if (prefixIndex > suffixIndex) {
shift += doBoundCommentingAndGetShift(prefixIndex, commentedPrefix, normalizedPrefix.length(), commentSuffix, false, selection);
--i;
}
else {
//if (insertPos < myDocument.getTextLength() && Character.isWhitespace(myDocument.getCharsSequence().charAt(insertPos))) {
// insertPos = suffixIndex + commentSuffix.length();
//}
shift += doBoundCommentingAndGetShift(suffixIndex, commentedSuffix, normalizedSuffix.length(), commentPrefix, true, selection);
--j;
}
}
while (i >= 0) {
final int prefixIndex = nestedCommentPrefixes.get(i);
shift += doBoundCommentingAndGetShift(prefixIndex, commentedPrefix, normalizedPrefix.length(), commentSuffix, false, selection);
--i;
}
while (j >= 0) {
final int suffixIndex = nestedCommentSuffixes.get(j);
shift += doBoundCommentingAndGetShift(suffixIndex, commentedSuffix, normalizedSuffix.length(), commentPrefix, true, selection);
--j;
}
if (!(commentedPrefix == null && !nestedCommentPrefixes.isEmpty() && nestedCommentPrefixes.get(0) == startOffset)) {
myDocument.insertString(startOffset, commentPrefix);
shift += commentPrefix.length();
}
RangeMarker marker = myDocument.createRangeMarker(startOffset, endOffset + shift);
try {
return processDocument(myDocument, marker, commenter, true);
}
finally {
marker.dispose();
}
}
static TextRange processDocument(Document document, RangeMarker marker, Commenter commenter, boolean escape) {
if (commenter instanceof EscapingCommenter) {
if (escape) {
((EscapingCommenter)commenter).escape(document, marker);
}
else {
((EscapingCommenter)commenter).unescape(document, marker);
}
}
return TextRange.create(marker.getStartOffset(), marker.getEndOffset());
}
private static int getNearest(String text, String pattern, int position) {
int result = text.indexOf(pattern, position);
return result == -1 ? text.length() : result;
}
static void commentNestedComments(@NotNull Document document, TextRange range, Commenter commenter) {
final int offset = range.getStartOffset();
final IntArrayList toReplaceWithComments = new IntArrayList();
final IntArrayList prefixes = new IntArrayList();
final String text = document.getCharsSequence().subSequence(range.getStartOffset(), range.getEndOffset()).toString();
final String commentedPrefix = commenter.getCommentedBlockCommentPrefix();
final String commentedSuffix = commenter.getCommentedBlockCommentSuffix();
final String commentPrefix = commenter.getBlockCommentPrefix();
final String commentSuffix = commenter.getBlockCommentSuffix();
int nearestSuffix = getNearest(text, commentedSuffix, 0);
int nearestPrefix = getNearest(text, commentedPrefix, 0);
int level = 0;
int lastSuffix = -1;
for (int i = Math.min(nearestPrefix, nearestSuffix); i < text.length(); i = Math.min(nearestPrefix, nearestSuffix)) {
if (i > nearestPrefix) {
nearestPrefix = getNearest(text, commentedPrefix, i);
continue;
}
if (i > nearestSuffix) {
nearestSuffix = getNearest(text, commentedSuffix, i);
continue;
}
if (i == nearestPrefix) {
if (level <= 0) {
if (lastSuffix != -1) {
toReplaceWithComments.add(lastSuffix);
}
level = 1;
lastSuffix = -1;
toReplaceWithComments.add(i);
prefixes.add(i);
}
else {
level++;
}
nearestPrefix = getNearest(text, commentedPrefix, nearestPrefix + 1);
}
else {
lastSuffix = i;
level--;
nearestSuffix = getNearest(text, commentedSuffix, nearestSuffix + 1);
}
}
if (lastSuffix != -1) {
toReplaceWithComments.add(lastSuffix);
}
int prefixIndex = prefixes.size() - 1;
for (int i = toReplaceWithComments.size() - 1; i >= 0; i--) {
int position = toReplaceWithComments.get(i);
if (prefixIndex >= 0 && position == prefixes.get(prefixIndex)) {
prefixIndex--;
document.replaceString(offset + position, offset + position + commentedPrefix.length(), commentPrefix);
}
else {
document.replaceString(offset + position, offset + position + commentedSuffix.length(), commentSuffix);
}
}
}
private TextRange expandRange(int delOffset1, int delOffset2) {
CharSequence chars = myDocument.getCharsSequence();
int offset1 = CharArrayUtil.shiftBackward(chars, delOffset1 - 1, " \t");
if (offset1 < 0 || chars.charAt(offset1) == '\n' || chars.charAt(offset1) == '\r') {
int offset2 = CharArrayUtil.shiftForward(chars, delOffset2, " \t");
if (offset2 == myDocument.getTextLength() || chars.charAt(offset2) == '\r' || chars.charAt(offset2) == '\n') {
delOffset1 = offset1 + 1;
if (offset2 < myDocument.getTextLength()) {
delOffset2 = offset2 + 1;
if (chars.charAt(offset2) == '\r' && offset2 + 1 < myDocument.getTextLength() && chars.charAt(offset2 + 1) == '\n') {
delOffset2++;
}
}
}
}
return new TextRange(delOffset1, delOffset2);
}
private Couple<TextRange> findCommentBlock(TextRange range, String commentPrefix, String commentSuffix) {
CharSequence chars = myDocument.getCharsSequence();
int startOffset = range.getStartOffset();
boolean endsProperly = CharArrayUtil.regionMatches(chars, range.getEndOffset() - commentSuffix.length(), commentSuffix);
TextRange start = expandRange(startOffset, startOffset + commentPrefix.length());
TextRange end;
if (endsProperly) {
end = expandRange(range.getEndOffset() - commentSuffix.length(), range.getEndOffset());
}
else {
end = new TextRange(range.getEndOffset(), range.getEndOffset());
}
return Couple.of(start, end);
}
public void uncommentRange(TextRange range, String commentPrefix, String commentSuffix, Commenter commenter) {
if (commenter instanceof SelfManagingCommenter) {
final SelfManagingCommenter selfManagingCommenter = (SelfManagingCommenter)commenter;
selfManagingCommenter.uncommentBlockComment(
range.getStartOffset(),
range.getEndOffset(),
myDocument,
mySelfManagedCommenterData
);
return;
}
String text = myDocument.getCharsSequence().subSequence(range.getStartOffset(), range.getEndOffset()).toString();
int startOffset = range.getStartOffset();
//boolean endsProperly = CharArrayUtil.regionMatches(chars, range.getEndOffset() - commentSuffix.length(), commentSuffix);
List<Couple<TextRange>> ranges = new ArrayList<Couple<TextRange>>();
if (commenter instanceof CustomUncommenter) {
/**
* In case of custom uncommenter, we need to ask it for list of [commentOpen-start,commentOpen-end], [commentClose-start,commentClose-end]
* and shift if according to current offset
*/
CustomUncommenter customUncommenter = (CustomUncommenter)commenter;
for (Couple<TextRange> coupleFromCommenter : customUncommenter.getCommentRangesToDelete(text)) {
TextRange openComment = coupleFromCommenter.first.shiftRight(startOffset);
TextRange closeComment = coupleFromCommenter.second.shiftRight(startOffset);
ranges.add(Couple.of(openComment, closeComment));
}
}
else {
// If commenter is not custom, we need to get this list by our selves
int position = 0;
while (true) {
int start = getNearest(text, commentPrefix, position);
if (start == text.length()) {
break;
}
position = start;
int end = getNearest(text, commentSuffix, position + commentPrefix.length()) + commentSuffix.length();
position = end;
Couple<TextRange> pair =
findCommentBlock(new TextRange(start + startOffset, end + startOffset), commentPrefix, commentSuffix);
ranges.add(pair);
}
}
RangeMarker marker = myDocument.createRangeMarker(range);
try {
for (int i = ranges.size() - 1; i >= 0; i--) {
Couple<TextRange> toDelete = ranges.get(i);
myDocument.deleteString(toDelete.first.getStartOffset(), toDelete.first.getEndOffset());
int shift = toDelete.first.getEndOffset() - toDelete.first.getStartOffset();
myDocument.deleteString(toDelete.second.getStartOffset() - shift, toDelete.second.getEndOffset() - shift);
if (commenter.getCommentedBlockCommentPrefix() != null) {
commentNestedComments(myDocument, new TextRange(toDelete.first.getEndOffset() - shift, toDelete.second.getStartOffset() - shift),
commenter);
}
}
processDocument(myDocument, marker, commenter, false);
}
finally {
marker.dispose();
}
}
}
| apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk/jdk/src/share/classes/javax/security/auth/DestroyFailedException.java | 2136 | /*
* Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.auth;
/**
* Signals that a <code>destroy</code> operation failed.
*
* <p> This exception is thrown by credentials implementing
* the <code>Destroyable</code> interface when the <code>destroy</code>
* method fails.
*
*/
public class DestroyFailedException extends Exception {
private static final long serialVersionUID = -7790152857282749162L;
/**
* Constructs a DestroyFailedException with no detail message. A detail
* message is a String that describes this particular exception.
*/
public DestroyFailedException() {
super();
}
/**
* Constructs a DestroyFailedException with the specified detail
* message. A detail message is a String that describes this particular
* exception.
*
* <p>
*
* @param msg the detail message.
*/
public DestroyFailedException(String msg) {
super(msg);
}
}
| mit |
mxrrow/zaicoin | src/deps/db/java/src/com/sleepycat/util/ExceptionWrapper.java | 1021 | /*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2000-2009 Oracle. All rights reserved.
*
* $Id$
*/
package com.sleepycat.util;
/**
* Interface implemented by exceptions that can contain nested exceptions.
*
* @author Mark Hayes
*/
public interface ExceptionWrapper {
/**
* Returns the nested exception or null if none is present.
*
* @return the nested exception or null if none is present.
*
* @deprecated replaced by {@link #getCause}.
*/
Throwable getDetail();
/**
* Returns the nested exception or null if none is present.
*
* <p>This method is intentionally defined to be the same signature as the
* <code>java.lang.Throwable.getCause</code> method in Java 1.4 and
* greater. By defining this method to return a nested exception, the Java
* 1.4 runtime will print the nested stack trace.</p>
*
* @return the nested exception or null if none is present.
*/
Throwable getCause();
}
| mit |
mxrrow/zaicoin | src/deps/db/test/scr024/src/com/sleepycat/util/test/ExceptionWrapperTest.java | 3867 | /*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2002-2009 Oracle. All rights reserved.
*
* $Id$
*/
package com.sleepycat.util.test;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import com.sleepycat.util.ExceptionUnwrapper;
import com.sleepycat.util.IOExceptionWrapper;
import com.sleepycat.util.RuntimeExceptionWrapper;
/**
* @author Mark Hayes
*/
public class ExceptionWrapperTest extends TestCase {
public static void main(String[] args) {
junit.framework.TestResult tr =
junit.textui.TestRunner.run(suite());
if (tr.errorCount() > 0 ||
tr.failureCount() > 0) {
System.exit(1);
} else {
System.exit(0);
}
}
public static Test suite() {
TestSuite suite = new TestSuite(ExceptionWrapperTest.class);
return suite;
}
public ExceptionWrapperTest(String name) {
super(name);
}
@Override
public void setUp() {
SharedTestUtils.printTestName("ExceptionWrapperTest." + getName());
}
public void testIOWrapper() {
try {
throw new IOExceptionWrapper(new RuntimeException("msg"));
} catch (IOException e) {
Exception ee = ExceptionUnwrapper.unwrap(e);
assertTrue(ee instanceof RuntimeException);
assertEquals("msg", ee.getMessage());
Throwable t = ExceptionUnwrapper.unwrapAny(e);
assertTrue(t instanceof RuntimeException);
assertEquals("msg", t.getMessage());
}
}
public void testRuntimeWrapper() {
try {
throw new RuntimeExceptionWrapper(new IOException("msg"));
} catch (RuntimeException e) {
Exception ee = ExceptionUnwrapper.unwrap(e);
assertTrue(ee instanceof IOException);
assertEquals("msg", ee.getMessage());
Throwable t = ExceptionUnwrapper.unwrapAny(e);
assertTrue(t instanceof IOException);
assertEquals("msg", t.getMessage());
}
}
public void testErrorWrapper() {
try {
throw new RuntimeExceptionWrapper(new Error("msg"));
} catch (RuntimeException e) {
try {
ExceptionUnwrapper.unwrap(e);
fail();
} catch (Error ee) {
assertTrue(ee instanceof Error);
assertEquals("msg", ee.getMessage());
}
Throwable t = ExceptionUnwrapper.unwrapAny(e);
assertTrue(t instanceof Error);
assertEquals("msg", t.getMessage());
}
}
/**
* Generates a stack trace for a nested exception and checks the output
* for the nested exception.
*/
public void testStackTrace() {
/* Nested stack traces are not avilable in Java 1.3. */
String version = System.getProperty("java.version");
if (version.startsWith("1.3.")) {
return;
}
Exception ex = new Exception("some exception");
String causedBy = "Caused by: java.lang.Exception: some exception";
try {
throw new RuntimeExceptionWrapper(ex);
} catch (RuntimeException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String s = sw.toString();
assertTrue(s.indexOf(causedBy) != -1);
}
try {
throw new IOExceptionWrapper(ex);
} catch (IOException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String s = sw.toString();
assertTrue(s.indexOf(causedBy) != -1);
}
}
}
| mit |
lcssos/cas-server | cas-server-webapp-support/src/test/java/org/jasig/cas/web/flow/ServiceAuthorizationCheckTests.java | 4644 | /*
* Licensed to Apereo under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Apereo 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 the following location:
*
* 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.jasig.cas.web.flow;
import java.util.ArrayList;
import java.util.List;
import org.jasig.cas.authentication.principal.WebApplicationService;
import org.jasig.cas.services.RegisteredService;
import org.jasig.cas.services.RegisteredServiceImpl;
import org.jasig.cas.services.ServicesManager;
import org.jasig.cas.services.UnauthorizedServiceException;
import org.jasig.cas.services.DefaultRegisteredServiceAccessStrategy;
import org.junit.Before;
import org.junit.Test;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.test.MockRequestContext;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
/**
* Mockito based tests for @{link ServiceAuthorizationCheck}
*
* @author Dmitriy Kopylenko
* @since 3.5.0
*/
public class ServiceAuthorizationCheckTests {
private ServiceAuthorizationCheck serviceAuthorizationCheck;
private final WebApplicationService authorizedService = mock(WebApplicationService.class);
private final WebApplicationService unauthorizedService = mock(WebApplicationService.class);
private final WebApplicationService undefinedService = mock(WebApplicationService.class);
private final ServicesManager servicesManager = mock(ServicesManager.class);
@Before
public void setUpMocks() {
final RegisteredServiceImpl authorizedRegisteredService = new RegisteredServiceImpl();
final RegisteredServiceImpl unauthorizedRegisteredService = new RegisteredServiceImpl();
unauthorizedRegisteredService.setAccessStrategy(
new DefaultRegisteredServiceAccessStrategy(false, false));
final List<RegisteredService> list = new ArrayList<>();
list.add(authorizedRegisteredService);
list.add(unauthorizedRegisteredService);
when(this.servicesManager.findServiceBy(this.authorizedService)).thenReturn(authorizedRegisteredService);
when(this.servicesManager.findServiceBy(this.unauthorizedService)).thenReturn(unauthorizedRegisteredService);
when(this.servicesManager.findServiceBy(this.undefinedService)).thenReturn(null);
when(this.servicesManager.getAllServices()).thenReturn(list);
this.serviceAuthorizationCheck = new ServiceAuthorizationCheck(this.servicesManager);
}
@Test
public void noServiceProvided() throws Exception {
final MockRequestContext mockRequestContext = new MockRequestContext();
final Event event = this.serviceAuthorizationCheck.doExecute(mockRequestContext);
assertEquals("success", event.getId());
}
@Test
public void authorizedServiceProvided() throws Exception {
final MockRequestContext mockRequestContext = new MockRequestContext();
mockRequestContext.getFlowScope().put("service", this.authorizedService);
final Event event = this.serviceAuthorizationCheck.doExecute(mockRequestContext);
assertEquals("success", event.getId());
}
@Test(expected=UnauthorizedServiceException.class)
public void unauthorizedServiceProvided() throws Exception {
final MockRequestContext mockRequestContext = new MockRequestContext();
mockRequestContext.getFlowScope().put("service", this.unauthorizedService);
this.serviceAuthorizationCheck.doExecute(mockRequestContext);
fail("Should have thrown UnauthorizedServiceException");
}
@Test(expected=UnauthorizedServiceException.class)
public void serviceThatIsNotRegisteredProvided() throws Exception {
final MockRequestContext mockRequestContext = new MockRequestContext();
mockRequestContext.getFlowScope().put("service", this.undefinedService);
this.serviceAuthorizationCheck.doExecute(mockRequestContext);
fail("Should have thrown UnauthorizedServiceException");
}
}
| apache-2.0 |
tomwscott/GoCD | config/config-api/src/com/thoughtworks/go/config/StageNotFoundException.java | 1760 | /*************************GO-LICENSE-START*********************************
* Copyright 2014 ThoughtWorks, 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.
*************************GO-LICENSE-END***********************************/
package com.thoughtworks.go.config;
public class StageNotFoundException extends RuntimeException {
private final String pipelineName;
private final String stageName;
public StageNotFoundException(String pipelineName, String stageName) {
super(String.format("Stage '%s' not found in pipeline '%s'", stageName, pipelineName));
this.pipelineName = pipelineName;
this.stageName = stageName;
}
public StageNotFoundException(CaseInsensitiveString pipelineName, CaseInsensitiveString stageName) {
this(CaseInsensitiveString.str(pipelineName), CaseInsensitiveString.str(stageName));
}
public String getPipelineName() {
return pipelineName;
}
public String getStageName() {
return stageName;
}
public static void bombIfNull(Object obj, CaseInsensitiveString pipelineName, CaseInsensitiveString stageName) {
if (obj == null) {
throw new StageNotFoundException(pipelineName, stageName);
}
}
} | apache-2.0 |
cxzl25/es | web/src/main/java/com/sishuok/es/showcase/move/repository/MoveRepository.java | 449 | /**
* Copyright (c) 2005-2012 https://github.com/zhangkaitao
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.sishuok.es.showcase.move.repository;
import com.sishuok.es.common.repository.BaseRepository;
import com.sishuok.es.showcase.move.entity.Move;
/**
* <p>User: Zhang Kaitao
* <p>Date: 13-2-4 下午3:00
* <p>Version: 1.0
*/
public interface MoveRepository extends BaseRepository<Move, Long> {
}
| apache-2.0 |
ivan-fedorov/intellij-community | plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/associations/impl/FileAssociationsManagerImpl.java | 9413 | /*
* Copyright 2005 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.lang.xpath.xslt.associations.impl;
import com.intellij.ide.projectView.ProjectView;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.JDOMExternalizable;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.pointers.VirtualFilePointer;
import com.intellij.openapi.vfs.pointers.VirtualFilePointerContainer;
import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.util.PsiUtilCore;
import org.intellij.lang.xpath.xslt.associations.FileAssociationsManager;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.util.*;
class FileAssociationsManagerImpl extends FileAssociationsManager implements ProjectComponent, JDOMExternalizable {
private static final Logger LOG = Logger.getInstance(FileAssociationsManagerImpl.class);
private final Project myProject;
private final VirtualFilePointerManager myFilePointerManager;
private final Map<VirtualFilePointer, VirtualFilePointerContainer> myAssociations;
private boolean myTempCopy;
public FileAssociationsManagerImpl(Project project, VirtualFilePointerManager filePointerManager) {
myProject = project;
myFilePointerManager = filePointerManager;
myAssociations = new LinkedHashMap<VirtualFilePointer, VirtualFilePointerContainer>();
}
public void markAsTempCopy() {
myTempCopy = true;
}
@SuppressWarnings({"unchecked"})
public void readExternal(Element element) throws InvalidDataException {
final List<Element> children = element.getChildren("file");
for (Element child : children) {
final String url = child.getAttributeValue("url");
if (url != null) {
final VirtualFilePointer pointer = myFilePointerManager.create(url, myProject, null);
final VirtualFilePointerContainer container = myFilePointerManager.createContainer(myProject);
container.readExternal(child, "association");
myAssociations.put(pointer, container);
}
}
}
public void writeExternal(Element element) throws WriteExternalException {
for (VirtualFilePointer pointer : myAssociations.keySet()) {
final Element e = new Element("file");
e.setAttribute("url", pointer.getUrl());
final VirtualFilePointerContainer container = myAssociations.get(pointer);
container.writeExternal(e, "association");
element.addContent(e);
}
}
public TransactionalManager getTempManager() {
return new TempManager(this, myProject, myFilePointerManager);
}
public void projectOpened() {
}
public void projectClosed() {
}
@NotNull
@NonNls
public String getComponentName() {
return "XSLT-Support.FileAssociationsManager";
}
public void initComponent() {
}
public void disposeComponent() {
clear();
}
private void clear() {
final Set<VirtualFilePointer> virtualFilePointers = myAssociations.keySet();
for (VirtualFilePointer pointer : virtualFilePointers) {
myAssociations.get(pointer).killAll();
}
myAssociations.clear();
}
void copyFrom(FileAssociationsManagerImpl source) {
clear();
myAssociations.putAll(copy(source));
touch();
}
private void touch() {
incModificationCount();
if (!myTempCopy) {
final ProjectView view = ProjectView.getInstance(myProject);
if (view != null) {
view.refresh();
}
}
}
private static HashMap<VirtualFilePointer, VirtualFilePointerContainer> copy(FileAssociationsManagerImpl other) {
final HashMap<VirtualFilePointer, VirtualFilePointerContainer> hashMap = new LinkedHashMap<VirtualFilePointer, VirtualFilePointerContainer>();
final Set<VirtualFilePointer> virtualFilePointers = other.myAssociations.keySet();
for (VirtualFilePointer pointer : virtualFilePointers) {
final VirtualFilePointerContainer container = other.myFilePointerManager.createContainer(other.myProject);
container.addAll(other.myAssociations.get(pointer));
hashMap.put(other.myFilePointerManager.duplicate(pointer, other.myProject, null), container);
}
return hashMap;
}
public void removeAssociations(PsiFile file) {
final VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile == null) return;
for (VirtualFilePointer pointer : myAssociations.keySet()) {
if (pointer.getUrl().equals(virtualFile.getUrl())) {
myAssociations.remove(pointer);
touch();
return;
}
}
}
public void removeAssociation(PsiFile file, PsiFile assoc) {
final VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile == null) return;
if (assoc.getVirtualFile() == null) return;
for (VirtualFilePointer pointer : myAssociations.keySet()) {
if (pointer.getUrl().equals(virtualFile.getUrl())) {
VirtualFilePointerContainer container = myAssociations.get(pointer);
if (container != null) {
//noinspection ConstantConditions
final VirtualFilePointer p = container.findByUrl(assoc.getVirtualFile().getUrl());
if (p != null) {
container.remove(p);
if (container.size() == 0) {
myAssociations.remove(pointer);
}
touch();
}
}
return;
}
}
}
public void addAssociation(PsiFile file, PsiFile assoc) {
final VirtualFile virtualFile = assoc.getVirtualFile();
if (virtualFile == null) {
LOG.warn("No VirtualFile for " + file.getName());
return;
}
addAssociation(file, virtualFile);
}
public void addAssociation(PsiFile file, VirtualFile assoc) {
final VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile == null) {
LOG.warn("No VirtualFile for " + file.getName());
return;
}
for (VirtualFilePointer pointer : myAssociations.keySet()) {
if (pointer.getUrl().equals(virtualFile.getUrl())) {
VirtualFilePointerContainer container = myAssociations.get(pointer);
if (container == null) {
container = myFilePointerManager.createContainer(myProject);
myAssociations.put(pointer, container);
}
if (container.findByUrl(assoc.getUrl()) == null) {
container.add(assoc);
touch();
}
return;
}
}
final VirtualFilePointerContainer container = myFilePointerManager.createContainer(myProject);
container.add(assoc);
myAssociations.put(myFilePointerManager.create(virtualFile, myProject, null), container);
touch();
}
public Map<VirtualFile, VirtualFile[]> getAssociations() {
final HashMap<VirtualFile, VirtualFile[]> map = new LinkedHashMap<VirtualFile, VirtualFile[]>();
final Set<VirtualFilePointer> set = myAssociations.keySet();
for (VirtualFilePointer pointer : set) {
if (pointer.isValid()) {
final VirtualFile file = pointer.getFile();
map.put(file, myAssociations.get(pointer).getFiles());
}
}
return map;
}
public PsiFile[] getAssociationsFor(PsiFile file) {
return getAssociationsFor(file, FileType.EMPTY_ARRAY);
}
public PsiFile[] getAssociationsFor(PsiFile file, FileType... fileTypes) {
final VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile == null) return PsiFile.EMPTY_ARRAY;
for (VirtualFilePointer pointer : myAssociations.keySet()) {
if (pointer.isValid() && pointer.getUrl().equals(virtualFile.getUrl())) {
final VirtualFilePointerContainer container = myAssociations.get(pointer);
if (container != null) {
final VirtualFile[] files = container.getFiles();
final Set<PsiFile> list = new HashSet<PsiFile>();
final PsiManager psiManager = PsiManager.getInstance(myProject);
for (VirtualFile assoc : files) {
final PsiFile psiFile = psiManager.findFile(assoc);
if (psiFile != null && (fileTypes.length == 0 || matchesFileType(psiFile, fileTypes))) {
list.add(psiFile);
}
}
return PsiUtilCore.toPsiFileArray(list);
}
else {
return PsiFile.EMPTY_ARRAY;
}
}
}
return PsiFile.EMPTY_ARRAY;
}
private static boolean matchesFileType(PsiFile psiFile, FileType... fileTypes) {
for (FileType fileType : fileTypes) {
if (psiFile.getFileType().equals(fileType)) return true;
}
return false;
}
}
| apache-2.0 |
keycloak/keycloak | util/embedded-ldap/src/main/java/org/keycloak/util/ldap/KerberosKeytabCreator.java | 3739 | /*
* Copyright 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.keycloak.util.ldap;
import org.apache.directory.server.kerberos.shared.crypto.encryption.KerberosKeyFactory;
import org.apache.directory.server.kerberos.shared.keytab.Keytab;
import org.apache.directory.server.kerberos.shared.keytab.KeytabEntry;
import org.apache.directory.shared.kerberos.KerberosTime;
import org.apache.directory.shared.kerberos.codec.types.EncryptionType;
import org.apache.directory.shared.kerberos.components.EncryptionKey;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* Helper utility for creating Keytab files.
*
* @author Josef Cacek
*/
public class KerberosKeytabCreator {
// Public methods --------------------------------------------------------
/**
* The main.
*
* @param args
* @throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
if (args == null || args.length != 3) {
System.out.println("Kerberos keytab generator");
System.out.println("-------------------------");
System.out.println("Arguments missing or invalid. Required arguments are: <principalName> <passPhrase> <outputKeytabFile>");
System.out.println("Example of usage:");
System.out.println("java -jar embedded-ldap/target/embedded-ldap.jar keytabCreator HTTP/localhost@KEYCLOAK.ORG httppassword http.keytab");
} else {
final File keytabFile = new File(args[2]);
createKeytab(args[0], args[1], keytabFile);
System.out.println("Keytab file was created: " + keytabFile.getAbsolutePath() + ", principal: " + args[0] + ", passphrase: " + args[1]);
}
}
// Just for the reflection purposes
public static void execute(String[] args, Properties defaultProperties) throws Exception {
main(args);
}
/**
* Creates a keytab file for given principal.
*
* @param principalName
* @param passPhrase
* @param keytabFile
* @throws IOException
*/
public static void createKeytab(final String principalName, final String passPhrase, final File keytabFile)
throws IOException {
final KerberosTime timeStamp = new KerberosTime();
final int principalType = 1; // KRB5_NT_PRINCIPAL
final Keytab keytab = Keytab.getInstance();
final List<KeytabEntry> entries = new ArrayList<KeytabEntry>();
for (Map.Entry<EncryptionType, EncryptionKey> keyEntry : KerberosKeyFactory.getKerberosKeys(principalName, passPhrase)
.entrySet()) {
System.out.println("Adding keytab entry of type: " + keyEntry.getKey().getName());
final EncryptionKey key = keyEntry.getValue();
final byte keyVersion = (byte) key.getKeyVersion();
entries.add(new KeytabEntry(principalName, principalType, timeStamp, keyVersion, key));
}
keytab.setEntries(entries);
keytab.write(keytabFile);
}
}
| apache-2.0 |
idea4bsd/idea4bsd | platform/diff-impl/src/com/intellij/diff/util/TextDiffType.java | 1286 | /*
* 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.diff.util;
import com.intellij.openapi.editor.Editor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
public interface TextDiffType {
@NotNull TextDiffType INSERTED = TextDiffTypeFactory.INSERTED;
@NotNull TextDiffType DELETED = TextDiffTypeFactory.DELETED;
@NotNull TextDiffType MODIFIED = TextDiffTypeFactory.MODIFIED;
@NotNull TextDiffType CONFLICT = TextDiffTypeFactory.CONFLICT;
@NotNull
String getName();
@NotNull
Color getColor(@Nullable Editor editor);
@NotNull
Color getIgnoredColor(@Nullable Editor editor);
@Nullable
Color getMarkerColor(@Nullable Editor editor);
}
| apache-2.0 |
roadlabs/android | zxing-1.6/core/src/com/google/zxing/oned/UPCAReader.java | 2583 | /*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.oned;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.common.BitArray;
import java.util.Hashtable;
/**
* <p>Implements decoding of the UPC-A format.</p>
*
* @author dswitkin@google.com (Daniel Switkin)
* @author Sean Owen
*/
public final class UPCAReader extends UPCEANReader {
private final UPCEANReader ean13Reader = new EAN13Reader();
public Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange, Hashtable hints)
throws NotFoundException, FormatException, ChecksumException {
return maybeReturnResult(ean13Reader.decodeRow(rowNumber, row, startGuardRange, hints));
}
public Result decodeRow(int rowNumber, BitArray row, Hashtable hints)
throws NotFoundException, FormatException, ChecksumException {
return maybeReturnResult(ean13Reader.decodeRow(rowNumber, row, hints));
}
public Result decode(BinaryBitmap image) throws NotFoundException, FormatException {
return maybeReturnResult(ean13Reader.decode(image));
}
public Result decode(BinaryBitmap image, Hashtable hints) throws NotFoundException, FormatException {
return maybeReturnResult(ean13Reader.decode(image, hints));
}
BarcodeFormat getBarcodeFormat() {
return BarcodeFormat.UPC_A;
}
protected int decodeMiddle(BitArray row, int[] startRange, StringBuffer resultString)
throws NotFoundException {
return ean13Reader.decodeMiddle(row, startRange, resultString);
}
private static Result maybeReturnResult(Result result) throws FormatException {
String text = result.getText();
if (text.charAt(0) == '0') {
return new Result(text.substring(1), null, result.getResultPoints(), BarcodeFormat.UPC_A);
} else {
throw FormatException.getFormatInstance();
}
}
}
| mit |
akosyakov/intellij-community | plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/renamer/PoolInterceptor.java | 1494 | /*
* 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 org.jetbrains.java.decompiler.modules.renamer;
import org.jetbrains.java.decompiler.main.extern.IIdentifierRenamer;
import java.util.HashMap;
public class PoolInterceptor {
private final IIdentifierRenamer helper;
private final HashMap<String, String> mapOldToNewNames = new HashMap<String, String>();
private final HashMap<String, String> mapNewToOldNames = new HashMap<String, String>();
public PoolInterceptor(IIdentifierRenamer helper) {
this.helper = helper;
}
public void addName(String oldName, String newName) {
mapOldToNewNames.put(oldName, newName);
mapNewToOldNames.put(newName, oldName);
}
public String getName(String oldName) {
return mapOldToNewNames.get(oldName);
}
public String getOldName(String newName) {
return mapNewToOldNames.get(newName);
}
public IIdentifierRenamer getHelper() {
return helper;
}
}
| apache-2.0 |
caot/intellij-community | platform/platform-impl/src/com/intellij/util/ui/ValidatingTableEditor.java | 12809 | /*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.util.ui;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CustomShortcutSet;
import com.intellij.openapi.application.ApplicationBundle;
import com.intellij.openapi.util.NullableComputable;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.ui.AnActionButton;
import com.intellij.ui.AnActionButtonRunnable;
import com.intellij.ui.HoverHyperlinkLabel;
import com.intellij.ui.ToolbarDecorator;
import com.intellij.ui.table.TableView;
import com.intellij.util.IconUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public abstract class ValidatingTableEditor<Item> implements ComponentWithEmptyText {
private static final Icon WARNING_ICON = UIUtil.getBalloonWarningIcon();
private static final Icon EMPTY_ICON = EmptyIcon.create(WARNING_ICON);
@NonNls private static final String REMOVE_KEY = "REMOVE_SELECTED";
public interface RowHeightProvider {
int getRowHeight();
}
public interface Fix extends Runnable {
String getTitle();
}
private class ColumnInfoWrapper extends ColumnInfo<Item, Object> {
private final ColumnInfo<Item, Object> myDelegate;
public ColumnInfoWrapper(ColumnInfo<Item, Object> delegate) {
super(delegate.getName());
myDelegate = delegate;
}
@Override
public Object valueOf(Item item) {
return myDelegate.valueOf(item);
}
@Override
public boolean isCellEditable(Item item) {
return myDelegate.isCellEditable(item);
}
@Override
public void setValue(Item item, Object value) {
myDelegate.setValue(item, value);
updateMessage(-1, null);
}
@Override
public TableCellEditor getEditor(Item item) {
return myDelegate.getEditor(item);
}
@Override
public int getWidth(JTable table) {
return myDelegate.getWidth(table);
}
@Override
public Class getColumnClass() {
return myDelegate.getColumnClass();
}
@Override
public TableCellRenderer getRenderer(Item item) {
return myDelegate.getRenderer(item);
}
}
private JPanel myContentPane;
private TableView<Item> myTable;
private AnActionButton myRemoveButton;
private JLabel myMessageLabel;
private HoverHyperlinkLabel myFixLink;
private JPanel myTablePanel;
private final List<String> myWarnings = new ArrayList<String>();
private Fix myFixRunnable;
protected abstract Item cloneOf(Item item);
@Nullable
protected Pair<String, Fix> validate(List<Item> current, List<String> warnings) {
String error = null;
for (int i = 0; i < current.size(); i++) {
Item item = current.get(i);
String s = validate(item);
warnings.set(i, s);
if (error == null) {
error = s;
}
}
return error != null ? Pair.create(error, (Fix)null) : null;
}
@Nullable
protected String validate(Item item) {
return null;
}
@Nullable
protected abstract Item createItem();
private class IconColumn extends ColumnInfo<Item, Object> implements RowHeightProvider {
public IconColumn() {
super(" ");
}
public String valueOf(Item item) {
return null;
}
@Override
public int getWidth(JTable table) {
return WARNING_ICON.getIconWidth() + 2;
}
public int getRowHeight() {
return WARNING_ICON.getIconHeight();
}
@Override
public TableCellRenderer getRenderer(final Item item) {
return new WarningIconCellRenderer(new NullableComputable<String>() {
public String compute() {
return myWarnings.get(doGetItems().indexOf(item));
}
});
}
}
@NotNull
@Override
public StatusText getEmptyText() {
return myTable.getEmptyText();
}
private void createUIComponents() {
myTable = new ChangesTrackingTableView<Item>() {
protected void onCellValueChanged(int row, int column, Object value) {
final Item original = getItems().get(row);
Item override = cloneOf(original);
final ColumnInfo<Item, Object> columnInfo = getTableModel().getColumnInfos()[column];
columnInfo.setValue(override, value);
updateMessage(row, override);
}
@Override
protected void onEditingStopped() {
updateMessage(-1, null);
}
};
myFixLink = new HoverHyperlinkLabel(null);
}
protected ValidatingTableEditor(@Nullable AnActionButton ... extraButtons) {
ToolbarDecorator decorator =
ToolbarDecorator.createDecorator(myTable).disableRemoveAction().disableUpAction().disableDownAction();
decorator.setAddAction(new AnActionButtonRunnable() {
@Override
public void run(AnActionButton anActionButton) {
addItem();
}
});
myRemoveButton = new AnActionButton(ApplicationBundle.message("button.remove"), IconUtil.getRemoveIcon()) {
@Override
public void actionPerformed(AnActionEvent e) {
removeSelected();
}
};
myRemoveButton.setShortcut(CustomShortcutSet.fromString("alt DELETE")); //NON-NLS
decorator.addExtraAction(myRemoveButton);
if (extraButtons != null && extraButtons.length != 0) {
for (AnActionButton extraButton : extraButtons) {
decorator.addExtraAction(extraButton);
}
}
myTablePanel.add(decorator.createPanel(), BorderLayout.CENTER);
myTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
updateButtons();
}
});
myTable.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), REMOVE_KEY);
myTable.getActionMap().put(REMOVE_KEY, new AbstractAction() {
public void actionPerformed(final ActionEvent e) {
removeSelected();
}
});
myFixLink.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED && myFixRunnable != null) {
myFixRunnable.run();
}
}
});
}
protected ValidatingTableEditor() {
//noinspection NullArgumentToVariableArgMethod
this(null);
}
@Nullable
public List<Item> getSelectedItems() {
return myTable.getSelectedObjects();
}
private void removeSelected() {
myTable.stopEditing();
List<Item> items = new ArrayList<Item>(doGetItems());
final int[] rows = myTable.getSelectedRows();
for (int i = rows.length - 1; i >= 0; i--) {
items.remove(rows[i]);
}
setItems(items);
updateMessage(-1, null);
if (!items.isEmpty()) {
int index = Math.min(rows[0], items.size() - 1);
myTable.getSelectionModel().addSelectionInterval(index, index);
}
}
protected void addItem() {
Item newItem = createItem();
if (newItem == null) {
return;
}
List<Item> items = new ArrayList<Item>(doGetItems());
items.add(newItem);
setItems(items);
final int row = items.size() - 1;
myTable.getSelectionModel().setSelectionInterval(row, row);
myTable.scrollRectToVisible(myTable.getCellRect(row, 0, true));
if (getTableModel().getColumnInfos()[1].isCellEditable(items.get(row))) {
myTable.editCellAt(row, 1);
IdeFocusManager.findInstanceByComponent(myContentPane).requestFocus(myTable.getEditorComponent(), true);
}
updateMessage(-1, null);
}
private ListTableModel<Item> getTableModel() {
return (ListTableModel<Item>)myTable.getModel();
}
public void setModel(ColumnInfo<Item, Object>[] valueColumns, List<Item> items) {
ColumnInfo[] columns = new ColumnInfo[valueColumns.length + 1];
IconColumn iconColumn = new IconColumn();
int maxHeight = iconColumn.getRowHeight();
columns[0] = iconColumn;
for (int i = 0; i < valueColumns.length; i++) {
columns[i + 1] = new ColumnInfoWrapper(valueColumns[i]);
if (valueColumns[i] instanceof RowHeightProvider) {
maxHeight = Math.max(maxHeight, ((RowHeightProvider)valueColumns[i]).getRowHeight());
}
}
myTable.stopEditing();
myTable.setModelAndUpdateColumns(new ListTableModel<Item>(columns));
if (maxHeight > 0) {
myTable.setRowHeight(maxHeight);
}
setItems(items);
updateMessage(-1, null);
}
public List<Item> getItems() {
return Collections.unmodifiableList(doGetItems());
}
private List<Item> doGetItems() {
List<Item> items = new ArrayList<Item>(getTableModel().getItems());
if (myTable.isEditing()) {
Object value = ChangesTrackingTableView.getValue(myTable.getEditorComponent());
ColumnInfo column = ((ListTableModel)myTable.getModel()).getColumnInfos()[myTable.getEditingColumn()];
((ColumnInfoWrapper)column).myDelegate.setValue(items.get(myTable.getEditingRow()), value);
}
return items;
}
private void setItems(List<Item> items) {
if (items.isEmpty()) {
getTableModel().setItems(Collections.<Item>emptyList());
myWarnings.clear();
}
else {
myWarnings.clear();
for (Item item : items) {
myWarnings.add(null);
}
getTableModel().setItems(new ArrayList<Item>(items));
}
updateButtons();
}
public void setTableHeader(JTableHeader header) {
myTable.setTableHeader(header);
}
private void updateButtons() {
myRemoveButton.setEnabled(myTable.getSelectedRow() != -1);
}
public void updateMessage(int index, @Nullable Item override) {
List<Item> current = new ArrayList<Item>(doGetItems());
if (override != null) {
current.set(index, override);
}
displayMessageAndFix(validate(current, myWarnings));
myTable.repaint();
}
protected void displayMessageAndFix(@Nullable Pair<String, Fix> messageAndFix) {
if (messageAndFix != null) {
myMessageLabel.setText(messageAndFix.first);
myMessageLabel.setIcon(WARNING_ICON);
myMessageLabel.setVisible(true);
myFixRunnable = messageAndFix.second;
myFixLink.setVisible(myFixRunnable != null);
myFixLink.setText(myFixRunnable != null ? myFixRunnable.getTitle() : null);
}
else {
myMessageLabel.setText(" ");
myMessageLabel.setIcon(EMPTY_ICON);
myFixLink.setVisible(false);
myFixRunnable = null;
}
}
public void hideMessageLabel() {
myMessageLabel.setVisible(false);
myFixLink.setVisible(false);
}
public JComponent getPreferredFocusedComponent() {
return myTable;
}
private static class WarningIconCellRenderer extends DefaultTableCellRenderer {
private final NullableComputable<String> myWarningProvider;
public WarningIconCellRenderer(NullableComputable<String> warningProvider) {
myWarningProvider = warningProvider;
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
JLabel label = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
String message = myWarningProvider.compute();
label.setIcon(message != null ? WARNING_ICON : null);
label.setToolTipText(message);
label.setHorizontalAlignment(CENTER);
label.setVerticalAlignment(CENTER);
return label;
}
}
public Component getContentPane() {
return myContentPane;
}
public void setColumnReorderingAllowed(boolean value) {
JTableHeader header = myTable.getTableHeader();
if (header != null) {
header.setReorderingAllowed(value);
}
}
}
| apache-2.0 |
nvoron23/hadoop-20 | src/mapred/org/apache/hadoop/mapred/pipes/UpwardProtocol.java | 2946 | /**
* 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.mapred.pipes;
import java.io.IOException;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
/**
* The interface for the messages that can come up from the child. All of these
* calls are asynchronous and return before the message has been processed.
*/
interface UpwardProtocol<K extends WritableComparable, V extends Writable> {
/**
* Output a record from the child.
* @param key the record's key
* @param value the record's value
* @throws IOException
*/
void output(K key, V value) throws IOException;
/**
* Map functions where the application has defined a partition function
* output records along with their partition.
* @param reduce the reduce to send this record to
* @param key the record's key
* @param value the record's value
* @throws IOException
*/
void partitionedOutput(int reduce, K key,
V value) throws IOException;
/**
* Update the task's status message
* @param msg the string to display to the user
* @throws IOException
*/
void status(String msg) throws IOException;
/**
* Report making progress (and the current progress)
* @param progress the current progress (0.0 to 1.0)
* @throws IOException
*/
void progress(float progress) throws IOException;
/**
* Report that the application has finished processing all inputs
* successfully.
* @throws IOException
*/
void done() throws IOException;
/**
* Report that the application or more likely communication failed.
* @param e
*/
void failed(Throwable e);
/**
* Register a counter with the given id and group/name.
* @param group counter group
* @param name counter name
* @throws IOException
*/
void registerCounter(int id, String group, String name) throws IOException;
/**
* Increment the value of a registered counter.
* @param id counter id of the registered counter
* @param amount increment for the counter value
* @throws IOException
*/
void incrementCounter(int id, long amount) throws IOException;
}
| apache-2.0 |
kindras/OwnCloud-Android | src/com/owncloud/android/ui/activity/UploadPathActivity.java | 2639 | /**
* ownCloud Android client application
*
* Copyright (C) 2015 ownCloud Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This 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/>.
*
*/
package com.owncloud.android.ui.activity;
import android.accounts.Account;
import android.os.Bundle;
import android.view.View.OnClickListener;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.ui.fragment.FileFragment;
import com.owncloud.android.ui.fragment.OCFileListFragment;
public class UploadPathActivity extends FolderPickerActivity implements FileFragment.ContainerActivity,
OnClickListener, OnEnforceableRefreshListener {
public static final String KEY_INSTANT_UPLOAD_PATH = "INSTANT_UPLOAD_PATH";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String instantUploadPath = getIntent().getStringExtra(KEY_INSTANT_UPLOAD_PATH);
// The caller activity (Preferences) is not a FileActivity, so it has no OCFile, only a path.
OCFile folder = new OCFile(instantUploadPath);
setFile(folder);
}
/**
* Called when the ownCloud {@link Account} associated to the Activity was
* just updated.
*/
@Override
protected void onAccountSet(boolean stateWasRecovered) {
super.onAccountSet(stateWasRecovered);
if (getAccount() != null) {
updateFileFromDB();
OCFile folder = getFile();
if (folder == null || !folder.isFolder()) {
// fall back to root folder
setFile(getStorageManager().getFileByPath(OCFile.ROOT_PATH));
folder = getFile();
}
onBrowsedDownTo(folder);
if (!stateWasRecovered) {
OCFileListFragment listOfFolders = getListOfFilesFragment();
// TODO Enable when "On Device" is recovered ?
listOfFolders.listDirectory(folder/*, false*/);
startSyncFolderOperation(folder, false);
}
updateNavigationElementsInActionBar();
}
}
}
| gpl-2.0 |
caot/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/execution/ExternalSystemBeforeRunTask.java | 3393 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.externalSystem.service.execution;
import com.intellij.execution.BeforeRunTask;
import com.intellij.openapi.externalSystem.model.ProjectSystemId;
import com.intellij.openapi.externalSystem.model.execution.ExternalSystemTaskExecutionSettings;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.text.StringUtil;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
/**
* @author Vladislav.Soroka
* @since 5/30/2014
*/
public class ExternalSystemBeforeRunTask extends BeforeRunTask<ExternalSystemBeforeRunTask> {
@NotNull
private final ExternalSystemTaskExecutionSettings myTaskExecutionSettings;
public ExternalSystemBeforeRunTask(@NotNull Key<ExternalSystemBeforeRunTask> providerId, @NotNull ProjectSystemId systemId) {
super(providerId);
myTaskExecutionSettings = new ExternalSystemTaskExecutionSettings();
myTaskExecutionSettings.setExternalSystemIdString(systemId.getId());
}
@NotNull
public ExternalSystemTaskExecutionSettings getTaskExecutionSettings() {
return myTaskExecutionSettings;
}
@Override
public void writeExternal(Element element) {
super.writeExternal(element);
element.setAttribute("tasks", StringUtil.join(myTaskExecutionSettings.getTaskNames(), " "));
if (myTaskExecutionSettings.getExternalProjectPath() != null) {
element.setAttribute("externalProjectPath", myTaskExecutionSettings.getExternalProjectPath());
}
if (myTaskExecutionSettings.getVmOptions() != null) element.setAttribute("vmOptions", myTaskExecutionSettings.getVmOptions());
if (myTaskExecutionSettings.getScriptParameters() != null) {
element.setAttribute("scriptParameters", myTaskExecutionSettings.getScriptParameters());
}
}
@Override
public void readExternal(Element element) {
super.readExternal(element);
myTaskExecutionSettings.setTaskNames(StringUtil.split(StringUtil.notNullize(element.getAttributeValue("tasks")), " "));
myTaskExecutionSettings.setExternalProjectPath(element.getAttributeValue("externalProjectPath"));
myTaskExecutionSettings.setVmOptions(element.getAttributeValue("vmOptions"));
myTaskExecutionSettings.setScriptParameters(element.getAttributeValue("scriptParameters"));
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ExternalSystemBeforeRunTask)) return false;
if (!super.equals(o)) return false;
ExternalSystemBeforeRunTask task = (ExternalSystemBeforeRunTask)o;
if (!myTaskExecutionSettings.equals(task.myTaskExecutionSettings)) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + myTaskExecutionSettings.hashCode();
return result;
}
}
| apache-2.0 |
android-ia/platform_tools_idea | java/java-impl/src/com/intellij/codeInsight/generation/PropertyClassMember.java | 1255 | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.generation;
import com.intellij.psi.PsiClass;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.Nullable;
/**
* User: anna
* Date: 3/4/13
*/
public interface PropertyClassMember extends EncapsulatableClassMember {
/**
* @return PsiElement or TemplateGenerationInfo
* @param aClass
*/
@Nullable
GenerationInfo[] generateGetters(PsiClass aClass) throws IncorrectOperationException;
/**
* @return PsiElement or TemplateGenerationInfo
* @param aClass
*/
@Nullable
GenerationInfo[] generateSetters(PsiClass aClass) throws IncorrectOperationException;
}
| apache-2.0 |
liuqk/mybatis-3 | src/test/java/org/apache/ibatis/submitted/call_setters_on_nulls/DoNotCallSettersOnNullsTest.java | 2902 | /**
* Copyright 2009-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ibatis.submitted.call_setters_on_nulls;
import java.io.Reader;
import java.sql.Connection;
import java.util.Map;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
public class DoNotCallSettersOnNullsTest {
private static SqlSessionFactory sqlSessionFactory;
@BeforeClass
public static void setUp() throws Exception {
// create a SqlSessionFactory
Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/call_setters_on_nulls/mybatis-config-2.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
reader.close();
// populate in-memory database
SqlSession session = sqlSessionFactory.openSession();
Connection conn = session.getConnection();
reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/call_setters_on_nulls/CreateDB.sql");
ScriptRunner runner = new ScriptRunner(conn);
runner.setLogWriter(null);
runner.runScript(reader);
reader.close();
session.close();
}
@Test
public void shouldCallNullOnMappedProperty() {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
Mapper mapper = sqlSession.getMapper(Mapper.class);
User user = mapper.getUserMapped(1);
Assert.assertFalse(user.nullReceived);
} finally {
sqlSession.close();
}
}
@Test
public void shouldCallNullOnAutomaticMapping() {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
Mapper mapper = sqlSession.getMapper(Mapper.class);
User user = mapper.getUserUnmapped(1);
Assert.assertFalse(user.nullReceived);
} finally {
sqlSession.close();
}
}
@Test
public void shouldCallNullOnMap() {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
Mapper mapper = sqlSession.getMapper(Mapper.class);
Map user = mapper.getUserInMap(1);
Assert.assertFalse(user.containsKey("NAME"));
} finally {
sqlSession.close();
}
}
}
| apache-2.0 |
tsuna/opentsdb | src/tsd/WordSplitter.java | 1555 | // This file is part of OpenTSDB.
// Copyright (C) 2010-2012 The OpenTSDB Authors.
//
// 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.1 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,
// see <http://www.gnu.org/licenses/>.
package net.opentsdb.tsd;
import java.nio.charset.Charset;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.oneone.OneToOneDecoder;
import net.opentsdb.core.Tags;
/**
* Splits a ChannelBuffer in multiple space separated words.
*/
final class WordSplitter extends OneToOneDecoder {
private static final Charset CHARSET = Charset.forName("ISO-8859-1");
/** Constructor. */
public WordSplitter() {
}
@Override
protected Object decode(final ChannelHandlerContext ctx,
final Channel channel,
final Object msg) throws Exception {
return Tags.splitString(((ChannelBuffer) msg).toString(CHARSET), ' ');
}
}
| gpl-3.0 |
GreenLightning/libgdx | tests/gdx-tests/src/com/badlogic/gdx/tests/g3d/ShaderTest.java | 9212 | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.tests.g3d;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g3d.Attribute;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.model.Node;
import com.badlogic.gdx.graphics.g3d.shaders.BaseShader;
import com.badlogic.gdx.graphics.g3d.utils.BaseShaderProvider;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.DefaultShaderProvider;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.graphics.g3d.utils.RenderContext;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.GdxRuntimeException;
public class ShaderTest extends GdxTest {
// Create a custom attribute, see https://github.com/libgdx/libgdx/wiki/Material-and-environment
// See also: http://blog.xoppa.com/using-materials-with-libgdx/
public static class TestAttribute extends Attribute {
public final static String Alias = "Test";
public final static long ID = register(Alias);
public float value;
protected TestAttribute (final float value) {
super(ID);
this.value = value;
}
@Override
public Attribute copy () {
return new TestAttribute(value);
}
@Override
protected boolean equals (Attribute other) {
return ((TestAttribute)other).value == value;
}
@Override
public int compareTo (Attribute o) {
if (type != o.type) return type < o.type ? -1 : 1;
float otherValue = ((TestAttribute)o).value;
return MathUtils.isEqual(value, otherValue) ? 0 : (value < otherValue ? -1 : 1);
}
}
// Create a custom shader, see also http://blog.xoppa.com/creating-a-shader-with-libgdx
// BaseShader adds some basic functionality used to manage uniforms etc.
public static class TestShader extends BaseShader {
// @off
public final static String vertexShader =
"attribute vec3 a_position;\n"
+ "uniform mat4 u_projTrans;\n"
+ "uniform mat4 u_worldTrans;\n"
+ "void main() {\n"
+ " gl_Position = u_projTrans * u_worldTrans * vec4(a_position, 1.0);\n"
+ "}\n";
public final static String fragmentShader =
"#ifdef GL_ES\n"
+ "#define LOWP lowp\n"
+ "precision mediump float;\n"
+ "#else\n"
+ "#define LOWP\n"
+ "#endif\n"
+ "uniform float u_test;\n"
+ "#ifdef HasDiffuseColor\n"
+ "uniform vec4 u_color;\n"
+ "#endif //HasDiffuseColor\n"
+ "void main() {\n"
+ "#ifdef HasDiffuseColor\n"
+ " gl_FragColor.rgb = u_color.rgb * vec3(u_test);\n"
+ "#else\n"
+ " gl_FragColor.rgb = vec3(u_test);\n"
+ "#endif //HasDiffuseColor\n"
+ "}\n";
// @on
protected final int u_projTrans = register(new Uniform("u_projTrans"));
protected final int u_worldTrans = register(new Uniform("u_worldTrans"));
protected final int u_test = register(new Uniform("u_test"));
protected final int u_color = register(new Uniform("u_color"));
protected final ShaderProgram program;
private boolean withColor;
public TestShader (Renderable renderable) {
super();
withColor = renderable.material.has(ColorAttribute.Diffuse);
if (withColor)
Gdx.app.log("ShaderTest", "Compiling test shader with u_color uniform");
else
Gdx.app.log("ShaderTest", "Compiling test shader without u_color uniform");
String prefix = withColor ? "#define HasDiffuseColor\n" : "";
program = new ShaderProgram(vertexShader, prefix + fragmentShader);
if (!program.isCompiled()) throw new GdxRuntimeException("Couldn't compile shader " + program.getLog());
String log = program.getLog();
if (log.length() > 0) Gdx.app.error("ShaderTest", "Shader compilation log: " + log);
}
@Override
public void init () {
super.init(program, null);
}
@Override
public int compareTo (Shader other) {
return 0;
}
@Override
public boolean canRender (Renderable instance) {
return instance.material.has(TestAttribute.ID) && (instance.material.has(ColorAttribute.Diffuse) == withColor);
}
@Override
public void begin (Camera camera, RenderContext context) {
program.begin();
context.setDepthTest(GL20.GL_LEQUAL, 0f, 1f);
context.setDepthMask(true);
set(u_projTrans, camera.combined);
}
@Override
public void render (Renderable renderable) {
set(u_worldTrans, renderable.worldTransform);
TestAttribute testAttr = (TestAttribute)renderable.material.get(TestAttribute.ID);
set(u_test, testAttr.value);
if (withColor) {
ColorAttribute colorAttr = (ColorAttribute)renderable.material.get(ColorAttribute.Diffuse);
set(u_color, colorAttr.color);
}
renderable.mesh.render(program, renderable.primitiveType, renderable.meshPartOffset, renderable.meshPartSize);
}
@Override
public void end () {
program.end();
}
@Override
public void dispose () {
super.dispose();
program.dispose();
}
}
public PerspectiveCamera cam;
public CameraInputController camController;
public ModelBatch modelBatch;
public Model model;
public Array<ModelInstance> instances = new Array<ModelInstance>();
public TestAttribute testAttribute1, testAttribute2;
@Override
public void create () {
modelBatch = new ModelBatch(new DefaultShaderProvider() {
@Override
protected Shader createShader (Renderable renderable) {
if (renderable.material.has(TestAttribute.ID)) return new TestShader(renderable);
return super.createShader(renderable);
}
});
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(0f, 0f, 20f);
cam.lookAt(0, 0, 0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
Material testMaterial1 = new Material("TestMaterial1", new TestAttribute(1f));
Material redMaterial = new Material("RedMaterial", ColorAttribute.createDiffuse(Color.RED));
Material testMaterial2 = new Material("TestMaterial2", new TestAttribute(1f), ColorAttribute.createDiffuse(Color.BLUE));
ModelBuilder builder = new ModelBuilder();
Node node;
builder.begin();
node = builder.node();
node.id = "testCone1";
node.translation.set(-10, 0f, 0f);
builder.part("testCone", GL20.GL_TRIANGLES, Usage.Position, testMaterial1).cone(5, 5, 5, 20);
node = builder.node();
node.id = "redSphere";
builder.part("redSphere", GL20.GL_TRIANGLES, Usage.Position, redMaterial).sphere(5, 5, 5, 20, 20);
node = builder.node();
node.id = "testCone1";
node.translation.set(10, 0f, 0f);
builder.part("testCone", GL20.GL_TRIANGLES, Usage.Position, testMaterial2).cone(5, 5, 5, 20);
model = builder.end();
ModelInstance modelInstance;
modelInstance = new ModelInstance(model);
testAttribute1 = (TestAttribute)modelInstance.getMaterial("TestMaterial1").get(TestAttribute.ID);
testAttribute2 = (TestAttribute)modelInstance.getMaterial("TestMaterial2").get(TestAttribute.ID);
instances.add(modelInstance);
}
private float counter;
@Override
public void render () {
counter = (counter + Gdx.graphics.getDeltaTime()) % 2.f;
testAttribute1.value = Math.abs(1f - counter);
testAttribute2.value = 1f - testAttribute1.value;
camController.update();
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
modelBatch.begin(cam);
modelBatch.render(instances);
modelBatch.end();
}
@Override
public void dispose () {
modelBatch.dispose();
model.dispose();
}
}
| apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk2/jdk/test/java/awt/event/MouseWheelEvent/InfiniteRecursion/InfiniteRecursion_1.java | 3610 | /*
* Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
@test
@bug 6480024
@library ../../../regtesthelpers
@build Util Sysout AbstractTest
@summary stack overflow on mouse wheel rotation
@author Andrei Dmitriev: area=awt.event
@run main InfiniteRecursion_1
*/
/**
* InfiniteRecursion_1.java
*
* summary: put a JButton into JPanel and then put JPanel into JFrame.
* Add MouseWheelListener to JFrame.
* Add MouseListener to JPanel.
* Rotating a wheel over the JButton would result in stack overflow.
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import test.java.awt.regtesthelpers.Util;
import test.java.awt.regtesthelpers.AbstractTest;
import test.java.awt.regtesthelpers.Sysout;
public class InfiniteRecursion_1 {
final static Robot robot = Util.createRobot();
final static int MOVE_COUNT = 5;
//*2 for both rotation directions,
//*2 as Java sends the wheel event to every for nested component in hierarchy under cursor
final static int EXPECTED_COUNT = MOVE_COUNT * 2 * 2;
static int actualEvents = 0;
public static void main(String []s)
{
JFrame frame = new JFrame("A test frame");
JPanel outputBox = new JPanel();
JButton jButton = new JButton();
frame.setSize(200, 200);
frame.addMouseWheelListener(new MouseWheelListener() {
public void mouseWheelMoved(MouseWheelEvent e)
{
System.out.println("Wheel moved on FRAME : "+e);
actualEvents++;
}
});
outputBox.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e)
{
System.out.println("MousePressed on OUTBOX : "+e);
}
});
frame.add(outputBox);
outputBox.add(jButton);
frame.setVisible(true);
Util.waitForIdle(robot);
Util.pointOnComp(jButton, robot);
Util.waitForIdle(robot);
for (int i = 0; i < MOVE_COUNT; i++){
robot.mouseWheel(1);
robot.delay(10);
}
for (int i = 0; i < MOVE_COUNT; i++){
robot.mouseWheel(-1);
robot.delay(10);
}
Util.waitForIdle(robot);
//Not fair to check for multiplier 4 as it's not specified actual number of WheelEvents
//result in a single wheel rotation.
if (actualEvents != EXPECTED_COUNT) {
AbstractTest.fail("Expected events count: "+ EXPECTED_COUNT+" Actual events count: "+ actualEvents);
}
}
}
| mit |
ivan-fedorov/intellij-community | plugins/gradle/src/org/jetbrains/plugins/gradle/service/notification/GradleNotificationExtension.java | 3485 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.gradle.service.notification;
import com.intellij.execution.rmi.RemoteUtil;
import com.intellij.openapi.externalSystem.model.ExternalSystemException;
import com.intellij.openapi.externalSystem.model.LocationAwareExternalSystemException;
import com.intellij.openapi.externalSystem.model.ProjectSystemId;
import com.intellij.openapi.externalSystem.service.notification.ExternalSystemNotificationExtension;
import com.intellij.openapi.externalSystem.service.notification.NotificationData;
import com.intellij.openapi.externalSystem.service.notification.callback.OpenExternalSystemSettingsCallback;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.gradle.util.GradleConstants;
/**
* @author Vladislav.Soroka
* @since 3/27/14
*/
public class GradleNotificationExtension implements ExternalSystemNotificationExtension {
@NotNull
@Override
public ProjectSystemId getTargetExternalSystemId() {
return GradleConstants.SYSTEM_ID;
}
@Override
public void customize(@NotNull NotificationData notification,
@NotNull Project project,
@Nullable Throwable error) {
if (error == null) return;
//noinspection ThrowableResultOfMethodCallIgnored
Throwable unwrapped = RemoteUtil.unwrap(error);
if (unwrapped instanceof ExternalSystemException) {
updateNotification(notification, project, (ExternalSystemException)unwrapped);
}
}
private static void updateNotification(@NotNull final NotificationData notificationData,
@NotNull final Project project,
@NotNull ExternalSystemException e) {
for (String fix : e.getQuickFixes()) {
if (OpenGradleSettingsCallback.ID.equals(fix)) {
notificationData.setListener(OpenGradleSettingsCallback.ID, new OpenGradleSettingsCallback(project));
}
else if (ApplyGradlePluginCallback.ID.equals(fix)) {
notificationData.setListener(ApplyGradlePluginCallback.ID, new ApplyGradlePluginCallback(notificationData, project));
}
else if (GotoSourceNotificationCallback.ID.equals(fix)) {
notificationData.setListener(GotoSourceNotificationCallback.ID, new GotoSourceNotificationCallback(notificationData, project));
}
else if (OpenExternalSystemSettingsCallback.ID.equals(fix)) {
String linkedProjectPath = e instanceof LocationAwareExternalSystemException ?
((LocationAwareExternalSystemException)e).getFilePath() : null;
notificationData.setListener(
OpenExternalSystemSettingsCallback.ID,
new OpenExternalSystemSettingsCallback(project, GradleConstants.SYSTEM_ID, linkedProjectPath)
);
}
}
}
}
| apache-2.0 |
guiquanz/binnavi | src/main/java/com/google/security/zynamics/binnavi/Startup/CommandlineParser.java | 2150 | /*
Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.security.zynamics.binnavi.Startup;
import com.google.common.base.Preconditions;
import com.google.security.zynamics.binnavi.Log.NaviLogger;
import java.util.logging.Level;
/**
* Parses command lines passed to BinNavi.
*/
public final class CommandlineParser {
/**
* You are not supposed to instantiate this class.
*/
private CommandlineParser() {}
/**
* Processes the parsed command line options.
*
* @param commandLine
*/
private static void processCommandLineOptions(final CommandlineOptions commandLine) {
if (commandLine.isVeryVerboseMode()) {
NaviLogger.setLevel(Level.ALL);
} else if (commandLine.isVerboseMode()) {
NaviLogger.setLevel(Level.INFO);
}
}
/**
* Parses the command line arguments passed to BinNavi.
*
* @param arguments The command line arguments passed to BinNavi.
*
* @return The command line options parsed from the arguments.
*/
public static CommandlineOptions parseCommandLine(final String[] arguments) {
Preconditions.checkNotNull(arguments, "IE02087: Arguments argument can not be null");
final CommandlineOptions options = new CommandlineOptions();
for (final String argument : arguments) {
if ("-v".equals(argument)) {
options.setVerboseMode();
} else if ("-vv".equals(argument)) {
options.setVeryVerboseMode();
} else if (argument.startsWith("-X:")) {
options.setBatchPlugin(arguments[0].substring(3));
}
}
processCommandLineOptions(options);
return options;
}
}
| apache-2.0 |
jxjjdccj/smile | springside4-master/examples/showcase/src/main/java/org/springside/examples/showcase/entity/Role.java | 1467 | /*******************************************************************************
* Copyright (c) 2005, 2014 springside.github.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
*******************************************************************************/
package org.springside.examples.showcase.entity;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import com.google.common.collect.ImmutableList;
/**
* 角色.
*
* @author calvin
*/
@Entity
@Table(name = "ss_role")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Role extends IdEntity {
private String name;
private String permissions;
public Role() {
}
public Role(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPermissions() {
return permissions;
}
public void setPermissions(String permissions) {
this.permissions = permissions;
}
@Transient
public List<String> getPermissionList() {
return ImmutableList.copyOf(StringUtils.split(permissions, ","));
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
| apache-2.0 |
PolymorhicCode/openhab | bundles/binding/org.openhab.binding.zwave/src/main/java/org/openhab/binding/zwave/internal/protocol/commandclass/ZWaveSceneActivationCommandClass.java | 3607 | /**
* Copyright (c) 2010-2015, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.zwave.internal.protocol.commandclass;
import org.openhab.binding.zwave.internal.protocol.SerialMessage;
import org.openhab.binding.zwave.internal.protocol.ZWaveController;
import org.openhab.binding.zwave.internal.protocol.ZWaveEndpoint;
import org.openhab.binding.zwave.internal.protocol.ZWaveNode;
import org.openhab.binding.zwave.internal.protocol.event.ZWaveCommandClassValueEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
/**
* Handles scene activation messages
* @author Chris Jackson
* @since 1.4.0
*/
@XStreamAlias("sceneActivationCommandClass")
public class ZWaveSceneActivationCommandClass extends ZWaveCommandClass {
@XStreamOmitField
private static final Logger logger = LoggerFactory.getLogger(ZWaveBasicCommandClass.class);
private static final int SCENEACTIVATION_SET = 0x01;
/**
* Creates a new instance of the ZWaveSceneActivationCommandClass class.
* @param node the node this command class belongs to
* @param controller the controller to use
* @param endpoint the endpoint this Command class belongs to
*/
public ZWaveSceneActivationCommandClass(ZWaveNode node,
ZWaveController controller, ZWaveEndpoint endpoint) {
super(node, controller, endpoint);
}
/**
* {@inheritDoc}
*/
@Override
public CommandClass getCommandClass() {
return CommandClass.SCENE_ACTIVATION;
}
/**
* {@inheritDoc}
*/
@Override
public void handleApplicationCommandRequest(SerialMessage serialMessage,
int offset, int endpoint) {
logger.debug(String.format("Received Scene Activation for Node ID = %d", this.getNode().getNodeId()));
int command = serialMessage.getMessagePayloadByte(offset);
switch (command) {
case SCENEACTIVATION_SET:
logger.debug("Scene Activation Set");
processSceneActivationSet(serialMessage, offset, endpoint);
break;
default:
logger.warn(String.format("Unsupported Command 0x%02X for command class %s (0x%02X).",
command,
this.getCommandClass().getLabel(),
this.getCommandClass().getKey()));
}
}
/**
* Processes a SCENEACTIVATION_SET message.
* @param serialMessage the incoming message to process.
* @param offset the offset position from which to start message processing.
* @param endpoint the endpoint or instance number this message is meant for.
*/
protected void processSceneActivationSet(SerialMessage serialMessage, int offset, int endpoint) {
int sceneId = serialMessage.getMessagePayloadByte(offset + 1);
int sceneTime = 0;
// Aeon Minimote fw 1.19 sends SceneActivationSet without Time parameter
if (serialMessage.getMessagePayload().length > (offset + 2)) {
sceneTime = serialMessage.getMessagePayloadByte(offset + 2);
}
logger.debug(String.format("Scene activation node from node %d: Scene %d, Time %d", this.getNode().getNodeId(),
sceneId, sceneTime));
// Ignore the time for now at least!
ZWaveCommandClassValueEvent zEvent = new ZWaveCommandClassValueEvent(this.getNode().getNodeId(), endpoint, this.getCommandClass(), sceneId);
this.getController().notifyEventListeners(zEvent);
}
}
| epl-1.0 |
iloveyou416068/CookNIOServer | netty_source_4_0_25/codec-http/src/main/java/io/netty/handler/codec/spdy/DefaultSpdySynReplyFrame.java | 2087 | /*
* Copyright 2013 The Netty Project
*
* The Netty Project 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.netty.handler.codec.spdy;
import io.netty.util.internal.StringUtil;
/**
* The default {@link SpdySynReplyFrame} implementation.
*/
public class DefaultSpdySynReplyFrame extends DefaultSpdyHeadersFrame
implements SpdySynReplyFrame {
/**
* Creates a new instance.
*
* @param streamId the Stream-ID of this frame
*/
public DefaultSpdySynReplyFrame(int streamId) {
super(streamId);
}
@Override
public SpdySynReplyFrame setStreamId(int streamId) {
super.setStreamId(streamId);
return this;
}
@Override
public SpdySynReplyFrame setLast(boolean last) {
super.setLast(last);
return this;
}
@Override
public SpdySynReplyFrame setInvalid() {
super.setInvalid();
return this;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder()
.append(StringUtil.simpleClassName(this))
.append("(last: ")
.append(isLast())
.append(')')
.append(StringUtil.NEWLINE)
.append("--> Stream-ID = ")
.append(streamId())
.append(StringUtil.NEWLINE)
.append("--> Headers:")
.append(StringUtil.NEWLINE);
appendHeaders(buf);
// Remove the last newline.
buf.setLength(buf.length() - StringUtil.NEWLINE.length());
return buf.toString();
}
}
| apache-2.0 |
lindzh/jenkins | core/src/main/java/hudson/model/TaskThread.java | 6567 | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Red Hat, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model;
import hudson.console.AnnotatedLargeText;
import hudson.util.StreamTaskListener;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.lang.ref.WeakReference;
import java.nio.charset.Charset;
import org.kohsuke.stapler.framework.io.LargeText;
import org.kohsuke.stapler.framework.io.ByteBuffer;
/**
* {@link Thread} for performing one-off task.
*
* <p>
* Designed to be used inside {@link TaskAction}.
*
*
*
* @author Kohsuke Kawaguchi
* @since 1.191
* @see TaskAction
*/
public abstract class TaskThread extends Thread {
/**
* @deprecated as of Hudson 1.350
* Use {@link #log}. It's the same object, in a better type.
*/
@Deprecated
private final LargeText text;
/**
* Represents the output from this task thread.
*/
private final AnnotatedLargeText<TaskAction> log;
/**
* Represents the interface to produce output.
*/
private TaskListener listener;
private final TaskAction owner;
private volatile boolean isRunning;
/**
*
* @param output
* Determines where the output from this task thread goes.
*/
protected TaskThread(TaskAction owner, ListenerAndText output) {
//FIXME this failed to compile super(owner.getBuild().toString()+' '+owner.getDisplayName());
//Please implement more general way how to get information about action owner,
//if you want it in the thread's name.
super(owner.getDisplayName());
this.owner = owner;
this.text = this.log = output.text;
this.listener = output.listener;
this.isRunning = true;
}
public Reader readAll() throws IOException {
// this method can be invoked from another thread.
return text.readAll();
}
/**
* Registers that this {@link TaskThread} is run for the specified
* {@link TaskAction}. This can be explicitly called from subtypes
* to associate a single {@link TaskThread} across multiple tag actions.
*/
protected final void associateWith(TaskAction action) {
action.workerThread = this;
action.log = new WeakReference<AnnotatedLargeText>(log);
}
/**
* Starts the task execution asynchronously.
*/
@Override
public void start() {
associateWith(owner);
super.start();
}
public boolean isRunning() {
return isRunning;
}
/**
* Determines where the output of this {@link TaskThread} goes.
* <p>
* Subclass can override this to send the output to a file, for example.
*/
protected ListenerAndText createListener() throws IOException {
return ListenerAndText.forMemory();
}
@Override
public final void run() {
isRunning = true;
try {
perform(listener);
listener.getLogger().println("Completed");
owner.workerThread = null;
} catch (InterruptedException e) {
listener.getLogger().println("Aborted");
} catch (Exception e) {
e.printStackTrace(listener.getLogger());
} finally {
listener = null;
isRunning =false;
}
log.markAsComplete();
}
/**
* Do the actual work.
*
* @throws Exception
* The exception is recorded and reported as a failure.
*/
protected abstract void perform(TaskListener listener) throws Exception;
/**
* Tuple of {@link TaskListener} and {@link AnnotatedLargeText}, representing
* the interface for producing output and how to retrieve it later.
*/
public static final class ListenerAndText {
final TaskListener listener;
final AnnotatedLargeText<TaskAction> text;
public ListenerAndText(TaskListener listener, AnnotatedLargeText<TaskAction> text) {
this.listener = listener;
this.text = text;
}
/**
* @deprecated as of Hudson 1.350
* Use {@link #forMemory(TaskAction)} and pass in the calling {@link TaskAction}
*/
@Deprecated
public static ListenerAndText forMemory() {
return forMemory(null);
}
/**
* @deprecated as of Hudson 1.350
* Use {@link #forFile(File, TaskAction)} and pass in the calling {@link TaskAction}
*/
@Deprecated
public static ListenerAndText forFile(File f) throws IOException {
return forFile(f,null);
}
/**
* Creates one that's backed by memory.
*/
public static ListenerAndText forMemory(TaskAction context) {
// StringWriter is synchronized
ByteBuffer log = new ByteBuffer();
return new ListenerAndText(
new StreamTaskListener(log),
new AnnotatedLargeText<TaskAction>(log,Charset.defaultCharset(),false,context)
);
}
/**
* Creates one that's backed by a file.
*/
public static ListenerAndText forFile(File f, TaskAction context) throws IOException {
return new ListenerAndText(
new StreamTaskListener(f),
new AnnotatedLargeText<TaskAction>(f,Charset.defaultCharset(),false,context)
);
}
}
}
| mit |
rokn/Count_Words_2015 | testing/openjdk2/jdk/src/share/classes/sun/tools/tree/AssignBitAndExpression.java | 1902 | /*
* Copyright (c) 1994, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.tools.tree;
import sun.tools.java.*;
import sun.tools.asm.Assembler;
/**
* WARNING: The contents of this source file are not part of any
* supported API. Code that depends on them does so at its own risk:
* they are subject to change or removal without notice.
*/
public
class AssignBitAndExpression extends AssignOpExpression {
/**
* Constructor
*/
public AssignBitAndExpression(long where, Expression left, Expression right) {
super(ASGBITAND, where, left, right);
}
/**
* Code
*/
void codeOperation(Environment env, Context ctx, Assembler asm) {
asm.add(where, opc_iand + itype.getTypeCodeOffset());
}
}
| mit |
consulo/consulo-javafx | src/test/resources/highlighting/custom/_CustomVBox.java | 318 | import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
public class _CustomVBox extends VBox {
@FXML
private TextField tf;
@FXML
private Label lab1;
@FXML
void myMethod(){
lab1.setText(tf.getText());
}
} | apache-2.0 |
seem-sky/FrameworkBenchmarks | undertow/src/main/java/hello/CacheHandler.java | 1169 | package hello;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.cache.LoadingCache;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.Headers;
import java.util.Objects;
import static hello.HelloWebServer.JSON_UTF8;
/**
* Handles the cache access test.
*/
final class CacheHandler implements HttpHandler {
private final ObjectMapper objectMapper;
private final LoadingCache<Integer, World> worldCache;
CacheHandler(ObjectMapper objectMapper,
LoadingCache<Integer, World> worldCache) {
this.objectMapper = Objects.requireNonNull(objectMapper);
this.worldCache = Objects.requireNonNull(worldCache);
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
int queries = Helper.getQueries(exchange);
World[] worlds = new World[queries];
for (int i = 0; i < queries; i++) {
worlds[i] = worldCache.get(Helper.randomWorld());
}
exchange.getResponseHeaders().put(
Headers.CONTENT_TYPE, JSON_UTF8);
exchange.getResponseSender().send(objectMapper.writeValueAsString(worlds));
}
}
| bsd-3-clause |
rokn/Count_Words_2015 | testing/openjdk2/hotspot/agent/src/share/classes/sun/jvm/hotspot/debugger/win32/coff/DebugVC50SSFileIndex.java | 2412 | /*
* Copyright (c) 2001, 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 sun.jvm.hotspot.debugger.win32.coff;
/** Models the "sstFileIndex" subsection in Visual C++ 5.0 debug
information. This subsection contains a list of all of the source
files that contribute code to any module (compiland) in the
executable. File names are partially qualified relative to the
compilation directory. */
public interface DebugVC50SSFileIndex extends DebugVC50Subsection {
/** Number of file name references per module. */
public short getNumModules();
/** Count of the total number of file name references. */
public short getNumReferences();
/** Array of indices into the <i>NameOffset</i> table for each
module. Each index is the start of the file name references for
each module. */
public short[] getModStart();
/** Number of file name references per module. */
public short[] getRefCount();
/** Array of offsets into the Names table. For each module, the
offset to first referenced file name is at NameRef[ModStart] and
continues for cRefCnt entries. FIXME: this probably is useless
and needs fixup to convert these offsets into indices into the
following array. */
public int[] getNameRef();
/** List of zero terminated file names. Each file name is partially
qualified relative to the compilation directory. */
public String[] getNames();
}
| mit |
bravo-zhang/spark | sql/hive-thriftserver/src/main/java/org/apache/hive/service/cli/CLIServiceUtils.java | 2392 | /**
* 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.hive.service.cli;
import org.apache.log4j.Layout;
import org.apache.log4j.PatternLayout;
/**
* CLIServiceUtils.
*
*/
public class CLIServiceUtils {
private static final char SEARCH_STRING_ESCAPE = '\\';
public static final Layout verboseLayout = new PatternLayout(
"%d{yy/MM/dd HH:mm:ss} %p %c{2}: %m%n");
public static final Layout nonVerboseLayout = new PatternLayout(
"%-5p : %m%n");
/**
* Convert a SQL search pattern into an equivalent Java Regex.
*
* @param pattern input which may contain '%' or '_' wildcard characters, or
* these characters escaped using {@code getSearchStringEscape()}.
* @return replace %/_ with regex search characters, also handle escaped
* characters.
*/
public static String patternToRegex(String pattern) {
if (pattern == null) {
return ".*";
} else {
StringBuilder result = new StringBuilder(pattern.length());
boolean escaped = false;
for (int i = 0, len = pattern.length(); i < len; i++) {
char c = pattern.charAt(i);
if (escaped) {
if (c != SEARCH_STRING_ESCAPE) {
escaped = false;
}
result.append(c);
} else {
if (c == SEARCH_STRING_ESCAPE) {
escaped = true;
continue;
} else if (c == '%') {
result.append(".*");
} else if (c == '_') {
result.append('.');
} else {
result.append(Character.toLowerCase(c));
}
}
}
return result.toString();
}
}
}
| apache-2.0 |
seanli310/guava | guava-testlib/src/com/google/common/collect/testing/testers/CollectionToStringTester.java | 2967 | /*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER;
import static com.google.common.collect.testing.features.CollectionFeature.NON_STANDARD_TOSTRING;
import static com.google.common.collect.testing.features.CollectionSize.ONE;
import static com.google.common.collect.testing.features.CollectionSize.SEVERAL;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.AbstractCollectionTester;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
/**
* A generic JUnit test which tests {@code toString()} operations on a
* collection. Can't be invoked directly; please see
* {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}.
*
* @author Kevin Bourrillion
*/
@GwtCompatible
public class CollectionToStringTester<E> extends AbstractCollectionTester<E> {
public void testToString_minimal() {
assertNotNull("toString() should not return null",
collection.toString());
}
@CollectionSize.Require(ZERO)
@CollectionFeature.Require(absent = NON_STANDARD_TOSTRING)
public void testToString_size0() {
assertEquals("emptyCollection.toString should return []", "[]",
collection.toString());
}
@CollectionSize.Require(ONE)
@CollectionFeature.Require(absent = NON_STANDARD_TOSTRING)
public void testToString_size1() {
assertEquals("size1Collection.toString should return [{element}]",
"[" + e0() + "]", collection.toString());
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(
value = KNOWN_ORDER, absent = NON_STANDARD_TOSTRING)
public void testToString_sizeSeveral() {
String expected = Helpers.copyToList(getOrderedElements()).toString();
assertEquals("collection.toString() incorrect",
expected, collection.toString());
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
public void testToString_null() {
initCollectionWithNullElement();
testToString_minimal();
}
}
| apache-2.0 |
grafiszti/ReplicaIsland | src/main/java/com/replica/replicaisland/TiledWorld.java | 4430 | /*
* 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 com.replica.replicaisland;
import java.io.IOException;
import java.io.InputStream;
import android.content.res.AssetManager;
/**
* TiledWorld manages a 2D map of tile indexes that define a "world" of tiles. These may be
* foreground or background layers in a scrolling game, or a layer of collision tiles, or some other
* type of tile map entirely. The TiledWorld maps xy positions to tile indices and also handles
* deserialization of tilemap files.
*/
public class TiledWorld extends AllocationGuard {
private int[][] mTilesArray;
private int mRowCount;
private int mColCount;
private byte[] mWorkspaceBytes;
public TiledWorld(int cols, int rows) {
super();
mTilesArray = new int[cols][rows];
mRowCount = rows;
mColCount = cols;
for (int x = 0; x < cols; x++) {
for (int y = 0; y < rows; y++) {
mTilesArray[x][y] = -1;
}
}
mWorkspaceBytes = new byte[4];
calculateSkips();
}
public TiledWorld(InputStream stream) {
super();
mWorkspaceBytes = new byte[4];
parseInput(stream);
calculateSkips();
}
public int getTile(int x, int y) {
int result = -1;
if (x >= 0 && x < mColCount && y >= 0 && y < mRowCount) {
result = mTilesArray[x][y];
}
return result;
}
// Builds a tiled world from a simple map file input source. The map file format is as follows:
// First byte: signature. Must always be decimal 42.
// Second byte: width of the world in tiles.
// Third byte: height of the world in tiles.
// Subsequent bytes: actual tile data in column-major order.
// TODO: add a checksum in here somewhere.
protected boolean parseInput(InputStream stream) {
boolean success = false;
AssetManager.AssetInputStream byteStream = (AssetManager.AssetInputStream) stream;
int signature;
try {
signature = (byte)byteStream.read();
if (signature == 42) {
byteStream.read(mWorkspaceBytes, 0, 4);
final int width = Utils.byteArrayToInt(mWorkspaceBytes);
byteStream.read(mWorkspaceBytes, 0, 4);
final int height = Utils.byteArrayToInt(mWorkspaceBytes);
final int totalTiles = width * height;
final int bytesRemaining = byteStream.available();
assert bytesRemaining >= totalTiles;
if (bytesRemaining >= totalTiles) {
mTilesArray = new int[width][height];
mRowCount = height;
mColCount = width;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
mTilesArray[x][y] = (byte)byteStream.read();
}
}
success = true;
}
}
} catch (IOException e) {
//TODO: figure out the best way to deal with this. Assert?
}
return success;
}
protected void calculateSkips() {
int emptyTileCount = 0;
for (int y = mRowCount - 1; y >= 0; y--) {
for (int x = mColCount - 1; x >= 0; x--) {
if (mTilesArray[x][y] < 0) {
emptyTileCount++;
mTilesArray[x][y] = -emptyTileCount;
} else {
emptyTileCount = 0;
}
}
}
}
public final int getWidth() {
return mColCount;
}
public final int getHeight() {
return mRowCount;
}
public final int[][] getTiles() {
return mTilesArray;
}
}
| apache-2.0 |
firebase/netty | transport-sctp/src/main/java/io/netty/channel/sctp/oio/package-info.java | 801 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project 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.
*/
/**
* Old blocking I/O based SCTP channel API implementation - recommended for
* a small number of connections (< 1000).
*/
package io.netty.channel.sctp.oio;
| apache-2.0 |
dantuffery/elasticsearch | src/main/java/org/elasticsearch/index/analysis/StandardTokenizerFactory.java | 2256 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.analysis;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.analysis.standard.StandardTokenizer;
import org.apache.lucene.analysis.standard.std40.StandardTokenizer40;
import org.apache.lucene.util.Version;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.inject.assistedinject.Assisted;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.settings.IndexSettings;
/**
*/
public class StandardTokenizerFactory extends AbstractTokenizerFactory {
private final int maxTokenLength;
@Inject
public StandardTokenizerFactory(Index index, @IndexSettings Settings indexSettings, @Assisted String name, @Assisted Settings settings) {
super(index, indexSettings, name, settings);
maxTokenLength = settings.getAsInt("max_token_length", StandardAnalyzer.DEFAULT_MAX_TOKEN_LENGTH);
}
@Override
public Tokenizer create() {
if (version.onOrAfter(Version.LUCENE_4_7_0)) {
StandardTokenizer tokenizer = new StandardTokenizer();
tokenizer.setMaxTokenLength(maxTokenLength);
return tokenizer;
} else {
StandardTokenizer40 tokenizer = new StandardTokenizer40();
tokenizer.setMaxTokenLength(maxTokenLength);
return tokenizer;
}
}
}
| apache-2.0 |
davidwilliams1978/camel | components/camel-test-spring40/src/test/java/org/apache/camel/test/spring/CamelSpringJUnit4ClassRunnerProvidesBreakpointTest.java | 2490 | /**
* 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.test.spring;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.impl.BreakpointSupport;
import org.apache.camel.model.ProcessorDefinition;
import org.apache.camel.spi.Breakpoint;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class CamelSpringJUnit4ClassRunnerProvidesBreakpointTest
extends CamelSpringJUnit4ClassRunnerPlainTest {
@ProvidesBreakpoint
public static Breakpoint createBreakpoint() {
return new TestBreakpoint();
}
@Test
@Override
public void testProvidesBreakpoint() {
assertNotNull(camelContext.getDebugger());
assertNotNull(camelContext2.getDebugger());
start.sendBody("David");
assertNotNull(camelContext.getDebugger());
assertNotNull(camelContext.getDebugger().getBreakpoints());
assertEquals(1, camelContext.getDebugger().getBreakpoints().size());
assertTrue(camelContext.getDebugger().getBreakpoints().get(0) instanceof TestBreakpoint);
assertTrue(((TestBreakpoint) camelContext.getDebugger().getBreakpoints().get(0)).isBreakpointHit());
}
private static final class TestBreakpoint extends BreakpointSupport {
private boolean breakpointHit;
@Override
public void beforeProcess(Exchange exchange, Processor processor, ProcessorDefinition<?> definition) {
breakpointHit = true;
}
public boolean isBreakpointHit() {
return breakpointHit;
}
}
}
| apache-2.0 |
zhushuchen/Ocean | 项目源码/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/com/alibaba/dubbo/rpc/filter/TpsLimitFilterTest.java | 2455 | /*
* Copyright 1999-2012 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.alibaba.dubbo.rpc.filter;
import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.RpcException;
import com.alibaba.dubbo.rpc.RpcStatus;
import com.alibaba.dubbo.rpc.support.MockInvocation;
import com.alibaba.dubbo.rpc.support.MyInvoker;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
/**
* @author <a href="mailto:gang.lvg@alibaba-inc.com">kimi</a>
*/
public class TpsLimitFilterTest {
private TpsLimitFilter filter = new TpsLimitFilter();
@Test
public void testWithoutCount() throws Exception {
URL url = URL.valueOf("test://test");
url = url.addParameter(Constants.INTERFACE_KEY,
"com.alibaba.dubbo.rpc.file.TpsService");
url = url.addParameter(Constants.TPS_LIMIT_RATE_KEY, 5);
Invoker<TpsLimitFilterTest> invoker = new MyInvoker<TpsLimitFilterTest>(url);
Invocation invocation = new MockInvocation();
filter.invoke(invoker, invocation);
}
@Test(expected = RpcException.class)
public void testFail() throws Exception {
URL url = URL.valueOf("test://test");
url = url.addParameter(Constants.INTERFACE_KEY,
"com.alibaba.dubbo.rpc.file.TpsService");
url = url.addParameter(Constants.TPS_LIMIT_RATE_KEY, 5);
Invoker<TpsLimitFilterTest> invoker = new MyInvoker<TpsLimitFilterTest>(url);
Invocation invocation = new MockInvocation();
for (int i = 0; i < 10; i++) {
try {
filter.invoke(invoker, invocation);
} catch (Exception e) {
assertTrue(i >= 5);
throw e;
}
}
}
}
| agpl-3.0 |
tseen/Federated-HDFS | tseenliu/FedHDFS-hadoop-src/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/SortedRanges.java | 10894 | /**
* 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.mapred;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.io.Writable;
/**
* Keeps the Ranges sorted by startIndex.
* The added ranges are always ensured to be non-overlapping.
* Provides the SkipRangeIterator, which skips the Ranges
* stored in this object.
*/
class SortedRanges implements Writable{
private static final Log LOG =
LogFactory.getLog(SortedRanges.class);
private TreeSet<Range> ranges = new TreeSet<Range>();
private long indicesCount;
/**
* Get Iterator which skips the stored ranges.
* The Iterator.next() call return the index starting from 0.
* @return SkipRangeIterator
*/
synchronized SkipRangeIterator skipRangeIterator(){
return new SkipRangeIterator(ranges.iterator());
}
/**
* Get the no of indices stored in the ranges.
* @return indices count
*/
synchronized long getIndicesCount() {
return indicesCount;
}
/**
* Get the sorted set of ranges.
* @return ranges
*/
synchronized SortedSet<Range> getRanges() {
return ranges;
}
/**
* Add the range indices. It is ensured that the added range
* doesn't overlap the existing ranges. If it overlaps, the
* existing overlapping ranges are removed and a single range
* having the superset of all the removed ranges and this range
* is added.
* If the range is of 0 length, doesn't do anything.
* @param range Range to be added.
*/
synchronized void add(Range range){
if(range.isEmpty()) {
return;
}
long startIndex = range.getStartIndex();
long endIndex = range.getEndIndex();
//make sure that there are no overlapping ranges
SortedSet<Range> headSet = ranges.headSet(range);
if(headSet.size()>0) {
Range previousRange = headSet.last();
LOG.debug("previousRange "+previousRange);
if(startIndex<previousRange.getEndIndex()) {
//previousRange overlaps this range
//remove the previousRange
if(ranges.remove(previousRange)) {
indicesCount-=previousRange.getLength();
}
//expand this range
startIndex = previousRange.getStartIndex();
endIndex = endIndex>=previousRange.getEndIndex() ?
endIndex : previousRange.getEndIndex();
}
}
Iterator<Range> tailSetIt = ranges.tailSet(range).iterator();
while(tailSetIt.hasNext()) {
Range nextRange = tailSetIt.next();
LOG.debug("nextRange "+nextRange +" startIndex:"+startIndex+
" endIndex:"+endIndex);
if(endIndex>=nextRange.getStartIndex()) {
//nextRange overlaps this range
//remove the nextRange
tailSetIt.remove();
indicesCount-=nextRange.getLength();
if(endIndex<nextRange.getEndIndex()) {
//expand this range
endIndex = nextRange.getEndIndex();
break;
}
} else {
break;
}
}
add(startIndex,endIndex);
}
/**
* Remove the range indices. If this range is
* found in existing ranges, the existing ranges
* are shrunk.
* If range is of 0 length, doesn't do anything.
* @param range Range to be removed.
*/
synchronized void remove(Range range) {
if(range.isEmpty()) {
return;
}
long startIndex = range.getStartIndex();
long endIndex = range.getEndIndex();
//make sure that there are no overlapping ranges
SortedSet<Range> headSet = ranges.headSet(range);
if(headSet.size()>0) {
Range previousRange = headSet.last();
LOG.debug("previousRange "+previousRange);
if(startIndex<previousRange.getEndIndex()) {
//previousRange overlaps this range
//narrow down the previousRange
if(ranges.remove(previousRange)) {
indicesCount-=previousRange.getLength();
LOG.debug("removed previousRange "+previousRange);
}
add(previousRange.getStartIndex(), startIndex);
if(endIndex<=previousRange.getEndIndex()) {
add(endIndex, previousRange.getEndIndex());
}
}
}
Iterator<Range> tailSetIt = ranges.tailSet(range).iterator();
while(tailSetIt.hasNext()) {
Range nextRange = tailSetIt.next();
LOG.debug("nextRange "+nextRange +" startIndex:"+startIndex+
" endIndex:"+endIndex);
if(endIndex>nextRange.getStartIndex()) {
//nextRange overlaps this range
//narrow down the nextRange
tailSetIt.remove();
indicesCount-=nextRange.getLength();
if(endIndex<nextRange.getEndIndex()) {
add(endIndex, nextRange.getEndIndex());
break;
}
} else {
break;
}
}
}
private void add(long start, long end) {
if(end>start) {
Range recRange = new Range(start, end-start);
ranges.add(recRange);
indicesCount+=recRange.getLength();
LOG.debug("added "+recRange);
}
}
public synchronized void readFields(DataInput in) throws IOException {
indicesCount = in.readLong();
ranges = new TreeSet<Range>();
int size = in.readInt();
for(int i=0;i<size;i++) {
Range range = new Range();
range.readFields(in);
ranges.add(range);
}
}
public synchronized void write(DataOutput out) throws IOException {
out.writeLong(indicesCount);
out.writeInt(ranges.size());
Iterator<Range> it = ranges.iterator();
while(it.hasNext()) {
Range range = it.next();
range.write(out);
}
}
public String toString() {
StringBuffer sb = new StringBuffer();
Iterator<Range> it = ranges.iterator();
while(it.hasNext()) {
Range range = it.next();
sb.append(range.toString()+"\n");
}
return sb.toString();
}
/**
* Index Range. Comprises of start index and length.
* A Range can be of 0 length also. The Range stores indices
* of type long.
*/
static class Range implements Comparable<Range>, Writable{
private long startIndex;
private long length;
Range(long startIndex, long length) {
if(length<0) {
throw new RuntimeException("length can't be negative");
}
this.startIndex = startIndex;
this.length = length;
}
Range() {
this(0,0);
}
/**
* Get the start index. Start index in inclusive.
* @return startIndex.
*/
long getStartIndex() {
return startIndex;
}
/**
* Get the end index. End index is exclusive.
* @return endIndex.
*/
long getEndIndex() {
return startIndex + length;
}
/**
* Get Length.
* @return length
*/
long getLength() {
return length;
}
/**
* Range is empty if its length is zero.
* @return <code>true</code> if empty
* <code>false</code> otherwise.
*/
boolean isEmpty() {
return length==0;
}
public boolean equals(Object o) {
if (o instanceof Range) {
Range range = (Range)o;
return startIndex==range.startIndex &&
length==range.length;
}
return false;
}
public int hashCode() {
return Long.valueOf(startIndex).hashCode() +
Long.valueOf(length).hashCode();
}
public int compareTo(Range o) {
// Ensure sgn(x.compareTo(y) == -sgn(y.compareTo(x))
return this.startIndex < o.startIndex ? -1 :
(this.startIndex > o.startIndex ? 1 :
(this.length < o.length ? -1 :
(this.length > o.length ? 1 : 0)));
}
public void readFields(DataInput in) throws IOException {
startIndex = in.readLong();
length = in.readLong();
}
public void write(DataOutput out) throws IOException {
out.writeLong(startIndex);
out.writeLong(length);
}
public String toString() {
return startIndex +":" + length;
}
}
/**
* Index Iterator which skips the stored ranges.
*/
static class SkipRangeIterator implements Iterator<Long> {
Iterator<Range> rangeIterator;
Range range = new Range();
long next = -1;
/**
* Constructor
* @param rangeIterator the iterator which gives the ranges.
*/
SkipRangeIterator(Iterator<Range> rangeIterator) {
this.rangeIterator = rangeIterator;
doNext();
}
/**
* Returns true till the index reaches Long.MAX_VALUE.
* @return <code>true</code> next index exists.
* <code>false</code> otherwise.
*/
public synchronized boolean hasNext() {
return next<Long.MAX_VALUE;
}
/**
* Get the next available index. The index starts from 0.
* @return next index
*/
public synchronized Long next() {
long ci = next;
doNext();
return ci;
}
private void doNext() {
next++;
LOG.debug("currentIndex "+next +" "+range);
skipIfInRange();
while(next>=range.getEndIndex() && rangeIterator.hasNext()) {
range = rangeIterator.next();
skipIfInRange();
}
}
private void skipIfInRange() {
if(next>=range.getStartIndex() &&
next<range.getEndIndex()) {
//need to skip the range
LOG.warn("Skipping index " + next +"-" + range.getEndIndex());
next = range.getEndIndex();
}
}
/**
* Get whether all the ranges have been skipped.
* @return <code>true</code> if all ranges have been skipped.
* <code>false</code> otherwise.
*/
synchronized boolean skippedAllRanges() {
return !rangeIterator.hasNext() && next>range.getEndIndex();
}
/**
* Remove is not supported. Doesn't apply.
*/
public void remove() {
throw new UnsupportedOperationException("remove not supported.");
}
}
}
| apache-2.0 |
io7m/jcanephora | com.io7m.jcanephora.tests/src/test/java/com/io7m/jcanephora/tests/core/JCGLVersionTest.java | 3648 | /*
* Copyright © 2014 <code@io7m.com> http://io7m.com
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.io7m.jcanephora.tests.core;
import com.io7m.jcanephora.core.JCGLVersion;
import com.io7m.jcanephora.core.JCGLVersionNumber;
import org.junit.Assert;
import org.junit.Test;
public final class JCGLVersionTest
{
@Test
public void testEquals()
{
final JCGLVersion v0 = JCGLVersion.of(
JCGLVersionNumber.of(1, 0, 0), "OpenGL ES GLSL ES 1.00");
final JCGLVersion v1 = JCGLVersion.of(
JCGLVersionNumber.of(1, 0, 0), "OpenGL ES GLSL ES 1.00");
final JCGLVersion v2 = JCGLVersion.of(
JCGLVersionNumber.of(2, 0, 0), "OpenGL ES GLSL ES 1.00");
final JCGLVersion v3 = JCGLVersion.of(
JCGLVersionNumber.of(1, 0, 0), "OpenGL ES GLSL ES 1.0x");
Assert.assertEquals(v0, v0);
Assert.assertNotEquals(v0, null);
Assert.assertNotEquals(v0, (Integer.valueOf(23)));
Assert.assertEquals(v0, v1);
Assert.assertNotEquals(v0, v2);
Assert.assertNotEquals(v0, v3);
}
@Test
public void testHashCode()
{
final JCGLVersion v0 = JCGLVersion.of(
JCGLVersionNumber.of(1, 0, 0), "OpenGL ES GLSL ES 1.00");
final JCGLVersion v1 = JCGLVersion.of(
JCGLVersionNumber.of(1, 0, 0), "OpenGL ES GLSL ES 1.00");
final JCGLVersion v2 = JCGLVersion.of(
JCGLVersionNumber.of(2, 0, 0), "OpenGL ES GLSL ES 1.00");
final JCGLVersion v3 = JCGLVersion.of(
JCGLVersionNumber.of(1, 0, 0), "OpenGL ES GLSL ES 1.0x");
Assert.assertEquals((long) v0.hashCode(), (long) (v0.hashCode()));
Assert.assertEquals((long) v0.hashCode(), (long) (v1.hashCode()));
Assert.assertNotEquals((long) v0.hashCode(), (long) (v2.hashCode()));
Assert.assertNotEquals((long) v0.hashCode(), (long) (v3.hashCode()));
}
@Test
public void testIdentities()
{
final JCGLVersion v0 = JCGLVersion.of(
JCGLVersionNumber.of(1, 2, 3), "OpenGL ES GLSL ES 1.00");
Assert.assertEquals("OpenGL ES GLSL ES 1.00", v0.text());
Assert.assertEquals(JCGLVersionNumber.of(1, 2, 3), v0.number());
Assert.assertEquals(1L, (long) v0.number().major());
Assert.assertEquals(2L, (long) v0.number().minor());
Assert.assertEquals(3L, (long) v0.number().micro());
}
@Test
public void testToString()
{
final JCGLVersion v0 = JCGLVersion.of(
JCGLVersionNumber.of(1, 0, 0), "OpenGL ES GLSL ES 1.00");
final JCGLVersion v1 = JCGLVersion.of(
JCGLVersionNumber.of(1, 0, 0), "OpenGL ES GLSL ES 1.00");
final JCGLVersion v2 = JCGLVersion.of(
JCGLVersionNumber.of(2, 0, 0), "OpenGL ES GLSL ES 1.00");
final JCGLVersion v3 = JCGLVersion.of(
JCGLVersionNumber.of(1, 0, 0), "OpenGL ES GLSL ES 1.0x");
Assert.assertEquals(v0.toString(), v0.toString());
Assert.assertEquals(v0.toString(), v1.toString());
Assert.assertNotEquals(v0.toString(), v2.toString());
Assert.assertNotEquals(v0.toString(), v3.toString());
}
}
| isc |
rchodava/datamill | core/src/main/java/foundation/stack/datamill/serialization/Serializer.java | 291 | package foundation.stack.datamill.serialization;
import rx.functions.Func1;
/**
* @author Ravi Chodavarapu (rchodava@gmail.com)
*/
@FunctionalInterface
public interface Serializer<SourceType, SerializedType extends StructuredOutput>
extends Func1<SourceType, SerializedType> {
}
| isc |
Nunnery/CPSC475 | slots1/src/test/java/com/tealcube/slots1/ExampleUnitTest.java | 1176 | /*
* This file is part of CPSC475, licensed under the ISC License.
*
* Copyright (c) 2016, Richard Harrah <richard.harrah.13@cnu.edu>
*
* Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
* provided that the above copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
package com.tealcube.slots1;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | isc |
xdv/ripple-lib-java | ripple-bouncycastle/src/main/java/org/ripple/bouncycastle/jcajce/provider/symmetric/CAST6.java | 1685 | package org.ripple.bouncycastle.jcajce.provider.symmetric;
import org.ripple.bouncycastle.crypto.CipherKeyGenerator;
import org.ripple.bouncycastle.crypto.engines.CAST6Engine;
import org.ripple.bouncycastle.crypto.macs.GMac;
import org.ripple.bouncycastle.crypto.modes.GCMBlockCipher;
import org.ripple.bouncycastle.jcajce.provider.config.ConfigurableProvider;
import org.ripple.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher;
import org.ripple.bouncycastle.jcajce.provider.symmetric.util.BaseKeyGenerator;
import org.ripple.bouncycastle.jcajce.provider.symmetric.util.BaseMac;
public final class CAST6
{
private CAST6()
{
}
public static class ECB
extends BaseBlockCipher
{
public ECB()
{
super(new CAST6Engine());
}
}
public static class KeyGen
extends BaseKeyGenerator
{
public KeyGen()
{
super("CAST6", 256, new CipherKeyGenerator());
}
}
public static class GMAC
extends BaseMac
{
public GMAC()
{
super(new GMac(new GCMBlockCipher(new CAST6Engine())));
}
}
public static class Mappings
extends SymmetricAlgorithmProvider
{
private static final String PREFIX = CAST6.class.getName();
public Mappings()
{
}
public void configure(ConfigurableProvider provider)
{
provider.addAlgorithm("Cipher.CAST6", PREFIX + "$ECB");
provider.addAlgorithm("KeyGenerator.CAST6", PREFIX + "$KeyGen");
addGMacAlgorithm(provider, "CAST6", PREFIX + "$GMAC", PREFIX + "$KeyGen");
}
}
}
| isc |
i-den/SoftwareUniversity | Software University/09) Java Advanced - January 2017/13. Manual String Processing - Lab/02. Parse URL.java | 1955 | import java.util.Scanner;
public class ParseURL {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
URL inputURL = new URL(scanner.nextLine());
System.out.println(inputURL.printStats());
}
}
class URL {
private String rawURL;
private String protocol;
private String host;
private String request;
URL(String rawURL) {
this.setRawURL(rawURL);
}
private boolean isInvalid() {
return this.rawURL.matches(".*(://).*(://).*");
}
String printStats() {
if (this.isInvalid()) {
return "Invalid URL";
}
int startIndex = this.rawURL.indexOf("://");
int endIndex = this.rawURL.indexOf("/", startIndex + 3);
this.setProtocol(this.rawURL.substring(
0,
startIndex
));
this.setHost(this.rawURL.substring(
startIndex + 3,
endIndex
));
this.setRequest(this.rawURL.substring(
endIndex + 1
));
return String.format(
"Protocol = %s%nServer = %s%nResources = %s%n",
this.getProtocol(),
this.getHost(),
this.getRequest()
);
}
private void setRawURL(String rawURL) {
this.rawURL = rawURL;
}
public String getRawURL() {
return rawURL;
}
private String getProtocol() {
return protocol;
}
private void setProtocol(String protocol) {
this.protocol = protocol;
}
private String getHost() {
return host;
}
private void setHost(String host) {
this.host = host;
}
private String getRequest() {
return request;
}
private void setRequest(String request) {
this.request = request;
}
} | mit |
NicolasDucom/Pick-n-Eat-Android | app/src/main/java/com/nicolasdu/pick_n_eat/Restaurant.java | 2579 | package com.nicolasdu.pick_n_eat;
import android.media.Image;
import java.io.Serializable;
import java.net.URL;
import java.util.ArrayList;
/**
* Created by Nicolas on 1/30/2015.
*/
public class Restaurant implements Serializable{
private String Title;
private ArrayList<String> Address;
private URL Website;
private float Longitude;
private float Latitude;
private URL Rating;
private ArrayList<Review> Reviews = new ArrayList<>();
private String Phone;
private String DisplayPhone;
private Restaurant() {
}
public Restaurant(String title, ArrayList<String> address, URL website, float longitude, float latitude, URL rating, String phone, String displayPhone) {
Title = title;
Address = address;
Website = website;
Longitude = longitude;
Latitude = latitude;
Rating = rating;
Phone = phone;
DisplayPhone = displayPhone;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public ArrayList<String> getAddress() {
return Address;
}
public void setAddress(ArrayList<String> address) {
Address = address;
}
public URL getWebsite() {
return Website;
}
public void setWebsite(URL website) {
Website = website;
}
public float getLongitude() {
return Longitude;
}
public void setLongitude(float longitude) {
Longitude = longitude;
}
public float getLatitude() {
return Latitude;
}
public void setLatitude(float latitude) {
Latitude = latitude;
}
public URL getRating() {
return Rating;
}
public void setRating(URL rating) {
Rating = rating;
}
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public String getDisplayPhone() {
return DisplayPhone;
}
public void setDisplayPhone(String displayPhone) {
DisplayPhone = displayPhone;
}
@Override
public String toString(){
return "Name :"+getTitle()+
" Address :"+getAddress()+
" Website :"+getWebsite()+
" Longitude :"+getLongitude()+
" Latitude :"+getLatitude()+
" Rating :"+getRating() +
" Phone :"+getPhone();
}
}
| mit |
insky2005/iems-platform | iems/iems-webapp/src/main/java/com/iems/biz/service/IEventInfoService.java | 658 | package com.iems.biz.service;
import com.iems.biz.entity.EventInfo;
import com.iems.biz.model.EventInfoModel;
import com.iems.core.dao.support.PageResults;
import com.iems.core.dao.support.SearchConditions;
public interface IEventInfoService {
PageResults<EventInfoModel> getEventInfoModels(int pageNo, int pageSize,
SearchConditions<EventInfoModel> searchConditions);
PageResults<EventInfo> getEventInfos(int pageNo, int pageSize,
SearchConditions<EventInfo> searchConditions);
EventInfo getEventInfo(String id);
void addEventInfo(EventInfo eventInfo);
void updateEventInfo(EventInfo eventInfo);
void deleteEventInfo(String id);
}
| mit |
digero/maestro | src/com/digero/maestro/view/SettingsDialog.java | 18081 | package com.digero.maestro.view;
import info.clearthought.layout.TableLayout;
import info.clearthought.layout.TableLayoutConstants;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import com.digero.common.abc.LotroInstrument;
import com.digero.common.util.Util;
import com.digero.maestro.abc.AbcMetadataSource;
import com.digero.maestro.abc.AbcPartMetadataSource;
import com.digero.maestro.abc.AbcSong;
import com.digero.maestro.abc.PartAutoNumberer;
import com.digero.maestro.abc.PartNameTemplate;
public class SettingsDialog extends JDialog implements TableLayoutConstants
{
public static final int NUMBERING_TAB = 0;
public static final int NAME_TEMPLATE_TAB = 1;
public static final int SAVE_EXPORT_TAB = 2;
private static final int PAD = 4;
private boolean success = false;
private boolean numbererSettingsChanged = false;
private JTabbedPane tabPanel;
private PartAutoNumberer.Settings numSettings;
private PartNameTemplate.Settings nameTemplateSettings;
private PartNameTemplate nameTemplate;
private JLabel nameTemplateExampleLabel;
private SaveAndExportSettings saveSettings;
public SettingsDialog(JFrame owner, PartAutoNumberer.Settings numbererSettings, PartNameTemplate nameTemplate,
SaveAndExportSettings saveSettings)
{
super(owner, "Options", true);
setDefaultCloseOperation(HIDE_ON_CLOSE);
this.numSettings = numbererSettings;
this.nameTemplate = nameTemplate;
this.nameTemplateSettings = nameTemplate.getSettingsCopy();
this.saveSettings = saveSettings;
JButton okButton = new JButton("OK");
getRootPane().setDefaultButton(okButton);
okButton.setMnemonic('O');
okButton.addActionListener(new ActionListener()
{
@Override public void actionPerformed(ActionEvent e)
{
success = true;
SettingsDialog.this.setVisible(false);
}
});
JButton cancelButton = new JButton("Cancel");
cancelButton.setMnemonic('C');
cancelButton.addActionListener(new ActionListener()
{
@Override public void actionPerformed(ActionEvent e)
{
success = false;
SettingsDialog.this.setVisible(false);
}
});
final String CLOSE_WINDOW_ACTION = "com.digero.maestro.view.SettingsDialog:CLOSE_WINDOW_ACTION";
getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
CLOSE_WINDOW_ACTION);
getRootPane().getActionMap().put(CLOSE_WINDOW_ACTION, new AbstractAction()
{
@Override public void actionPerformed(ActionEvent e)
{
success = false;
SettingsDialog.this.setVisible(false);
}
});
JPanel buttonsPanel = new JPanel(new TableLayout(//
new double[] { 0.50, 0.50 },//
new double[] { PREFERRED }));
((TableLayout) buttonsPanel.getLayout()).setHGap(PAD);
buttonsPanel.add(okButton, "0, 0, f, f");
buttonsPanel.add(cancelButton, "1, 0, f, f");
JPanel buttonsContainerPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, PAD / 2));
buttonsContainerPanel.add(buttonsPanel);
tabPanel = new JTabbedPane();
tabPanel.addTab("ABC Part Numbering", createNumberingPanel()); // NUMBERING_TAB
tabPanel.addTab("ABC Part Naming", createNameTemplatePanel()); // NAME_TEMPLATE_TAB
tabPanel.addTab("Save & Export", createSaveAndExportSettingsPanel()); // SAVE_EXPORT_TAB
JPanel mainPanel = new JPanel(new BorderLayout(PAD, PAD));
mainPanel.setBorder(BorderFactory.createEmptyBorder(PAD, PAD, PAD, PAD));
mainPanel.add(tabPanel, BorderLayout.CENTER);
mainPanel.add(buttonsContainerPanel, BorderLayout.SOUTH);
setContentPane(mainPanel);
pack();
if (owner != null)
{
int left = owner.getX() + (owner.getWidth() - this.getWidth()) / 2;
int top = owner.getY() + (owner.getHeight() - this.getHeight()) / 2;
this.setLocation(left, top);
}
// This must be done after layout is done: the call to pack() does layout
updateNameTemplateExample();
}
private JPanel createNumberingPanel()
{
JLabel instrumentsTitle = new JLabel("<html><b><u>First part number</u></b></html>");
TableLayout instrumentsLayout = new TableLayout(//
new double[] { 50, PREFERRED, 2 * PAD, 50, PREFERRED },//
new double[] { });
instrumentsLayout.setHGap(PAD);
instrumentsLayout.setVGap(3);
JPanel instrumentsPanel = new JPanel(instrumentsLayout);
instrumentsPanel.setBorder(BorderFactory.createEmptyBorder(0, PAD, 0, 0));
final List<InstrumentSpinner> instrumentSpinners = new ArrayList<InstrumentSpinner>();
LotroInstrument[] instruments = LotroInstrument.values();
for (int i = 0; i < instruments.length; i++)
{
LotroInstrument inst = instruments[i];
int row = i;
int col = 0;
if (i >= (instruments.length + 1) / 2)
{
row -= (instruments.length + 1) / 2;
col = 3;
}
else
{
instrumentsLayout.insertRow(row, PREFERRED);
}
InstrumentSpinner spinner = new InstrumentSpinner(inst);
instrumentSpinners.add(spinner);
instrumentsPanel.add(spinner, col + ", " + row);
instrumentsPanel.add(new JLabel(inst.toString() + " "), (col + 1) + ", " + row);
}
JLabel incrementTitle = new JLabel("<html><b><u>Increment</u></b></html>");
JLabel incrementDescr = new JLabel("<html>Interval between multiple parts of the same instrument.<br>"
+ "<b>1</b>: number Lute parts as 10, 11, 12, etc.<br>"
+ "<b>10</b>: number Lute parts as 1, 11, 21, etc.</html>");
final JComboBox<Integer> incrementComboBox = new JComboBox<Integer>(new Integer[] { 1, 10 });
incrementComboBox.setSelectedItem(numSettings.getIncrement());
incrementComboBox.addActionListener(new ActionListener()
{
@Override public void actionPerformed(ActionEvent e)
{
int oldInc = numSettings.getIncrement();
int newInc = (Integer) incrementComboBox.getSelectedItem();
if (oldInc == newInc)
return;
numbererSettingsChanged = true;
for (InstrumentSpinner spinner : instrumentSpinners)
{
int firstNumber = numSettings.getFirstNumber(spinner.instrument);
firstNumber = (firstNumber * oldInc) / newInc;
numSettings.setFirstNumber(spinner.instrument, firstNumber);
spinner.setValue(firstNumber);
if (newInc == 1)
{
spinner.getModel().setMaximum(999);
}
else
{
spinner.getModel().setMaximum(10);
}
}
numSettings.setIncrementByTen(newInc == 10);
}
});
TableLayout incrementPanelLayout = new TableLayout(//
new double[] { PREFERRED, FILL },//
new double[] { PREFERRED });
incrementPanelLayout.setHGap(10);
JPanel incrementPanel = new JPanel(incrementPanelLayout);
incrementPanel.setBorder(BorderFactory.createEmptyBorder(0, PAD, 0, 0));
incrementPanel.add(incrementComboBox, "0, 0, C, T");
incrementPanel.add(incrementDescr, "1, 0");
TableLayout numberingLayout = new TableLayout(//
new double[] { FILL },//
new double[] { PREFERRED, PREFERRED, PREFERRED, PREFERRED, PREFERRED });
numberingLayout.setVGap(PAD);
JPanel numberingPanel = new JPanel(numberingLayout);
numberingPanel.setBorder(BorderFactory.createEmptyBorder(PAD, PAD, PAD, PAD));
numberingPanel.add(instrumentsTitle, "0, 0");
numberingPanel.add(instrumentsPanel, "0, 1, L, F");
numberingPanel.add(incrementTitle, "0, 3");
numberingPanel.add(incrementPanel, "0, 4, F, F");
return numberingPanel;
}
private class InstrumentSpinner extends JSpinner implements ChangeListener
{
private LotroInstrument instrument;
public InstrumentSpinner(LotroInstrument instrument)
{
super(new SpinnerNumberModel(numSettings.getFirstNumber(instrument), 0, numSettings.isIncrementByTen() ? 10
: 999, 1));
this.instrument = instrument;
addChangeListener(this);
}
@Override public SpinnerNumberModel getModel()
{
return (SpinnerNumberModel) super.getModel();
}
@Override public void stateChanged(ChangeEvent e)
{
numSettings.setFirstNumber(instrument, (Integer) getValue());
numbererSettingsChanged = true;
}
}
private JPanel createNameTemplatePanel()
{
final JTextField partNameTextField = new JTextField(nameTemplateSettings.getPartNamePattern(), 40);
partNameTextField.getDocument().addDocumentListener(new DocumentListener()
{
@Override public void removeUpdate(DocumentEvent e)
{
nameTemplateSettings.setPartNamePattern(partNameTextField.getText());
updateNameTemplateExample();
}
@Override public void insertUpdate(DocumentEvent e)
{
nameTemplateSettings.setPartNamePattern(partNameTextField.getText());
updateNameTemplateExample();
}
@Override public void changedUpdate(DocumentEvent e)
{
nameTemplateSettings.setPartNamePattern(partNameTextField.getText());
updateNameTemplateExample();
}
});
nameTemplateExampleLabel = new JLabel(" ");
JPanel examplePanel = new JPanel(new BorderLayout());
examplePanel.setBorder(BorderFactory.createEmptyBorder(0, 3, 0, 0));
examplePanel.add(nameTemplateExampleLabel, BorderLayout.CENTER);
TableLayout layout = new TableLayout();
layout.insertColumn(0, PREFERRED);
layout.insertColumn(1, FILL);
layout.setVGap(3);
layout.setHGap(10);
JPanel nameTemplatePanel = new JPanel(layout);
nameTemplatePanel.setBorder(BorderFactory.createEmptyBorder(PAD, PAD, PAD, PAD));
int row = 0;
layout.insertRow(row, PREFERRED);
JLabel patternLabel = new JLabel("<html><b><u>Pattern for ABC Part Name</b></u></html>");
nameTemplatePanel.add(patternLabel, "0, " + row + ", 1, " + row);
layout.insertRow(++row, PREFERRED);
nameTemplatePanel.add(partNameTextField, "0, " + row + ", 1, " + row);
layout.insertRow(++row, PREFERRED);
nameTemplatePanel.add(examplePanel, "0, " + row + ", 1, " + row + ", F, F");
layout.insertRow(++row, PREFERRED);
JLabel nameLabel = new JLabel("<html><u><b>Variable Name</b></u></html>");
JLabel exampleLabel = new JLabel("<html><u><b>Example</b></u></html>");
layout.insertRow(++row, PREFERRED);
nameTemplatePanel.add(nameLabel, "0, " + row);
nameTemplatePanel.add(exampleLabel, "1, " + row);
AbcMetadataSource originalMetadataSource = nameTemplate.getMetadataSource();
AbcPartMetadataSource originalAbcPart = nameTemplate.getCurrentAbcPart();
MockMetadataSource mockMetadata = new MockMetadataSource(originalMetadataSource);
nameTemplate.setMetadataSource(mockMetadata);
nameTemplate.setCurrentAbcPart(mockMetadata);
for (Entry<String, PartNameTemplate.Variable> entry : nameTemplate.getVariables().entrySet())
{
String tooltipText = "<html><b>" + entry.getKey() + "</b><br>"
+ entry.getValue().getDescription().replace("\n", "<br>") + "</html>";
JLabel keyLabel = new JLabel(entry.getKey());
keyLabel.setToolTipText(tooltipText);
JLabel descriptionLabel = new JLabel(entry.getValue().getValue());
descriptionLabel.setToolTipText(tooltipText);
layout.insertRow(++row, PREFERRED);
nameTemplatePanel.add(keyLabel, "0, " + row);
nameTemplatePanel.add(descriptionLabel, "1, " + row);
}
nameTemplate.setMetadataSource(originalMetadataSource);
nameTemplate.setCurrentAbcPart(originalAbcPart);
return nameTemplatePanel;
}
private void updateNameTemplateExample()
{
AbcMetadataSource originalMetadataSource = nameTemplate.getMetadataSource();
MockMetadataSource mockMetadata = new MockMetadataSource(originalMetadataSource);
nameTemplate.setMetadataSource(mockMetadata);
String exampleText = nameTemplate.formatName(nameTemplateSettings.getPartNamePattern(), mockMetadata);
String exampleTextEllipsis = Util.ellipsis(exampleText, nameTemplateExampleLabel.getWidth(),
nameTemplateExampleLabel.getFont());
nameTemplateExampleLabel.setText(exampleTextEllipsis);
if (!exampleText.equals(exampleTextEllipsis))
nameTemplateExampleLabel.setToolTipText(exampleText);
nameTemplate.setMetadataSource(originalMetadataSource);
}
private JPanel createSaveAndExportSettingsPanel()
{
JLabel titleLabel = new JLabel("<html><u><b>Save & Export</b></u></html>");
final JCheckBox promptSaveCheckBox = new JCheckBox("Prompt to save new " + AbcSong.MSX_FILE_DESCRIPTION_PLURAL);
promptSaveCheckBox.setToolTipText("<html>Select to be prompted to save new "
+ AbcSong.MSX_FILE_DESCRIPTION_PLURAL + "<br>"
+ "when opening a new file or closing the application.</html>");
promptSaveCheckBox.setSelected(saveSettings.promptSaveNewSong);
promptSaveCheckBox.addActionListener(new ActionListener()
{
@Override public void actionPerformed(ActionEvent e)
{
saveSettings.promptSaveNewSong = promptSaveCheckBox.isSelected();
}
});
final JCheckBox showExportFileChooserCheckBox = new JCheckBox(
"Always prompt for the ABC file name when exporting");
showExportFileChooserCheckBox.setToolTipText("<html>Select to have the <b>Export ABC</b> button always<br>"
+ "prompt for the name of the file.</html>");
showExportFileChooserCheckBox.setSelected(saveSettings.showExportFileChooser);
showExportFileChooserCheckBox.addActionListener(new ActionListener()
{
@Override public void actionPerformed(ActionEvent e)
{
saveSettings.showExportFileChooser = showExportFileChooserCheckBox.isSelected();
}
});
final JCheckBox skipSilenceAtStartCheckBox = new JCheckBox("Remove silence from start of exported ABC");
skipSilenceAtStartCheckBox.setToolTipText("<html>" //
+ "Exported ABC files will not include silent measures from the<br>" //
+ "beginning of the song.<br>" //
+ "<br>" //
+ "Uncheck if you want to export multiple ABC files from the same<br>" //
+ "MIDI file that will be played together and need to line up." //
+ "</html>");
skipSilenceAtStartCheckBox.setSelected(saveSettings.skipSilenceAtStart);
skipSilenceAtStartCheckBox.addActionListener(new ActionListener()
{
@Override public void actionPerformed(ActionEvent e)
{
saveSettings.skipSilenceAtStart = skipSilenceAtStartCheckBox.isSelected();
}
});
TableLayout layout = new TableLayout();
layout.insertColumn(0, FILL);
layout.setVGap(PAD);
JPanel panel = new JPanel(layout);
panel.setBorder(BorderFactory.createEmptyBorder(PAD, PAD, PAD, PAD));
int row = -1;
layout.insertRow(++row, PREFERRED);
panel.add(titleLabel, "0, " + row);
layout.insertRow(++row, PREFERRED);
panel.add(promptSaveCheckBox, "0, " + row);
layout.insertRow(++row, PREFERRED);
panel.add(showExportFileChooserCheckBox, "0, " + row);
layout.insertRow(++row, PREFERRED);
panel.add(skipSilenceAtStartCheckBox, "0, " + row);
return panel;
}
public void setActiveTab(int tab)
{
if (tab >= 0 && tab < tabPanel.getComponentCount())
tabPanel.setSelectedIndex(tab);
}
public int getActiveTab()
{
return tabPanel.getSelectedIndex();
}
public boolean isSuccess()
{
return success;
}
public boolean isNumbererSettingsChanged()
{
return numbererSettingsChanged;
}
public PartAutoNumberer.Settings getNumbererSettings()
{
return numSettings;
}
public PartNameTemplate.Settings getNameTemplateSettings()
{
return nameTemplateSettings;
}
public SaveAndExportSettings getSaveAndExportSettings()
{
return saveSettings;
}
public static class MockMetadataSource implements AbcMetadataSource, AbcPartMetadataSource
{
private AbcMetadataSource originalSource;
public MockMetadataSource(AbcMetadataSource originalSource)
{
this.originalSource = originalSource;
}
@Override public String getTitle()
{
return "First Flute";
}
@Override public LotroInstrument getInstrument()
{
return LotroInstrument.BASIC_FLUTE;
}
@Override public int getPartNumber()
{
return 4;
}
@Override public String getSongTitle()
{
if (originalSource != null && originalSource.getSongTitle().length() > 0)
return originalSource.getSongTitle();
return "Example Title";
}
@Override public String getComposer()
{
if (originalSource != null && originalSource.getComposer().length() > 0)
return originalSource.getComposer();
return "Example Composer";
}
@Override public String getTranscriber()
{
if (originalSource != null && originalSource.getTranscriber().length() > 0)
return originalSource.getTranscriber();
return "Your Name Here";
}
@Override public long getSongLengthMicros()
{
long length = 0;
if (originalSource != null)
length = originalSource.getSongLengthMicros();
return (length != 0) ? length : 227000000/* 3:47 */;
}
@Override public File getExportFile()
{
if (originalSource != null)
{
File saveFile = originalSource.getExportFile();
if (saveFile != null)
return saveFile;
}
return new File(Util.getLotroMusicPath(false), "band/examplesong.abc");
}
@Override public String getPartName(AbcPartMetadataSource abcPart)
{
return null;
}
}
}
| mit |
ashkanent/GP_FitnessSharing | GP project/ecj/ec/app/ecsuite/ECSuite.java | 30336 | /*
Copyright 2006 by Sean Luke and George Mason University
Licensed under the Academic Free License version 3.0
See the file "LICENSE" for more information
*/
package ec.app.ecsuite;
import ec.util.*;
import ec.*;
import ec.simple.*;
import ec.vector.*;
/*
* ECSuite.java
*
* Created: Thu Mar 22 16:27:15 2001
* By: Liviu Panait and Sean Luke
*/
/*
* @author Liviu Panait and Sean Luke and Khaled Talukder
* @version 2.0
*/
/**
Several standard Evolutionary Computation functions are implemented.
As the SimpleFitness is used for maximization problems, the mapping f(x) --> -f(x) is used to transform
the problems into maximization ones.
<p><b>Parameters</b><br>
<table>
<tr><td valign=top><i>base</i>.<tt>type</tt><br>
<font size=-1>String, one of: rosenbrock rastrigin sphere step noisy-quartic kdj-f1 kdj-f2 kdj-f3 kdj-f4 booth griewank median sum product schwefel min rotated-rastrigin rotated-schwefel rotated-griewank langerman lennard-jones lunacek</font></td>
<td valign=top>(The vector problem to test against. Some of the types are synonyms: kdj-f1 = sphere, kdj-f2 = rosenbrock, kdj-f3 = step, kdj-f4 = noisy-quartic. "kdj" stands for "Ken DeJong", and the numbers are the problems in his test suite)</td></tr>
</table>
*/
public class ECSuite extends Problem implements SimpleProblemForm
{
public static final String P_WHICH_PROBLEM = "type";
public static final String V_ROSENBROCK = "rosenbrock";
public static final String V_RASTRIGIN = "rastrigin";
public static final String V_SPHERE = "sphere";
public static final String V_STEP = "step";
public static final String V_NOISY_QUARTIC = "noisy-quartic";
public static final String V_F1 = "kdj-f1";
public static final String V_F2 = "kdj-f2";
public static final String V_F3 = "kdj-f3";
public static final String V_F4 = "kdj-f4";
public static final String V_BOOTH = "booth";
public static final String V_GRIEWANGK = "griewangk";
public static final String V_GRIEWANK = "griewank";
public static final String V_MEDIAN = "median";
public static final String V_SUM = "sum";
public static final String V_PRODUCT = "product";
public static final String V_SCHWEFEL = "schwefel";
public static final String V_MIN = "min";
public static final String V_ROTATED_RASTRIGIN = "rotated-rastrigin";
public static final String V_ROTATED_SCHWEFEL = "rotated-schwefel";
public static final String V_ROTATED_GRIEWANK = "rotated-griewank";
public static final String V_LANGERMAN = "langerman" ;
public static final String V_LENNARDJONES = "lennard-jones" ;
public static final String V_LUNACEK = "lunacek" ;
public static final int PROB_ROSENBROCK = 0;
public static final int PROB_RASTRIGIN = 1;
public static final int PROB_SPHERE = 2;
public static final int PROB_STEP = 3;
public static final int PROB_NOISY_QUARTIC = 4;
public static final int PROB_BOOTH = 5;
public static final int PROB_GRIEWANK = 6;
public static final int PROB_MEDIAN = 7;
public static final int PROB_SUM = 8;
public static final int PROB_PRODUCT = 9;
public static final int PROB_SCHWEFEL = 10;
public static final int PROB_MIN = 11;
public static final int PROB_ROTATED_RASTRIGIN = 12;
public static final int PROB_ROTATED_SCHWEFEL = 13;
public static final int PROB_ROTATED_GRIEWANK = 14;
public static final int PROB_LANGERMAN = 15 ;
public static final int PROB_LENNARDJONES = 16 ;
public static final int PROB_LUNACEK = 17 ;
public int problemType = PROB_ROSENBROCK; // defaults on Rosenbrock
public static final String problemName[] = new String[]
{
V_ROSENBROCK,
V_RASTRIGIN,
V_SPHERE,
V_STEP,
V_NOISY_QUARTIC,
V_BOOTH,
V_GRIEWANK,
V_MEDIAN,
V_SUM,
V_PRODUCT,
V_SCHWEFEL,
V_MIN,
V_ROTATED_RASTRIGIN,
V_ROTATED_SCHWEFEL,
V_ROTATED_GRIEWANK,
V_LANGERMAN,
V_LENNARDJONES,
V_LUNACEK
};
public static final double minRange[] = new double[]
{
-2.048, // rosenbrock
-5.12, // rastrigin
-5.12, // sphere
-5.12, // step
-1.28, // noisy quartic
-5.12, // booth
-600.0, // griewank
0.0, // median
0.0, // sum
0.0, // product
-512.03, // schwefel
0.0, // min
-5.12, // rotated-rastrigin
-512.03, // rotated-schwefel
-600.0, // rotated-griewank
0, // langerman
-3.0, // lennard-jones
-5.0, // lunacek
};
public static final double maxRange[] = new double[]
{
2.048, // rosenbrock
5.12, // rastrigin
5.12, // sphere
5.12, // step
1.28, // noisy quartic
5.12, // booth
600.0, // griewank
1.0, // median
1.0, // sum
2.0, // product
511.97, // schwefel
1.0, // min
5.12, // rotated-rastrigin
511.97, // rotated-schwefel
600.0, // rotated-griewank
10, // langerman
3.0, // lennard-jones
5.0 // lunacek
};
boolean alreadyChecked = false;
public void checkRange(EvolutionState state, int problem, double[] genome)
{
if (alreadyChecked || state.generation > 0) return;
alreadyChecked = true;
for(int i = 0; i < state.population.subpops.length; i++)
{
if (!(state.population.subpops[i].species instanceof FloatVectorSpecies))
{
state.output.fatal("ECSuite requires species " + i + " to be a FloatVectorSpecies, but it is a: " + state.population.subpops[i].species);
}
FloatVectorSpecies species = (FloatVectorSpecies)(state.population.subpops[i].species);
for(int k = 0; k < genome.length; k++)
{
if (species.minGene(k) != minRange[problem] ||
species.maxGene(k) != maxRange[problem])
{
state.output.warning("Gene range is nonstandard for problem " + problemName[problem] + ".\nFirst occurrence: Subpopulation " + i + " Gene " + k +
" range was [" + species.minGene(k) + ", " + species.maxGene(k) +
"], expected [" + minRange[problem] + ", " + maxRange[problem] + "]");
return; // done here
}
}
}
if (problemType == PROB_LANGERMAN)
{
// Langerman has a maximum genome size of 10
if (genome.length > 10)
state.output.fatal("The Langerman function requires that the genome size be a value from 1 to 10 inclusive. It is presently " + genome.length);
}
else if (problemType == PROB_LENNARDJONES)
{
// Lennard-Jones requires that its genomes be multiples of 3
if (genome.length % 3 != 0)
state.output.fatal("The Lennard-Jones function requires that the genome size be a multiple of 3. It is presently " + genome.length);
}
}
// nothing....
public void setup(final EvolutionState state, final Parameter base)
{
super.setup(state, base);
String wp = state.parameters.getStringWithDefault( base.push( P_WHICH_PROBLEM ), null, "" );
if( wp.compareTo( V_ROSENBROCK ) == 0 || wp.compareTo (V_F2)==0 )
problemType = PROB_ROSENBROCK;
else if ( wp.compareTo( V_RASTRIGIN ) == 0 )
problemType = PROB_RASTRIGIN;
else if ( wp.compareTo( V_SPHERE ) == 0 || wp.compareTo (V_F1)==0)
problemType = PROB_SPHERE;
else if ( wp.compareTo( V_STEP ) == 0 || wp.compareTo (V_F3)==0)
problemType = PROB_STEP;
else if ( wp.compareTo( V_NOISY_QUARTIC ) == 0 || wp.compareTo (V_F4)==0)
problemType = PROB_NOISY_QUARTIC;
else if( wp.compareTo( V_BOOTH ) == 0 )
problemType = PROB_BOOTH;
else if( wp.compareTo( V_GRIEWANK ) == 0 )
problemType = PROB_GRIEWANK;
else if (wp.compareTo( V_GRIEWANGK ) == 0 )
{
state.output.warning("Incorrect parameter name (\"griewangk\") used, should be \"griewank\"", base.push( P_WHICH_PROBLEM ), null );
problemType = PROB_GRIEWANK;
}
else if( wp.compareTo( V_MEDIAN ) == 0 )
problemType = PROB_MEDIAN;
else if( wp.compareTo( V_SUM ) == 0 )
problemType = PROB_SUM;
else if( wp.compareTo( V_PRODUCT ) == 0 )
problemType = PROB_PRODUCT;
else if (wp.compareTo( V_SCHWEFEL ) == 0 )
problemType = PROB_SCHWEFEL;
else if (wp.compareTo( V_MIN ) == 0 )
problemType = PROB_MIN;
else if (wp.compareTo( V_ROTATED_RASTRIGIN) == 0)
problemType = PROB_ROTATED_RASTRIGIN;
else if (wp.compareTo( V_ROTATED_SCHWEFEL) == 0)
problemType = PROB_ROTATED_SCHWEFEL;
else if (wp.compareTo( V_ROTATED_GRIEWANK) == 0)
problemType = PROB_ROTATED_GRIEWANK;
else if (wp.compareTo(V_LANGERMAN) == 0)
problemType = PROB_LANGERMAN ;
else if (wp.compareTo(V_LENNARDJONES) == 0)
problemType = PROB_LENNARDJONES ;
else if (wp.compareTo(V_LUNACEK) == 0)
problemType = PROB_LUNACEK ;
else state.output.fatal(
"Invalid value for parameter, or parameter not found.\n" +
"Acceptable values are:\n" +
" " + V_ROSENBROCK + " (or " + V_F2 + ")\n" +
" " + V_RASTRIGIN + "\n" +
" " + V_SPHERE + " (or " + V_F1 + ")\n" +
" " + V_STEP + " (or " + V_F3 + ")\n" +
" " + V_NOISY_QUARTIC + " (or " + V_F4 + ")\n"+
" " + V_BOOTH + "\n" +
" " + V_GRIEWANK + "\n" +
" " + V_MEDIAN + "\n" +
" " + V_SUM + "\n" +
" " + V_PRODUCT + "\n" +
" " + V_SCHWEFEL + "\n"+
" " + V_MIN + "\n"+
" " + V_ROTATED_RASTRIGIN + "\n" +
" " + V_ROTATED_SCHWEFEL + "\n" +
" " + V_ROTATED_GRIEWANK + "\n" +
" " + V_LANGERMAN + "\n" +
" " + V_LENNARDJONES + "\n" +
" " + V_LUNACEK + "\n",
base.push( P_WHICH_PROBLEM ) );
}
public void evaluate(final EvolutionState state,
final Individual ind,
final int subpopulation,
final int threadnum)
{
if (ind.evaluated) // don't bother reevaluating
return;
if( !( ind instanceof DoubleVectorIndividual ) )
state.output.fatal( "The individuals for this problem should be DoubleVectorIndividuals." );
DoubleVectorIndividual temp = (DoubleVectorIndividual)ind;
double[] genome = temp.genome;
int len = genome.length;
// this curious break-out makes it easy to use the isOptimal() and function() methods
// for other purposes, such as coevolutionary versions of this class.
// compute the fitness on a per-function basis
double fit = (function(state, problemType, temp.genome, threadnum));
// compute if we're optimal on a per-function basis
boolean isOptimal = isOptimal(problemType, fit);
// set the fitness appropriately
if ((float)fit < (0.0f - Float.MAX_VALUE)) // uh oh -- can be caused by Product for example
{
((SimpleFitness)(ind.fitness)).setFitness( state, 0.0f - Float.MAX_VALUE, isOptimal );
state.output.warnOnce("'Product' type used: some fitnesses are negative infinity, setting to lowest legal negative number.");
}
else if ((float)fit > Float.MAX_VALUE) // uh oh -- can be caused by Product for example
{
((SimpleFitness)(ind.fitness)).setFitness( state, Float.MAX_VALUE, isOptimal );
state.output.warnOnce("'Product' type used: some fitnesses are negative infinity, setting to lowest legal negative number.");
}
else
{
((SimpleFitness)(ind.fitness)).setFitness( state, (float)fit, isOptimal );
}
ind.evaluated = true;
}
public boolean isOptimal(int function, double fitness)
{
switch(problemType)
{
case PROB_ROSENBROCK:
case PROB_RASTRIGIN:
case PROB_SPHERE:
case PROB_STEP:
return fitness == 0.0f;
case PROB_NOISY_QUARTIC:
case PROB_BOOTH:
case PROB_GRIEWANK:
case PROB_MEDIAN:
case PROB_SUM:
case PROB_PRODUCT:
case PROB_SCHWEFEL:
case PROB_ROTATED_RASTRIGIN: // not sure
case PROB_ROTATED_SCHWEFEL:
case PROB_ROTATED_GRIEWANK:
case PROB_MIN:
case PROB_LANGERMAN: // may be around -1.4
case PROB_LENNARDJONES:
case PROB_LUNACEK:
default:
return false;
}
}
public double function(EvolutionState state, int function, double[] genome, int threadnum)
{
checkRange(state, function, genome);
double value = 0;
double len = genome.length;
switch(function)
{
case PROB_ROSENBROCK:
for( int i = 1 ; i < len ; i++ )
{
double gj = genome[i-1] ;
double gi = genome[i] ;
value += 100 * (gj*gj - gj) * (gj*gj - gj) + (1-gj) * (1-gj);
}
return -value;
case PROB_RASTRIGIN:
final float A = 10.0f;
value = len * A;
for( int i = 0 ; i < len ; i++ )
{
double gi = genome[i] ;
value += ( gi*gi - A * Math.cos( 2 * Math.PI * gi ) );
}
return -value;
case PROB_SPHERE:
for( int i = 0 ; i < len ; i++ )
{
double gi = genome[i] ;
value += gi * gi;
}
return -value;
case PROB_STEP:
for( int i = 0 ; i < len ; i++ )
{
double gi = genome[i] ;
value += 6 + Math.floor( gi );
}
return -value;
case PROB_NOISY_QUARTIC:
for( int i = 0 ; i < len ; i++ )
{
double gi = genome[i] ;
value += (i+1)*(gi*gi*gi*gi) + state.random[threadnum].nextDouble();
}
return -value;
case PROB_BOOTH:
if( len != 2 )
state.output.fatal( "The Booth problem is defined for only two terms, and as a consequence the genome of the DoubleVectorIndividual should have size 2." );
double g0 = genome[0] ;
double g1 = genome[1] ;
value = (g0 + 2*g1 - 7) * (g0 + 2*g1 - 7) +
(2*g0 + g1 - 5) * (2*g0 + g1 - 5);
return -value;
case PROB_GRIEWANK:
value = 1;
double prod = 1;
for( int i = 0 ; i < len ; i++ )
{
double gi = genome[i] ;
value += (gi*gi)/4000.0;
prod *= Math.cos( gi / Math.sqrt(i+1) );
}
value -= prod;
return -value;
case PROB_SCHWEFEL:
for( int i = 0 ; i < len ; i++ )
{
double gi = genome[i] ;
value += -gi * Math.sin(Math.sqrt(Math.abs(gi)));
}
return -value;
case PROB_MEDIAN: // FIXME, need to do a better median-finding algorithm, such as http://www.ics.uci.edu/~eppstein/161/960130.html
double[] sorted = new double[(int)len];
System.arraycopy(genome, 0, sorted, 0, sorted.length);
ec.util.QuickSort.qsort(sorted);
return sorted[sorted.length / 2] ; // note positive
case PROB_SUM:
value = 0.0;
for( int i = 0 ; i < len ; i++ )
{
double gi = genome[i] ;
value += gi;
}
return value; // note positive
case PROB_MIN:
value = genome[0] ;
for( int i = 1 ; i < len ; i++ )
{
double gi = genome[i] ;
if (value > gi) value = gi;
}
return value; // note positive
case PROB_PRODUCT:
value = 1.0;
for( int i = 0 ; i < len ; i++ )
{
double gi = genome[i] ;
value *= gi;
}
return value; // note positive
case PROB_ROTATED_RASTRIGIN:
{
synchronized(rotationMatrix) // synchronizations are rare in ECJ. :-(
{
if (rotationMatrix[0] == null)
rotationMatrix[0] = buildRotationMatrix(ROTATION_SEED, (int)len);
}
// now we know the matrix exists rotate the matrix and return its value
double[] val = mul(rotationMatrix[0], genome);
return function(state, PROB_RASTRIGIN, val, threadnum);
}
case PROB_ROTATED_SCHWEFEL:
{
synchronized(rotationMatrix) // synchronizations are rare in ECJ. :-(
{
if (rotationMatrix[0] == null)
rotationMatrix[0] = buildRotationMatrix(ROTATION_SEED, (int)len);
}
// now we know the matrix exists rotate the matrix and return its value
double[] val = mul(rotationMatrix[0], genome);
return function(state, PROB_SCHWEFEL, val, threadnum);
}
case PROB_ROTATED_GRIEWANK:
{
synchronized(rotationMatrix) // synchronizations are rare in ECJ. :-(
{
if (rotationMatrix[0] == null)
rotationMatrix[0] = buildRotationMatrix(ROTATION_SEED, (int)len);
}
// now we know the matrix exists rotate the matrix and return its value
double[] val = mul(rotationMatrix[0], genome);
return function(state, PROB_GRIEWANK, val, threadnum);
}
case PROB_LANGERMAN:
{
return 0.0 - langerman(genome);
}
case PROB_LENNARDJONES:
{
int numAtoms = genome.length / 3;
double v = 0.0 ;
for(int i = 0 ; i < numAtoms - 1 ; i++ )
{
for(int j = i + 1 ; j < numAtoms ; j++ )
{
// double d = dist(genome, i, j);
double a = genome[i * 3] - genome[j * 3];
double b = genome[i * 3 + 1] - genome[j * 3 + 1];
double c = genome[i * 3 + 2] - genome[j * 3 + 2];
double d = Math.sqrt(a * a + b * b + c * c);
double r12 = Math.pow(d, -12.0);
double r6 = Math.pow(d, -6.0);
double e = r12 - r6 ;
v += e ;
}
}
v *= -4.0 ;
return v;
}
case PROB_LUNACEK:
{
// Lunacek function: for more information, please see --
// http://arxiv.org/pdf/1207.4318.pdf
// http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.154.1657
// // // //
double s = 0.7 ; // The shape of the boundary of the double sphere,
// could be like [0.2 - 1.4] but not 0.0.
// > 1.0 or < 1.0 means a parabolic shape, 1.0 means a linear boundary.
double d = 1.0 ; // depth of the sphere, could be 1, 2, 3, or 4. 1 is deeper than 4
// this could be also be a fraction I guess.
double mu1 = 0.0 ;
for(int i = 0 ; i < genome.length ; i++)
mu1 = genome[i] ;
double mu2 = -1.0 * Math.sqrt(((mu1 * mu1) - d)/s);
double sigma1 = 0.0;
double sigma2 = 0.0 ;
for(int i = 0 ; i < genome.length ; i++)
{
sigma1 = (genome[i] - mu1) * (genome[i] - mu1);
sigma2 = (genome[i] - mu2) * (genome[i] - mu2);
}
sigma2 = d * genome.length + s * sigma1 ;
double sphere = Math.min(sigma1, sigma2);
double rastrigin = function(state, PROB_RASTRIGIN, genome, threadnum);
// + or - ? not sure, I always get confused.
// Lunacek function is a combination of Rastrigin and a Double Sphere.
// As the Rastrigin is -, so this function should be.
return -1.0 * (sphere + rastrigin) ;
}
default:
state.output.fatal( "ec.app.ecsuite.ECSuite has an invalid problem -- how on earth did that happen?" );
return 0; // never happens
}
}
// magic arrays for the Langerman problem
private double[][] afox10 =
{
{9.681, 0.667, 4.783, 9.095, 3.517, 9.325, 6.544, 0.211, 5.122, 2.020},
{9.400, 2.041, 3.788, 7.931, 2.882, 2.672, 3.568, 1.284, 7.033, 7.374},
{8.025, 9.152, 5.114, 7.621, 4.564, 4.711, 2.996, 6.126, 0.734, 4.982},
{2.196, 0.415, 5.649, 6.979, 9.510, 9.166, 6.304, 6.054, 9.377, 1.426},
{8.074, 8.777, 3.467, 1.863, 6.708, 6.349, 4.534, 0.276, 7.633, 1.567},
{7.650, 5.658, 0.720, 2.764, 3.278, 5.283, 7.474, 6.274, 1.409, 8.208},
{1.256, 3.605, 8.623, 6.905, 0.584, 8.133, 6.071, 6.888, 4.187, 5.448},
{8.314, 2.261, 4.224, 1.781, 4.124, 0.932, 8.129, 8.658, 1.208, 5.762},
{0.226, 8.858, 1.420, 0.945, 1.622, 4.698, 6.228, 9.096, 0.972, 7.637},
{7.305, 2.228, 1.242, 5.928, 9.133, 1.826, 4.060, 5.204, 8.713, 8.247},
{0.652, 7.027, 0.508, 4.876, 8.807, 4.632, 5.808, 6.937, 3.291, 7.016},
{2.699, 3.516, 5.874, 4.119, 4.461, 7.496, 8.817, 0.690, 6.593, 9.789},
{8.327, 3.897, 2.017, 9.570, 9.825, 1.150, 1.395, 3.885, 6.354, 0.109},
{2.132, 7.006, 7.136, 2.641, 1.882, 5.943, 7.273, 7.691, 2.880, 0.564},
{4.707, 5.579, 4.080, 0.581, 9.698, 8.542, 8.077, 8.515, 9.231, 4.670},
{8.304, 7.559, 8.567, 0.322, 7.128, 8.392, 1.472, 8.524, 2.277, 7.826},
{8.632, 4.409, 4.832, 5.768, 7.050, 6.715, 1.711, 4.323, 4.405, 4.591},
{4.887, 9.112, 0.170, 8.967, 9.693, 9.867, 7.508, 7.770, 8.382, 6.740},
{2.440, 6.686, 4.299, 1.007, 7.008, 1.427, 9.398, 8.480, 9.950, 1.675},
{6.306, 8.583, 6.084, 1.138, 4.350, 3.134, 7.853, 6.061, 7.457, 2.258},
{0.652, 0.343, 1.370, 0.821, 1.310, 1.063, 0.689, 8.819, 8.833, 9.070},
{5.558, 1.272, 5.756, 9.857, 2.279, 2.764, 1.284, 1.677, 1.244, 1.234},
{3.352, 7.549, 9.817, 9.437, 8.687, 4.167, 2.570, 6.540, 0.228, 0.027},
{8.798, 0.880, 2.370, 0.168, 1.701, 3.680, 1.231, 2.390, 2.499, 0.064},
{1.460, 8.057, 1.336, 7.217, 7.914, 3.615, 9.981, 9.198, 5.292, 1.224},
{0.432, 8.645, 8.774, 0.249, 8.081, 7.461, 4.416, 0.652, 4.002, 4.644},
{0.679, 2.800, 5.523, 3.049, 2.968, 7.225, 6.730, 4.199, 9.614, 9.229},
{4.263, 1.074, 7.286, 5.599, 8.291, 5.200, 9.214, 8.272, 4.398, 4.506},
{9.496, 4.830, 3.150, 8.270, 5.079, 1.231, 5.731, 9.494, 1.883, 9.732},
{4.138, 2.562, 2.532, 9.661, 5.611, 5.500, 6.886, 2.341, 9.699, 6.500}
};
private double[] cfox10 =
{
0.806, 0.517, 1.5, 0.908, 0.965,
0.669, 0.524, 0.902, 0.531, 0.876,
0.462, 0.491, 0.463, 0.714, 0.352,
0.869, 0.813, 0.811, 0.828, 0.964,
0.789, 0.360, 0.369, 0.992, 0.332,
0.817, 0.632, 0.883, 0.608, 0.326
};
private double langerman(double genome[])
{
double sum = 0 ;
for ( int i = 0 ; i < 30 ; i++ )
{
// compute squared distance
double distsq = 0.0;
double t;
double[] afox10i = afox10[i];
for(int j = 0; j < genome.length; j++)
{
t = genome[j] - afox10i[j];
distsq += t * t;
}
sum += cfox10[i] * Math.exp(-distsq / Math.PI) * Math.cos(distsq * Math.PI);
}
return 0 - sum;
}
/*
-----------------
Rotation facility
-----------------
This code is just used by the Rotated Schwefel and Rotated Rastrigin functions to rotate their
functions by a certain amount. The code is largely based on the rotation scheme described in
"Completely Derandomized Self-Adaptation in Evolutionary Strategies",
Nikolaus Hansen and Andreas Ostermeier, Evolutionary Computation 9(2): 159--195.
We fix a hard-coded rotation matrix which is the same for all problems, in order to guarantee
correctness in gathering results over multiple jobs. But you can change that easily if you like.
*/
public static double[][][] rotationMatrix = new double[1][][]; // the actual matrix is stored in rotationMatrix[0] -- a hack
/** Dot product between two column vectors. Does not modify the original vectors. */
public static double dot(double[] x, double[] y)
{
double val = 0;
for(int i =0; i < x.length; i++)
val += x[i] * y[i];
return val;
}
/** Multiply a column vector against a matrix[row][column]. Does not modify the original vector or matrix. */
public static double[] mul(double [/* row */ ][ /* column */] matrix, double[] x)
{
double[] val = new double[matrix.length];
for(int i = 0; i < matrix.length; i++)
{
double sum = 0.0;
double[] m = matrix[i];
for(int j = 0; j < m.length; j++)
sum += m[j] * x[j];
val[i] = sum;
}
return val;
}
/** Scalar multiply against a column vector. Does not modify the original vector. */
public static double[] scalarMul(double scalar, double[] x)
{
double[] val = new double[x.length];
for(int i =0; i < x.length; i++)
val[i] = x[i] * scalar;
return val;
}
/** Subtract two column vectors. Does not modify the original vectors. */
public static double[] sub(double[] x, double[] y)
{
double[] val = new double[x.length];
for(int i =0; i < x.length; i++)
val[i] = x[i] - y[i];
return val;
}
/** Normalize a column vector. Does not modify the original vector. */
public static double[] normalize(double[] x)
{
double[] val = new double[x.length];
double sumsq = 0;
for(int i =0; i < x.length; i++)
sumsq += x[i] * x[i];
sumsq = Math.sqrt(sumsq);
for(int i =0; i < x.length; i++)
val[i] = x[i] / sumsq;
return val;
}
/** Fixed rotation seed so all jobs use exactly the same rotation space. */
public static final long ROTATION_SEED = 9731297;
/** Build an NxN rotation matrix[row][column] with a given seed. */
public static double[ /* row */ ][ /* column */] buildRotationMatrix(double rotationSeed, int N)
{
MersenneTwisterFast rand = new MersenneTwisterFast(ROTATION_SEED); // it's rare to need to do this, but we need to guarantee the same rotation space
double o[ /* row */ ][ /* column */ ] = new double[N][N];
// make random values
for(int i = 0; i < N; i++)
for(int k = 0; k < N; k++)
o[i][k] = rand.nextGaussian();
// build random values
for(int i = 0; i < N; i++)
{
// extract o[i] -> no
double[] no = new double[N];
for(int k=0; k < N; k++)
no[k] = o[i][k];
// go through o[i] and o[j], modifying no
for(int j = 0; j < i; j++)
{
double d = dot(o[i], o[j]);
double[] val = scalarMul(d, o[j]);
no = sub(no, val);
}
o[i] = normalize(no);
}
return o;
}
}
| mit |
darvid7/ForkMe-Mobile | ForkMe-Mobile/app/src/main/java/dlei/forkme/gui/adapters/RepositoryRecyclerViewAdapter.java | 2815 | package dlei.forkme.gui.adapters;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import dlei.forkme.R;
import dlei.forkme.gui.activities.github.RepositoryViewActivity;
import dlei.forkme.model.Repository;
public class RepositoryRecyclerViewAdapter extends RecyclerView.Adapter<RepositoryViewHolder> {
private ArrayList<Repository> mRepositoryList;
public RepositoryRecyclerViewAdapter(ArrayList<Repository> repositories) {
mRepositoryList = repositories; // Just a pointer, not a deep copy.
}
/**
* Get number of items in mRepositoryList.
* @return size of mRepositoryList.
*/
@Override
public int getItemCount() {
return mRepositoryList.size();
}
/**
* Inflate a view to be used to display an item in the adapter.
* @param parent parent view.
* @param viewType type of view.
* @return RepositoryViewHolder, the view to display.
*/
@Override
public RepositoryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.repository_list_card, parent, false);
RepositoryViewHolder repositoryCard = new RepositoryViewHolder(itemView);
return repositoryCard;
}
/**
* For each view item displayed by the adapter, this is called to bind the repository data to the view
* so the view item displays the right information.
* Also sets listener for clicking on the repository.
* @param repositoryCard, RepositoryViewHolder view to display for each Repository in mRepositoryList.
* @param position, int position of Repository.
*/
@Override
public void onBindViewHolder(RepositoryViewHolder repositoryCard, int position) {
final Repository repository = mRepositoryList.get(position);
// Set UI elements.
repositoryCard.setLanguage(repository.getLanguage());
repositoryCard.setOwnerUserNameText(repository.getOwnerName());
repositoryCard.setRepoDescriptionText(repository.getDescription());
repositoryCard.setRepoNameText(repository.getRepoName());
repositoryCard.setForkCountText(repository.getForkCount());
repositoryCard.setStarCountText(repository.getStargazerCount());
repositoryCard.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), RepositoryViewActivity.class);
i.putExtra("repository", repository);
v.getContext().startActivity(i);
}
});
}
}
| mit |
OpenMods/OpenModsLib | src/main/java/openmods/network/event/NetworkEventMeta.java | 359 | package openmods.network.event;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface NetworkEventMeta {
public EventDirection direction() default EventDirection.ANY;
}
| mit |
prat0318/dbms | mini_dbms/je-5.0.103/src/com/sleepycat/bind/tuple/SortedFloatBinding.java | 1989 | /*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2000, 2010 Oracle and/or its affiliates. All rights reserved.
*
*/
package com.sleepycat.bind.tuple;
import com.sleepycat.je.DatabaseEntry;
/**
* A concrete <code>TupleBinding</code> for a sorted <code>Float</code>
* primitive wrapper or sorted a <code>float</code> primitive.
*
* <p>There are two ways to use this class:</p>
* <ol>
* <li>When using the {@link com.sleepycat.je} package directly, the static
* methods in this class can be used to convert between primitive values and
* {@link DatabaseEntry} objects.</li>
* <li>When using the {@link com.sleepycat.collections} package, an instance of
* this class can be used with any stored collection.</li>
* </ol>
*
* @see <a href="package-summary.html#floatFormats">Floating Point Formats</a>
*/
public class SortedFloatBinding extends TupleBinding<Float> {
/* javadoc is inherited */
public Float entryToObject(TupleInput input) {
return input.readSortedFloat();
}
/* javadoc is inherited */
public void objectToEntry(Float object, TupleOutput output) {
output.writeSortedFloat(object);
}
/* javadoc is inherited */
protected TupleOutput getTupleOutput(Float object) {
return FloatBinding.sizedOutput();
}
/**
* Converts an entry buffer into a simple <code>float</code> value.
*
* @param entry is the source entry buffer.
*
* @return the resulting value.
*/
public static float entryToFloat(DatabaseEntry entry) {
return entryToInput(entry).readSortedFloat();
}
/**
* Converts a simple <code>float</code> value into an entry buffer.
*
* @param val is the source value.
*
* @param entry is the destination entry buffer.
*/
public static void floatToEntry(float val, DatabaseEntry entry) {
outputToEntry(FloatBinding.sizedOutput().writeSortedFloat(val), entry);
}
}
| mit |
chav1961/purelib | src/test/java/chav1961/purelib/basic/BooleanOwner.java | 270 | package chav1961.purelib.basic;
public class BooleanOwner {
public boolean value = false;
private boolean privateValue = false;
public boolean getPrivateValue(){return privateValue;}
public void setPrivateValue(final boolean newValue){privateValue = newValue;}
}
| mit |
occloxium/Monoid | src/synth/modulation/Envelope.java | 4051 | package synth.modulation;
import net.beadsproject.beads.core.AudioContext;
import synth.container.Device;
/**
* A basic envelope wrapping class.
*/
public class Envelope extends Modulator implements Modulatable {
/** attack time in milliseconds */
protected int attack;
/** decay time in milliseconds */
protected int decay;
/** sustain level in [0,1] */
protected float sustain;
/** release time in milliseconds */
protected int release;
/** Audio context */
protected AudioContext context;
/** Backend Envelope UGen */
protected net.beadsproject.beads.ugens.Envelope current;
/** Default envelope */
public Envelope(AudioContext ac){
this(ac,5, 0, 1f, 20);
}
/**
* AR-Envelope
* @param attack attack time
* @param release release time
*/
public Envelope(AudioContext ac, int attack, int release){
this(ac, attack, 0, 1f, release);
}
/**
* ADSR-Envelope
* @param attack attack time
* @param decay decay time
* @param sustain sustain level
* @param release release time
*/
public Envelope(AudioContext ac, int attack, int decay, float sustain, int release){
super(ac);
this.context = ac;
this.attack = attack;
this.decay = decay;
this.sustain = sustain;
this.release = release;
current = new net.beadsproject.beads.ugens.Envelope(this.context);
this.outputInitializationRegime = OutputInitializationRegime.ZERO;
this.outputPauseRegime = OutputPauseRegime.ZERO;
}
/**
* Gets the attack time in [ms]
* @return attack time
*/
public int attack() {
return attack;
}
/**
* Sets the attack time
* @param attack attack time in ms
*/
public void setAttack(int attack) {
this.attack = attack;
}
/**
* Gets the decay time in [ms]
* @return decay time
*/
public int decay() {
return decay;
}
/**
* Sets the decay time in [ms]
* @param decay decay time
*/
public void setDecay(int decay) {
this.decay = decay;
}
/**
* Gets the sustain level
* @return sustain level
*/
public float sustain() {
return sustain;
}
/**
* Sets the sustain level
* @param sustain decay time
*/
public void setSustain(float sustain) {
this.sustain = sustain;
this.current.setValue(sustain);
}
/**
* Gets the release time in [ms]
* @return release time
*/
public int release() {
return release;
}
/**
* Sets the release time in [ms]
* @param release release time
*/
public void setRelease(int release) {
this.release = release;
}
@Override
public void calculateBuffer(){
current.update();
for(int i = 0; i < bufferSize; i++){
bufOut[0][i] = modulationStrength * current.getValue(0, i) + centerValue;
}
}
public float getValue(){
return this.centerValue;
}
public Envelope clone(){
Envelope e = new Envelope(this.ac, this.attack, this.decay, this.sustain, this.release);
return (Envelope)(e.setModulationStrength(this.modulationStrength).setModulationMode(this.modulationMode).setCenterValue(this.centerValue));
}
/**
* Method for {@link Device} when a send for MIDI data with noteOn command appears to happen
*/
public void noteOn(){
this.current.setValue(0);
this.current.clear();
this.current.addSegment(1f, this.attack);
this.current.addSegment(this.sustain, this.decay);
}
/**
* Method for {@link Device} when a send for MIDI data with noteOff command appears to happen
*/
public void noteOff(){
this.current.addSegment(0f, this.release);
}
public NormEnvelope normalize(){
return new NormEnvelope(ac, this.attack, this.decay, this.sustain, this.release);
}
}
| mit |
pegurnee/2013-03-211 | complete/src/data_struct/labs/l04/a/Commission.java | 773 | package data_struct.labs.l04.a;
/**
* This is the Commission class for lab4
*
* @author Eddie Gurnee
* @version 10/14/2013
*/
public class Commission extends Hourly {
protected double totalSales;
protected double commissionRate;
public Commission(String eName, String eAddress, String ePhone,
String socSecNumber, double rate, double commissionRate) {
super(eName, eAddress, ePhone, socSecNumber, rate);
this.commissionRate = commissionRate;
}
public void addSales (double totalSales) {
this.totalSales += totalSales;
}
@Override
public double pay() {
double thePay = super.pay() + commissionRate * totalSales;
totalSales = 0;
return thePay;
}
public String toString() {
return super.toString() + "\nTotal Sales: " + totalSales;
}
}
| mit |
NickToony/scrAI | src/main/java/com/nicktoony/screeps/structures/Wall.java | 202 | package com.nicktoony.screeps.structures;
import com.nicktoony.screeps.interfaces.DecayableStructure;
/**
* Created by nick on 10/08/15.
*/
public abstract class Wall extends DecayableStructure {
}
| mit |
Shalantor/JSF-Course | JSF2-Expression-Language/exercises_1_and_2/src/TestBean.java | 613 | import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
@ManagedBean
public class TestBean {
private String[] colors= {"red","blue","green","black"};
private List<String> meals = new ArrayList<>();
public TestBean(){
meals.add("soup");
meals.add("fish fillet");
meals.add("fried chips");
meals.add("steak");
}
public String[] getColors() {
return colors;
}
public void setColors(String[] colors) {
this.colors = colors;
}
public List<String> getMeals() {
return meals;
}
public void setMeals(List<String> meals) {
this.meals = meals;
}
}
| mit |
TheOpenCloudEngine/metaworks | metaworks3/src/main/java/org/metaworks/AllChildFacesAreIgnored.java | 129 | package org.metaworks;
/**
* Created by jangjinyoung on 15. 9. 17..
*/
public interface AllChildFacesAreIgnored extends Face{} | mit |
Mr-DLib/jabref | src/main/java/net/sf/jabref/JabRefMain.java | 6658 | package net.sf.jabref;
import java.net.Authenticator;
import java.util.Map;
import javax.swing.SwingUtilities;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.stage.Stage;
import net.sf.jabref.cli.ArgumentProcessor;
import net.sf.jabref.gui.remote.JabRefMessageHandler;
import net.sf.jabref.logic.exporter.ExportFormat;
import net.sf.jabref.logic.exporter.ExportFormats;
import net.sf.jabref.logic.exporter.SavePreferences;
import net.sf.jabref.logic.formatter.casechanger.ProtectTermsFormatter;
import net.sf.jabref.logic.journals.JournalAbbreviationLoader;
import net.sf.jabref.logic.l10n.Localization;
import net.sf.jabref.logic.layout.LayoutFormatterPreferences;
import net.sf.jabref.logic.net.ProxyAuthenticator;
import net.sf.jabref.logic.net.ProxyPreferences;
import net.sf.jabref.logic.net.ProxyRegisterer;
import net.sf.jabref.logic.protectedterms.ProtectedTermsLoader;
import net.sf.jabref.logic.remote.RemotePreferences;
import net.sf.jabref.logic.remote.client.RemoteListenerClient;
import net.sf.jabref.logic.util.OS;
import net.sf.jabref.migrations.PreferencesMigrations;
import net.sf.jabref.model.EntryTypes;
import net.sf.jabref.model.database.BibDatabaseMode;
import net.sf.jabref.model.entry.InternalBibtexFields;
import net.sf.jabref.preferences.JabRefPreferences;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* JabRef MainClass
*/
public class JabRefMain extends Application {
private static final Log LOGGER = LogFactory.getLog(JabRefMain.class);
private static String[] arguments;
public static void main(String[] args) {
arguments = args;
launch(arguments);
}
@Override
public void start(Stage mainStage) throws Exception {
Platform.setImplicitExit(false);
SwingUtilities.invokeLater(() -> start(arguments));
}
private static void start(String[] args) {
FallbackExceptionHandler.installExceptionHandler();
JabRefPreferences preferences = JabRefPreferences.getInstance();
ProxyPreferences proxyPreferences = preferences.getProxyPreferences();
ProxyRegisterer.register(proxyPreferences);
if (proxyPreferences.isUseProxy() && proxyPreferences.isUseAuthentication()) {
Authenticator.setDefault(new ProxyAuthenticator());
}
Globals.startBackgroundTasks();
Globals.prefs = preferences;
Localization.setLanguage(preferences.get(JabRefPreferences.LANGUAGE));
Globals.prefs.setLanguageDependentDefaultValues();
// Perform Migrations
// Perform checks and changes for users with a preference set from an older JabRef version.
PreferencesMigrations.upgradeSortOrder();
PreferencesMigrations.upgradeFaultyEncodingStrings();
PreferencesMigrations.upgradeLabelPatternToBibtexKeyPattern();
PreferencesMigrations.upgradeStoredCustomEntryTypes();
// Update handling of special fields based on preferences
InternalBibtexFields
.updateSpecialFields(Globals.prefs.getBoolean(JabRefPreferences.SERIALIZESPECIALFIELDS));
// Update name of the time stamp field based on preferences
InternalBibtexFields.updateTimeStampField(Globals.prefs.get(JabRefPreferences.TIME_STAMP_FIELD));
// Update which fields should be treated as numeric, based on preferences:
InternalBibtexFields.setNumericFields(Globals.prefs.getStringList(JabRefPreferences.NUMERIC_FIELDS));
// Read list(s) of journal names and abbreviations
Globals.journalAbbreviationLoader = new JournalAbbreviationLoader();
/* Build list of Import and Export formats */
Globals.IMPORT_FORMAT_READER.resetImportFormats(Globals.prefs.getImportFormatPreferences(),
Globals.prefs.getXMPPreferences());
EntryTypes.loadCustomEntryTypes(preferences.loadCustomEntryTypes(BibDatabaseMode.BIBTEX),
preferences.loadCustomEntryTypes(BibDatabaseMode.BIBLATEX));
Map<String, ExportFormat> customFormats = Globals.prefs.customExports.getCustomExportFormats(Globals.prefs,
Globals.journalAbbreviationLoader);
LayoutFormatterPreferences layoutPreferences = Globals.prefs
.getLayoutFormatterPreferences(Globals.journalAbbreviationLoader);
SavePreferences savePreferences = SavePreferences.loadForExportFromPreferences(Globals.prefs);
ExportFormats.initAllExports(customFormats, layoutPreferences, savePreferences);
// Initialize protected terms loader
Globals.protectedTermsLoader = new ProtectedTermsLoader(Globals.prefs.getProtectedTermsPreferences());
ProtectTermsFormatter.setProtectedTermsLoader(Globals.protectedTermsLoader);
// Check for running JabRef
RemotePreferences remotePreferences = Globals.prefs.getRemotePreferences();
if (remotePreferences.useRemoteServer()) {
Globals.REMOTE_LISTENER.open(new JabRefMessageHandler(), remotePreferences.getPort());
if (!Globals.REMOTE_LISTENER.isOpen()) {
// we are not alone, there is already a server out there, try to contact already running JabRef:
if (RemoteListenerClient.sendToActiveJabRefInstance(args, remotePreferences.getPort())) {
// We have successfully sent our command line options through the socket to another JabRef instance.
// So we assume it's all taken care of, and quit.
LOGGER.info(Localization.lang("Arguments passed on to running JabRef instance. Shutting down."));
JabRefExecutorService.INSTANCE.shutdownEverything();
return;
}
}
// we are alone, we start the server
Globals.REMOTE_LISTENER.start();
}
// override used newline character with the one stored in the preferences
// The preferences return the system newline character sequence as default
OS.NEWLINE = Globals.prefs.get(JabRefPreferences.NEWLINE);
// Process arguments
ArgumentProcessor argumentProcessor = new ArgumentProcessor(args, ArgumentProcessor.Mode.INITIAL_START);
// See if we should shut down now
if (argumentProcessor.shouldShutDown()) {
JabRefExecutorService.INSTANCE.shutdownEverything();
return;
}
// If not, start GUI
SwingUtilities
.invokeLater(() -> new JabRefGUI(argumentProcessor.getParserResults(),
argumentProcessor.isBlank()));
}
}
| mit |
venwyhk/ikasoa | ikasoa-spring-boot-starter/src/main/java/com/ikasoa/springboot/autoconfigure/ClientAutoConfiguration.java | 4079 | package com.ikasoa.springboot.autoconfigure;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportAware;
import org.springframework.core.type.AnnotationMetadata;
import com.ikasoa.core.ServerInfo;
import com.ikasoa.core.loadbalance.Node;
import com.ikasoa.core.thrift.client.ThriftClientConfiguration;
import com.ikasoa.core.utils.ServerUtil;
import com.ikasoa.core.utils.StringUtil;
import com.ikasoa.rpc.Configurator;
import com.ikasoa.rpc.RpcException;
import com.ikasoa.springboot.ServiceProxy;
import com.ikasoa.springboot.annotation.RpcEurekaClient;
import com.ikasoa.zk.ZkServerCheck;
import lombok.extern.slf4j.Slf4j;
import com.ikasoa.springboot.annotation.RpcClient;
/**
* IKASOA客户端自动配置
*
* @author <a href="mailto:larry7696@gmail.com">Larry</a>
* @version 0.1
*/
@Configuration
@Slf4j
public class ClientAutoConfiguration extends AbstractAutoConfiguration implements ImportAware {
private String eurekaAppName;
private int eurekaAppPort;
@Autowired
private DiscoveryClient discoveryClient;
@Bean
public ServiceProxy getServiceProxy() throws RpcException {
if (discoveryClient != null && StringUtil.isNotEmpty(eurekaAppName) && ServerUtil.isPort(eurekaAppPort)) {
log.debug("Eureka services : " + discoveryClient.getServices());
if (!ServerUtil.isPort(eurekaAppPort))
throw new RpcException("Port '" + eurekaAppPort + "' is error !");
List<ServiceInstance> instanceList = discoveryClient.getInstances(eurekaAppName);
if (instanceList.isEmpty())
throw new RpcException(StringUtil.merge("Service '", eurekaAppName, "' is empty !"));
List<Node<ServerInfo>> serverInfoList = instanceList.stream()
.map(i -> new Node<ServerInfo>(new ServerInfo(i.getHost(), eurekaAppPort)))
.collect(Collectors.toList());
return StringUtil.isEmpty(configurator)
? new ServiceProxy(serverInfoList)
: new ServiceProxy(serverInfoList, getConfigurator());
} else if (StringUtil.isNotEmpty(zkServerString)) {
Configurator configurator = getConfigurator();
ThriftClientConfiguration thriftClientConfiguration = new ThriftClientConfiguration();
thriftClientConfiguration.setServerCheck(new ZkServerCheck(zkServerString, zkNode));
configurator.setThriftClientConfiguration(thriftClientConfiguration);
return new ServiceProxy(getHost(), getPort(), configurator);
} else
return StringUtil.isEmpty(configurator) ? new ServiceProxy(getHost(), getPort())
: new ServiceProxy(getHost(), getPort(), getConfigurator());
}
@Override
public void setImportMetadata(AnnotationMetadata annotationMetadata) {
Map<String, Object> rpcClientAttributes = annotationMetadata.getAnnotationAttributes(RpcClient.class.getName());
if (rpcClientAttributes != null && !rpcClientAttributes.isEmpty()) {
if (rpcClientAttributes.containsKey("host"))
host = rpcClientAttributes.get("host").toString();
if (rpcClientAttributes.containsKey("port"))
port = rpcClientAttributes.get("port").toString();
if (rpcClientAttributes.containsKey("config"))
configurator = rpcClientAttributes.get("config").toString();
}
Map<String, Object> rpcEurekaClientAttributes = annotationMetadata
.getAnnotationAttributes(RpcEurekaClient.class.getName());
if (rpcEurekaClientAttributes != null && !rpcEurekaClientAttributes.isEmpty()) {
if (rpcEurekaClientAttributes.containsKey("name"))
eurekaAppName = rpcEurekaClientAttributes.get("name").toString();
if (rpcEurekaClientAttributes.containsKey("port"))
eurekaAppPort = (Integer) rpcEurekaClientAttributes.get("port");
if (rpcEurekaClientAttributes.containsKey("config"))
configurator = rpcEurekaClientAttributes.get("config").toString();
}
}
}
| mit |
PrinceOfAmber/CyclicMagic | src/main/java/com/lothrazar/cyclic/item/storagebag/RefillMode.java | 356 | package com.lothrazar.cyclic.item.storagebag;
import java.util.Locale;
import net.minecraft.util.StringRepresentable;
public enum RefillMode implements StringRepresentable {
NOTHING, HOTBAR;
public static final String NBT = "refill_mode";
@Override
public String getSerializedName() {
return this.name().toLowerCase(Locale.ENGLISH);
}
}
| mit |
Zaraka/Reaper | src/reaper/model/LinkSet.java | 2810 | /*
* The MIT License
*
* Copyright 2015 Reaper.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package reaper.model;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.OCommandSQL;
import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory;
import java.util.List;
import java.util.Map;
/**
*
* @author zaraka
*/
public class LinkSet {
OrientGraphFactory factory;
LinkSet(OrientGraphFactory factory){
this.factory = factory;
}
public void setFactory(OrientGraphFactory factory){
this.factory = factory;
}
public void put(String key, String value, String cluster){
ODatabaseDocumentTx oDB = factory.getDatabase();
try {
oDB.command(
new OCommandSQL("INSERT INTO "
+ DatabaseClasses.LINKSET.getName() + " cluster "
+ DatabaseClasses.LINKSET.getName() + cluster
+ " SET key = ?, value = ?"
)
).execute(key, value);
} finally {
oDB.close();
}
}
public void fillMap(Map<String, String> resources, String cluster){
ODatabaseDocumentTx oDB = factory.getDatabase();
try {
List<ODocument> result = oDB.command(new OCommandSQL("SELECT * FROM cluster:"
+ DatabaseClasses.LINKSET.getName()
+ cluster
)).execute();
for(ODocument doc : result){
resources.put(doc.field("key"), doc.field("value"));
}
} finally {
oDB.close();
}
}
}
| mit |
reflectoring/coderadar | coderadar-plugin-api/src/main/java/io/reflectoring/coderadar/plugin/api/FileMetrics.java | 5411 | package io.reflectoring.coderadar.plugin.api;
import java.util.*;
public class FileMetrics {
private Map<Metric, Integer> counts = new HashMap<>();
private Map<Metric, List<Finding>> findings = new HashMap<>();
public FileMetrics() {
}
/**
* Copy constructor.
*
* @param copyFrom the object whose state to copy into this object.
*/
public FileMetrics(FileMetrics copyFrom) {
this.counts = copyFrom.counts;
this.findings = copyFrom.findings;
}
/**
* Returns all metrics for which a count or findings exist within this FileMetrics object.
*
* @return all metrics for which a count or findings exist within this FileMetrics object.
*/
public Set<Metric> getMetrics() {
Set<Metric> metrics = new HashSet<>();
metrics.addAll(counts.keySet());
metrics.addAll(findings.keySet());
return metrics;
}
/**
* Returns the count for the given metric.
*
* @param metric the metric whose count to return.
* @return count of the specified metric.
*/
public int getMetricCount(Metric metric) {
Integer result = counts.get(metric);
if (result != null) {
return result;
} else {
return 0;
}
}
/**
* Sets the count for the given metric.
*
* @param metric the metric whose count to set.
* @param count the value to which to set the count.
*/
public void setMetricCount(Metric metric, int count) {
counts.put(metric, count);
}
/**
* Increments the count of the specified metric for this file by one.
*
* @param metric the metric whose count to increment.
*/
private void incrementMetricCount(Metric metric, int increment) {
Integer count = counts.get(metric);
if (count == null) {
count = 0;
}
counts.put(metric, count + increment);
}
public void incrementMetricCount(Metric metric) {
incrementMetricCount(metric, 1);
}
/**
* Adds a finding for the specified metric to this FileMetrics object. <strong>This method also
* increments the metric count by 1 so that incrementMetricCount() should not be called for the
* findings passed into addFinding()!</strong>
*
* @param metric the metric for which to add the finding.
* @param finding the finding to add.
*/
public void addFinding(Metric metric, Finding finding) {
addFinding(metric, finding, 1);
}
/**
* Adds a finding for the specified metric to this FileMetrics object. <strong>This method also
* increments the metric count by <code>count</code> so that incrementMetricCount() should not be
* called for the findings passed into addFinding()!</strong>
*
* @param metric the metric for which to add the finding.
* @param finding the finding to add.
* @param count the number by which to increment the metric count
*/
public void addFinding(Metric metric, Finding finding, Integer count) {
List<Finding> findingsForMetric = findings.computeIfAbsent(metric, k -> new ArrayList<>());
incrementMetricCount(metric, count);
findingsForMetric.add(finding);
}
/**
* Adds a collection of findings for the specified metric to this FileMetrics object. <strong>This
* method also increments the metric count so that incrementMetricCount() should not be called for
* the findings passed into addFinding()!</strong>
*
* @param metric the metric for which to add the findings.
* @param findingsToAdd the findings to add.
*/
public void addFindings(Metric metric, Collection<Finding> findingsToAdd) {
List<Finding> findingsForMetric = findings.computeIfAbsent(metric, k -> new ArrayList<>());
incrementMetricCount(metric, findingsToAdd.size());
findingsForMetric.addAll(findingsToAdd);
}
/**
* Returns the findings of the given metric stored in this FileMetrics object.
*
* @param metric the metric whose findings to return.
* @return the findings of the specified metric.
*/
public List<Finding> getFindings(Metric metric) {
List<Finding> resultList = findings.get(metric);
if (resultList == null) {
return Collections.emptyList();
} else {
return resultList;
}
}
/**
* Adds the given metrics to the metrics stored in this object.
*
* @param metrics the metrics to add to this FileMetrics object
*/
public void add(FileMetrics metrics) {
for (Metric metric : metrics.getMetrics()) {
Integer currentValue = counts.get(metric);
if (currentValue == null) {
currentValue = 0;
}
counts.put(metric, currentValue + metrics.getMetricCount(metric));
findings.put(metric, metrics.getFindings(metric));
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FileMetrics that = (FileMetrics) o;
return counts != null ? counts.equals(that.counts) : that.counts == null;
}
@Override
public int hashCode() {
return counts != null ? counts.hashCode() : 0;
}
}
| mit |
chr-krenn/fhj-ws2015-sd13-pse | pse/src/main/java/at/fhj/swd13/pse/domain/document/DocumentLibraryRightsProviderFactory.java | 447 | package at.fhj.swd13.pse.domain.document;
import javax.inject.Inject;
import at.fhj.swd13.pse.plumbing.UserSession;
public class DocumentLibraryRightsProviderFactory {
@Inject
private UserSession userSession;
public DocumentLibraryRightsProvider create(int communityId)
{
if(communityId == 1)
return new GlobalDocumentLibraryRightsProvider(userSession);
else
return new DefaultDocumentLibraryRightsProvider(communityId);
}
}
| mit |
bnguyen82/stuff-projects | database-util/src/book/util/MiscUtil.java | 2765 | package book.util;
import java.io.*;
import java.util.*;
public class MiscUtil {
public static boolean hasDuplicates(Vector v) {
int i = 0;
int j = 0;
boolean duplicates = false;
for (i = 0; i < v.size() - 1; i++) {
for (j = (i + 1); j < v.size(); j++) {
if (v.elementAt(i).toString().equalsIgnoreCase(
v.elementAt(j).toString())) {
duplicates = true;
}
}
}
return duplicates;
}
public static Vector removeDuplicates(Vector s) {
int i = 0;
int j = 0;
boolean duplicates = false;
Vector v = new Vector();
for (i = 0; i < s.size(); i++) {
duplicates = false;
for (j = (i + 1); j < s.size(); j++) {
if (s.elementAt(i).toString().equalsIgnoreCase(
s.elementAt(j).toString())) {
duplicates = true;
}
}
if (duplicates == false) {
v.addElement(s.elementAt(i).toString().trim());
}
}
return v;
}
public static Vector removeDuplicateDomains(Vector s) {
int i = 0;
int j = 0;
boolean duplicates = false;
String str1 = "";
String str2 = "";
Vector v = new Vector();
for (i = 0; i < s.size(); i++) {
duplicates = false;
for (j = (i + 1); j < s.size(); j++) {
str1 = "";
str2 = "";
str1 = s.elementAt(i).toString().trim();
str2 = s.elementAt(j).toString().trim();
if (str1.indexOf('@') > -1) {
str1 = str1.substring(str1.indexOf('@'));
}
if (str2.indexOf('@') > -1) {
str2 = str2.substring(str2.indexOf('@'));
}
if (str1.equalsIgnoreCase(str2)) {
duplicates = true;
}
}
if (duplicates == false) {
v.addElement(s.elementAt(i).toString().trim());
}
}
return v;
}
public static boolean areVectorsEqual(Vector a, Vector b) {
if (a.size() != b.size()) {
return false;
}
int i = 0;
int vectorSize = a.size();
boolean identical = true;
for (i = 0; i < vectorSize; i++) {
if (!(a.elementAt(i).toString().equalsIgnoreCase(
b.elementAt(i).toString()))) {
identical = false;
}
}
return identical;
}
public static Vector removeDuplicates(Vector a, Vector b) {
int i = 0;
int j = 0;
boolean present = true;
Vector v = new Vector();
for (i = 0; i < a.size(); i++) {
present = false;
for (j = 0; j < b.size(); j++) {
if (a.elementAt(i).toString().equalsIgnoreCase(
b.elementAt(j).toString())) {
present = true;
}
}
if (!(present)) {
v.addElement(a.elementAt(i));
}
}
return v;
}
}// end of class
| mit |