repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
snavaneethan1/jaffa-framework | jaffa-core/source/java/org/jaffa/presentation/portlet/widgets/taglib/GridRowTag.java | 7649 | /*
* ====================================================================
* JAFFA - Java Application Framework For All
*
* Copyright (C) 2002 JAFFA Development Group
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Redistribution and use of this software and associated documentation ("Software"),
* with or without modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain copyright statements and notices.
* Redistributions must also contain a copy of this document.
* 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 "JAFFA" must not be used to endorse or promote products derived from
* this Software without prior written permission. For written permission,
* please contact mail to: jaffagroup@yahoo.com.
* 4. Products derived from this Software may not be called "JAFFA" nor may "JAFFA"
* appear in their names without prior written permission.
* 5. Due credit should be given to the JAFFA Project (http://jaffa.sourceforge.net).
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*/
package org.jaffa.presentation.portlet.widgets.taglib;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyContent;
import org.apache.log4j.Logger;
import org.jaffa.presentation.portlet.widgets.taglib.exceptions.OuterGridTagMissingRuntimeException;
/** Tag Handler for the GridRow widget.*/
public class GridRowTag extends CustomTag implements IFormTag, IBodyTag {
private static Logger log = Logger.getLogger(GridRowTag.class);
private static final String TAG_NAME = "GridRowTag";
//----------------------------------------------
//-- TLD Attributes
/** property declaration for tag attribute: rowCssClass.*/
private String m_rowCssClass;
/** property declaration for tag attribute: style.*/
private String m_style;
//----------------------------------------------
private Properties attributes = new Properties();
/** Default constructor. */
public GridRowTag() {
super();
initTag();
}
private void initTag() {
m_rowCssClass = null;
m_style = null;
attributes = new Properties();
}
/** Adds a ColumnHead to the outer GridTag. */
public void otherDoStartTagOperations() throws JspException {
// This will register this row with the grid.
super.otherDoStartTagOperations();
// GridTag should be present
GridTag gridTag = (GridTag) findCustomTagAncestorWithClass(this, GridTag.class);
if (gridTag == null) {
String str = "The " + TAG_NAME + " should be inside a GridTag";
log.error(str);
throw new OuterGridTagMissingRuntimeException(str);
}
}
/** Returns a false
* @return false
*/
public boolean theBodyShouldBeEvaluated() {
return true;
}
public int doAfterBody() throws JspException {
log.debug("entering doafterbody method.");
if (getBodyContent() != null) {
try {
attributes.load(new ByteArrayInputStream(getBodyContent().getString().getBytes()));
// remove possible duplicated attributes
for (Iterator i=attributes.keySet().iterator(); i.hasNext(); ) {
String k = (String) i.next();
if (k.equalsIgnoreCase("style"))
attributes.remove(k);
else if (k.equalsIgnoreCase("rowCssClass"))
attributes.remove(k);
}
log.debug("grid row content = "+attributes.toString());
} catch (IOException ex) {
if (log.isDebugEnabled()) {
log.debug("loading GridRowTag body failed.");
ex.printStackTrace();
}
}
}
return SKIP_BODY;
}
/** Invoked in all cases after doEndTag() for any class implementing Tag, IterationTag or BodyTag. This method is invoked even if an exception has occurred in the BODY of the tag, or in any of the following methods: Tag.doStartTag(), Tag.doEndTag(), IterationTag.doAfterBody() and BodyTag.doInitBody().
* This method is not invoked if the Throwable occurs during one of the setter methods.
* This will reset the internal fields, so that the Tag can be re-used.
*/
public void doFinally() {
super.doFinally();
initTag();
}
//---------------------------------------------------
//-- Start: TLD Attributes
//---------------------------------------------------
/** Setter for the attribute rowCssClass.
* @param value New value of attribute rowCssClass.
*/
public void setRowCssClass(String value) {
if(value!=null && value.trim().length()==0)
value=null;
m_rowCssClass = value;
}
/** Getter for the attribute rowCssClass.
* @return Value of attribute rowCssClass.
*/
public String getRowCssClass() {
return m_rowCssClass;
}
/** Setter for the attribute style.
* @param value New value of attribute style.
*/
public void setStyle(String value) {
if(value!=null && value.trim().length()==0)
value=null;
m_style = value;
}
/** Getter for the attribute style.
* @return Value of attribute style.
*/
public String getStyle() {
return m_style;
}
/** Getter for all other attributes.
* @return a list of attribute name=value pairs in a string
*/
public Properties getAttributes() {
return this.attributes;
}
//---------------------------------------------------
}
| gpl-3.0 |
lukw00/TextSecure | src/org/thoughtcrime/securesms/database/MmsSmsDatabase.java | 14974 | /**
* Copyright (C) 2011 Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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 org.thoughtcrime.securesms.database;
import android.annotation.TargetApi;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.database.model.MessageRecord;
import org.whispersystems.libaxolotl.util.guava.Optional;
import java.util.HashSet;
import java.util.Set;
public class MmsSmsDatabase extends Database {
private static final String TAG = MmsSmsDatabase.class.getSimpleName();
public static final String TRANSPORT = "transport_type";
public static final String MMS_TRANSPORT = "mms";
public static final String SMS_TRANSPORT = "sms";
private static final String[] PROJECTION = {MmsSmsColumns.ID, SmsDatabase.BODY, SmsDatabase.TYPE,
MmsSmsColumns.THREAD_ID,
SmsDatabase.ADDRESS, SmsDatabase.ADDRESS_DEVICE_ID, SmsDatabase.SUBJECT,
MmsSmsColumns.NORMALIZED_DATE_SENT,
MmsSmsColumns.NORMALIZED_DATE_RECEIVED,
MmsDatabase.MESSAGE_TYPE, MmsDatabase.MESSAGE_BOX,
SmsDatabase.STATUS, MmsDatabase.PART_COUNT,
MmsDatabase.CONTENT_LOCATION, MmsDatabase.TRANSACTION_ID,
MmsDatabase.MESSAGE_SIZE, MmsDatabase.EXPIRY,
MmsDatabase.STATUS, MmsSmsColumns.RECEIPT_COUNT,
MmsSmsColumns.MISMATCHED_IDENTITIES,
MmsDatabase.NETWORK_FAILURE, TRANSPORT,
AttachmentDatabase.ATTACHMENT_ID_ALIAS,
AttachmentDatabase.UNIQUE_ID,
AttachmentDatabase.MMS_ID,
AttachmentDatabase.SIZE,
AttachmentDatabase.DATA,
AttachmentDatabase.CONTENT_TYPE,
AttachmentDatabase.CONTENT_LOCATION,
AttachmentDatabase.CONTENT_DISPOSITION,
AttachmentDatabase.NAME,
AttachmentDatabase.TRANSFER_STATE};
public MmsSmsDatabase(Context context, SQLiteOpenHelper databaseHelper) {
super(context, databaseHelper);
}
public Cursor getConversation(long threadId, long limit) {
String order = MmsSmsColumns.NORMALIZED_DATE_RECEIVED + " DESC";
String selection = MmsSmsColumns.THREAD_ID + " = " + threadId;
Cursor cursor = queryTables(PROJECTION, selection, order, limit > 0 ? String.valueOf(limit) : null);
setNotifyConverationListeners(cursor, threadId);
return cursor;
}
public Cursor getConversation(long threadId) {
return getConversation(threadId, 0);
}
public Cursor getIdentityConflictMessagesForThread(long threadId) {
String order = MmsSmsColumns.NORMALIZED_DATE_RECEIVED + " ASC";
String selection = MmsSmsColumns.THREAD_ID + " = " + threadId + " AND " + MmsSmsColumns.MISMATCHED_IDENTITIES + " IS NOT NULL";
Cursor cursor = queryTables(PROJECTION, selection, order, null);
setNotifyConverationListeners(cursor, threadId);
return cursor;
}
public Cursor getConversationSnippet(long threadId) {
String order = MmsSmsColumns.NORMALIZED_DATE_RECEIVED + " DESC";
String selection = MmsSmsColumns.THREAD_ID + " = " + threadId;
return queryTables(PROJECTION, selection, order, "1");
}
public Cursor getUnread() {
String order = MmsSmsColumns.NORMALIZED_DATE_RECEIVED + " ASC";
String selection = MmsSmsColumns.READ + " = 0";
return queryTables(PROJECTION, selection, order, null);
}
public int getConversationCount(long threadId) {
int count = DatabaseFactory.getSmsDatabase(context).getMessageCountForThread(threadId);
count += DatabaseFactory.getMmsDatabase(context).getMessageCountForThread(threadId);
return count;
}
public void incrementDeliveryReceiptCount(String address, long timestamp) {
DatabaseFactory.getSmsDatabase(context).incrementDeliveryReceiptCount(address, timestamp);
DatabaseFactory.getMmsDatabase(context).incrementDeliveryReceiptCount(address, timestamp);
}
private Cursor queryTables(String[] projection, String selection, String order, String limit) {
String[] mmsProjection = {MmsDatabase.DATE_SENT + " AS " + MmsSmsColumns.NORMALIZED_DATE_SENT,
MmsDatabase.DATE_RECEIVED + " AS " + MmsSmsColumns.NORMALIZED_DATE_RECEIVED,
MmsDatabase.TABLE_NAME + "." + MmsDatabase.ID + " AS " + MmsSmsColumns.ID,
AttachmentDatabase.TABLE_NAME + "." + AttachmentDatabase.ROW_ID + " AS " + AttachmentDatabase.ATTACHMENT_ID_ALIAS,
SmsDatabase.BODY, MmsSmsColumns.READ, MmsSmsColumns.THREAD_ID,
SmsDatabase.TYPE, SmsDatabase.ADDRESS, SmsDatabase.ADDRESS_DEVICE_ID, SmsDatabase.SUBJECT, MmsDatabase.MESSAGE_TYPE,
MmsDatabase.MESSAGE_BOX, SmsDatabase.STATUS, MmsDatabase.PART_COUNT,
MmsDatabase.CONTENT_LOCATION, MmsDatabase.TRANSACTION_ID,
MmsDatabase.MESSAGE_SIZE, MmsDatabase.EXPIRY, MmsDatabase.STATUS,
MmsSmsColumns.RECEIPT_COUNT, MmsSmsColumns.MISMATCHED_IDENTITIES,
MmsDatabase.NETWORK_FAILURE, TRANSPORT,
AttachmentDatabase.UNIQUE_ID,
AttachmentDatabase.MMS_ID,
AttachmentDatabase.SIZE,
AttachmentDatabase.DATA,
AttachmentDatabase.CONTENT_TYPE,
AttachmentDatabase.CONTENT_LOCATION,
AttachmentDatabase.CONTENT_DISPOSITION,
AttachmentDatabase.NAME,
AttachmentDatabase.TRANSFER_STATE};
String[] smsProjection = {SmsDatabase.DATE_SENT + " AS " + MmsSmsColumns.NORMALIZED_DATE_SENT,
SmsDatabase.DATE_RECEIVED + " AS " + MmsSmsColumns.NORMALIZED_DATE_RECEIVED,
MmsSmsColumns.ID, "NULL AS " + AttachmentDatabase.ATTACHMENT_ID_ALIAS,
SmsDatabase.BODY, MmsSmsColumns.READ, MmsSmsColumns.THREAD_ID,
SmsDatabase.TYPE, SmsDatabase.ADDRESS, SmsDatabase.ADDRESS_DEVICE_ID, SmsDatabase.SUBJECT, MmsDatabase.MESSAGE_TYPE,
MmsDatabase.MESSAGE_BOX, SmsDatabase.STATUS, MmsDatabase.PART_COUNT,
MmsDatabase.CONTENT_LOCATION, MmsDatabase.TRANSACTION_ID,
MmsDatabase.MESSAGE_SIZE, MmsDatabase.EXPIRY, MmsDatabase.STATUS,
MmsSmsColumns.RECEIPT_COUNT, MmsSmsColumns.MISMATCHED_IDENTITIES,
MmsDatabase.NETWORK_FAILURE, TRANSPORT,
AttachmentDatabase.UNIQUE_ID,
AttachmentDatabase.MMS_ID,
AttachmentDatabase.SIZE,
AttachmentDatabase.DATA,
AttachmentDatabase.CONTENT_TYPE,
AttachmentDatabase.CONTENT_LOCATION,
AttachmentDatabase.CONTENT_DISPOSITION,
AttachmentDatabase.NAME,
AttachmentDatabase.TRANSFER_STATE};
SQLiteQueryBuilder mmsQueryBuilder = new SQLiteQueryBuilder();
SQLiteQueryBuilder smsQueryBuilder = new SQLiteQueryBuilder();
mmsQueryBuilder.setDistinct(true);
smsQueryBuilder.setDistinct(true);
smsQueryBuilder.setTables(SmsDatabase.TABLE_NAME);
mmsQueryBuilder.setTables(MmsDatabase.TABLE_NAME + " LEFT OUTER JOIN " +
AttachmentDatabase.TABLE_NAME +
" ON " + AttachmentDatabase.TABLE_NAME + "." + AttachmentDatabase.ROW_ID + " = " +
" (SELECT " + AttachmentDatabase.TABLE_NAME + "." + AttachmentDatabase.ROW_ID +
" FROM " + AttachmentDatabase.TABLE_NAME + " WHERE " +
AttachmentDatabase.TABLE_NAME + "." + AttachmentDatabase.MMS_ID + " = " +
MmsDatabase.TABLE_NAME + "." + MmsDatabase.ID + " LIMIT 1)");
Set<String> mmsColumnsPresent = new HashSet<>();
mmsColumnsPresent.add(MmsSmsColumns.ID);
mmsColumnsPresent.add(MmsSmsColumns.READ);
mmsColumnsPresent.add(MmsSmsColumns.THREAD_ID);
mmsColumnsPresent.add(MmsSmsColumns.BODY);
mmsColumnsPresent.add(MmsSmsColumns.ADDRESS);
mmsColumnsPresent.add(MmsSmsColumns.ADDRESS_DEVICE_ID);
mmsColumnsPresent.add(MmsSmsColumns.RECEIPT_COUNT);
mmsColumnsPresent.add(MmsSmsColumns.MISMATCHED_IDENTITIES);
mmsColumnsPresent.add(MmsDatabase.MESSAGE_TYPE);
mmsColumnsPresent.add(MmsDatabase.MESSAGE_BOX);
mmsColumnsPresent.add(MmsDatabase.DATE_SENT);
mmsColumnsPresent.add(MmsDatabase.DATE_RECEIVED);
mmsColumnsPresent.add(MmsDatabase.PART_COUNT);
mmsColumnsPresent.add(MmsDatabase.CONTENT_LOCATION);
mmsColumnsPresent.add(MmsDatabase.TRANSACTION_ID);
mmsColumnsPresent.add(MmsDatabase.MESSAGE_SIZE);
mmsColumnsPresent.add(MmsDatabase.EXPIRY);
mmsColumnsPresent.add(MmsDatabase.STATUS);
mmsColumnsPresent.add(MmsDatabase.NETWORK_FAILURE);
mmsColumnsPresent.add(AttachmentDatabase.ROW_ID);
mmsColumnsPresent.add(AttachmentDatabase.UNIQUE_ID);
mmsColumnsPresent.add(AttachmentDatabase.SIZE);
mmsColumnsPresent.add(AttachmentDatabase.CONTENT_TYPE);
mmsColumnsPresent.add(AttachmentDatabase.CONTENT_LOCATION);
mmsColumnsPresent.add(AttachmentDatabase.CONTENT_DISPOSITION);
mmsColumnsPresent.add(AttachmentDatabase.NAME);
mmsColumnsPresent.add(AttachmentDatabase.TRANSFER_STATE);
Set<String> smsColumnsPresent = new HashSet<>();
smsColumnsPresent.add(MmsSmsColumns.ID);
smsColumnsPresent.add(MmsSmsColumns.BODY);
smsColumnsPresent.add(MmsSmsColumns.ADDRESS);
smsColumnsPresent.add(MmsSmsColumns.ADDRESS_DEVICE_ID);
smsColumnsPresent.add(MmsSmsColumns.READ);
smsColumnsPresent.add(MmsSmsColumns.THREAD_ID);
smsColumnsPresent.add(MmsSmsColumns.RECEIPT_COUNT);
smsColumnsPresent.add(MmsSmsColumns.MISMATCHED_IDENTITIES);
smsColumnsPresent.add(SmsDatabase.TYPE);
smsColumnsPresent.add(SmsDatabase.SUBJECT);
smsColumnsPresent.add(SmsDatabase.DATE_SENT);
smsColumnsPresent.add(SmsDatabase.DATE_RECEIVED);
smsColumnsPresent.add(SmsDatabase.STATUS);
String mmsSubQuery = mmsQueryBuilder.buildUnionSubQuery(TRANSPORT, mmsProjection, mmsColumnsPresent, 3, MMS_TRANSPORT, selection, null, null, null);
String smsSubQuery = smsQueryBuilder.buildUnionSubQuery(TRANSPORT, smsProjection, smsColumnsPresent, 3, SMS_TRANSPORT, selection, null, null, null);
SQLiteQueryBuilder unionQueryBuilder = new SQLiteQueryBuilder();
String unionQuery = unionQueryBuilder.buildUnionQuery(new String[] {smsSubQuery, mmsSubQuery}, order, limit);
SQLiteQueryBuilder outerQueryBuilder = new SQLiteQueryBuilder();
outerQueryBuilder.setTables("(" + unionQuery + ")");
String query = outerQueryBuilder.buildQuery(projection, null, null, null, null, null, null);
Log.w("MmsSmsDatabase", "Executing query: " + query);
SQLiteDatabase db = databaseHelper.getReadableDatabase();
return db.rawQuery(query, null);
}
public Reader readerFor(@NonNull Cursor cursor, @Nullable MasterSecret masterSecret) {
return new Reader(cursor, masterSecret);
}
public Reader readerFor(@NonNull Cursor cursor) {
return new Reader(cursor);
}
public class Reader {
private final Cursor cursor;
private final Optional<MasterSecret> masterSecret;
private EncryptingSmsDatabase.Reader smsReader;
private MmsDatabase.Reader mmsReader;
public Reader(Cursor cursor, @Nullable MasterSecret masterSecret) {
this.cursor = cursor;
this.masterSecret = Optional.fromNullable(masterSecret);
}
public Reader(Cursor cursor) {
this(cursor, null);
}
private EncryptingSmsDatabase.Reader getSmsReader() {
if (smsReader == null) {
if (masterSecret.isPresent()) smsReader = DatabaseFactory.getEncryptingSmsDatabase(context).readerFor(masterSecret.get(), cursor);
else smsReader = DatabaseFactory.getSmsDatabase(context).readerFor(cursor);
}
return smsReader;
}
private MmsDatabase.Reader getMmsReader() {
if (mmsReader == null) {
mmsReader = DatabaseFactory.getMmsDatabase(context).readerFor(masterSecret.orNull(), cursor);
}
return mmsReader;
}
public MessageRecord getNext() {
if (cursor == null || !cursor.moveToNext())
return null;
return getCurrent();
}
public MessageRecord getCurrent() {
String type = cursor.getString(cursor.getColumnIndexOrThrow(TRANSPORT));
Log.w("MmsSmsDatabase", "Type: " + type);
if (MmsSmsDatabase.MMS_TRANSPORT.equals(type)) return getMmsReader().getCurrent();
else if (MmsSmsDatabase.SMS_TRANSPORT.equals(type)) return getSmsReader().getCurrent();
else throw new AssertionError("Bad type: " + type);
}
public void close() {
cursor.close();
}
}
}
| gpl-3.0 |
cerberustesting/cerberus-source | source/src/main/java/org/cerberus/crud/dao/IBuildRevisionInvariantDAO.java | 3132 | /**
* Cerberus Copyright (C) 2013 - 2017 cerberustesting
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This file is part of Cerberus.
*
* Cerberus is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Cerberus 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 Cerberus. If not, see <http://www.gnu.org/licenses/>.
*/
package org.cerberus.crud.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import org.cerberus.crud.entity.BuildRevisionInvariant;
import org.cerberus.util.answer.Answer;
import org.cerberus.util.answer.AnswerItem;
import org.cerberus.util.answer.AnswerList;
/**
* {Insert class description here}
*
* @author Tiago Bernardes
* @version 1.0, 31/12/2012
* @since 2.0.0
*/
public interface IBuildRevisionInvariantDAO {
/**
*
* @param system
* @param level
* @param seq
* @return
*/
AnswerItem<BuildRevisionInvariant> readByKey(String system, Integer level, Integer seq);
/**
*
* @param system
* @param level
* @param versionName
* @return
*/
AnswerItem<BuildRevisionInvariant> readByKey(String system, Integer level, String versionName);
/**
*
* @param system
* @param level
* @param start
* @param amount
* @param column
* @param dir
* @param searchTerm
* @param individualSearch
* @return
*/
AnswerList<BuildRevisionInvariant> readByVariousByCriteria(List<String> system, Integer level, int start, int amount, String column, String dir, String searchTerm, Map<String, List<String>> individualSearch);
/**
*
* @param buildRevisionInvariant
* @return
*/
Answer create(BuildRevisionInvariant buildRevisionInvariant);
/**
*
* @param buildRevisionInvariant
* @return
*/
Answer delete(BuildRevisionInvariant buildRevisionInvariant);
/**
*
* @param system
* @param level
* @param seq
* @param buildRevisionInvariant
* @return
*/
Answer update(String system, Integer level, Integer seq, BuildRevisionInvariant buildRevisionInvariant);
/**
*
* @param resultSet
* @return
* @throws SQLException
*/
BuildRevisionInvariant loadFromResultSet(ResultSet resultSet) throws SQLException;
/**
*
* @param system
* @param searchParameter
* @param individualSearch
* @param columnName
* @return
*/
public AnswerList<String> readDistinctValuesByCriteria(List<String> system, String searchParameter, Map<String, List<String>> individualSearch, String columnName);
}
| gpl-3.0 |
lankeren/taolijie | src/main/java/com/fh/taolijie/domain/ImageModel.java | 6236 | package com.fh.taolijie.domain;
public class ImageModel {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column image_resource.id
*
* @mbggenerated
*/
private Integer id;
private Integer jobPostId;
private JobPostModel jobPost;
private Integer shPostId;
private SHPostModel shPost;
private Integer newsId;
private NewsModel news;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column image_resource.file_name
*
* @mbggenerated
*/
private String fileName;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column image_resource.extension
*
* @mbggenerated
*/
private String extension;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column image_resource.type
*
* @mbggenerated
*/
private String type;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column image_resource.member_id
*
* @mbggenerated
*/
private Integer memberId;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column image_resource.bin_data
*
* @mbggenerated
*/
private byte[] binData;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column image_resource.id
*
* @return the value of image_resource.id
*
* @mbggenerated
*/
public Integer getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column image_resource.id
*
* @param id the value for image_resource.id
*
* @mbggenerated
*/
public void setId(Integer id) {
this.id = id;
}
public Integer getJobPostId() {
return jobPostId;
}
public void setJobPostId(Integer jobPostId) {
this.jobPostId = jobPostId;
}
public JobPostModel getJobPost() {
return jobPost;
}
public void setJobPost(JobPostModel jobPost) {
this.jobPost = jobPost;
}
public Integer getShPostId() {
return shPostId;
}
public void setShPostId(Integer shPostId) {
this.shPostId = shPostId;
}
public SHPostModel getShPost() {
return shPost;
}
public void setShPost(SHPostModel shPost) {
this.shPost = shPost;
}
public Integer getNewsId() {
return newsId;
}
public void setNewsId(Integer newsId) {
this.newsId = newsId;
}
public NewsModel getNews() {
return news;
}
public void setNews(NewsModel news) {
this.news = news;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column image_resource.file_name
*
* @return the value of image_resource.file_name
*
* @mbggenerated
*/
public String getFileName() {
return fileName;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column image_resource.file_name
*
* @param fileName the value for image_resource.file_name
*
* @mbggenerated
*/
public void setFileName(String fileName) {
this.fileName = fileName == null ? null : fileName.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column image_resource.extension
*
* @return the value of image_resource.extension
*
* @mbggenerated
*/
public String getExtension() {
return extension;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column image_resource.extension
*
* @param extension the value for image_resource.extension
*
* @mbggenerated
*/
public void setExtension(String extension) {
this.extension = extension == null ? null : extension.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column image_resource.type
*
* @return the value of image_resource.type
*
* @mbggenerated
*/
public String getType() {
return type;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column image_resource.type
*
* @param type the value for image_resource.type
*
* @mbggenerated
*/
public void setType(String type) {
this.type = type == null ? null : type.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column image_resource.member_id
*
* @return the value of image_resource.member_id
*
* @mbggenerated
*/
public Integer getMemberId() {
return memberId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column image_resource.member_id
*
* @param memberId the value for image_resource.member_id
*
* @mbggenerated
*/
public void setMemberId(Integer memberId) {
this.memberId = memberId;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column image_resource.bin_data
*
* @return the value of image_resource.bin_data
*
* @mbggenerated
*/
public byte[] getBinData() {
return binData;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column image_resource.bin_data
*
* @param binData the value for image_resource.bin_data
*
* @mbggenerated
*/
public void setBinData(byte[] binData) {
this.binData = binData;
}
} | gpl-3.0 |
srnsw/xena | plugins/image/ext/src/batik-1.7/sources/org/apache/batik/ext/awt/image/codec/tiff/TIFFTranscoderInternalCodecWriteAdapter.java | 4704 | /*
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.batik.ext.awt.image.codec.tiff;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.PixelInterleavedSampleModel;
import java.awt.image.RenderedImage;
import java.awt.image.SampleModel;
import java.awt.image.SinglePixelPackedSampleModel;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.batik.ext.awt.image.GraphicsUtil;
import org.apache.batik.ext.awt.image.rendered.FormatRed;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.TranscodingHints;
import org.apache.batik.transcoder.image.TIFFTranscoder;
/**
* This class is a helper to <tt>TIFFTranscoder</tt> that writes TIFF images
* through the internal TIFF codec.
*
* @version $Id$
*/
public class TIFFTranscoderInternalCodecWriteAdapter implements
TIFFTranscoder.WriteAdapter {
/**
* @throws TranscoderException
* @see org.apache.batik.transcoder.image.PNGTranscoder.WriteAdapter#writeImage(org.apache.batik.transcoder.image.PNGTranscoder, java.awt.image.BufferedImage, org.apache.batik.transcoder.TranscoderOutput)
*/
public void writeImage(TIFFTranscoder transcoder, BufferedImage img,
TranscoderOutput output) throws TranscoderException {
TranscodingHints hints = transcoder.getTranscodingHints();
TIFFEncodeParam params = new TIFFEncodeParam();
float PixSzMM = transcoder.getUserAgent().getPixelUnitToMillimeter();
// num Pixs in 100 Meters
int numPix = (int)(((1000 * 100) / PixSzMM) + 0.5);
int denom = 100 * 100; // Centimeters per 100 Meters;
long [] rational = {numPix, denom};
TIFFField [] fields = {
new TIFFField(TIFFImageDecoder.TIFF_RESOLUTION_UNIT,
TIFFField.TIFF_SHORT, 1,
new char [] { (char)3 }),
new TIFFField(TIFFImageDecoder.TIFF_X_RESOLUTION,
TIFFField.TIFF_RATIONAL, 1,
new long [][] { rational }),
new TIFFField(TIFFImageDecoder.TIFF_Y_RESOLUTION,
TIFFField.TIFF_RATIONAL, 1,
new long [][] { rational })
};
params.setExtraFields(fields);
if (hints.containsKey(TIFFTranscoder.KEY_COMPRESSION_METHOD)) {
String method = (String)hints.get(TIFFTranscoder.KEY_COMPRESSION_METHOD);
if ("packbits".equals(method)) {
params.setCompression(TIFFEncodeParam.COMPRESSION_PACKBITS);
} else if ("deflate".equals(method)) {
params.setCompression(TIFFEncodeParam.COMPRESSION_DEFLATE);
/* TODO: NPE occurs when used.
} else if ("jpeg".equals(method)) {
params.setCompression(TIFFEncodeParam.COMPRESSION_JPEG_TTN2);
*/
} else {
//nop
}
}
try {
int w = img.getWidth();
int h = img.getHeight();
SinglePixelPackedSampleModel sppsm;
sppsm = (SinglePixelPackedSampleModel)img.getSampleModel();
OutputStream ostream = output.getOutputStream();
TIFFImageEncoder tiffEncoder =
new TIFFImageEncoder(ostream, params);
int bands = sppsm.getNumBands();
int [] off = new int[bands];
for (int i = 0; i < bands; i++)
off[i] = i;
SampleModel sm = new PixelInterleavedSampleModel
(DataBuffer.TYPE_BYTE, w, h, bands, w * bands, off);
RenderedImage rimg = new FormatRed(GraphicsUtil.wrap(img), sm);
tiffEncoder.encode(rimg);
ostream.flush();
} catch (IOException ex) {
throw new TranscoderException(ex);
}
}
}
| gpl-3.0 |
wangyan9110/APDPlat | APDPlat_Core/src/main/java/org/apdplat/module/system/service/backup/SQLServerBackupService.java | 4104 | /**
*
* APDPlat - Application Product Development Platform
* Copyright (c) 2013, 杨尚川, yang-shangchuan@qq.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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 org.apdplat.module.system.service.backup;
import org.apdplat.module.system.service.Lock;
import org.apdplat.module.system.service.PropertyHolder;
import org.apdplat.platform.action.converter.DateTypeConverter;
import org.apdplat.platform.search.IndexManager;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import javax.annotation.Resource;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.stereotype.Service;
/**
* SQLServer备份恢复实现
* @author 杨尚川
*/
@Service("SQL_SERVER")
public class SQLServerBackupService extends BackupService{
@Resource(name="dataSource")
private BasicDataSource dataSource;
@Resource(name="indexManager")
private IndexManager indexManager;
/**
* SQLServer备份数据库实现
* @return
*/
@Override
public boolean backupImpl(){
Connection con = null;
PreparedStatement bps = null;
try {
con = dataSource.getConnection();
String path=getPath()+DateTypeConverter.toFileName(new Date())+".bak";
String bakSQL=PropertyHolder.getProperty("db.backup.sql");
bps=con.prepareStatement(bakSQL);
bps.setString(1,path);
if(!bps.execute()){
return true;
}
return false;
} catch (Exception e) {
LOG.error("备份出错",e);
return false;
}finally{
if(bps!=null){
try {
bps.close();
} catch (SQLException e) {
LOG.error("备份出错",e);
}
}
if(con!=null){
try {
con.close();
} catch (SQLException e) {
LOG.error("备份出错",e);
}
}
}
}
/**
* SQLServer恢复数据库实现
* @return
*/
@Override
public boolean restoreImpl(String date){
Lock.setRestore(true);
Connection con = null;
PreparedStatement rps = null;
try {
con= DriverManager.getConnection(PropertyHolder.getProperty("db.restore.url"),username,password);
String path=getPath()+date+".bak";
String restoreSQL=PropertyHolder.getProperty("db.restore.sql");
rps=con.prepareStatement(restoreSQL);
rps.setString(1,path);
dataSource.close();
if(!rps.execute()){
indexManager.rebuidAll();
return true;
}
else{
return false;
}
} catch (Exception e) {
LOG.error("恢复出错",e);
return false;
} finally{
Lock.setRestore(false);
if(rps!=null){
try {
rps.close();
} catch (SQLException e) {
LOG.error("恢复出错",e);
}
}
if(con!=null){
try {
con.close();
} catch (SQLException e) {
LOG.error("恢复出错",e);
}
}
}
}
} | gpl-3.0 |
MrKickkiller/BuildcraftAdditions2 | src/main/java/buildcraftAdditions/client/gui/gui/GuiBase.java | 5643 | package buildcraftAdditions.client.gui.gui;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.text.WordUtils;
import org.lwjgl.opengl.GL11;
import net.minecraft.client.Minecraft;
import net.minecraft.client.audio.SoundHandler;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.inventory.Container;
import net.minecraft.util.ResourceLocation;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import buildcraftAdditions.client.gui.widgets.WidgetBase;
import buildcraftAdditions.utils.RenderUtils;
import eureka.utils.Utils;
/**
* Copyright (c) 2014, AEnterprise
* http://buildcraftadditions.wordpress.com/
* Buildcraft Additions is distributed under the terms of GNU GPL v3.0
* Please check the contents of the license located in
* http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/
*/
@SideOnly(Side.CLIENT)
public abstract class GuiBase extends GuiContainer {
public static final ResourceLocation PLAYER_INV_TEXTURE = new ResourceLocation("bcadditions:textures/gui/guiPlayerInv.png");
private final ResourceLocation texture;
private boolean drawPlayerInv = false;
public List<WidgetBase> widgets = new ArrayList<WidgetBase>();
public int xSizePlayerInv = 175;
public int ySizePlayerInv = 99;
public int titleXoffset = 5;
public int titleYoffset = 6;
public boolean shouldDrawWidgets = true;
public int textColor = 0x404040;
public boolean centerTitle = false;
public int tileGuiYSize = 0;
public GuiBase(Container container) {
super(container);
texture = texture();
xSize = getXSize();
ySize = getYSize();
tileGuiYSize = getYSize();
}
public GuiBase setDrawPlayerInv(boolean draw) {
drawPlayerInv = draw;
if (draw)
ySize = getYSize() + ySizePlayerInv;
return this;
}
public GuiBase setTitleXOffset(int offset) {
titleXoffset = offset;
return this;
}
public GuiBase setTitleYOffset(int offset) {
titleYoffset = offset;
return this;
}
public GuiBase setTextColor(int color) {
textColor = color;
return this;
}
public GuiBase setCenterTitle(boolean value) {
centerTitle = value;
return this;
}
public GuiBase setDrawWidgets(boolean value) {
shouldDrawWidgets = value;
return this;
}
public abstract ResourceLocation texture();
public abstract int getXSize();
public abstract int getYSize();
public abstract String getInventoryName();
public abstract void initialize();
public SoundHandler soundHandler() {
return Minecraft.getMinecraft().getSoundHandler();
}
public void bindTexture(ResourceLocation texture) {
RenderUtils.bindTexture(texture);
}
public void drawString(String text, int x, int y) {
drawString(text, x, y, textColor);
}
public void drawString(String text, int x, int y, int color) {
fontRendererObj.drawString(text, x, y, color);
}
public void widgetActionPerformed(WidgetBase widget) {
}
public void addWidget(WidgetBase widget) {
widgets.add(widget);
}
@Override
public void initGui() {
super.initGui();
if (drawPlayerInv)
this.guiTop = (this.height - this.ySize) / 2;
initialize();
}
@Override
protected void drawGuiContainerBackgroundLayer(float f, int x, int y) {
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
bindTexture(texture());
drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, tileGuiYSize);
if (drawPlayerInv) {
bindTexture(PLAYER_INV_TEXTURE);
drawTexturedModalRect(guiLeft, guiTop + tileGuiYSize, 0, 0, xSizePlayerInv, ySizePlayerInv);
}
bindTexture(texture());
drawBackgroundPreWidgets(f, x, y);
if (shouldDrawWidgets)
drawWidgets(x, y);
bindTexture(texture());
drawBackgroundPostWidgets(f, x, y);
}
public void drawBackgroundPreWidgets(float f, int x, int y) {
}
public void drawBackgroundPostWidgets(float f, int x, int y) {
}
protected void drawWidgets(int x, int y) {
for (WidgetBase widget : widgets)
widget.render(x, y);
}
@Override
protected void drawGuiContainerForegroundLayer(int x, int y) {
if (drawPlayerInv)
drawString(Utils.localize("container.inventory"), 5, tileGuiYSize + 6, textColor);
String name = Utils.localize(String.format("gui.%s.name", getInventoryName()));
drawString(name, centerTitle ? getXSize() / 2 - (name.length() * 2) : titleXoffset, titleYoffset, textColor);
drawForegroundExtra(x, y);
}
public void drawForegroundExtra(int x, int y) {
}
@Override
public void setWorldAndResolution(Minecraft minecraft, int width, int height) {
widgets.clear();
super.setWorldAndResolution(minecraft, width, height);
}
@Override
protected void mouseClicked(int x, int y, int button) {
super.mouseClicked(x, y, button);
for (WidgetBase widget : widgets) {
if (widget.getBounds().contains(x, y) && widget.enabled)
widget.onWidgetClicked(x, y, button);
}
}
@Override
public void drawScreen(int x, int y, float f) {
super.drawScreen(x, y, f);
List<String> tooltips = new ArrayList<String>();
for (WidgetBase widget : widgets)
if (widget.getBounds().contains(x, y))
widget.addTooltip(x, y, tooltips, isShiftKeyDown());
if (!tooltips.isEmpty()) {
List<String> finalLines = new ArrayList<String>();
for (String line : tooltips) {
String[] lines = WordUtils.wrap(line, 30).split(System.getProperty("line.separator"));
for (String wrappedLine : lines) {
finalLines.add(wrappedLine);
}
}
drawHoveringText(finalLines, x, y, fontRendererObj);
}
}
public void redraw() {
widgets.clear();
buttonList.clear();
initialize();
}
public int guiLeft() {
return guiLeft;
}
public int guiTop() {
return guiTop;
}
}
| gpl-3.0 |
ghedlund/phon | ipa/src/main/java/ca/phon/ipa/relations/MetathesisDetector.java | 1751 | /*
* Copyright (C) 2005-2020 Gregory Hedlund & Yvan Rose
*
* 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 ca.phon.ipa.relations;
import ca.phon.ipa.*;
import ca.phon.ipa.features.*;
import ca.phon.ipa.relations.SegmentalRelation.*;
public class MetathesisDetector extends AbstractSegmentalRelationDetector {
public MetathesisDetector() {
super(Relation.Metathesis, false, true, true);
}
@Override
protected boolean checkRelation(PhoneDimension dimension,
/*out*/ PhoneticProfile profile1, /*out*/ PhoneticProfile profile2,
PhoneticProfile t1Profile, PhoneticProfile t2Profile,
PhoneticProfile a1Profile, PhoneticProfile a2Profile) {
FeatureSet t1Val = t1Profile.getProfile().get(dimension);
FeatureSet t2Val = t2Profile.getProfile().get(dimension);
FeatureSet a1Val = a1Profile.getProfile().get(dimension);
FeatureSet a2Val = a2Profile.getProfile().get(dimension);
boolean isMetathesis = ( (t1Val.size() > 0) && (t2Val.size() > 0) &&
(!t1Val.equals(t2Val)) && (t1Val.equals(a2Val)) && (t2Val.equals(a1Val)) );
if(isMetathesis) {
profile1.put(dimension, t1Profile.getProfile().get(dimension));
profile2.put(dimension, a1Profile.getProfile().get(dimension));
}
return isMetathesis;
}
}
| gpl-3.0 |
autermann/matlab-connector | common/src/main/java/org/n52/matlab/connector/json/MatlabValueSerializer.java | 10553 | /*
* Copyright (C) 2012-2015 by it's authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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 org.n52.matlab.connector.json;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Map.Entry;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import org.n52.matlab.connector.value.MatlabArray;
import org.n52.matlab.connector.value.MatlabBoolean;
import org.n52.matlab.connector.value.MatlabCell;
import org.n52.matlab.connector.value.MatlabDateTime;
import org.n52.matlab.connector.value.MatlabFile;
import org.n52.matlab.connector.value.MatlabMatrix;
import org.n52.matlab.connector.value.MatlabScalar;
import org.n52.matlab.connector.value.MatlabString;
import org.n52.matlab.connector.value.MatlabStruct;
import org.n52.matlab.connector.value.MatlabType;
import org.n52.matlab.connector.value.MatlabValue;
import org.n52.matlab.connector.value.ReturningMatlabValueVisitor;
import com.google.common.io.BaseEncoding;
import com.google.common.io.ByteStreams;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
/**
* {@link MatlabValue} serializer.
*
* @author Richard Jones
*
*/
public class MatlabValueSerializer implements JsonSerializer<MatlabValue>,
JsonDeserializer<MatlabValue> {
@Override
public JsonElement serialize(MatlabValue value, Type type,
JsonSerializationContext ctx) {
if (value == null) {
return new JsonNull();
}
JsonObject object = new JsonObject();
object.addProperty(MatlabJSONConstants.TYPE,
value.getType().toString());
object.add(MatlabJSONConstants.VALUE,
value.accept(new VisitingSerializer(ctx)));
return object;
}
@Override
public MatlabValue deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context)
throws JsonParseException {
return deserializeValue(json);
}
/**
* Deserializes an {@link MatlabValue} from a {@link JsonElement}.
*
* @param element the <code>JsonElement</code> containing a
* serialized <code>MatlabValue</code>
*
* @return the deserialized <code>MatlabValue</code>
*/
public MatlabValue deserializeValue(JsonElement element) {
if (!element.isJsonObject()) {
throw new JsonParseException("expected JSON object");
}
JsonObject json = element.getAsJsonObject();
MatlabType type = getType(json);
JsonElement value = json.get(MatlabJSONConstants.VALUE);
switch (type) {
case ARRAY:
return parseMatlabArray(value);
case BOOLEAN:
return parseMatlabBoolean(value);
case CELL:
return parseMatlabCell(value);
case FILE:
return parseMatlabFile(value);
case MATRIX:
return parseMatlabMatrix(value);
case SCALAR:
return parseMatlabScalar(value);
case STRING:
return parseMatlabString(value);
case STRUCT:
return parseMatlabStruct(value);
case DATE_TIME:
return parseMatlabDateTime(value);
default:
throw new JsonParseException("Unknown type: " + type);
}
}
private MatlabType getType(JsonObject json) throws JsonParseException {
String type = json.get(MatlabJSONConstants.TYPE).getAsString();
try {
return MatlabType.fromString(type);
} catch (IllegalArgumentException e) {
throw new JsonParseException("Unknown type: " + type);
}
}
private MatlabMatrix parseMatlabMatrix(JsonElement value) {
JsonArray array = value.getAsJsonArray();
double[][] values = new double[array.size()][array.get(0)
.getAsJsonArray().size()];
for (int i = 0; i < array.size(); i++) {
JsonArray innerArray = array.get(i).getAsJsonArray();
for (int j = 0; j < innerArray.size(); j++) {
values[i][j] = innerArray.get(j).getAsDouble();
}
}
return new MatlabMatrix(values);
}
private MatlabArray parseMatlabArray(JsonElement value) {
JsonArray array = value.getAsJsonArray();
double[] values = new double[array.size()];
for (int i = 0; i < array.size(); i++) {
values[i] = array.get(i).getAsDouble();
}
return new MatlabArray(values);
}
private MatlabStruct parseMatlabStruct(JsonElement value) {
MatlabStruct struct = new MatlabStruct();
for (Entry<String, JsonElement> e : value.getAsJsonObject().entrySet()) {
struct.set(e.getKey(), deserializeValue(e.getValue()));
}
return struct;
}
private MatlabCell parseMatlabCell(JsonElement value) {
JsonArray array = value.getAsJsonArray();
MatlabValue[] cell = new MatlabValue[array.size()];
for (int i = 0; i < array.size(); i++) {
cell[i] = deserializeValue(array.get(i));
}
return new MatlabCell(cell);
}
private MatlabScalar parseMatlabScalar(JsonElement value) {
JsonPrimitive p = (JsonPrimitive) value;
if (p.isString()) {
return new MatlabScalar(Double.valueOf(p.getAsString()));
} else {
return new MatlabScalar(p.getAsDouble());
}
}
private MatlabBoolean parseMatlabBoolean(JsonElement value) {
return MatlabBoolean.fromBoolean(value.getAsBoolean());
}
private MatlabString parseMatlabString(JsonElement value) {
return new MatlabString(value.getAsString());
}
private MatlabFile parseMatlabFile(JsonElement value) {
return new MatlabFile(gunzip(value.getAsString()));
}
private byte[] gunzip(String value) {
GZIPInputStream in = null;
try {
byte[] gzipped = BaseEncoding.base64().decode(value);
in = new GZIPInputStream(new ByteArrayInputStream(gzipped));
return ByteStreams.toByteArray(in);
} catch (IOException ex) {
throw new RuntimeException(ex);
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
}
}
}
private String gzip(byte[] bytes) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream out = null;
try {
out = new GZIPOutputStream(baos);
out.write(bytes);
out.finish();
return BaseEncoding.base64().encode(baos.toByteArray());
} catch (IOException ex) {
throw new RuntimeException(ex);
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException ex) {
}
}
}
private MatlabDateTime parseMatlabDateTime(JsonElement value) {
DateTime dt = ISODateTimeFormat.dateTime()
.parseDateTime(value.getAsString());
return new MatlabDateTime(dt);
}
private class VisitingSerializer implements
ReturningMatlabValueVisitor<JsonElement> {
private final JsonSerializationContext ctx;
VisitingSerializer(JsonSerializationContext ctx) {
this.ctx = ctx;
}
@Override
public JsonElement visit(MatlabArray array) {
return ctx.serialize(array.value());
}
@Override
public JsonElement visit(MatlabBoolean bool) {
return ctx.serialize(bool.value());
}
@Override
public JsonElement visit(MatlabCell cell) {
return ctx.serialize(cell.value());
}
@Override
public JsonElement visit(MatlabMatrix matrix) {
return ctx.serialize(matrix.value());
}
@Override
public JsonElement visit(MatlabScalar scalar) {
if (Double.isNaN(scalar.value())||
Double.isInfinite(scalar.value())) {
return ctx.serialize(Double.toString(scalar.value()));
} else {
return ctx.serialize(scalar.value());
}
}
@Override
public JsonElement visit(MatlabString string) {
return ctx.serialize(string.value());
}
@Override
public JsonElement visit(MatlabStruct struct) {
JsonObject object = new JsonObject();
for (Entry<MatlabString, MatlabValue> e : struct.value().entrySet()) {
object.add(e.getKey().value(),
serialize(e.getValue(), MatlabValue.class, ctx));
}
return object;
}
@Override
public JsonElement visit(MatlabFile file) {
try {
return ctx.serialize(gzip(file.getContent()));
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
@Override
public JsonElement visit(MatlabDateTime time) {
return ctx.serialize(ISODateTimeFormat.dateTime()
.print(time.value()));
}
}
}
| gpl-3.0 |
chip/rhodes | platform/shared/rubyJVM/src/javolution/lang/ClassInitializer.java | 8345 | /*
* Javolution - Java(TM) Solution for Real-Time and Embedded Systems
* Copyright (C) 2006 - Javolution (http://javolution.org/)
* All rights reserved.
*
* Permission to use, copy, modify, and distribute this software is
* freely granted, provided that this notice is preserved.
*/
package javolution.lang;
import java.util.Enumeration;
import j2me.io.File;
import j2me.util.zip.ZipFile;
import j2me.util.zip.ZipEntry;
import javolution.util.StandardLog;
/**
* <p> This utility class allows for initialization of all classes
* at startup to avoid initialization delays at an innapropriate time.</p>
*
* <p> Note: Users might want to disable logging when initializing run-time
* classes at start-up because of the presence of old classes (never used)
* in the jar files for which initialization fails. For example:[code]
* public static main(String[] args) {
* LogContext.enter(LogContext.NULL); // Temporarely disables logging errors and warnings.
* try {
* ClassInitializer.initializeAll(); // Initializes bootstrap, extensions and classpath classes.
* } finally {
* LogContext.exit(LogContext.NULL); // Goes back to default logging.
* }
* ...
* }[/code]</p>
*
* @author <a href="mailto:jean-marie@dautelle.com">Jean-Marie Dautelle</a>
* @version 3.6, November 6, 2005
*/
public class ClassInitializer {
/**
* Default constructor (private for utility class)
*/
private ClassInitializer() {
}
/**
* Initializes all runtime and classpath classes.
*
* @see #initializeRuntime()
* @see #initializeClassPath()
*/
public static void initializeAll() {
initializeRuntime();
initializeClassPath();
}
/**
* Initializes runtime classes (bootstrap classes in <code>
* System.getProperty("sun.boot.class.path"))</code> and the
* extension <code>.jar</code> in <code>lib/ext</code> directory).
*/
public static void initializeRuntime() {
String bootPath = System.getProperty("sun.boot.class.path");
String pathSeparator = System.getProperty("path.separator");
if ((bootPath == null) || (pathSeparator == null)) {
StandardLog
.warning("Cannot initialize boot path through system properties");
return;
}
initialize(bootPath, pathSeparator);
String javaHome = System.getProperty("java.home");
String fileSeparator = System.getProperty("file.separator");
if ((javaHome == null) || (fileSeparator == null)) {
StandardLog
.warning("Cannot initialize extension library through system properties");
return;
}
File extDir = new File(javaHome + fileSeparator + "lib" + fileSeparator
+ "ext");
if (!extDir.getClass().getName().equals("java.io.File")) {
StandardLog
.warning("Extension classes initialization not supported for J2ME build");
return;
}
if (extDir.isDirectory()) {
File[] files = extDir.listFiles();
for (int i = 0; i < files.length; i++) {
String path = files[i].getPath();
if (path.endsWith(".jar") || path.endsWith(".zip")) {
initializeJar(path);
}
}
} else {
StandardLog.warning(extDir + " is not a directory");
}
}
/**
* Initializes all classes in current classpath.
*/
public static void initializeClassPath() {
String classPath = System.getProperty("java.class.path");
String pathSeparator = System.getProperty("path.separator");
if ((classPath == null) || (pathSeparator == null)) {
StandardLog
.warning("Cannot initialize classpath through system properties");
return;
}
initialize(classPath, pathSeparator);
}
private static void initialize(String classPath, String pathSeparator) {
StandardLog.fine("Initialize classpath: " + classPath);
while (classPath.length() > 0) {
String name;
int index = classPath.indexOf(pathSeparator);
if (index < 0) {
name = classPath;
classPath = "";
} else {
name = classPath.substring(0, index);
classPath = classPath.substring(index + pathSeparator.length());
}
if (name.endsWith(".jar") || name.endsWith(".zip")) {
initializeJar(name);
} else {
initializeDir(name);
}
}
}
/**
* Initializes the specified class.
*
* @param cls the class to initialize.
*/
public static void initialize(Class cls) {
try {
Reflection.getClass(cls.getName());
} catch (Throwable error) {
StandardLog.error(error);
}
}
/**
* Initializes the class with the specified name.
*
* @param className the name of the class to initialize.
*/
public static void initialize(String className) {
try {
Reflection.getClass(className);
} catch (ClassNotFoundException e) {
StandardLog.warning("Class + " + className + " not found");
} catch (Throwable error) {
StandardLog.error(error);
}
}
/**
* Initializes all the classes in the specified jar file.
*
* @param jarName the jar filename.
*/
public static void initializeJar(String jarName) {
try {
StandardLog.fine("Initialize Jar file: " + jarName);
ZipFile jarFile = new ZipFile(jarName);
if (!jarFile.getClass().getName().equals("java.util.zip.ZipFile")) {
StandardLog
.warning("Initialization of classes in jar file not supported for J2ME build");
return;
}
Enumeration e = jarFile.entries();
while (e.hasMoreElements()) {
ZipEntry entry = (ZipEntry) e.nextElement();
String entryName = entry.getName();
if (entryName.endsWith(".class")) {
String className = entryName.substring(0, entryName
.length() - 6);
className = className.replace('/', '.');
StandardLog.finer("Initialize " + className);
ClassInitializer.initialize(className);
}
}
} catch (Exception e) {
StandardLog.error(e);
}
}
/**
* Initializes all the classes in the specified directory.
*
* @param dirName the name of the directory containing the classes to
* initialize.
*/
public static void initializeDir(String dirName) {
StandardLog.fine("Initialize Directory: " + dirName);
File file = new File(dirName);
if (!file.getClass().getName().equals("java.io.File")) {
StandardLog
.warning("Initialization of classes in directory not supported for J2ME build");
return;
}
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
initialize("", files[i]);
}
} else {
StandardLog.warning(dirName + " is not a directory");
}
}
private static void initialize(String prefix, File file) {
String name = file.getName();
if (file.isDirectory()) {
File[] files = file.listFiles();
String newPrefix = (prefix.length() == 0) ? name : prefix + "."
+ name;
for (int i = 0; i < files.length; i++) {
initialize(newPrefix, files[i]);
}
} else {
if (name.endsWith(".class")) {
String className = prefix + "."
+ name.substring(0, name.length() - 6);
StandardLog.finer("Initialize " + className);
ClassInitializer.initialize(className);
}
}
}
}
| gpl-3.0 |
jdrossl/studio2 | src/main/java/org/craftercms/studio/api/v2/dal/AuditLog.java | 4041 | /*
* Copyright (C) 2007-2019 Crafter Software Corporation. All Rights Reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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 org.craftercms.studio.api.v2.dal;
import java.time.ZonedDateTime;
import java.util.List;
public class AuditLog {
private long id;
private long organizationId;
private long siteId;
private String siteName;
private String operation;
private ZonedDateTime operationTimestamp;
private String origin;
private String primaryTargetId;
private String primaryTargetType;
private String primaryTargetSubtype;
private String primaryTargetValue;
private String actorId;
private String actorDetails;
private String clusterNodeId;
private List<AuditLogParamter> parameters;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getOrganizationId() {
return organizationId;
}
public void setOrganizationId(long organizationId) {
this.organizationId = organizationId;
}
public long getSiteId() {
return siteId;
}
public void setSiteId(long siteId) {
this.siteId = siteId;
}
public String getSiteName() {
return siteName;
}
public void setSiteName(String siteName) {
this.siteName = siteName;
}
public String getOperation() {
return operation;
}
public void setOperation(String operation) {
this.operation = operation;
}
public ZonedDateTime getOperationTimestamp() {
return operationTimestamp;
}
public void setOperationTimestamp(ZonedDateTime operationTimestamp) {
this.operationTimestamp = operationTimestamp;
}
public String getOrigin() {
return origin;
}
public void setOrigin(String origin) {
this.origin = origin;
}
public String getPrimaryTargetId() {
return primaryTargetId;
}
public void setPrimaryTargetId(String primaryTargetId) {
this.primaryTargetId = primaryTargetId;
}
public String getPrimaryTargetType() {
return primaryTargetType;
}
public void setPrimaryTargetType(String primaryTargetType) {
this.primaryTargetType = primaryTargetType;
}
public String getPrimaryTargetSubtype() {
return primaryTargetSubtype;
}
public void setPrimaryTargetSubtype(String primaryTargetSubtype) {
this.primaryTargetSubtype = primaryTargetSubtype;
}
public String getPrimaryTargetValue() {
return primaryTargetValue;
}
public void setPrimaryTargetValue(String primaryTargetValue) {
this.primaryTargetValue = primaryTargetValue;
}
public String getActorId() {
return actorId;
}
public void setActorId(String actorId) {
this.actorId = actorId;
}
public String getActorDetails() {
return actorDetails;
}
public void setActorDetails(String actorDetails) {
this.actorDetails = actorDetails;
}
public String getClusterNodeId() {
return clusterNodeId;
}
public void setClusterNodeId(String clusterNodeId) {
this.clusterNodeId = clusterNodeId;
}
public List<AuditLogParamter> getParameters() {
return parameters;
}
public void setParameters(List<AuditLogParamter> parameters) {
this.parameters = parameters;
}
}
| gpl-3.0 |
juergenchrist/smtinterpol | SMTInterpol/src/de/uni_freiburg/informatik/ultimate/smtinterpol/theory/epr/TermTuple.java | 5434 | /*
* Copyright (C) 2016-2017 Alexander Nutz (nutz@informatik.uni-freiburg.de)
* Copyright (C) 2016-2017 University of Freiburg
*
* This file is part of SMTInterpol.
*
* SMTInterpol is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SMTInterpol 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 SMTInterpol. If not, see <http://www.gnu.org/licenses/>.
*/
package de.uni_freiburg.informatik.ultimate.smtinterpol.theory.epr;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Map;
import de.uni_freiburg.informatik.ultimate.logic.ApplicationTerm;
import de.uni_freiburg.informatik.ultimate.logic.Term;
import de.uni_freiburg.informatik.ultimate.logic.TermVariable;
import de.uni_freiburg.informatik.ultimate.smtinterpol.theory.cclosure.CCEquality;
import de.uni_freiburg.informatik.ultimate.util.HashUtils;
/**
*
* @author Alexander Nutz (nutz@informatik.uni-freiburg.de)
*
*/
public class TermTuple {
public final int arity;
public final Term[] terms;
private TermTuple(Term[] terms, int arity) {
this.terms = terms;
this.arity = arity;
}
public TermTuple(Term[] arguments) {
this(arguments, arguments.length);
}
@Override
public boolean equals(Object arg0) {
if (!(arg0 instanceof TermTuple))
return false;
TermTuple other = (TermTuple) arg0;
if (other.arity != this.arity)
return false;
for (int i = 0; i < arity; i++) {
if (!other.terms[i].equals(this.terms[i]))
return false;
}
return true;
}
@Override
public int hashCode() {
// TODO: double-check if this is a good hashing strategy
return HashUtils.hashJenkins(31, (Object[]) terms);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("(");
String comma = "";
for (Term t : terms) {
sb.append(comma + t.toString());
comma = ", ";
}
sb.append(")");
return sb.toString();
}
public TTSubstitution match(TermTuple other,
EqualityManager equalityManager) {
return match(other, new TTSubstitution(), equalityManager);
}
/**
* @param other A TermTuple that may contain variables and constants
* @param newSubs a substitution that constrains the matching of variables
* @return a possibly more constrained substitution that is a unifier, null if there is no unifier
*/
public TTSubstitution match(
TermTuple other,
TTSubstitution subs,
EqualityManager equalityManager) {
assert this.arity == other.arity;
TermTuple thisTT = subs.apply(new TermTuple(terms));
TermTuple otherTT = subs.apply(new TermTuple(other.terms));
TTSubstitution resultSubs = subs; // TODO: or is a copy needed?
for (int i = 0; i < this.terms.length; i++) {
Term thisTerm = thisTT.terms[i];
Term otherTerm = otherTT.terms[i];
TermVariable tvTerm = null;
Term termTerm = null;
if (thisTerm.equals(otherTerm)) {
//match -- > do nothing
continue;
} else if (otherTerm instanceof TermVariable) {
tvTerm = (TermVariable) otherTerm;
termTerm = thisTerm;
} else if (thisTerm instanceof TermVariable) {
tvTerm = (TermVariable) thisTerm;
termTerm = otherTerm;
}
if (tvTerm == null) {
ArrayList<CCEquality> eqPath = equalityManager.isEqual((ApplicationTerm) thisTerm, (ApplicationTerm) otherTerm);
if (eqPath == null){
return null;
}
resultSubs.addEquality(thisTerm, otherTerm, eqPath);
assert false : "TODO: rework/rethink equality handling (now that we switched to CDCL..)";
} else {
resultSubs.addSubs(termTerm, tvTerm);
}
thisTT = resultSubs.apply(thisTT);
otherTT = resultSubs.apply(otherTT);
}
assert resultSubs.apply(this).equals(resultSubs.apply(other))
: "the returned substitution should be a unifier";
return resultSubs;
}
public boolean onlyContainsConstants() {
//TODO cache
boolean result = true;
for (Term t : terms)
result &= t.getFreeVars().length == 0;
return result;
}
public TermTuple applySubstitution(Map<TermVariable, Term> sub) {
Term[] newTerms = new Term[terms.length];
for (int i = 0; i < newTerms.length; i++)
if (terms[i] instanceof TermVariable
&& sub.containsKey(terms[i]))
newTerms[i] = sub.get(terms[i]);
else
newTerms[i] = terms[i];
assert nonNull(newTerms) : "substitution created a null-entry";
return new TermTuple(newTerms);
}
private boolean nonNull(Term[] trms) {
for (Term t : trms)
if (t == null)
return false;
return true;
}
public HashSet<TermVariable> getFreeVars() {
HashSet<TermVariable> result = new HashSet<TermVariable>();
for (Term t : terms)
if (t instanceof TermVariable)
result.add((TermVariable) t);
return result;
}
public HashSet<ApplicationTerm> getConstants() {
HashSet<ApplicationTerm> result = new HashSet<ApplicationTerm>();
for (Term t : terms)
if (t instanceof ApplicationTerm)
result.add((ApplicationTerm) t);
return result;
}
public boolean isGround() {
return getFreeVars().size() == 0;
}
}
| gpl-3.0 |
esaito/ExemplosDemoiselle | fontes_tabeliao/src/gov/pr/celepar/teste/ValidarXMLEnveloping.java | 2967 | package gov.pr.celepar.teste;
/*
Este programa é licenciado de acordo com a
LPG-AP (LICENÇA PÚBLICA GERAL PARA PROGRAMAS DE COMPUTADOR DA ADMINISTRAÇÃO PÚBLICA),
versão 1.1 ou qualquer versão posterior.
A LPG-AP deve acompanhar todas PUBLICAÇÕES, DISTRIBUIÇÕES e REPRODUÇÕES deste Programa.
Caso uma cópia da LPG-AP não esteja disponível junto com este Programa,
você pode contatar o LICENCIANTE ou então acessar diretamente:
http://www.celepar.pr.gov.br/licenca/LPG-AP.pdf
Para poder USAR, PUBLICAR, DISTRIBUIR, REPRODUZIR ou ALTERAR este Programa
é preciso estar de acordo com os termos da LPG-AP
*/
import gov.pr.celepar.tabeliao.core.TabeliaoAssinaturaEnvelopingXML;
import gov.pr.celepar.tabeliao.core.TabeliaoCertificate;
import gov.pr.celepar.tabeliao.core.validacao.TabeliaoResultadoValidacao;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
public class ValidarXMLEnveloping {
final static String DIRETORIO = "/home/esaito/arquivosXML_Assinatura/";
//final static String DIRETORIO = "/home/esaito/arquivosXML_Assinatura/assinadosWeb/";
public static void main(String[] args) {
//String fileName = "192143_ING_assi.xml";
String fileName = "Enveloping_co_eclp_assinado.xml";
//String fileName = "192143_Enveloping_assi.xml";
TabeliaoAssinaturaEnvelopingXML assinaturaEnvelopingXML;
List<TabeliaoResultadoValidacao> resultados = new ArrayList<TabeliaoResultadoValidacao>();
List<TabeliaoCertificate> certificados = new ArrayList<TabeliaoCertificate>();
try {
assinaturaEnvelopingXML = new TabeliaoAssinaturaEnvelopingXML(new FileInputStream(DIRETORIO + fileName));
assinaturaEnvelopingXML.valida();
resultados = assinaturaEnvelopingXML.getResultadosValidacoes();
certificados = assinaturaEnvelopingXML.getCertificadosAssinantes();
//tags = assinaturaEnvelopedXML.getTagsAssinadas();
for(int j=0; j< assinaturaEnvelopingXML.getQuantidadeAssinaturas(); j++){
System.out.println("\n---------------\n");
System.out.println("Assinatura: "+j);
System.out.print("Valida: "+ resultados.get(j).toString());
System.out.println("Nome no Certificado: "+ certificados.get(j).getNome());
System.out.println("Validade De : "+certificados.get(j).getValidadeDe());
System.out.println("Validade Ate : "+certificados.get(j).getValidadeAte());
System.out.println("Data da Assinatura : "+assinaturaEnvelopingXML.getDataAssinatura(j));
// System.out.println("SPRUI : "+assinaturaEnvelopedXML.getSPURI(j));
// System.out.println("SigPolicyId : "+assinaturaEnvelopedXML.getSigPolicyId(j));
// System.out.println("SignaturePolicyIdentifier : "+assinaturaEnvelopedXML.getSignaturePolicyIdentifier(j).item(0).getTextContent());
// System.out.println("SigningCertificate : "+assinaturaEnvelopedXML.getSigningCertificate(j).item(0).getTextContent());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| gpl-3.0 |
dsmryder/android_packages_apps_FileManager | src/com/ghostsq/commander/utils/ForwardCompat.java | 391 | package com.ghostsq.commander.utils;
import java.io.File;
import android.view.View;
public class ForwardCompat
{
public static void disableOverScroll( View view )
{
view.setOverScrollMode( View.OVER_SCROLL_NEVER );
}
public static void setFullPermissions( File file )
{
file.setWritable( true, false );
file.setReadable( true, false );
}
}
| gpl-3.0 |
52North/matlab-connector | common/src/main/java/org/n52/matlab/connector/MatlabException.java | 1460 | /*
* Copyright (C) 2012-2015 by it's authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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 org.n52.matlab.connector;
/**
* Represents an exception returned by MATLAB during function execution.
*
* @author Richard Jones
*
*/
public class MatlabException extends Exception implements MatlabResponse {
private static final long serialVersionUID = 1L;
private long id = -1;
/**
* Creates a new <code>MLException</code> instance with the given message.
*
* @param message the exception message
*/
public MatlabException(String message) {
super(message);
}
public MatlabException(String message, Throwable cause) {
super(message, cause);
}
@Override
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
}
| gpl-3.0 |
bopjesvla/BCI | dataAcq/buffer/android/BufferBCIApp/app/src/main/java/nl/dcc/buffer_bci/monitor/BufferMonitor.java | 10344 | package nl.dcc.buffer_bci.monitor;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.util.SparseArray;
import nl.dcc.buffer_bci.C;
import nl.fcdonders.fieldtrip.bufferserver.FieldtripBufferMonitor;
import java.util.ArrayList;
public class BufferMonitor extends Thread implements FieldtripBufferMonitor {
public static final String TAG = BufferMonitor.class.toString();
private final Context context;
private final SparseArray<BufferConnectionInfo> clients = new SparseArray<BufferConnectionInfo>();
private final BufferInfo info;
private boolean run = true;
private boolean change = false;
public BufferMonitor(final Context context, final String address,
final long startTime) {
this.context = context;
setName("Fieldtrip Buffer Monitor");
info = new BufferInfo(address, startTime);
change = true;
Log.i(TAG, "Created Monitor.");
}
@Override
public void clientClosedConnection(final int clientID, final long time) {
if (clientID != -1) {
final BufferConnectionInfo client = clients.get(clientID);
client.connected = false;
client.timeLastActivity = time;
client.lastActivity = C.DISCONNECTED;
client.changed = true;
client.time = time;
change = true;
}
}
@Override
public void clientContinues(final int clientID, final long time) {
if (clientID != -1) {
final BufferConnectionInfo client = clients.get(clientID);
client.timeLastActivity = time;
client.lastActivity = C.STOPWAITING;
client.waitEvents = -1;
client.waitSamples = -1;
client.waitTimeout = -1;
client.changed = true;
change = true;
}
}
@Override
public void clientError(final int clientID, final int errorType,
final long time) {
if (clientID != -1) {
final BufferConnectionInfo client = clients.get(clientID);
client.timeLastActivity = time;
client.error = errorType;
client.connected = false;
client.changed = true;
client.time = time;
change = true;
}
}
@Override
public void clientFlushedData(final int clientID, final long time) {
if (clientID != -1) {
final BufferConnectionInfo client = clients.get(clientID);
client.timeLastActivity = time;
client.lastActivity = C.FLUSHSAMPLES;
client.changed = true;
}
info.nSamples = 0;
info.changed = true;
change = true;
}
@Override
public void clientFlushedEvents(final int clientID, final long time) {
if (clientID != -1) {
final BufferConnectionInfo client = clients.get(clientID);
client.timeLastActivity = time;
client.lastActivity = C.FLUSHEVENTS;
client.changed = true;
}
info.nEvents = 0;
info.changed = true;
change = true;
}
@Override
public void clientFlushedHeader(final int clientID, final long time) {
if (clientID != -1) {
final BufferConnectionInfo client = clients.get(clientID);
client.timeLastActivity = time;
client.lastActivity = C.FLUSHHEADER;
client.changed = true;
}
info.fSample = -1;
info.nChannels = -1;
info.dataType = -1;
info.changed = true;
change = true;
}
@Override
public void clientGetEvents(final int count, final int clientID,
final long time) {
if (clientID != -1) {
final BufferConnectionInfo client = clients.get(clientID);
client.timeLastActivity = time;
client.lastActivity = C.GOTEVENTS;
client.eventsGotten += count;
client.changed = true;
client.diff = count;
change = true;
}
}
@Override
public void clientGetHeader(final int clientID, final long time) {
if (clientID != -1) {
final BufferConnectionInfo client = clients.get(clientID);
client.timeLastActivity = time;
client.lastActivity = C.GOTHEADER;
client.changed = true;
change = true;
}
}
@Override
public void clientGetSamples(final int count, final int clientID,
final long time) {
if (clientID != -1) {
final BufferConnectionInfo client = clients.get(clientID);
client.timeLastActivity = time;
client.samplesGotten += count;
client.lastActivity = C.GOTSAMPLES;
client.changed = true;
client.diff = count;
change = true;
}
}
@Override
public void clientOpenedConnection(final int clientID, final String address,
final long time) {
if (clientID != -1) {
final BufferConnectionInfo client = new BufferConnectionInfo(address, clientID, time);
clients.put(clientID, client);
Log.i(TAG, "Added Client with id = " + clientID);
change = true;
}
}
@Override
public void clientPolls(final int clientID, final long time) {
if (clientID != -1) {
final BufferConnectionInfo client = clients.get(clientID);
client.timeLastActivity = time;
client.lastActivity = C.POLL;
client.changed = true;
change = true;
}
}
@Override
public void clientPutEvents(final int count, final int clientID,
final int diff, final long time) {
if (clientID != -1) {
final BufferConnectionInfo client = clients.get(clientID);
client.timeLastActivity = time;
client.lastActivity = C.PUTEVENTS;
client.eventsPut += diff;
client.changed = true;
client.diff = diff;
}
info.nEvents = count;
info.changed = true;
change = true;
}
@Override
public void clientPutHeader(final int dataType, final float fSample,
final int nChannels, final int clientID, final long time) {
if (clientID != -1) {
final BufferConnectionInfo client = clients.get(clientID);
client.timeLastActivity = time;
client.lastActivity = C.PUTHEADER;
client.changed = true;
}
info.dataType = dataType;
info.fSample = fSample;
info.nChannels = nChannels;
info.changed = true;
change = true;
}
@Override
public void clientPutSamples(final int count, final int clientID,
final int diff, final long time) {
if (clientID != -1) {
final BufferConnectionInfo client = clients.get(clientID);
client.timeLastActivity = time;
client.lastActivity = C.PUTSAMPLES;
client.samplesPut += diff;
client.diff = diff;
client.changed = true;
}
info.nSamples = count;
info.changed = true;
change = true;
}
@Override
public void clientWaits(final int nSamples, final int nEvents,
final int timeout, final int clientID, final long time) {
if (clientID != -1) {
final BufferConnectionInfo client = clients.get(clientID);
client.timeLastActivity = time;
client.lastActivity = C.WAIT;
client.waitSamples = nSamples;
client.waitEvents = nEvents;
client.waitTimeout = timeout;
client.changed = true;
change = false; // don't send every client wait...
}
}
@Override
public void run() {
while (run) {
try {
Thread.sleep(C.SERVER_INFO_UPDATE_INTERVAL);
} catch (final InterruptedException e) {
Log.e(TAG, "Exception during Thread.sleep(). Very exceptional!");
}
if (change && run) {
sendUpdate();
change = false;
}
}
}
public void sendAllInfo(){ sendUpdate(true); } // force a complete send
private void sendUpdate(){ sendUpdate(false); } // only send if updated
private void sendUpdate(boolean forceSend) {
// send a Broadcast *Implicit* intent, i.e. no component name specified only the action
// This allows other applications to recieve the intent, and also multiple recievers
Intent intent = new Intent();
intent.setAction(C.SEND_UPDATE_INFO_TO_CONTROLLER_ACTION);
intent.putExtra(C.MESSAGE_TYPE, C.UPDATE);
if (info.changed) {
intent.putExtra(C.IS_BUFFER_INFO, true);
intent.putExtra(C.BUFFER_INFO, info);
}
intent = generateConnectionInfoIntent(intent);
if (intent.getBooleanExtra(C.IS_BUFFER_INFO, false) || intent.getBooleanExtra(C.IS_BUFFER_CONNECTION_INFO, false)) {
Log.i(TAG, "Sending Update to Controller");
context.sendOrderedBroadcast(intent, null);
}
}
private Intent generateConnectionInfoIntent(Intent intent) {
final ArrayList<BufferConnectionInfo> clientInfo = new ArrayList<BufferConnectionInfo>();
for (int i = 0; i < clients.size(); i++) {
if (clients.valueAt(i).changed ) {
clientInfo.add(clients.valueAt(i));
}
}
if (clientInfo.size() > 0) {
intent.putExtra(C.IS_BUFFER_CONNECTION_INFO, true);
intent.putExtra(C.BUFFER_CONNECTION_N_INFOS, clientInfo.size());
for (int k = 0; k < clientInfo.size(); ++k) {
intent.putExtra(C.BUFFER_CONNECTION_INFO + k, clientInfo.get(k));
}
Log.i(TAG, "Including " + clientInfo.size() + " Clients Info in update");
}
return intent;
}
public void stopMonitoring() {
run = false;
Log.i(TAG, "BufferMonitor stopped");
}
}
| gpl-3.0 |
ckaestne/LEADT | workspace/argouml_critics/argouml-core-model-mdr/build/java/org/omg/uml/foundation/core/AssociationClassClass.java | 1191 | package org.omg.uml.foundation.core;
/**
* AssociationClass class proxy interface.
*
* <p><em><strong>Note:</strong> This type should not be subclassed or implemented
* by clients. It is generated from a MOF metamodel and automatically implemented
* by MDR (see <a href="http://mdr.netbeans.org/">mdr.netbeans.org</a>).</em></p>
*/
public interface AssociationClassClass extends javax.jmi.reflect.RefClass {
/**
* The default factory operation used to create an instance object.
* @return The created instance object.
*/
public AssociationClass createAssociationClass();
/**
* Creates an instance object having attributes initialized by the passed
* values.
* @param name
* @param visibility
* @param isSpecification
* @param isRoot
* @param isLeaf
* @param isAbstract
* @param isActive
* @return The created instance object.
*/
public AssociationClass createAssociationClass(java.lang.String name, org.omg.uml.foundation.datatypes.VisibilityKind visibility, boolean isSpecification, boolean isRoot, boolean isLeaf, boolean isAbstract, boolean isActive);
}
| gpl-3.0 |
Noterik/lou2 | src/org/springfield/lou/application/Html5AvailableApplicationVersion.java | 5257 | /*
* Html5AvailableApplicationVersion.java
*
* Copyright (c) 2012 Noterik B.V.
*
* This file is part of Lou, related to the Noterik Springfield project.
*
* Lou is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Lou 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 Lou. If not, see <http://www.gnu.org/licenses/>.
*/
package org.springfield.lou.application;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.springfield.lou.homer.LazyHomer;
import org.springfield.mojo.interfaces.ServiceInterface;
import org.springfield.mojo.interfaces.ServiceManager;
/**
* Html5AvailableApplicationVersion
*
* @author Daniel Ockeloen
* @copyright Copyright: Noterik B.V. 2012
* @package org.springfield.lou.application
*
*/
public class Html5AvailableApplicationVersion implements Comparable<Html5AvailableApplicationVersion> {
private static Map<String, String> nodes = new HashMap<String, String>();
private String id;
private Boolean production = false;
private Boolean development = false;
private Html5AvailableApplication app;
public Html5AvailableApplicationVersion(Html5AvailableApplication a) {
app = a;
}
public void setId(String i) {
this.id = i;
}
public String getId() {
return id;
}
public String getStatus() {
if (production && development) {
return "production/development";
} else if (production) {
return "production";
} else if (development) {
return "development";
}
return "";
}
public int getNodeCount() {
return nodes.size();
}
public void addNode(String ipnumber) {
nodes.put(ipnumber, ipnumber); // might have real objects in the future
}
public void loadDevelopmentState(Boolean b) {
development = b;
}
public void setDevelopmentState(Boolean b) {
ServiceInterface smithers = ServiceManager.getService("smithers");
if (smithers==null) return;
System.out.println("SD1");
if (b==development) return; // was already correct state
String basepath = "/domain/internal/service/lou/apps/"+app.getId()+"/development";
if (b==false) {
// want to turn it off need to remove symlink
smithers.delete(basepath,null,null);
//LazyHomer.sendRequestBart("DELETE",basepath,null,null);
} else {
// want to turn it on need to symlink it
String postpath = basepath+"/"+id;
String newpath = "/domain/internal/service/lou/apps/"+app.getId()+"/versions/"+id;
String newbody = "<fsxml><attributes><referid>"+newpath+"</referid></attributes></fsxml>";
System.out.println("SD2a="+smithers.put(postpath+"/attributes",newbody,"text/xml"));
//LazyHomer.sendRequest("PUT",postpath+"/attributes",newbody,"text/xml");
System.out.println("SD2");
}
development = b;
}
public void loadProductionState(Boolean b) {
production = b;
}
public void setProductionState(Boolean b) {
ServiceInterface smithers = ServiceManager.getService("smithers");
if (smithers==null) return;
System.out.println("SP1");
if (b==production) return; // was already correct state
String basepath = "/domain/internal/service/lou/apps/"+app.getId()+"/production";
if (b==false) {
// want to turn it off need to remove symlink
smithers.delete(basepath,null,null);
//LazyHomer.sendRequestBart("DELETE",basepath,null,null);
} else {
// want to turn it on need to symlink it
String postpath = basepath+"/"+id;
String newpath = "/domain/internal/service/lou/apps/"+app.getId()+"/versions/"+id;
String newbody = "<fsxml><attributes><referid>"+newpath+"</referid></attributes></fsxml>";
//LazyHomer.sendRequest("PUT",postpath+"/attributes",newbody,"text/xml");
System.out.println("SP2a="+smithers.put(postpath+"/attributes",newbody,"text/xml"));
System.out.println("SP2");
}
production = b;
}
public Boolean isProductionVersion() {
return production;
}
public Boolean isDevelopmentVersion() {
return development;
}
public int getSyncedAmount() {
// should return the amount of lou's that have this app deployed on sync (not perse production or development)
return 100;
}
public int compareTo(Html5AvailableApplicationVersion v2) {
String nid = id.replace("okt", "Oct");
nid = nid.replace("nov", "Nov");
nid = nid.replace("dec", "Dec");
nid = nid.replace("jan", "Jan");
nid = nid.replace("feb", "Feb");
nid = nid.replace("mar", "Mar");
nid = nid.replace("-", " ");
Date d1= new Date(nid);
Long i1 = new Long(d1.getTime());
nid = v2.getId().replace("okt", "Oct");
nid = nid.replace("nov", "Nov");
nid = nid.replace("dec", "Dec");
nid = nid.replace("jan", "Jan");
nid = nid.replace("feb", "Feb");
nid = nid.replace("mar", "Mar");
nid = nid.replace("-", " ");
Date d2= new Date(nid);
Long i2 = new Long(d2.getTime());
return i2.compareTo(i1);
}
}
| gpl-3.0 |
Garyteck/transdroid | app/src/main/java/org/transdroid/core/gui/settings/NotificationSettingsActivity.java | 3652 | /*
* Copyright 2010-2013 Eric Kok et al.
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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 Transdroid. If not, see <http://www.gnu.org/licenses/>.
*/
package org.transdroid.core.gui.settings;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.OptionsItem;
import org.transdroid.R;
import org.transdroid.core.app.settings.NotificationSettings;
import org.transdroid.core.service.BootReceiver;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceActivity;
@EActivity
public class NotificationSettingsActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
@Bean
protected NotificationSettings notificationSettings;
@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setDisplayHomeAsUpEnabled(true);
// Load the notification-related preferences from XML and update availability thereof
addPreferencesFromResource(R.xml.pref_notifications);
boolean disabled = !notificationSettings.isEnabledForRss() && !notificationSettings.isEnabledForTorrents();
updatePrefsEnabled(disabled);
}
@SuppressWarnings("deprecation")
@Override
protected void onResume() {
super.onResume();
// Start/stop the background service appropriately
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
@SuppressWarnings("deprecation")
@Override
protected void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@OptionsItem(android.R.id.home)
protected void navigateUp() {
MainSettingsActivity_.intent(this).flags(Intent.FLAG_ACTIVITY_CLEAR_TOP).start();
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
boolean disabled = !notificationSettings.isEnabledForRss() && !notificationSettings.isEnabledForTorrents();
updatePrefsEnabled(disabled);
if (disabled ) {
// Disabled all background notifications; disable the alarms that start the service
BootReceiver.cancelBackgroundServices(getApplicationContext());
}
// (Re-)enable the alarms for the background services
// Note that this still respects the user preference
BootReceiver.startBackgroundServices(getApplicationContext(), true);
}
@SuppressWarnings("deprecation")
private void updatePrefsEnabled(boolean disabled) {
findPreference("notifications_interval").setEnabled(!disabled);
findPreference("notifications_sound").setEnabled(!disabled);
findPreference("notifications_vibrate").setEnabled(!disabled);
findPreference("notifications_ledcolour").setEnabled(!disabled);
findPreference("notifications_adwnotify").setEnabled(!disabled);
}
}
| gpl-3.0 |
woolwind/uSkyBlock | uSkyBlock-Core/src/main/java/us/talabrek/ultimateskyblock/handler/AsyncWorldEditHandler.java | 6132 | package us.talabrek.ultimateskyblock.handler;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.bukkit.BukkitUtil;
import com.sk89q.worldedit.bukkit.BukkitWorld;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.regions.Regions;
import com.sk89q.worldedit.world.World;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import us.talabrek.ultimateskyblock.handler.asyncworldedit.AWEAdaptor;
import us.talabrek.ultimateskyblock.handler.task.WEPasteSchematic;
import us.talabrek.ultimateskyblock.player.PlayerPerk;
import us.talabrek.ultimateskyblock.uSkyBlock;
import us.talabrek.ultimateskyblock.util.VersionUtil;
import java.io.File;
import java.util.logging.Level;
import static us.talabrek.ultimateskyblock.util.LogUtil.log;
/**
* Handles integration with AWE.
* Very HACKY and VERY unstable.
*
* Only kept as a cosmetic measure, to at least try to give the players some feedback.
*/
public enum AsyncWorldEditHandler {;
private static AWEAdaptor adaptor = null;
public static void onEnable(uSkyBlock plugin) {
getAWEAdaptor().onEnable(plugin);
}
public static void onDisable(uSkyBlock plugin) {
getAWEAdaptor().onDisable(plugin);
adaptor = null;
}
public static void registerCompletion(Player player) {
getAWEAdaptor().registerCompletion(player);
}
public static EditSession createEditSession(World world, int maxblocks) {
return getAWEAdaptor().createEditSession(world, maxblocks);
}
public static void loadIslandSchematic(File file, Location origin, PlayerPerk playerPerk) {
new WEPasteSchematic(file, origin, playerPerk).runTask(uSkyBlock.getInstance());
}
public static void regenerate(Region region, Runnable onCompletion) {
getAWEAdaptor().regenerate(region, onCompletion);
}
public static AWEAdaptor getAWEAdaptor() {
if (adaptor == null) {
if (!uSkyBlock.getInstance().getConfig().getBoolean("asyncworldedit.enabled", true)) {
return NULL_ADAPTOR;
}
Plugin fawe = getFAWE();
Plugin awe = getAWE();
String className = null;
if (fawe != null) {
VersionUtil.Version version = VersionUtil.getVersion(fawe.getDescription().getVersion());
className = "us.talabrek.ultimateskyblock.handler.asyncworldedit.FAWEAdaptor";
try {
adaptor = (AWEAdaptor) Class.forName(className).<AWEAdaptor>newInstance();
log(Level.INFO, "Hooked into FAWE " + version);
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | NoClassDefFoundError e) {
log(Level.WARNING, "Unable to locate FAWE adaptor for version " + version + ": " + e);
adaptor = NULL_ADAPTOR;
}
} else if (awe != null) {
VersionUtil.Version version = VersionUtil.getVersion(awe.getDescription().getVersion());
if (version.isLT("3.0")) {
className = "us.talabrek.ultimateskyblock.handler.asyncworldedit.AWE211Adaptor";
} else if (version.isLT("3.2.0")) {
className = "us.talabrek.ultimateskyblock.handler.asyncworldedit.AWE311Adaptor";
} else if (version.isLT("3.3.0")) {
className = "us.talabrek.ultimateskyblock.handler.asyncworldedit.AWE321Adaptor";
} else { // Just HOPE to GOD it soon becomes backward compatible...
className = "us.talabrek.ultimateskyblock.handler.asyncworldedit.AWE330Adaptor";
}
try {
adaptor = (AWEAdaptor) Class.forName(className).<AWEAdaptor>newInstance();
log(Level.INFO, "Hooked into AWE " + version);
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | NoClassDefFoundError e) {
log(Level.WARNING, "Unable to locate AWE adaptor for version " + version + ": " + e);
adaptor = NULL_ADAPTOR;
}
} else {
adaptor = NULL_ADAPTOR;
}
}
return adaptor;
}
public static boolean isAWE() {
return getAWEAdaptor() != NULL_ADAPTOR;
}
public static Plugin getFAWE() {
return Bukkit.getPluginManager().getPlugin("FastAsyncWorldEdit");
}
public static Plugin getAWE() {
return Bukkit.getPluginManager().getPlugin("AsyncWorldEdit");
}
public static final AWEAdaptor NULL_ADAPTOR = new AWEAdaptor() {
@Override
public void onEnable(Plugin plugin) {
}
@Override
public void registerCompletion(Player player) {
}
@Override
public void loadIslandSchematic(File file, Location origin, PlayerPerk playerPerk) {
WorldEditHandler.loadIslandSchematic(file, origin, playerPerk);
}
@Override
public void onDisable(Plugin plugin) {
}
@Override
public EditSession createEditSession(World world, int maxBlocks) {
return WorldEditHandler.createEditSession(world, maxBlocks);
}
@Override
public void regenerate(final Region region, final Runnable onCompletion) {
uSkyBlock.getInstance().sync(new Runnable() {
@Override
public void run() {
try {
final EditSession editSession = WorldEditHandler.createEditSession(region.getWorld(), region.getArea() * 255);
editSession.enableQueue();
editSession.setFastMode(true);
editSession.getWorld().regenerate(region, editSession);
editSession.flushQueue();
} finally {
onCompletion.run();
}
}
});
}
};
}
| gpl-3.0 |
confluxtoo/finflux_automation_test | browsermob-proxy/src/main/java/org/browsermob/proxy/jetty/http/SslListener.java | 17697 | // ========================================================================
// $Id: SslListener.java,v 1.8 2006/11/22 20:21:30 gregwilkins Exp $
// Copyright 2000-2004 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========================================================================
//
package org.browsermob.proxy.jetty.http;
import org.apache.commons.logging.Log;
import org.browsermob.proxy.jetty.jetty.servlet.ServletSSL;
import org.browsermob.proxy.jetty.log.LogFactory;
import org.browsermob.proxy.jetty.util.InetAddrPort;
import org.browsermob.proxy.jetty.util.LogSupport;
import org.browsermob.proxy.jetty.util.Password;
import org.browsermob.proxy.jetty.util.Resource;
import javax.net.ssl.*;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.KeyStore;
import java.security.Security;
import java.security.cert.X509Certificate;
// TODO: Auto-generated Javadoc
/* ------------------------------------------------------------ */
/**
* JSSE Socket Listener.
*
* This is heavily based on the work from Court Demas, which in turn is based on
* the work from Forge Research.
*
* @version $Id: SslListener.java,v 1.8 2006/11/22 20:21:30 gregwilkins Exp $
* @author Greg Wilkins (gregw@mortbay.com)
* @author Court Demas (court@kiwiconsulting.com)
* @author Forge Research Pty Ltd ACN 003 491 576
* @author Jan Hlavaty
*/
public class SslListener extends SocketListener {
/** The log. */
private static Log log = LogFactory.getLog(SslListener.class);
/** Default value for the cipher Suites. */
private String cipherSuites[] = null;
/** Default value for the keystore location path. */
public static final String DEFAULT_KEYSTORE = System
.getProperty("user.home") + File.separator + ".keystore";
/** String name of keystore password property. */
public static final String PASSWORD_PROPERTY = "jetty.ssl.password";
/** String name of key password property. */
public static final String KEYPASSWORD_PROPERTY = "jetty.ssl.keypassword";
/**
* The name of the SSLSession attribute that will contain any cached
* information.
*/
static final String CACHED_INFO_ATTR = CachedInfo.class.getName();
/** The _keystore. */
private String _keystore = DEFAULT_KEYSTORE;
/** The _password. */
private transient Password _password;
/** The _keypassword. */
private transient Password _keypassword;
/** The _need client auth. */
private boolean _needClientAuth = false; // Set to true if we require client
// certificate authentication.
/** The _want client auth. */
private boolean _wantClientAuth = false; // Set to true if we would like
// client certificate
// authentication.
/** The _protocol. */
private String _protocol = "TLS";
/** The _algorithm. */
private String _algorithm = (Security
.getProperty("ssl.KeyManagerFactory.algorithm") == null ? "SunX509"
: Security.getProperty("ssl.KeyManagerFactory.algorithm")); // cert
// algorithm
/** The _keystore type. */
private String _keystoreType = "JKS"; // type of the key store
/** The _provider. */
private String _provider = null;
/* ------------------------------------------------------------ */
/**
* Constructor.
*/
public SslListener() {
super();
setDefaultScheme(HttpMessage.__SSL_SCHEME);
}
/* ------------------------------------------------------------ */
/**
* Constructor.
*
* @param p_address
* the p_address
*/
public SslListener(InetAddrPort p_address) {
super(p_address);
if (p_address.getPort() == 0) {
p_address.setPort(443);
setPort(443);
}
setDefaultScheme(HttpMessage.__SSL_SCHEME);
}
/* ------------------------------------------------------------ */
/**
* Gets the cipher suites.
*
* @return the cipher suites
*/
public String[] getCipherSuites() {
return cipherSuites;
}
/* ------------------------------------------------------------ */
/**
* Sets the cipher suites.
*
* @param cipherSuites
* the new cipher suites
* @author Tony Jiang
*/
public void setCipherSuites(String[] cipherSuites) {
this.cipherSuites = cipherSuites;
}
/* ------------------------------------------------------------ */
/**
* Sets the password.
*
* @param password
* the new password
*/
public void setPassword(String password) {
_password = Password.getPassword(PASSWORD_PROPERTY, password, null);
}
/* ------------------------------------------------------------ */
/**
* Sets the key password.
*
* @param password
* the new key password
*/
public void setKeyPassword(String password) {
_keypassword = Password.getPassword(KEYPASSWORD_PROPERTY, password,
null);
}
/* ------------------------------------------------------------ */
/**
* Gets the algorithm.
*
* @return the algorithm
*/
public String getAlgorithm() {
return (this._algorithm);
}
/* ------------------------------------------------------------ */
/**
* Sets the algorithm.
*
* @param algorithm
* the new algorithm
*/
public void setAlgorithm(String algorithm) {
this._algorithm = algorithm;
}
/* ------------------------------------------------------------ */
/**
* Gets the protocol.
*
* @return the protocol
*/
public String getProtocol() {
return _protocol;
}
/* ------------------------------------------------------------ */
/**
* Sets the protocol.
*
* @param protocol
* the new protocol
*/
public void setProtocol(String protocol) {
_protocol = protocol;
}
/* ------------------------------------------------------------ */
/**
* Sets the keystore.
*
* @param keystore
* the new keystore
*/
public void setKeystore(String keystore) {
_keystore = keystore;
}
/* ------------------------------------------------------------ */
/**
* Gets the keystore.
*
* @return the keystore
*/
public String getKeystore() {
return _keystore;
}
/* ------------------------------------------------------------ */
/**
* Gets the keystore type.
*
* @return the keystore type
*/
public String getKeystoreType() {
return (_keystoreType);
}
/* ------------------------------------------------------------ */
/**
* Sets the keystore type.
*
* @param keystoreType
* the new keystore type
*/
public void setKeystoreType(String keystoreType) {
_keystoreType = keystoreType;
}
/* ------------------------------------------------------------ */
/**
* Set the value of the needClientAuth property.
*
* @param needClientAuth
* true iff we require client certificate authentication.
*/
public void setNeedClientAuth(boolean needClientAuth) {
_needClientAuth = needClientAuth;
}
/* ------------------------------------------------------------ */
/**
* Gets the need client auth.
*
* @return the need client auth
*/
public boolean getNeedClientAuth() {
return _needClientAuth;
}
/* ------------------------------------------------------------ */
/**
* Set the value of the needClientAuth property.
*
* @param wantClientAuth
* true iff we would like client certificate authentication.
*/
public void setWantClientAuth(boolean wantClientAuth) {
_wantClientAuth = wantClientAuth;
}
/* ------------------------------------------------------------ */
/**
* Gets the want client auth.
*
* @return the want client auth
*/
public boolean getWantClientAuth() {
return _wantClientAuth;
}
/* ------------------------------------------------------------ */
/**
* By default, we're integral, given we speak SSL. But, if we've been told
* about an integral port, and said port is not our port, then we're not.
* This allows separation of listeners providing INTEGRAL versus
* CONFIDENTIAL constraints, such as one SSL listener configured to require
* client certs providing CONFIDENTIAL, whereas another SSL listener not
* requiring client certs providing mere INTEGRAL constraints.
*
* @param connection
* the connection
* @return true, if is integral
*/
public boolean isIntegral(HttpConnection connection) {
final int integralPort = getIntegralPort();
return integralPort == 0 || integralPort == getPort();
}
/* ------------------------------------------------------------ */
/**
* By default, we're confidential, given we speak SSL. But, if we've been
* told about an confidential port, and said port is not our port, then
* we're not. This allows separation of listeners providing INTEGRAL versus
* CONFIDENTIAL constraints, such as one SSL listener configured to require
* client certs providing CONFIDENTIAL, whereas another SSL listener not
* requiring client certs providing mere INTEGRAL constraints.
*
* @param connection
* the connection
* @return true, if is confidential
*/
public boolean isConfidential(HttpConnection connection) {
final int confidentialPort = getConfidentialPort();
return confidentialPort == 0 || confidentialPort == getPort();
}
/* ------------------------------------------------------------ */
/**
* Creates the factory.
*
* @return the sSL server socket factory
* @throws Exception
* the exception
*/
protected SSLServerSocketFactory createFactory() throws Exception {
SSLContext context;
if (_provider == null) {
context = SSLContext.getInstance(_protocol);
} else {
context = SSLContext.getInstance(_protocol, _provider);
}
KeyManagerFactory keyManagerFactory = KeyManagerFactory
.getInstance(_algorithm);
KeyStore keyStore = KeyStore.getInstance(_keystoreType);
keyStore.load(Resource.newResource(_keystore).getInputStream(),
_password.toString().toCharArray());
keyManagerFactory.init(keyStore, _keypassword.toString().toCharArray());
context.init(keyManagerFactory.getKeyManagers(), null,
new java.security.SecureRandom());
return context.getServerSocketFactory();
}
/* ------------------------------------------------------------ */
/**
* New server socket.
*
* @param p_address
* the p_address
* @param p_acceptQueueSize
* the p_accept queue size
* @return @exception IOException
* @throws IOException
* Signals that an I/O exception has occurred.
*/
protected ServerSocket newServerSocket(InetAddrPort p_address,
int p_acceptQueueSize) throws IOException {
SSLServerSocketFactory factory = null;
SSLServerSocket socket = null;
try {
factory = createFactory();
if (p_address == null) {
socket = (SSLServerSocket) factory.createServerSocket(0,
p_acceptQueueSize);
} else {
socket = (SSLServerSocket) factory.createServerSocket(
p_address.getPort(), p_acceptQueueSize,
p_address.getInetAddress());
}
if (_needClientAuth)
socket.setNeedClientAuth(true);
else if (_wantClientAuth)
socket.setWantClientAuth(true);
if (cipherSuites != null && cipherSuites.length > 0) {
socket.setEnabledCipherSuites(cipherSuites);
for (int i = 0; i < cipherSuites.length; i++) {
log.debug("SslListener enabled ciphersuite: "
+ cipherSuites[i]);
}
}
} catch (IOException e) {
throw e;
} catch (Exception e) {
log.warn(LogSupport.EXCEPTION, e);
throw new IOException("Could not create JsseListener: "
+ e.toString());
}
return socket;
}
/* ------------------------------------------------------------ */
/**
* Accept.
*
* @param p_serverSocket
* the p_server socket
* @return @exception IOException
* @throws IOException
* Signals that an I/O exception has occurred.
*/
protected Socket accept(ServerSocket p_serverSocket) throws IOException {
try {
SSLSocket s = (SSLSocket) p_serverSocket.accept();
if (getMaxIdleTimeMs() > 0)
s.setSoTimeout(getMaxIdleTimeMs());
s.startHandshake(); // block until SSL handshaking is done
return s;
} catch (SSLException e) {
log.warn(LogSupport.EXCEPTION, e);
throw new IOException(e.getMessage());
}
}
/* ------------------------------------------------------------ */
/**
* Allow the Listener a chance to customise the request. before the server
* does its stuff. <br>
* This allows the required attributes to be set for SSL requests. <br>
* The requirements of the Servlet specs are:
* <ul>
* <li>an attribute named "javax.servlet.request.cipher_suite" of type
* String.</li>
* <li>an attribute named "javax.servlet.request.key_size" of type Integer.</li>
* <li>an attribute named "javax.servlet.request.X509Certificate" of type
* java.security.cert.X509Certificate[]. This is an array of objects of type
* X509Certificate, the order of this array is defined as being in ascending
* order of trust. The first certificate in the chain is the one set by the
* client, the next is the one used to authenticate the first, and so on.</li>
* </ul>
*
* @param socket
* The Socket the request arrived on. This should be a
* javax.net.ssl.SSLSocket.
* @param request
* HttpRequest to be customised.
*/
protected void customizeRequest(Socket socket, HttpRequest request) {
super.customizeRequest(socket, request);
if (!(socket instanceof javax.net.ssl.SSLSocket))
return; // I'm tempted to let it throw an
// exception...
try {
SSLSocket sslSocket = (SSLSocket) socket;
SSLSession sslSession = sslSocket.getSession();
String cipherSuite = sslSession.getCipherSuite();
Integer keySize;
X509Certificate[] certs;
CachedInfo cachedInfo = (CachedInfo) sslSession
.getValue(CACHED_INFO_ATTR);
if (cachedInfo != null) {
keySize = cachedInfo.getKeySize();
certs = cachedInfo.getCerts();
} else {
keySize = new Integer(ServletSSL.deduceKeyLength(cipherSuite));
certs = getCertChain(sslSession);
cachedInfo = new CachedInfo(keySize, certs);
sslSession.putValue(CACHED_INFO_ATTR, cachedInfo);
}
if (certs != null)
request.setAttribute("javax.servlet.request.X509Certificate",
certs);
else if (_needClientAuth) // Sanity check
throw new HttpException(HttpResponse.__403_Forbidden);
request.setAttribute("javax.servlet.request.cipher_suite",
cipherSuite);
request.setAttribute("javax.servlet.request.key_size", keySize);
} catch (Exception e) {
log.warn(LogSupport.EXCEPTION, e);
}
}
/**
* Return the chain of X509 certificates used to negotiate the SSL Session.
* <p>
* Note: in order to do this we must convert a
* javax.security.cert.X509Certificate[], as used by JSSE to a
* java.security.cert.X509Certificate[],as required by the Servlet specs.
*
* @param sslSession
* the javax.net.ssl.SSLSession to use as the source of the cert
* chain.
* @return the chain of java.security.cert.X509Certificates used to
* negotiate the SSL connection. <br>
* Will be null if the chain is missing or empty.
*/
private static X509Certificate[] getCertChain(SSLSession sslSession) {
try {
javax.security.cert.X509Certificate javaxCerts[] = sslSession
.getPeerCertificateChain();
if (javaxCerts == null || javaxCerts.length == 0)
return null;
int length = javaxCerts.length;
X509Certificate[] javaCerts = new X509Certificate[length];
java.security.cert.CertificateFactory cf = java.security.cert.CertificateFactory
.getInstance("X.509");
for (int i = 0; i < length; i++) {
byte bytes[] = javaxCerts[i].getEncoded();
ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
javaCerts[i] = (X509Certificate) cf.generateCertificate(stream);
}
return javaCerts;
} catch (SSLPeerUnverifiedException pue) {
return null;
} catch (Exception e) {
log.warn(LogSupport.EXCEPTION, e);
return null;
}
}
/**
* Simple bundle of information that is cached in the SSLSession. Stores the
* effective keySize and the client certificate chain.
*/
private class CachedInfo {
/** The _key size. */
private Integer _keySize;
/** The _certs. */
private X509Certificate[] _certs;
/**
* Instantiates a new cached info.
*
* @param keySize
* the key size
* @param certs
* the certs
*/
CachedInfo(Integer keySize, X509Certificate[] certs) {
this._keySize = keySize;
this._certs = certs;
}
/**
* Gets the key size.
*
* @return the key size
*/
Integer getKeySize() {
return _keySize;
}
/**
* Gets the certs.
*
* @return the certs
*/
X509Certificate[] getCerts() {
return _certs;
}
}
/**
* Gets the provider.
*
* @return the provider
*/
public String getProvider() {
return _provider;
}
/**
* Sets the provider.
*
* @param _provider
* the new provider
*/
public void setProvider(String _provider) {
this._provider = _provider;
}
}
| mpl-2.0 |
servinglynk/hmis-lynk-open-source | hmis-serialize-v2014/src/main/java/com/servinglynk/hmis/warehouse/core/model/Project.java | 2665 | package com.servinglynk.hmis.warehouse.core.model;
import java.util.UUID;
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("project")
public class Project extends ClientModel {
private UUID projectId;
private UUID organizationId;
private String projectName;
private String projectCommonName;
private Integer continuumProject;
private Integer projectType;
private Integer residentialAffiliation;
private Integer targetPopulation;
private Integer trackingMethod;
private String projectGroup;
private String source;
private String sourceSystemId;
public Project() {
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public Project(UUID projectId) {
this.projectId = projectId;
}
public UUID getProjectId() {
return projectId;
}
public void setProjectId(UUID projectId) {
this.projectId = projectId;
}
public String getProjectCommonName() {
return projectCommonName;
}
public void setProjectCommonName(String projectCommonName) {
this.projectCommonName = projectCommonName;
}
public Integer getContinuumProject() {
return continuumProject;
}
public void setContinuumProject(Integer continuumProject) {
this.continuumProject = continuumProject;
}
public Integer getProjectType() {
return projectType;
}
public void setProjectType(Integer projectType) {
this.projectType = projectType;
}
public Integer getResidentialAffiliation() {
return residentialAffiliation;
}
public void setResidentialAffiliation(Integer residentialAffiliation) {
this.residentialAffiliation = residentialAffiliation;
}
public Integer getTargetPopulation() {
return targetPopulation;
}
public void setTargetPopulation(Integer targetPopulation) {
this.targetPopulation = targetPopulation;
}
public Integer getTrackingMethod() {
return trackingMethod;
}
public void setTrackingMethod(Integer trackingMethod) {
this.trackingMethod = trackingMethod;
}
public String getProjectGroup() {
return projectGroup;
}
public void setProjectGroup(String projectGroup) {
this.projectGroup = projectGroup;
}
public UUID getOrganizationId() {
return organizationId;
}
public void setOrganizationId(UUID organizationId) {
this.organizationId = organizationId;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getSourceSystemId() {
return sourceSystemId;
}
public void setSourceSystemId(String sourceSystemId) {
this.sourceSystemId = sourceSystemId;
}
} | mpl-2.0 |
TiWinDeTea/Raoul-the-Game | src/main/java/com/github/tiwindetea/raoulthegame/events/gui/requests/CastSpellRequestEvent.java | 1456 | //////////////////////////////////////////////////////////////////////////////////
// //
// This Source Code Form is subject to the terms of the Mozilla Public //
// License, v. 2.0. If a copy of the MPL was not distributed with this //
// file, You can obtain one at http://mozilla.org/MPL/2.0/. //
// //
//////////////////////////////////////////////////////////////////////////////////
package com.github.tiwindetea.raoulthegame.events.gui.requests;
/**
* The type CastSpellRequestEvent.
*/
public class CastSpellRequestEvent extends RequestEvent {
private int playerNumber;
private int spellNumber;
/**
* Instantiates a new CastSpellRequestEvent.
*
* @param playerNumber the player number
* @param spellNumber the spell number
*/
public CastSpellRequestEvent(int playerNumber, int spellNumber) {
this.playerNumber = playerNumber;
this.spellNumber = spellNumber;
}
@Override
public RequestEventType getSubType() {
return RequestEventType.CAST_SPELL_REQUEST_EVENT;
}
/**
* Gets player number.
*
* @return the player number
*/
public int getPlayerNumber() {
return this.playerNumber;
}
/**
* Gets spell number.
*
* @return the spell number
*/
public int getSpellNumber() {
return this.spellNumber;
}
}
| mpl-2.0 |
rapidminer/rapidminer-5 | src/com/rapidminer/operator/ports/metadata/CollectionPrecondition.java | 2152 | /*
* RapidMiner
*
* Copyright (C) 2001-2014 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.operator.ports.metadata;
/** This precondition checks whether the delivered object is of a given type
* or a collection of the given type (or a collection of such collections etc.).
*
* @author Simon Fischer
*
*/
public class CollectionPrecondition implements Precondition {
private final Precondition nestedPrecondition;
public CollectionPrecondition(Precondition precondition) {
this.nestedPrecondition = precondition;
}
@Override
public void assumeSatisfied() {
nestedPrecondition.assumeSatisfied();
}
@Override
public void check(MetaData md) {
if (md != null) {
if (md instanceof CollectionMetaData) {
check(((CollectionMetaData)md).getElementMetaData());
return;
}
}
nestedPrecondition.check(md);
}
@Override
public String getDescription() {
return nestedPrecondition + " (collection)";
}
@Override
public boolean isCompatible(MetaData input, CompatibilityLevel level) {
if (input instanceof CollectionMetaData) {
return isCompatible(((CollectionMetaData)input).getElementMetaData(), level);
} else {
return nestedPrecondition.isCompatible(input, level);
}
}
@Override
public MetaData getExpectedMetaData() {
return new CollectionMetaData(nestedPrecondition.getExpectedMetaData());
}
}
| agpl-3.0 |
aatxe/Orpheus | src/scripting/npc/NPCConversationManager.java | 19360 | /*
OrpheusMS: MapleStory Private Server based on OdinMS
Copyright (C) 2012 Aaron Weiss <aaron@deviant-core.net>
Patrick Huy <patrick.huy@frz.cc>
Matthias Butz <matze@odinms.de>
Jan Christian Meyer <vimes@odinms.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package scripting.npc;
import client.Equip;
import client.IItem;
import client.ISkill;
import client.ItemFactory;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import constants.ExpTable;
import constants.ServerConstants;
import client.MapleCharacter;
import client.MapleClient;
import client.MapleInventory;
import client.MapleInventoryType;
import client.MapleJob;
import client.MaplePet;
import client.MapleSkinColor;
import client.MapleStat;
import client.SkillFactory;
import tools.Randomizer;
import java.io.File;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
import net.server.Channel;
import tools.DatabaseConnection;
import net.server.MapleParty;
import net.server.MaplePartyCharacter;
import net.server.Server;
import net.server.guild.MapleAlliance;
import net.server.guild.MapleGuild;
import provider.MapleData;
import provider.MapleDataProviderFactory;
import scripting.AbstractPlayerInteraction;
import server.MapleInventoryManipulator;
import server.MapleItemInformationProvider;
import server.MapleShopFactory;
import server.MapleStatEffect;
import server.events.gm.MapleEvent;
import server.expeditions.MapleExpedition;
import server.maps.MapleMap;
import server.maps.MapleMapFactory;
import server.partyquest.Pyramid;
import server.partyquest.Pyramid.PyramidMode;
import server.quest.MapleQuest;
import tools.MaplePacketCreator;
/**
*
* @author Matze
*/
public class NPCConversationManager extends AbstractPlayerInteraction {
private int npc;
private String getText;
public NPCConversationManager(MapleClient c, int npc) {
super(c);
this.npc = npc;
}
public int getNpc() {
return npc;
}
public void dispose() {
NPCScriptManager.getInstance().dispose(this);
}
public void sendNext(String text) {
getClient().announce(MaplePacketCreator.getNPCTalk(npc, (byte) 0, text, "00 01", (byte) 0));
}
public void sendPrev(String text) {
getClient().announce(MaplePacketCreator.getNPCTalk(npc, (byte) 0, text, "01 00", (byte) 0));
}
public void sendNextPrev(String text) {
getClient().announce(MaplePacketCreator.getNPCTalk(npc, (byte) 0, text, "01 01", (byte) 0));
}
public void sendOk(String text) {
getClient().announce(MaplePacketCreator.getNPCTalk(npc, (byte) 0, text, "00 00", (byte) 0));
}
public void sendYesNo(String text) {
getClient().announce(MaplePacketCreator.getNPCTalk(npc, (byte) 1, text, "", (byte) 0));
}
public void sendAcceptDecline(String text) {
getClient().announce(MaplePacketCreator.getNPCTalk(npc, (byte) 0x0C, text, "", (byte) 0));
}
public void sendSimple(String text) {
getClient().announce(MaplePacketCreator.getNPCTalk(npc, (byte) 4, text, "", (byte) 0));
}
public void sendNext(String text, byte speaker) {
getClient().announce(MaplePacketCreator.getNPCTalk(npc, (byte) 0, text, "00 01", speaker));
}
public void sendPrev(String text, byte speaker) {
getClient().announce(MaplePacketCreator.getNPCTalk(npc, (byte) 0, text, "01 00", speaker));
}
public void sendNextPrev(String text, byte speaker) {
getClient().announce(MaplePacketCreator.getNPCTalk(npc, (byte) 0, text, "01 01", speaker));
}
public void sendOk(String text, byte speaker) {
getClient().announce(MaplePacketCreator.getNPCTalk(npc, (byte) 0, text, "00 00", speaker));
}
public void sendYesNo(String text, byte speaker) {
getClient().announce(MaplePacketCreator.getNPCTalk(npc, (byte) 1, text, "", speaker));
}
public void sendAcceptDecline(String text, byte speaker) {
getClient().announce(MaplePacketCreator.getNPCTalk(npc, (byte) 0x0C, text, "", speaker));
}
public void sendSimple(String text, byte speaker) {
getClient().announce(MaplePacketCreator.getNPCTalk(npc, (byte) 4, text, "", speaker));
}
public void sendStyle(String text, int styles[]) {
getClient().announce(MaplePacketCreator.getNPCTalkStyle(npc, text, styles));
}
public void sendGetNumber(String text, int def, int min, int max) {
getClient().announce(MaplePacketCreator.getNPCTalkNum(npc, text, def, min, max));
}
public void sendGetText(String text) {
getClient().announce(MaplePacketCreator.getNPCTalkText(npc, text, ""));
}
/*
* 0 = ariant colliseum 1 = Dojo 2 = Carnival 1 3 = Carnival 2 4 = Ghost
* Ship PQ? 5 = Pyramid PQ 6 = Kerning Subway
*/
public void sendDimensionalMirror(String text) {
getClient().announce(MaplePacketCreator.getDimensionalMirror(text));
}
public void setGetText(String text) {
this.getText = text;
}
public String getText() {
return this.getText;
}
public int getJobId() {
return getPlayer().getJob().getId();
}
public void startQuest(short id) {
try {
MapleQuest.getInstance(id).forceStart(getPlayer(), npc);
} catch (NullPointerException ex) {
}
}
public void completeQuest(short id) {
try {
MapleQuest.getInstance(id).forceComplete(getPlayer(), npc);
} catch (NullPointerException ex) {
}
}
public int getMeso() {
return getPlayer().getMeso();
}
public void gainMeso(int gain) {
getPlayer().gainMeso(gain, true, false, true);
}
public void gainExp(int gain) {
getPlayer().gainExp(gain, true, true);
}
public int getLevel() {
return getPlayer().getLevel();
}
public void showEffect(String effect) {
getPlayer().getMap().broadcastMessage(MaplePacketCreator.environmentChange(effect, 3));
}
public void playSound(String sound) {
getPlayer().getMap().broadcastMessage(MaplePacketCreator.environmentChange(sound, 4));
}
public void setHair(int hair) {
getPlayer().setHair(hair);
getPlayer().updateSingleStat(MapleStat.HAIR, hair);
getPlayer().equipChanged();
}
public void setFace(int face) {
getPlayer().setFace(face);
getPlayer().updateSingleStat(MapleStat.FACE, face);
getPlayer().equipChanged();
}
public void setSkin(int color) {
getPlayer().setSkinColor(MapleSkinColor.getById(color));
getPlayer().updateSingleStat(MapleStat.SKIN, color);
getPlayer().equipChanged();
}
public int itemQuantity(int itemid) {
return getPlayer().getInventory(MapleItemInformationProvider.getInstance().getInventoryType(itemid)).countById(itemid);
}
public void displayGuildRanks() {
MapleGuild.displayGuildRanks(getClient(), npc);
}
@Override
public MapleParty getParty() {
return getPlayer().getParty();
}
@Override
public void resetMap(int mapid) {
getClient().getChannelServer().getMapFactory().getMap(mapid).resetReactors();
}
public void gainCloseness(int closeness) {
for (MaplePet pet : getPlayer().getPets()) {
if (pet.getCloseness() > 30000) {
pet.setCloseness(30000);
return;
}
pet.gainCloseness(closeness);
while (pet.getCloseness() > ExpTable.getClosenessNeededForLevel(pet.getLevel())) {
pet.setLevel((byte) (pet.getLevel() + 1));
byte index = getPlayer().getPetIndex(pet);
getClient().announce(MaplePacketCreator.showOwnPetLevelUp(index));
getPlayer().getMap().broadcastMessage(getPlayer(), MaplePacketCreator.showPetLevelUp(getPlayer(), index));
}
IItem petz = getPlayer().getInventory(MapleInventoryType.CASH).getItem(pet.getPosition());
getPlayer().getClient().announce(MaplePacketCreator.updateSlot(petz));
}
}
public String getName() {
return getPlayer().getName();
}
public int getGender() {
return getPlayer().getGender();
}
public void changeJobById(int a) {
getPlayer().changeJob(MapleJob.getById(a));
}
public void addRandomItem(int id) {
MapleItemInformationProvider i = MapleItemInformationProvider.getInstance();
MapleInventoryManipulator.addFromDrop(getClient(), i.randomizeStats((Equip) i.getEquipById(id)), true);
}
public MapleJob getJobName(int id) {
return MapleJob.getById(id);
}
public MapleStatEffect getItemEffect(int itemId) {
return MapleItemInformationProvider.getInstance().getItemEffect(itemId);
}
public void resetStats() {
getPlayer().resetStats();
}
public void maxMastery() {
for (MapleData skill_ : MapleDataProviderFactory.getDataProvider(new File(System.getProperty("wzpath") + "/" + "String.wz")).getData("Skill.img").getChildren()) {
try {
ISkill skill = SkillFactory.getSkill(Integer.parseInt(skill_.getName()));
getPlayer().changeSkillLevel(skill, (byte) skill.getMaxLevel(), skill.getMaxLevel(), -1);
} catch (NumberFormatException nfe) {
break;
} catch (NullPointerException npe) {
continue;
}
}
}
public void processGachapon(int[] id, boolean remote) {
int[] gacMap = {100000000, 101000000, 102000000, 103000000, 105040300, 800000000, 809000101, 809000201, 600000000, 120000000};
int itemid = id[Randomizer.nextInt(id.length)];
addRandomItem(itemid);
if (!remote) {
gainItem(5220000, (short) -1);
}
sendNext("You have obtained a #b#t" + itemid + "##k.");
if (ServerConstants.BROADCAST_GACHAPON_ITEMS) {
getClient().getChannelServer().broadcastPacket(MaplePacketCreator.gachaponMessage(getPlayer().getInventory(MapleInventoryType.getByType((byte) (itemid / 1000000))).findById(itemid), c.getChannelServer().getMapFactory().getMap(gacMap[(getNpc() != 9100117 && getNpc() != 9100109) ? (getNpc() - 9100100) : getNpc() == 9100109 ? 8 : 9]).getMapName(), getPlayer()));
}
}
public void disbandAlliance(MapleClient c, int allianceId) {
PreparedStatement ps = null;
try {
ps = DatabaseConnection.getConnection().prepareStatement("DELETE FROM `alliance` WHERE id = ?");
ps.setInt(1, allianceId);
ps.executeUpdate();
ps.close();
Server.getInstance().allianceMessage(c.getPlayer().getGuild().getAllianceId(), MaplePacketCreator.disbandAlliance(allianceId), -1, -1);
Server.getInstance().disbandAlliance(allianceId);
} catch (SQLException sqle) {
sqle.printStackTrace();
} finally {
try {
if (ps != null && !ps.isClosed()) {
ps.close();
}
} catch (SQLException ex) {
}
}
}
public boolean canBeUsedAllianceName(String name) {
if (name.contains(" ") || name.length() > 12) {
return false;
}
try {
PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("SELECT name FROM alliance WHERE name = ?");
ps.setString(1, name);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
ps.close();
rs.close();
return false;
}
ps.close();
rs.close();
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
public static MapleAlliance createAlliance(MapleCharacter chr1, MapleCharacter chr2, String name) {
int id = 0;
int guild1 = chr1.getGuildId();
int guild2 = chr2.getGuildId();
try {
PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("INSERT INTO `alliance` (`name`, `guild1`, `guild2`) VALUES (?, ?, ?)", PreparedStatement.RETURN_GENERATED_KEYS);
ps.setString(1, name);
ps.setInt(2, guild1);
ps.setInt(3, guild2);
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
rs.next();
id = rs.getInt(1);
rs.close();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
return null;
}
MapleAlliance alliance = new MapleAlliance(name, id, guild1, guild2);
try {
Server.getInstance().setGuildAllianceId(guild1, id);
Server.getInstance().setGuildAllianceId(guild2, id);
chr1.setAllianceRank(1);
chr1.saveGuildStatus();
chr2.setAllianceRank(2);
chr2.saveGuildStatus();
Server.getInstance().addAlliance(id, alliance);
Server.getInstance().allianceMessage(id, MaplePacketCreator.makeNewAlliance(alliance, chr1.getClient()), -1, -1);
} catch (Exception e) {
return null;
}
return alliance;
}
public List<MapleCharacter> getPartyMembers() {
if (getPlayer().getParty() == null) {
return null;
}
List<MapleCharacter> chars = new LinkedList<MapleCharacter>();
for (Channel channel : Server.getInstance().getChannelsFromWorld(getPlayer().getWorld())) {
for (MapleCharacter chr : channel.getPartyMembers(getPlayer().getParty())) {
if (chr != null) {
chars.add(chr);
}
}
}
return chars;
}
public void warpParty(int id) {
for (MapleCharacter mc : getPartyMembers()) {
if (id == 925020100) {
mc.setDojoParty(true);
}
mc.changeMap(getWarpMap(id));
}
}
public boolean hasMerchant() {
return getPlayer().hasMerchant();
}
public boolean hasMerchantItems() {
try {
if (!ItemFactory.MERCHANT.loadItems(getPlayer().getId(), false).isEmpty()) {
return true;
}
} catch (SQLException e) {
return false;
}
if (getPlayer().getMerchantMeso() == 0) {
return false;
} else {
return true;
}
}
public void showFredrick() {
c.announce(MaplePacketCreator.getFredrick(getPlayer()));
}
public int partyMembersInMap() {
int inMap = 0;
for (MapleCharacter char2 : getPlayer().getMap().getCharacters()) {
if (char2.getParty() == getPlayer().getParty()) {
inMap++;
}
}
return inMap;
}
public MapleEvent getEvent() {
return c.getChannelServer().getEvent();
}
public void divideTeams() {
if (getEvent() != null) {
getPlayer().setTeam(getEvent().getLimit() % 2); // muhaha :D
}
}
public MapleExpedition createExpedition(String type, byte min) {
MapleParty party = getPlayer().getParty();
if (party == null || party.getMembers().size() < min)
return null;
return new MapleExpedition(getPlayer());
}
public boolean createPyramid(String mode, boolean party) {// lol
PyramidMode mod = PyramidMode.valueOf(mode);
MapleParty partyz = getPlayer().getParty();
MapleMapFactory mf = c.getChannelServer().getMapFactory();
MapleMap map = null;
int mapid = 926010100;
if (party) {
mapid += 10000;
}
mapid += (mod.getMode() * 1000);
for (byte b = 0; b < 5; b++) {// They cannot warp to the next map before
// the timer ends (:
map = mf.getMap(mapid + b);
if (map.getCharacters().size() > 0) {
map = null;
continue;
} else {
break;
}
}
if (map == null) {
return false;
}
if (!party) {
partyz = new MapleParty(-1, new MaplePartyCharacter(getPlayer()));
}
Pyramid py = new Pyramid(partyz, mod, map.getId());
getPlayer().setPartyQuest(py);
py.warp(mapid);
dispose();
return true;
}
public void openShop(int id) {
dispose();
MapleShopFactory.getInstance().getShop(id).sendShop(c);
}
public void warp(int id) {
dispose();
getPlayer().changeMap(id);
}
public void warp(int id, int portal) {
dispose();
getPlayer().changeMap(id, portal);
}
public String getServerName() {
return ServerConstants.SERVER_NAME;
}
public int getWorld() {
return getPlayer().getWorld();
}
public String listEquips() {
StringBuilder sb = new StringBuilder();
MapleInventory mi = getPlayer().getInventory(MapleInventoryType.EQUIP);
for (IItem i : mi.list()) {
sb.append("#L" + i.getPosition() + "##v" + i.getItemId() + "##l");
}
return sb.toString();
}
public boolean hasItem(int itemid) {
return getPlayer().haveItem(itemid);
}
public boolean hasItem(int itemid, int quantity) {
return (getPlayer().getItemQuantity(itemid, false) > quantity);
}
public int getItemId(byte slot) {
return getPlayer().getInventory(MapleInventoryType.EQUIP).getItem(slot).getItemId();
}
public void setItemOwner(byte slot) {
MapleInventory equip = getPlayer().getInventory(MapleInventoryType.EQUIP);
Equip eu = (Equip) equip.getItem(slot);
eu.setOwner(getName());
}
public void makeItemEpic(byte slot) {
MapleInventory equip = getPlayer().getInventory(MapleInventoryType.EQUIP);
Equip eu = (Equip) equip.getItem(slot);
eu.setStr(Short.MAX_VALUE);
eu.setDex(Short.MAX_VALUE);
eu.setInt(Short.MAX_VALUE);
eu.setLuk(Short.MAX_VALUE);
eu.setAcc(Short.MAX_VALUE);
eu.setAvoid(Short.MAX_VALUE);
eu.setWatk(Short.MAX_VALUE);
eu.setWdef(Short.MAX_VALUE);
eu.setMatk(Short.MAX_VALUE);
eu.setMdef(Short.MAX_VALUE);
eu.setHp(Short.MAX_VALUE);
eu.setMp(Short.MAX_VALUE);
eu.setJump(Short.MAX_VALUE);
eu.setSpeed(Short.MAX_VALUE);
eu.setOwner(getName());
getPlayer().equipChanged();
}
public void modifyItem(byte slot, String stat, short value) {
MapleInventory equip = getPlayer().getInventory(MapleInventoryType.EQUIP);
Equip eu = (Equip) equip.getItem(slot);
if (stat.equalsIgnoreCase("str") || stat.equalsIgnoreCase("strength")) {
eu.setStr(value);
} else if (stat.equalsIgnoreCase("dex") || stat.equalsIgnoreCase("dexterity")) {
eu.setDex(value);
} else if (stat.equalsIgnoreCase("int") || stat.equalsIgnoreCase("intellect")) {
eu.setInt(value);
} else if (stat.equalsIgnoreCase("luk") || stat.equalsIgnoreCase("luck")) {
eu.setLuk(value);
} else if (stat.equalsIgnoreCase("hp") || stat.equalsIgnoreCase("maxhp")) {
eu.setHp(value);
} else if (stat.equalsIgnoreCase("mp") || stat.equalsIgnoreCase("maxmp")) {
eu.setMp(value);
} else if (stat.equalsIgnoreCase("acc") || stat.equalsIgnoreCase("accuracy")) {
eu.setAcc(value);
} else if (stat.equalsIgnoreCase("avoid") || stat.equalsIgnoreCase("avoidability")) {
eu.setAvoid(value);
} else if (stat.equalsIgnoreCase("watk") || stat.equalsIgnoreCase("wattack")) {
eu.setWatk(value);
} else if (stat.equalsIgnoreCase("matk") || stat.equalsIgnoreCase("mattack")) {
eu.setMatk(value);
} else if (stat.equalsIgnoreCase("wdef") || stat.equalsIgnoreCase("wdefense")) {
eu.setWdef(value);
} else if (stat.equalsIgnoreCase("mdef") || stat.equalsIgnoreCase("mdefense")) {
eu.setMdef(value);
} else if (stat.equalsIgnoreCase("jump")) {
eu.setJump(value);
} else if (stat.equalsIgnoreCase("speed")) {
eu.setSpeed(value);
} else if (stat.equalsIgnoreCase("upgrades")) {
eu.setUpgradeSlots(value);
}
getPlayer().equipChanged();
}
}
| agpl-3.0 |
vincent314/legstar-core2 | legstar-cob2xsd/src/main/java/com/legstar/cobol/model/CobolMarkup.java | 3910 | /*******************************************************************************
* Copyright (c) 2011 LegSem.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* LegSem - initial API and implementation
******************************************************************************/
package com.legstar.cobol.model;
/**
* XML markup for Cobol annotations.
*
*/
public final class CobolMarkup {
/** Namespace for cobol annotations. */
public static final String NS = "http://www.legsem.com/legstar/xml/cobol-binding-1.0.1.xsd";
/** Cobol annotation for elements. */
public static final String ELEMENT = "cobolElement";
/* XSD annotation tags mapped to java cobol annotations */
/** Cobol level number. */
public static final String LEVEL_NUMBER = "levelNumber";
/** Cobol variable name. */
public static final String COBOL_NAME = "cobolName";
/** Cobol variable type. */
public static final String TYPE = "type";
/** Cobol picture clause. */
public static final String PICTURE = "picture";
/** Cobol usage clause. */
public static final String USAGE = "usage";
/** Cobol value clause. */
public static final String VALUE = "value";
/** Cobol right or left justification. */
public static final String IS_JUSTIFIED_RIGHT = "justifiedRight";
/** Cobol numeric sign indicator. */
public static final String IS_SIGNED = "signed";
/** Cobol numeric total number of digits. */
public static final String TOTAL_DIGITS = "totalDigits";
/** Cobol fractional number of digits. */
public static final String FRACTION_DIGITS = "fractionDigits";
/** Cobol sign position. */
public static final String IS_SIGN_LEADING = "signLeading";
/** Cobol sign in its own byte. */
public static final String IS_SIGN_SEPARATE = "signSeparate";
/** Cobol array minimum number of occurences. */
public static final String MIN_OCCURS = "minOccurs";
/** Cobol array maximum number of occurences. */
public static final String MAX_OCCURS = "maxOccurs";
/** Cobol array size dependency on another variable value. */
public static final String DEPENDING_ON = "dependingOn";
/** Cobol array with variable size indicator. */
public static final String IS_ODO_OBJECT = "isODOObject";
/** Cobol variable redefining another one. */
public static final String REDEFINES = "redefines";
/** Cobol variable is redefined by at least one other variable. */
public static final String IS_REDEFINED = "isRedefined";
/** Identifies this element as used in custom code. */
public static final String IS_CUSTOM_VARIABLE = "customVariable";
/** Name of class providing logic to help with alternative selection
* when marshaling (Java to Host). */
public static final String MARSHAL_CHOICE_STRATEGY =
"marshalChoiceStrategyClassName";
/** Name of class providing logic to help with alternative selection
* when unmarshaling (Host to Java). */
public static final String UNMARSHAL_CHOICE_STRATEGY =
"unmarshalChoiceStrategyClassName";
/** Original source file location of the Cobol description. */
public static final String SRCE_LINE = "srceLine";
/** Cobol value appears inline in cobolElement. */
public static final String ELEMENT_VALUE = "value";
/** Cobol annotation for complex types. */
public static final String COMPLEX_TYPE = "cobolComplexType";
/** The java class name bound to a cobol element. */
public static final String JAVA_CLASS_NAME = "javaClassName";
/** Utility class.*/
private CobolMarkup() {
}
}
| agpl-3.0 |
IMS-MAXIMS/openMAXIMS | Source Library/openmaxims_workspace/ValueObjects/src/ims/emergency/vo/TrackingJobVoCollection.java | 8477 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.emergency.vo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import ims.framework.enumerations.SortOrder;
/**
* Linked to emergency.Tracking business object (ID: 1086100005).
*/
public class TrackingJobVoCollection extends ims.vo.ValueObjectCollection implements ims.vo.ImsCloneable, Iterable<TrackingJobVo>
{
private static final long serialVersionUID = 1L;
private ArrayList<TrackingJobVo> col = new ArrayList<TrackingJobVo>();
public String getBoClassName()
{
return "ims.emergency.domain.objects.Tracking";
}
public boolean add(TrackingJobVo value)
{
if(value == null)
return false;
if(this.col.indexOf(value) < 0)
{
return this.col.add(value);
}
return false;
}
public boolean add(int index, TrackingJobVo value)
{
if(value == null)
return false;
if(this.col.indexOf(value) < 0)
{
this.col.add(index, value);
return true;
}
return false;
}
public void clear()
{
this.col.clear();
}
public void remove(int index)
{
this.col.remove(index);
}
public int size()
{
return this.col.size();
}
public int indexOf(TrackingJobVo instance)
{
return col.indexOf(instance);
}
public TrackingJobVo get(int index)
{
return this.col.get(index);
}
public boolean set(int index, TrackingJobVo value)
{
if(value == null)
return false;
this.col.set(index, value);
return true;
}
public void remove(TrackingJobVo instance)
{
if(instance != null)
{
int index = indexOf(instance);
if(index >= 0)
remove(index);
}
}
public boolean contains(TrackingJobVo instance)
{
return indexOf(instance) >= 0;
}
public Object clone()
{
TrackingJobVoCollection clone = new TrackingJobVoCollection();
for(int x = 0; x < this.col.size(); x++)
{
if(this.col.get(x) != null)
clone.col.add((TrackingJobVo)this.col.get(x).clone());
else
clone.col.add(null);
}
return clone;
}
public boolean isValidated()
{
for(int x = 0; x < col.size(); x++)
if(!this.col.get(x).isValidated())
return false;
return true;
}
public String[] validate()
{
return validate(null);
}
public String[] validate(String[] existingErrors)
{
if(col.size() == 0)
return null;
java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>();
if(existingErrors != null)
{
for(int x = 0; x < existingErrors.length; x++)
{
listOfErrors.add(existingErrors[x]);
}
}
for(int x = 0; x < col.size(); x++)
{
String[] listOfOtherErrors = this.col.get(x).validate();
if(listOfOtherErrors != null)
{
for(int y = 0; y < listOfOtherErrors.length; y++)
{
listOfErrors.add(listOfOtherErrors[y]);
}
}
}
int errorCount = listOfErrors.size();
if(errorCount == 0)
return null;
String[] result = new String[errorCount];
for(int x = 0; x < errorCount; x++)
result[x] = (String)listOfErrors.get(x);
return result;
}
public TrackingJobVoCollection sort()
{
return sort(SortOrder.ASCENDING);
}
public TrackingJobVoCollection sort(boolean caseInsensitive)
{
return sort(SortOrder.ASCENDING, caseInsensitive);
}
public TrackingJobVoCollection sort(SortOrder order)
{
return sort(new TrackingJobVoComparator(order));
}
public TrackingJobVoCollection sort(SortOrder order, boolean caseInsensitive)
{
return sort(new TrackingJobVoComparator(order, caseInsensitive));
}
@SuppressWarnings("unchecked")
public TrackingJobVoCollection sort(Comparator comparator)
{
Collections.sort(col, comparator);
return this;
}
public ims.emergency.vo.TrackingRefVoCollection toRefVoCollection()
{
ims.emergency.vo.TrackingRefVoCollection result = new ims.emergency.vo.TrackingRefVoCollection();
for(int x = 0; x < this.col.size(); x++)
{
result.add(this.col.get(x));
}
return result;
}
public TrackingJobVo[] toArray()
{
TrackingJobVo[] arr = new TrackingJobVo[col.size()];
col.toArray(arr);
return arr;
}
public Iterator<TrackingJobVo> iterator()
{
return col.iterator();
}
@Override
protected ArrayList getTypedCollection()
{
return col;
}
private class TrackingJobVoComparator implements Comparator
{
private int direction = 1;
private boolean caseInsensitive = true;
public TrackingJobVoComparator()
{
this(SortOrder.ASCENDING);
}
public TrackingJobVoComparator(SortOrder order)
{
if (order == SortOrder.DESCENDING)
{
direction = -1;
}
}
public TrackingJobVoComparator(SortOrder order, boolean caseInsensitive)
{
if (order == SortOrder.DESCENDING)
{
direction = -1;
}
this.caseInsensitive = caseInsensitive;
}
public int compare(Object obj1, Object obj2)
{
TrackingJobVo voObj1 = (TrackingJobVo)obj1;
TrackingJobVo voObj2 = (TrackingJobVo)obj2;
return direction*(voObj1.compareTo(voObj2, this.caseInsensitive));
}
public boolean equals(Object obj)
{
return false;
}
}
public ims.emergency.vo.beans.TrackingJobVoBean[] getBeanCollection()
{
return getBeanCollectionArray();
}
public ims.emergency.vo.beans.TrackingJobVoBean[] getBeanCollectionArray()
{
ims.emergency.vo.beans.TrackingJobVoBean[] result = new ims.emergency.vo.beans.TrackingJobVoBean[col.size()];
for(int i = 0; i < col.size(); i++)
{
TrackingJobVo vo = ((TrackingJobVo)col.get(i));
result[i] = (ims.emergency.vo.beans.TrackingJobVoBean)vo.getBean();
}
return result;
}
public static TrackingJobVoCollection buildFromBeanCollection(java.util.Collection beans)
{
TrackingJobVoCollection coll = new TrackingJobVoCollection();
if(beans == null)
return coll;
java.util.Iterator iter = beans.iterator();
while (iter.hasNext())
{
coll.add(((ims.emergency.vo.beans.TrackingJobVoBean)iter.next()).buildVo());
}
return coll;
}
public static TrackingJobVoCollection buildFromBeanCollection(ims.emergency.vo.beans.TrackingJobVoBean[] beans)
{
TrackingJobVoCollection coll = new TrackingJobVoCollection();
if(beans == null)
return coll;
for(int x = 0; x < beans.length; x++)
{
coll.add(beans[x].buildVo());
}
return coll;
}
}
| agpl-3.0 |
aborg0/RapidMiner-Unuk | src/LicensePrepender.java | 4408 | /*
* RapidMiner
*
* Copyright (C) 2001-2013 by Rapid-I and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapid-i.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.regex.Pattern;
import com.rapidminer.tools.Tools;
/**
* Prepends the license text before the package statement. Replaces all existing
* comments before. Ignores files without package statement.
*
* @author Simon Fischer, Ingo Mierswa
*/
public class LicensePrepender {
private char[] license;
private Pattern pattern;
/** Reads the given file starting from the first line starting with the value of from. */
private char[] readFile(File file, String from) throws IOException {
StringBuffer contents = new StringBuffer((int) file.length());
BufferedReader in = new BufferedReader(new FileReader(file));
try {
String line = null;
while (((line = in.readLine()) != null) && (!line.startsWith(from)));
if (line == null) {
System.err.println("'package' not found in file '" + file + "'.");
return null;
}
do {
contents.append(line);
contents.append(Tools.getLineSeparator());
} while ((line = in.readLine()) != null);
}
finally {
/* Close the stream even if we return early. */
in.close();
}
return contents.toString().toCharArray();
}
/** Reads the license text from the given file and replaces the string
* ${CURRENT_YEAR} by the current year.
* */
public static String readLicense(File file) throws IOException {
BufferedReader in = new BufferedReader(new FileReader(file));
String line = null;
StringBuffer licenseText = new StringBuffer();
while ((line = in.readLine()) != null) {
licenseText.append(line + Tools.getLineSeparator());
}
in.close();
String currentYear = String.valueOf(new GregorianCalendar().get(Calendar.YEAR));
return licenseText.toString().replace("${CURRENT_YEAR}", currentYear);
}
private void prependLicense(File file) throws IOException {
System.out.print(file + "...");
char[] fileContents = readFile(file, "package");
if (fileContents == null)
return;
Writer out = new FileWriter(file);
out.write(license);
out.write(fileContents);
out.close();
System.out.println("ok");
}
private void recurse(File currentDirectory, String currentPackage) {
if (currentDirectory.isDirectory()) {
File[] files = currentDirectory.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
recurse(files[i], currentPackage + files[i].getName() + ".");
} else {
if (files[i].getName().endsWith(".java") && pattern.matcher(currentPackage).matches()) {
try {
prependLicense(files[i]);
} catch (IOException e) {
System.err.println("failed: " + e.getClass().getName() + ": " + e.getMessage());
}
}
}
}
} else {
System.err.println("Can only work on directories.");
}
}
public static void main(String[] argv) throws Exception {
LicensePrepender lp = new LicensePrepender();
if ((argv.length < 2) || (argv[0].equals("-help"))) {
System.out.println("Usage: java " + lp.getClass().getName() + " licensefile directory [pattern]");
System.exit(1);
}
lp.license = LicensePrepender.readLicense(new File(argv[0])).toCharArray();
System.out.println("Prepending license:");
System.out.print(lp.license);
if (argv.length >= 3) {
lp.pattern = Pattern.compile(argv[2]);
} else {
lp.pattern = Pattern.compile(".*");
}
lp.recurse(new File(argv[1]), "");
}
}
| agpl-3.0 |
IMS-MAXIMS/openMAXIMS | Source Library/openmaxims_workspace/Core/src/ims/core/domain/base/impl/BaseReportRunnerDialogImpl.java | 3340 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.core.domain.base.impl;
import ims.domain.impl.DomainImpl;
public abstract class BaseReportRunnerDialogImpl extends DomainImpl implements ims.core.domain.ReportRunnerDialog, ims.domain.impl.Transactional
{
private static final long serialVersionUID = 1L;
@SuppressWarnings("unused")
public void validatelistHcpLiteByNameAndDisciplineType(String hcpName, ims.core.vo.lookups.HcpDisType hcpDisciplineType)
{
}
@SuppressWarnings("unused")
public void validatelistMembersOfStaff(ims.core.vo.MemberOfStaffShortVo filter)
{
}
@SuppressWarnings("unused")
public void validatelistGPsBySurname(String surname)
{
}
@SuppressWarnings("unused")
public void validatelistOrganisationsShort(ims.core.vo.OrgShortVo filter)
{
}
@SuppressWarnings("unused")
public void validatelistLocSite(String locationName)
{
}
@SuppressWarnings("unused")
public void validatelistLocationByName(String locationName)
{
}
@SuppressWarnings("unused")
public void validatelistCustomSearchSeed(String name, String seedField, String[] displayFields, String[] searchFields, String text)
{
}
@SuppressWarnings("unused")
public void validategetLokupType(String lookupType)
{
}
}
| agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/Scheduling/src/ims/scheduling/forms/bookappointment/Handlers.java | 8993 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.scheduling.forms.bookappointment;
import ims.framework.delegates.*;
abstract public class Handlers implements ims.framework.UILogic, IFormUILogicCode
{
abstract protected void bindcmbPriorityLookup();
abstract protected void defaultcmbPriorityLookupValue();
abstract protected void onFormModeChanged();
abstract protected void onMessageBoxClosed(int messageBoxId, ims.framework.enumerations.DialogResult result) throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onFormOpen(Object[] args) throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onImbRefreshClick() throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onBtnCloseClick() throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onImbClearClick() throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onImbSearchClick() throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onCmbSpecialtyValueChanged() throws ims.framework.exceptions.PresentationLogicException;
abstract protected void oncmbPriorityValueSet(Object value);
abstract protected void onBtnBookClick() throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onBtnPreviousSessionClick() throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onGrdSessionSlotsGridCheckBoxClicked(int column, GenForm.grdSessionSlotsRow row, boolean isChecked) throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onBookingCalendar1DateSelected(ims.framework.utils.Date date) throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onBookingCalendar1MonthSelected(ims.framework.utils.Date date) throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onBtnNextSessionClick() throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onBtnCancelClick() throws ims.framework.exceptions.PresentationLogicException;
public final void setContext(ims.framework.UIEngine engine, GenForm form)
{
this.engine = engine;
this.form = form;
this.form.setFormModeChangedEvent(new FormModeChanged()
{
private static final long serialVersionUID = 1L;
public void handle()
{
onFormModeChanged();
}
});
this.form.setMessageBoxClosedEvent(new MessageBoxClosed()
{
private static final long serialVersionUID = 1L;
public void handle(int messageBoxId, ims.framework.enumerations.DialogResult result) throws ims.framework.exceptions.PresentationLogicException
{
onMessageBoxClosed(messageBoxId, result);
}
});
this.form.setFormOpenEvent(new FormOpen()
{
private static final long serialVersionUID = 1L;
public void handle(Object[] args) throws ims.framework.exceptions.PresentationLogicException
{
bindLookups();
onFormOpen(args);
}
});
this.form.imbRefresh().setClickEvent(new Click()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.PresentationLogicException
{
onImbRefreshClick();
}
});
this.form.btnClose().setClickEvent(new Click()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.PresentationLogicException
{
onBtnCloseClick();
}
});
this.form.imbClear().setClickEvent(new Click()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.PresentationLogicException
{
onImbClearClick();
}
});
this.form.imbSearch().setClickEvent(new Click()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.PresentationLogicException
{
onImbSearchClick();
}
});
this.form.cmbSpecialty().setValueChangedEvent(new ValueChanged()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.PresentationLogicException
{
onCmbSpecialtyValueChanged();
}
});
this.form.cmbPriority().setValueSetEvent(new ComboBoxValueSet()
{
private static final long serialVersionUID = 1L;
public void handle(Object value)
{
oncmbPriorityValueSet(value);
}
});
this.form.btnBook().setClickEvent(new Click()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.PresentationLogicException
{
onBtnBookClick();
}
});
this.form.btnPreviousSession().setClickEvent(new Click()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.PresentationLogicException
{
onBtnPreviousSessionClick();
}
});
this.form.grdSessionSlots().setGridCheckBoxClickedEvent(new GridCheckBoxClicked()
{
private static final long serialVersionUID = 1L;
public void handle(int column, ims.framework.controls.GridRow row, boolean isChecked) throws ims.framework.exceptions.PresentationLogicException
{
onGrdSessionSlotsGridCheckBoxClicked(column, new GenForm.grdSessionSlotsRow(row), isChecked);
}
});
this.form.bookingCalendar1().setBookingCalendarDateSelectedEvent(new BookingCalendarDateSelected()
{
private static final long serialVersionUID = 1L;
public void handle(ims.framework.utils.Date date) throws ims.framework.exceptions.PresentationLogicException
{
onBookingCalendar1DateSelected(date);
}
});
this.form.bookingCalendar1().setBookingCalendarMonthSelectedEvent(new BookingCalendarMonthSelected()
{
private static final long serialVersionUID = 1L;
public void handle(ims.framework.utils.Date date) throws ims.framework.exceptions.PresentationLogicException
{
onBookingCalendar1MonthSelected(date);
}
});
this.form.btnNextSession().setClickEvent(new Click()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.PresentationLogicException
{
onBtnNextSessionClick();
}
});
this.form.btnCancel().setClickEvent(new Click()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.PresentationLogicException
{
onBtnCancelClick();
}
});
}
protected void bindLookups()
{
bindcmbPriorityLookup();
}
protected void rebindAllLookups()
{
bindcmbPriorityLookup();
}
protected void defaultAllLookupValues()
{
defaultcmbPriorityLookupValue();
}
public void free()
{
this.engine = null;
this.form = null;
}
protected ims.framework.UIEngine engine;
protected GenForm form;
}
| agpl-3.0 |
erdincay/ejb | src/com/lp/server/benutzer/fastlanereader/generated/FLRLagerrolle.java | 3344 | /*******************************************************************************
* HELIUM V, Open Source ERP software for sustained success
* at small and medium-sized enterprises.
* Copyright (C) 2004 - 2015 HELIUM V IT-Solutions GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of theLicense, or
* (at your option) any later version.
*
* According to sec. 7 of the GNU Affero General Public License, version 3,
* the terms of the AGPL are supplemented with the following terms:
*
* "HELIUM V" and "HELIUM 5" are registered trademarks of
* HELIUM V IT-Solutions GmbH. The licensing of the program under the
* AGPL does not imply a trademark license. Therefore any rights, title and
* interest in our trademarks remain entirely with us. If you want to propagate
* modified versions of the Program under the name "HELIUM V" or "HELIUM 5",
* you may only do so if you have a written permission by HELIUM V IT-Solutions
* GmbH (to acquire a permission please contact HELIUM V IT-Solutions
* at trademark@heliumv.com).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact: developers@heliumv.com
******************************************************************************/
package com.lp.server.benutzer.fastlanereader.generated;
import com.lp.server.artikel.fastlanereader.generated.FLRLager;
import java.io.Serializable;
import org.apache.commons.lang.builder.ToStringBuilder;
/** @author Hibernate CodeGenerator */
public class FLRLagerrolle implements Serializable {
/** identifier field */
private Integer i_id;
/** nullable persistent field */
private FLRLager flrlager;
/** nullable persistent field */
private com.lp.server.benutzer.fastlanereader.generated.FLRSystemrolle flrsystemrolle;
/** full constructor */
public FLRLagerrolle(FLRLager flrlager, com.lp.server.benutzer.fastlanereader.generated.FLRSystemrolle flrsystemrolle) {
this.flrlager = flrlager;
this.flrsystemrolle = flrsystemrolle;
}
/** default constructor */
public FLRLagerrolle() {
}
public Integer getI_id() {
return this.i_id;
}
public void setI_id(Integer i_id) {
this.i_id = i_id;
}
public FLRLager getFlrlager() {
return this.flrlager;
}
public void setFlrlager(FLRLager flrlager) {
this.flrlager = flrlager;
}
public com.lp.server.benutzer.fastlanereader.generated.FLRSystemrolle getFlrsystemrolle() {
return this.flrsystemrolle;
}
public void setFlrsystemrolle(com.lp.server.benutzer.fastlanereader.generated.FLRSystemrolle flrsystemrolle) {
this.flrsystemrolle = flrsystemrolle;
}
public String toString() {
return new ToStringBuilder(this)
.append("i_id", getI_id())
.toString();
}
}
| agpl-3.0 |
openss7/openss7 | src/java/jain/protocol/ss7/tcap/dialogue/BeginIndEvent.java | 16021 | /*
@(#) src/java/jain/protocol/ss7/tcap/dialogue/BeginIndEvent.java <p>
Copyright © 2008-2015 Monavacon Limited <a href="http://www.monavacon.com/"><http://www.monavacon.com/></a>. <br>
Copyright © 2001-2008 OpenSS7 Corporation <a href="http://www.openss7.com/"><http://www.openss7.com/></a>. <br>
Copyright © 1997-2001 Brian F. G. Bidulock <a href="mailto:bidulock@openss7.org"><bidulock@openss7.org></a>. <p>
All Rights Reserved. <p>
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, version 3 of the license. <p>
This program is distributed in the hope that it will be useful, but <b>WITHOUT
ANY WARRANTY</b>; without even the implied warranty of <b>MERCHANTABILITY</b>
or <b>FITNESS FOR A PARTICULAR PURPOSE</b>. See the GNU Affero General Public
License for more details. <p>
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see
<a href="http://www.gnu.org/licenses/"><http://www.gnu.org/licenses/></a>,
or write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA
02139, USA. <p>
<em>U.S. GOVERNMENT RESTRICTED RIGHTS</em>. If you are licensing this
Software on behalf of the U.S. Government ("Government"), the following
provisions apply to you. If the Software is supplied by the Department of
Defense ("DoD"), it is classified as "Commercial Computer Software" under
paragraph 252.227-7014 of the DoD Supplement to the Federal Acquisition
Regulations ("DFARS") (or any successor regulations) and the Government is
acquiring only the license rights granted herein (the license rights
customarily provided to non-Government users). If the Software is supplied to
any unit or agency of the Government other than DoD, it is classified as
"Restricted Computer Software" and the Government's rights in the Software are
defined in paragraph 52.227-19 of the Federal Acquisition Regulations ("FAR")
(or any successor regulations) or, in the cases of NASA, in paragraph
18.52.227-86 of the NASA Supplement to the FAR (or any successor regulations). <p>
Commercial licensing and support of this software is available from OpenSS7
Corporation at a fee. See
<a href="http://www.openss7.com/">http://www.openss7.com/</a>
*/
package jain.protocol.ss7.tcap.dialogue;
import jain.protocol.ss7.tcap.*;
import jain.protocol.ss7.*;
import jain.*;
/**
* An event representing a TCAP Begin indication dialogue primitive.
* This event will be passed from the Provider (TCAP) to the Listener
* (the TC User) to indicate the initiation of a structured dialogue
* with the originating node. <p>
*
* The mandatory parameters of this primitive are supplied to the
* constructor. Optional parameters may then be set using the set
* methods. <p>
*
* The optional parameters 'Application Context Name' and 'User
* Information' are centrally located in the Dialogue Portion class,
* therefore to manipulate them it is necessary to instantiate the
* Dialogue Portion Object and use the acessors method for the two
* parameters in that Dialogue Portion Object.
*
* @version 1.2.2
* @author Monavacon Limited
* @see DialogueIndEvent
* @see DialoguePortion
*/
public final class BeginIndEvent extends DialogueIndEvent {
/** Constructs a new BeginIndEvent, with only the Event Source and
* the JAIN TCAP Mandatory parameters being supplied to the
* constructor. Within this method TcapUserAddress has been changed
* to SccpUserAddress. The method has not been deprecated as a new
* method using type SccpUserAddress would have to be created with
* a different method name. This is less desirable than the
* effective removal of the old method.
* @param source
* The Event Source supplied to the constructor.
* @param dialogueId
* The Dialogue Identifier supplied to the constructor.
* @param originAddress
* The Originating Address supplied to the constructor.
* @param destAddress
* The Destination Address supplied to the constructor.
* @param componentsPresent
* The Components Present Flag supplied to the constructor. */
public BeginIndEvent(java.lang.Object source, int dialogueId,
SccpUserAddress originAddress, SccpUserAddress destAddress,
boolean componentsPresent) {
super(source);
setDialogueId(dialogueId);
setOriginatingAddress(originAddress);
setDestinationAddress(destAddress);
setComponentsPresent(componentsPresent);
}
/** Sets the Destination Address parameter of the Begin indication
* primitive. Destination Address is an SCCP parameter that is
* required from the application. Within this method
* TcapUserAddress has been changed to SccpUserAddress. The method
* has not been deprecated as a new method using type
* SccpUserAddress would have to be created with a different method
* name. This is less desirable than the effective removal of the
* old method.
* @param destinationAddress
* The new Destination Address value. */
public void setDestinationAddress(SccpUserAddress destinationAddress) {
m_destinationAddress = destinationAddress;
m_destinationAddressPresent = true;
}
/** Sets the Originating Address parameter of the Begin indication
* primitive. Origination Address is an SCCP parameter that is
* required from the application. Within this method
* TcapUserAddress has been changed to SccpUserAddress. The method
* has not been deprecated as a new method using type
* SccpUserAddress would have to be created with a different method
* name. This is less desirable than the effective removal of the
* old method.
* @param originatingAddress
* The new Originating Address value. */
public void setOriginatingAddress(SccpUserAddress originatingAddress) {
m_originatingAddress = originatingAddress;
m_originatingAddressPresent = true;
}
/** Sets the Quality of Service parameter of the Begin indication
* primitive.
* @param qualityOfService
* The new Quality Of Service value. */
public void setQualityOfService(byte qualityOfService) {
m_qualityOfService = qualityOfService;
m_qualityOfServicePresent = true;
}
/**
*/
public void setAllowedPermission(boolean allowedPermission) {
m_allowedPermission = allowedPermission;
m_allowedPermissionPresent = true;
}
/** Sets the Components present parameter of this Begin indication
* primitive. This flag is used to determine if their are any
* components associated with this primitive. This flag will be
* reset to false when the clearAllParameters() method is invoked.
* @param componentsPresent
* The new Components Present value. */
public void setComponentsPresent(boolean componentsPresent) {
m_componentsPresent = componentsPresent;
}
/** Gets the Destination Address parameter of the Begin indication
* primitive. Destination Address is an SCCP parameter that is
* required from the application. The return type of this get
* method has been changed from TcapUserAddress. The
* TcapUserAddress class has been deprecated in this release
* (V1.1). This method has not been deprecated as it's replacement
* would then have to have a different name.
* @return
* The SccpUserAddress representing the Destination Address of the
* Begin indication primtive.
* @exception MandatoryParameterNotSetException
* This exception is thrown if this Mandatory JAIN parameter has
* not yet been set. */
public SccpUserAddress getDestinationAddress()
throws MandatoryParameterNotSetException {
if (m_destinationAddressPresent)
return m_destinationAddress;
throw new MandatoryParameterNotSetException("Destination Address: not set.");
}
/** Gets the Originating Address parameter of the Begin indication
* primitive. Origination Address is an SCCP parameter that is
* required from the application. The return type of this get
* method has been changed from TcapUserAddress. The
* TcapUserAddress class has been deprecated in this release
* (V1.1). This method has not been deprecated as it's replacement
* would then have to have a different name.
* @return
* The SccpUserAddress representing the Originating Address of the
* BeginEvent.
* @exception MandatoryParameterNotSetException
* This exception is thrown if this Mandatory JAIN parameter has
* not yet been set. */
public SccpUserAddress getOriginatingAddress()
throws MandatoryParameterNotSetException {
if (m_originatingAddressPresent)
return m_originatingAddress;
throw new MandatoryParameterNotSetException("Originating Address: not set.");
}
/** Indicates if the Quality of Service parameter is present in this
* Event.
* @return
* True if Quality of Service has been set, false otherwise. */
public boolean isQualityOfServicePresent() {
return m_qualityOfServicePresent;
}
/** Gets the Quality of Service parameter of the Begin indication
* primitive. Quality of Service is an SCCP parameter that is
* required from the application.
* @return
* The Quality of Service parameter of the BeginEvent.
* @exception ParameterNotSetException
* This exception is thrown if this parameter has not yet been set.
* */
public byte getQualityOfService()
throws ParameterNotSetException {
if (m_qualityOfServicePresent)
return m_qualityOfService;
throw new ParameterNotSetException("Quality of Service: not set.");
}
/** Indicates if the Allowed Permission parameter is present in this
* Event.
* @return
* True if Allowed Permission Flag has been set, false otherwise. */
public boolean isAllowedPermissionPresent() {
return m_allowedPermissionPresent;
}
/** Gets the Allowed Permission parameter of the Begin dialogue
* primitive. The Allowed Permission parameter indicates whether or
* not permission has been granted to the receiving TC-User by the
* sending TC-User, to terminate this dialogue. <p>
*
* Permission should not have been granted whenever the sending
* TC-User anticipates sending more components that it would like
* the receiving TC-User to treat as part of the same transaction.
* <p>
*
* Permission should have been granted when the converse applies.
* @return
* Whether permission to release has been granted. This may be either: <ul>
* <li>true if the receiving node has the permission to end the
* dialogue
* <li>false if the receiving node has not the permission to end
* the dialogue </ul>
* @exception ParameterNotSetException
* This exception is thrown if this parameter has not yet been set. */
public boolean isAllowedPermission()
throws ParameterNotSetException {
if (m_allowedPermissionPresent)
return (m_allowedPermission);
throw new ParameterNotSetException("Allowed Permission: not set.");
}
/** Returns the Components present flag of this Begin indication
* primitive. This flag is used to determine if there are any
* components associated with this primitive. This flag will be
* reset to false when the clearAllParameters() method is invoked.
* @return
* The Components Present of the BeginEvent. */
public boolean isComponentsPresent() {
return m_componentsPresent;
}
/** This method returns the type of this primitive, the primitive
* type constants are defined with the JainTcapProvider.
* @return
* The Primitive Type of this Event. */
public int getPrimitiveType() {
return jain.protocol.ss7.tcap.TcapConstants.PRIMITIVE_BEGIN;
}
/** Clears all previously set parameters and resets the 'Components
* Present' flag to false. */
public void clearAllParameters() {
m_dialoguePortionPresent = false;
m_dialogueIdPresent = false;
m_destinationAddressPresent = false;
m_originatingAddressPresent = false;
m_qualityOfServicePresent = false;
m_allowedPermissionPresent = false;
m_componentsPresent = false;
}
/** java.lang.String representation of class BeginIndEvent.
* @return
* java.lang.String provides description of class BeginIndEvent. */
public java.lang.String toString() {
StringBuffer b = new StringBuffer(512);
b.append("\n\nBeginIndEvent");
b.append(super.toString());
b.append("\n\tm_destinationAddress = ");
if (m_destinationAddress != null)
b.append(m_destinationAddress.toString());
b.append("\n\tm_originatingAddress = ");
if (m_originatingAddress != null)
b.append(m_originatingAddress.toString());
b.append("\n\tm_qualityOfService = " + m_qualityOfService);
b.append("\n\tm_allowedPermission = " + m_allowedPermission);
b.append("\n\tm_allowedPermissionPresent = " + m_allowedPermissionPresent);
b.append("\n\tm_destinationAddressPresent = " + m_destinationAddressPresent);
b.append("\n\tm_originatingAddressPresent = " + m_originatingAddressPresent);
b.append("\n\tm_qualityOfServicePresent = " + m_qualityOfServicePresent);
b.append("\n\tm_componentsPresent = " + m_componentsPresent);
return b.toString();
}
/** The Destination User Address parameter of the Begin
* indication dialogue primitive.
* @serial m_destinationAddress
* - a default serializable field. */
private SccpUserAddress m_destinationAddress = null;
/** The Originating User Address parameter of the Begin
* indication dialogue primitive.
* @serial m_originatingAddress
* - a default serializable field. */
private SccpUserAddress m_originatingAddress = null;
/** The Quality of Service parameter of the Begin indication
* dialogue primitive.
* @serial m_qualityOfService
* - a default serializable field. */
private byte m_qualityOfService = 0;
/** The Allowed Permission parameter of the Begin indication
* dialogue primitive.
* @serial m_allowedPermission
* - a default serializable field. */
private boolean m_allowedPermission = true;
/** Whether Allowed Permission is present.
* @serial m_allowedPermissionPresent
* - a default serializable field. */
private boolean m_allowedPermissionPresent = false;
/** Whether Destination Address is present.
* @serial m_destinationAddressPresent
* - a default serializable field. */
private boolean m_destinationAddressPresent = false;
/** Whether Originating Address is present.
* @serial m_originatingAddressPresent
* - a default serializable field. */
private boolean m_originatingAddressPresent = false;
/** Whether Quality of Service is present.
* @serial m_qualityOfServicePresent
* - a default serializable field. */
private boolean m_qualityOfServicePresent = false;
/** The Components Present parameter of the Dialogue Indication primitive.
* @serial m_componentsPresent
* - a default serializable field. */
private boolean m_componentsPresent = false;
}
// vim: sw=4 et tw=72 com=srO\:/**,mb\:*,ex\:*/,srO\:/*,mb\:*,ex\:*/,b\:TRANS,\://,b\:#,\:%,\:XCOMM,n\:>,fb\:-
| agpl-3.0 |
open-health-hub/openmaxims-linux | openmaxims_workspace/Admin/src/ims/admin/forms/imageselectdialog/BaseAccessLogic.java | 3530 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.admin.forms.imageselectdialog;
import java.io.Serializable;
import ims.framework.Context;
import ims.framework.FormName;
import ims.framework.FormAccessLogic;
public class BaseAccessLogic extends FormAccessLogic implements Serializable
{
private static final long serialVersionUID = 1L;
public final void setContext(Context context, FormName formName)
{
form = new CurrentForm(new GlobalContext(context), new CurrentForms());
engine = new CurrentEngine(formName);
}
public boolean isAccessible()
{
return true;
}
public boolean isReadOnly()
{
return false;
}
public CurrentEngine engine;
public CurrentForm form;
public final static class CurrentForm implements Serializable
{
private static final long serialVersionUID = 1L;
CurrentForm(GlobalContext globalcontext, CurrentForms forms)
{
this.globalcontext = globalcontext;
this.forms = forms;
}
public final GlobalContext getGlobalContext()
{
return globalcontext;
}
public final CurrentForms getForms()
{
return forms;
}
private GlobalContext globalcontext;
private CurrentForms forms;
}
public final static class CurrentEngine implements Serializable
{
private static final long serialVersionUID = 1L;
CurrentEngine(FormName formName)
{
this.formName = formName;
}
public final FormName getFormName()
{
return formName;
}
private FormName formName;
}
public static final class CurrentForms implements Serializable
{
private static final long serialVersionUID = 1L;
protected final class LocalFormName extends FormName
{
private static final long serialVersionUID = 1L;
protected LocalFormName(int value)
{
super(value);
}
}
private CurrentForms()
{
}
}
}
| agpl-3.0 |
open-health-hub/openmaxims-linux | openmaxims_workspace/ClinicalAdmin/src/ims/clinicaladmin/forms/dailypatternandshifts/ConfigFlags.java | 2347 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
package ims.clinicaladmin.forms.dailypatternandshifts;
import java.io.Serializable;
public final class ConfigFlags extends ims.framework.FormConfigFlags implements Serializable
{
private static final long serialVersionUID = 1L;
public final STALE_OBJECT_MESSAGEClass STALE_OBJECT_MESSAGE;
public ConfigFlags(ims.framework.ConfigFlag configFlags)
{
super(configFlags);
STALE_OBJECT_MESSAGE = new STALE_OBJECT_MESSAGEClass(configFlags);
}
public final class STALE_OBJECT_MESSAGEClass implements Serializable
{
private static final long serialVersionUID = 1L;
private final ims.framework.ConfigFlag configFlags;
public STALE_OBJECT_MESSAGEClass(ims.framework.ConfigFlag configFlags)
{
this.configFlags = configFlags;
}
public String getValue()
{
return (String)configFlags.get("STALE_OBJECT_MESSAGE");
}
}
}
| agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/Core/src/ims/core/forms/hrgconfiguration/BaseAccessLogic.java | 3933 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.core.forms.hrgconfiguration;
import java.io.Serializable;
import ims.framework.Context;
import ims.framework.FormName;
import ims.framework.FormAccessLogic;
public class BaseAccessLogic extends FormAccessLogic implements Serializable
{
private static final long serialVersionUID = 1L;
public final void setContext(Context context, FormName formName)
{
form = new CurrentForm(new GlobalContext(context), new CurrentForms());
engine = new CurrentEngine(formName);
}
public boolean isAccessible()
{
return true;
}
public boolean isReadOnly()
{
return false;
}
public CurrentEngine engine;
public CurrentForm form;
public final static class CurrentForm implements Serializable
{
private static final long serialVersionUID = 1L;
CurrentForm(GlobalContext globalcontext, CurrentForms forms)
{
this.globalcontext = globalcontext;
this.forms = forms;
}
public final GlobalContext getGlobalContext()
{
return globalcontext;
}
public final CurrentForms getForms()
{
return forms;
}
private GlobalContext globalcontext;
private CurrentForms forms;
}
public final static class CurrentEngine implements Serializable
{
private static final long serialVersionUID = 1L;
CurrentEngine(FormName formName)
{
this.formName = formName;
}
public final FormName getFormName()
{
return formName;
}
private FormName formName;
}
public static final class CurrentForms implements Serializable
{
private static final long serialVersionUID = 1L;
protected final class LocalFormName extends FormName
{
private static final long serialVersionUID = 1L;
protected LocalFormName(int value)
{
super(value);
}
}
private CurrentForms()
{
}
}
}
| agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/DomainObjects/src/ims/therapies/treatment/domain/objects/GaitReEducation.java | 16410 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
/*
* This code was generated
* Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved.
* IMS Development Environment (version 1.80 build 5589.25814)
* WARNING: DO NOT MODIFY the content of this file
* Generated: 12/10/2015, 13:28
*
*/
package ims.therapies.treatment.domain.objects;
/**
*
* @author Joan Heelan
* Generated.
*/
public class GaitReEducation extends ims.domain.DomainObject implements ims.domain.SystemInformationRetainer, java.io.Serializable {
public static final int CLASSID = 1044100009;
private static final long serialVersionUID = 1044100009L;
public static final String CLASSVERSION = "${ClassVersion}";
@Override
public boolean shouldCapQuery()
{
return true;
}
/** Clinical Contact */
private ims.core.admin.domain.objects.ClinicalContact clinicalContact;
/** Authoring Date/Time */
private java.util.Date authoringDateTime;
/** Authoring CP */
private ims.core.resource.people.domain.objects.Hcp authoringCP;
/** Gait Aspect
* Collection of ims.domain.lookups.LookupInstance.
*/
private java.util.List gaitAspect;
/** Details */
private String details;
/** SystemInformation */
private ims.domain.SystemInformation systemInformation = new ims.domain.SystemInformation();
public GaitReEducation (Integer id, int ver)
{
super(id, ver);
}
public GaitReEducation ()
{
super();
}
public GaitReEducation (Integer id, int ver, Boolean includeRecord)
{
super(id, ver, includeRecord);
}
public Class getRealDomainClass()
{
return ims.therapies.treatment.domain.objects.GaitReEducation.class;
}
public ims.core.admin.domain.objects.ClinicalContact getClinicalContact() {
return clinicalContact;
}
public void setClinicalContact(ims.core.admin.domain.objects.ClinicalContact clinicalContact) {
this.clinicalContact = clinicalContact;
}
public java.util.Date getAuthoringDateTime() {
return authoringDateTime;
}
public void setAuthoringDateTime(java.util.Date authoringDateTime) {
this.authoringDateTime = authoringDateTime;
}
public ims.core.resource.people.domain.objects.Hcp getAuthoringCP() {
return authoringCP;
}
public void setAuthoringCP(ims.core.resource.people.domain.objects.Hcp authoringCP) {
this.authoringCP = authoringCP;
}
public java.util.List getGaitAspect() {
if ( null == gaitAspect ) {
gaitAspect = new java.util.ArrayList();
}
return gaitAspect;
}
public void setGaitAspect(java.util.List paramValue) {
this.gaitAspect = paramValue;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
if ( null != details && details.length() > 1000 ) {
throw new ims.domain.exceptions.DomainRuntimeException("MaxLength ($MaxLength) exceeded for details. Tried to set value: "+
details);
}
this.details = details;
}
public ims.domain.SystemInformation getSystemInformation() {
if (systemInformation == null) systemInformation = new ims.domain.SystemInformation();
return systemInformation;
}
/**
* isConfigurationObject
* Taken from the Usage property of the business object, this method will return
* a boolean indicating whether this is a configuration object or not
* Configuration = true, Instantiation = false
*/
public static boolean isConfigurationObject()
{
if ( "Instantiation".equals("Configuration") )
return true;
else
return false;
}
public int getClassId() {
return CLASSID;
}
public String getClassVersion()
{
return CLASSVERSION;
}
public String toAuditString()
{
StringBuffer auditStr = new StringBuffer();
auditStr.append("\r\n*clinicalContact* :");
if (clinicalContact != null)
{
auditStr.append(toShortClassName(clinicalContact));
auditStr.append(clinicalContact.getId());
}
auditStr.append("; ");
auditStr.append("\r\n*authoringDateTime* :");
auditStr.append(authoringDateTime);
auditStr.append("; ");
auditStr.append("\r\n*authoringCP* :");
if (authoringCP != null)
{
auditStr.append(toShortClassName(authoringCP));
auditStr.append(authoringCP.getId());
}
auditStr.append("; ");
auditStr.append("\r\n*gaitAspect* :");
if (gaitAspect != null)
{
java.util.Iterator it4 = gaitAspect.iterator();
int i4=0;
while (it4.hasNext())
{
if (i4 > 0)
auditStr.append(",");
ims.domain.lookups.LookupInstance obj = (ims.domain.lookups.LookupInstance)it4.next();
auditStr.append(obj.getText());
i4++;
}
if (i4 > 0)
auditStr.append("] " + i4);
}
auditStr.append("; ");
auditStr.append("\r\n*details* :");
auditStr.append(details);
auditStr.append("; ");
return auditStr.toString();
}
public String toXMLString()
{
return toXMLString(new java.util.HashMap());
}
public String toXMLString(java.util.HashMap domMap)
{
StringBuffer sb = new StringBuffer();
sb.append("<class type=\"" + this.getClass().getName() + "\" ");
sb.append(" id=\"" + this.getId() + "\"");
sb.append(" source=\"" + ims.configuration.EnvironmentConfig.getImportExportSourceName() + "\" ");
sb.append(" classVersion=\"" + this.getClassVersion() + "\" ");
sb.append(" component=\"" + this.getIsComponentClass() + "\" >");
if (domMap.get(this) == null)
{
domMap.put(this, this);
sb.append(this.fieldsToXMLString(domMap));
}
sb.append("</class>");
String keyClassName = "GaitReEducation";
String externalSource = ims.configuration.EnvironmentConfig.getImportExportSourceName();
ims.configuration.ImportedObject impObj = (ims.configuration.ImportedObject)domMap.get(keyClassName + "_" + externalSource + "_" + this.getId());
if (impObj == null)
{
impObj = new ims.configuration.ImportedObject();
impObj.setExternalId(this.getId());
impObj.setExternalSource(externalSource);
impObj.setDomainObject(this);
impObj.setLocalId(this.getId());
impObj.setClassName(keyClassName);
domMap.put(keyClassName + "_" + externalSource + "_" + this.getId(), impObj);
}
return sb.toString();
}
public String fieldsToXMLString(java.util.HashMap domMap)
{
StringBuffer sb = new StringBuffer();
if (this.getClinicalContact() != null)
{
sb.append("<clinicalContact>");
sb.append(this.getClinicalContact().toXMLString(domMap));
sb.append("</clinicalContact>");
}
if (this.getAuthoringDateTime() != null)
{
sb.append("<authoringDateTime>");
sb.append(new ims.framework.utils.DateTime(this.getAuthoringDateTime()).toString(ims.framework.utils.DateTimeFormat.MILLI));
sb.append("</authoringDateTime>");
}
if (this.getAuthoringCP() != null)
{
sb.append("<authoringCP>");
sb.append(this.getAuthoringCP().toXMLString(domMap));
sb.append("</authoringCP>");
}
if (this.getGaitAspect() != null)
{
if (this.getGaitAspect().size() > 0 )
{
sb.append("<gaitAspect>");
sb.append(ims.domain.lookups.LookupInstance.toXMLString(this.getGaitAspect()));
sb.append("</gaitAspect>");
}
}
if (this.getDetails() != null)
{
sb.append("<details>");
sb.append(ims.framework.utils.StringUtils.encodeXML(this.getDetails().toString()));
sb.append("</details>");
}
return sb.toString();
}
public static java.util.List fromListXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.List list, java.util.HashMap domMap) throws Exception
{
if (list == null)
list = new java.util.ArrayList();
fillListFromXMLString(list, el, factory, domMap);
return list;
}
public static java.util.Set fromSetXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.Set set, java.util.HashMap domMap) throws Exception
{
if (set == null)
set = new java.util.HashSet();
fillSetFromXMLString(set, el, factory, domMap);
return set;
}
private static void fillSetFromXMLString(java.util.Set set, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
if (el == null)
return;
java.util.List cl = el.elements("class");
int size = cl.size();
java.util.Set newSet = new java.util.HashSet();
for(int i=0; i<size; i++)
{
org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i);
GaitReEducation domainObject = getGaitReEducationfromXML(itemEl, factory, domMap);
if (domainObject == null)
{
continue;
}
//Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add)
if (!set.contains(domainObject))
set.add(domainObject);
newSet.add(domainObject);
}
java.util.Set removedSet = new java.util.HashSet();
java.util.Iterator iter = set.iterator();
//Find out which objects need to be removed
while (iter.hasNext())
{
ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next();
if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o))
{
removedSet.add(o);
}
}
iter = removedSet.iterator();
//Remove the unwanted objects
while (iter.hasNext())
{
set.remove(iter.next());
}
}
private static void fillListFromXMLString(java.util.List list, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
if (el == null)
return;
java.util.List cl = el.elements("class");
int size = cl.size();
for(int i=0; i<size; i++)
{
org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i);
GaitReEducation domainObject = getGaitReEducationfromXML(itemEl, factory, domMap);
if (domainObject == null)
{
continue;
}
int domIdx = list.indexOf(domainObject);
if (domIdx == -1)
{
list.add(i, domainObject);
}
else if (i != domIdx && i < list.size())
{
Object tmp = list.get(i);
list.set(i, list.get(domIdx));
list.set(domIdx, tmp);
}
}
//Remove all ones in domList where index > voCollection.size() as these should
//now represent the ones removed from the VO collection. No longer referenced.
int i1=list.size();
while (i1 > size)
{
list.remove(i1-1);
i1=list.size();
}
}
public static GaitReEducation getGaitReEducationfromXML(String xml, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
org.dom4j.Document doc = new org.dom4j.io.SAXReader().read(new org.xml.sax.InputSource(xml));
return getGaitReEducationfromXML(doc.getRootElement(), factory, domMap);
}
public static GaitReEducation getGaitReEducationfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
if (el == null)
return null;
String className = el.attributeValue("type");
if (!GaitReEducation.class.getName().equals(className))
{
Class clz = Class.forName(className);
if (!GaitReEducation.class.isAssignableFrom(clz))
throw new Exception("Element of type = " + className + " cannot be imported using the GaitReEducation class");
String shortClassName = className.substring(className.lastIndexOf(".")+1);
String methodName = "get" + shortClassName + "fromXML";
java.lang.reflect.Method m = clz.getMethod(methodName, new Class[]{org.dom4j.Element.class, ims.domain.DomainFactory.class, java.util.HashMap.class});
return (GaitReEducation)m.invoke(null, new Object[]{el, factory, domMap});
}
String impVersion = el.attributeValue("classVersion");
if(!impVersion.equals(GaitReEducation.CLASSVERSION))
{
throw new Exception("Incompatible class structure found. Cannot import instance.");
}
GaitReEducation ret = null;
int extId = Integer.parseInt(el.attributeValue("id"));
String externalSource = el.attributeValue("source");
ret = (GaitReEducation)factory.getImportedDomainObject(GaitReEducation.class, externalSource, extId);
if (ret == null)
{
ret = new GaitReEducation();
}
String keyClassName = "GaitReEducation";
ims.configuration.ImportedObject impObj = (ims.configuration.ImportedObject)domMap.get(keyClassName + "_" + externalSource + "_" + extId);
if (impObj != null)
{
return (GaitReEducation)impObj.getDomainObject();
}
else
{
impObj = new ims.configuration.ImportedObject();
impObj.setExternalId(extId);
impObj.setExternalSource(externalSource);
impObj.setDomainObject(ret);
domMap.put(keyClassName + "_" + externalSource + "_" + extId, impObj);
}
fillFieldsfromXML(el, factory, ret, domMap);
return ret;
}
public static void fillFieldsfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, GaitReEducation obj, java.util.HashMap domMap) throws Exception
{
org.dom4j.Element fldEl;
fldEl = el.element("clinicalContact");
if(fldEl != null)
{
fldEl = fldEl.element("class");
obj.setClinicalContact(ims.core.admin.domain.objects.ClinicalContact.getClinicalContactfromXML(fldEl, factory, domMap));
}
fldEl = el.element("authoringDateTime");
if(fldEl != null)
{
obj.setAuthoringDateTime(new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").parse(fldEl.getTextTrim()));
}
fldEl = el.element("authoringCP");
if(fldEl != null)
{
fldEl = fldEl.element("class");
obj.setAuthoringCP(ims.core.resource.people.domain.objects.Hcp.getHcpfromXML(fldEl, factory, domMap));
}
fldEl = el.element("gaitAspect");
if(fldEl != null)
{
fldEl = fldEl.element("list");
obj.setGaitAspect(ims.domain.lookups.LookupInstance.fromListXMLString(fldEl, factory, obj.getGaitAspect()));
}
fldEl = el.element("details");
if(fldEl != null)
{
obj.setDetails(new String(fldEl.getTextTrim()));
}
}
public static String[] getCollectionFields()
{
return new String[]{
"gaitAspect"
};
}
public static class FieldNames
{
public static final String ID = "id";
public static final String ClinicalContact = "clinicalContact";
public static final String AuthoringDateTime = "authoringDateTime";
public static final String AuthoringCP = "authoringCP";
public static final String GaitAspect = "gaitAspect";
public static final String Details = "details";
}
}
| agpl-3.0 |
yukoff/concourse-connect | src/main/java/com/concursive/connect/web/modules/contribution/dao/LookupContribution.java | 9997 | /*
* ConcourseConnect
* Copyright 2009 Concursive Corporation
* http://www.concursive.com
*
* This file is part of ConcourseConnect, an open source social business
* software and community platform.
*
* Concursive ConcourseConnect is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, version 3 of the License.
*
* Under the terms of the GNU Affero General Public License you must release the
* complete source code for any application that uses any part of ConcourseConnect
* (system header files and libraries used by the operating system are excluded).
* These terms must be included in any work that has ConcourseConnect components.
* If you are developing and distributing open source applications under the
* GNU Affero General Public License, then you are free to use ConcourseConnect
* under the GNU Affero General Public License.
*
* If you are deploying a web site in which users interact with any portion of
* ConcourseConnect over a network, the complete source code changes must be made
* available. For example, include a link to the source archive directly from
* your web site.
*
* For OEMs, ISVs, SIs and VARs who distribute ConcourseConnect with their
* products, and do not license and distribute their source code under the GNU
* Affero General Public License, Concursive provides a flexible commercial
* license.
*
* To anyone in doubt, we recommend the commercial license. Our commercial license
* is competitively priced and will eliminate any confusion about how
* ConcourseConnect can be used and distributed.
*
* ConcourseConnect is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License
* along with ConcourseConnect. If not, see <http://www.gnu.org/licenses/>.
*
* Attribution Notice: ConcourseConnect is an Original Work of software created
* by Concursive Corporation
*/
package com.concursive.connect.web.modules.contribution.dao;
import com.concursive.commons.db.DatabaseUtils;
import com.concursive.commons.text.StringUtils;
import com.concursive.commons.web.mvc.beans.GenericBean;
import com.concursive.connect.web.modules.common.social.contribution.dao.UserContributionLogList;
import java.sql.*;
/**
* Handles viewing an object by a user
*
* @author Kailash Bhoopalam
* @created January 27, 2009
*/
public class LookupContribution extends GenericBean {
private int id = -1;
private String constant = null;
private String description = null;
private int level = 0;
private boolean enabled = true;
private Timestamp runDate = null;
private int pointsAwarded = 1;
public LookupContribution() {
}
public LookupContribution(Connection db, int id) throws SQLException {
queryRecord(db, id);
}
public LookupContribution(ResultSet rs) throws SQLException {
buildRecord(rs);
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
public void setId(String id) {
this.id = Integer.parseInt(id);
}
/**
* @return the constant
*/
public String getConstant() {
return constant;
}
/**
* @param constant the constant to set
*/
public void setConstant(String constant) {
this.constant = constant;
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
/**
* @param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* @return the level
*/
public int getLevel() {
return level;
}
/**
* @param level the level to set
*/
public void setLevel(int level) {
this.level = level;
}
public void setLevel(String level) {
this.level = Integer.parseInt(level);
}
/**
* @return the enabled
*/
public boolean getEnabled() {
return enabled;
}
/**
* @param enabled the enabled to set
*/
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
/**
* @return the runDate
*/
public Timestamp getRunDate() {
return runDate;
}
/**
* @param runDate the runDate to set
*/
public void setRunDate(Timestamp runDate) {
this.runDate = runDate;
}
public void setRunDate(String runDate) {
this.runDate = DatabaseUtils.parseTimestamp(runDate);
}
/**
* @return the pointsAwarded
*/
public int getPointsAwarded() {
return pointsAwarded;
}
/**
* @param pointsAwarded the pointsAwarded to set
*/
public void setPointsAwarded(int pointsAwarded) {
this.pointsAwarded = pointsAwarded;
}
public void setPointsAwarded(String pointsAwarded) {
this.pointsAwarded = Integer.parseInt(pointsAwarded);
}
public void queryRecord(Connection db, int id) throws SQLException {
StringBuffer sql = new StringBuffer();
sql.append(
"SELECT lc.* " +
"FROM lookup_contribution lc " +
"WHERE code = ? ");
PreparedStatement pst = db.prepareStatement(sql.toString());
int i = 0;
pst.setInt(++i, id);
ResultSet rs = pst.executeQuery();
if (rs.next()) {
buildRecord(rs);
}
rs.close();
pst.close();
if (id == -1) {
throw new SQLException("Contribution record not found.");
}
}
public boolean insert(Connection db) throws SQLException {
if (!isValid()) {
return false;
}
StringBuffer sql = new StringBuffer();
sql.append(
"INSERT INTO lookup_contribution " +
"(" + (id > -1 ? "code," : "") +
(runDate != null ? "run_date, " : "") +
"constant, description, level, enabled, points_awarded )");
sql.append("VALUES (");
if (id > -1) {
sql.append("?,");
}
if (runDate != null) {
sql.append("?,");
}
sql.append("?, ?, ?, ?, ? )");
int i = 0;
boolean commit = db.getAutoCommit();
try {
if (commit) {
db.setAutoCommit(false);
}
//Insert the topic
PreparedStatement pst = db.prepareStatement(sql.toString());
if (id > -1) {
pst.setInt(++i, id);
}
if (runDate != null) {
pst.setTimestamp(++i, runDate);
}
pst.setString(++i, constant);
pst.setString(++i, description);
pst.setInt(++i, level);
pst.setBoolean(++i, enabled);
pst.setInt(++i, pointsAwarded);
pst.execute();
pst.close();
id = DatabaseUtils.getCurrVal(db, "lookup_contribution_code_seq", -1);
if (commit) {
db.commit();
}
} catch (SQLException e) {
if (commit) {
db.rollback();
}
throw e;
} finally {
if (commit) {
db.setAutoCommit(true);
}
}
return true;
}
public int update(Connection db) throws SQLException {
if (this.getId() == -1) {
throw new SQLException("ID was not specified");
}
if (!isValid()) {
return -1;
}
// Update the project
int resultCount = 0;
PreparedStatement pst = db.prepareStatement(
"UPDATE lookup_contribution SET " +
(runDate != null ? "run_date = ?, " : "") +
" constant = ? , " +
" description = ? , " +
" level = ? , " +
" enabled = ? , " +
" points_awarded = ? " +
"WHERE code = ? ");
int i = 0;
if (runDate != null) {
pst.setTimestamp(++i, runDate);
}
pst.setString(++i, constant);
pst.setString(++i, description);
pst.setInt(++i, level);
pst.setBoolean(++i, enabled);
pst.setInt(++i, pointsAwarded);
pst.setInt(++i, id);
resultCount = pst.executeUpdate();
pst.close();
return resultCount;
}
public boolean delete(Connection db) throws SQLException {
if (this.getId() == -1) {
throw new SQLException("ID was not specified");
}
int recordCount = 0;
boolean commit = db.getAutoCommit();
try {
if (commit) {
db.setAutoCommit(false);
}
UserContributionLogList userContributionLogList = new UserContributionLogList();
userContributionLogList.setContributionId(id);
userContributionLogList.buildList(db);
userContributionLogList.delete(db);
//Delete the private message
PreparedStatement pst = db.prepareStatement(
"DELETE FROM lookup_contribution " +
"WHERE code = ? ");
pst.setInt(1, id);
recordCount = pst.executeUpdate();
pst.close();
if (commit) {
db.commit();
}
} catch (Exception e) {
if (commit) {
db.rollback();
}
e.printStackTrace(System.out);
throw new SQLException(e.getMessage());
} finally {
if (commit) {
db.setAutoCommit(true);
}
}
if (recordCount == 0) {
errors.put("actionError", "Contribution could not be deleted because it no longer exists.");
return false;
} else {
return true;
}
}
private boolean isValid() {
if (!StringUtils.hasText(constant)) {
errors.put("constantError", "Constant is required");
}
if (!StringUtils.hasText(description)) {
errors.put("descriptionError", "Description is required");
}
return !this.hasErrors();
}
/**
* @param rs
*/
private void buildRecord(ResultSet rs) throws SQLException {
id = rs.getInt("code");
constant = rs.getString("constant");
description = rs.getString("description");
level = rs.getInt("level");
enabled = rs.getBoolean("enabled");
runDate = rs.getTimestamp("run_date");
pointsAwarded = rs.getInt("points_awarded");
}
} | agpl-3.0 |
NicolasEYSSERIC/Silverpeas-Components | classifieds/classifieds-war/src/main/java/com/silverpeas/classifieds/servlets/ClassifiedsRequestRouter.java | 4904 | /**
* Copyright (C) 2000 - 2011 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have recieved a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://repository.silverpeas.com/legal/licensing"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.silverpeas.classifieds.servlets;
import com.silverpeas.classifieds.control.ClassifiedsRole;
import com.silverpeas.classifieds.control.ClassifiedsSessionController;
import com.silverpeas.classifieds.servlets.handler.HandlerProvider;
import com.silverpeas.look.LookHelper;
import com.stratelia.silverpeas.peasCore.ComponentContext;
import com.stratelia.silverpeas.peasCore.MainSessionController;
import com.stratelia.silverpeas.peasCore.servlets.ComponentRequestRouter;
import com.stratelia.silverpeas.silvertrace.SilverTrace;
import javax.servlet.http.HttpServletRequest;
public class ClassifiedsRequestRouter extends ComponentRequestRouter<ClassifiedsSessionController> {
private static final long serialVersionUID = -4872776979680116068L;
/**
* This method has to be implemented in the component request rooter class. returns the session
* control bean name to be put in the request object ex : for almanach, returns "almanach"
*/
@Override
public String getSessionControlBeanName() {
return "classifieds";
}
/**
* Method declaration
*
* @param mainSessionCtrl
* @param componentContext
* @return
* @see
*/
@Override
public ClassifiedsSessionController createComponentSessionController(
MainSessionController mainSessionCtrl, ComponentContext componentContext) {
return new ClassifiedsSessionController(mainSessionCtrl, componentContext);
}
/**
* This method has to be implemented by the component request rooter it has to compute a
* destination page
*
* @param function The entering request function (ex : "Main.jsp")
* @param classifiedsSC The component Session Control, build and initialised.
* @return The complete destination URL for a forward (ex : "/almanach/jsp/almanach.jsp?flag=user")
*/
@Override
public String getDestination(String function, ClassifiedsSessionController classifiedsSC,
HttpServletRequest request) {
String destination = "";
String rootDest = "/classifieds/jsp/";
SilverTrace.info("classifieds", "classifiedsRequestRouter.getDestination()",
"root.MSG_GEN_PARAM_VALUE", "User=" + classifiedsSC.getUserId() + " Function=" + function);
// Common parameters
ClassifiedsRole highestRole = (isAnonymousAccess(request)) ? ClassifiedsRole.ANONYMOUS :
ClassifiedsRole.getRole(classifiedsSC.getUserRoles());
String userId = classifiedsSC.getUserId();
// Store them in request as attributes
request.setAttribute("Profile", highestRole);
request.setAttribute("UserId", userId);
request.setAttribute("InstanceId", classifiedsSC.getComponentId());
request.setAttribute("Language", classifiedsSC.getLanguage());
request.setAttribute("isWysiwygHeaderEnabled", classifiedsSC.isWysiwygHeaderEnabled());
SilverTrace.debug("classifieds", "classifiedsRequestRouter.getDestination()",
"root.MSG_GEN_PARAM_VALUE", "Profile=" + highestRole);
// Delegate to specific Handler
FunctionHandler handler = HandlerProvider.getHandler(function);
if (handler != null) {
destination = handler.computeDestination(classifiedsSC, request);
} else {
destination = rootDest + function;
}
SilverTrace.info("classifieds", "classifiedsRequestRouter.getDestination()",
"root.MSG_GEN_PARAM_VALUE", "Destination=" + destination);
return destination;
}
private boolean isAnonymousAccess(HttpServletRequest request) {
LookHelper lookHelper = (LookHelper) request.getSession().getAttribute(LookHelper.SESSION_ATT);
if (lookHelper != null) {
return lookHelper.isAnonymousAccess();
}
return false;
}
} | agpl-3.0 |
AlienQueen/alienlabs-skeleton-for-wicket-spring-hibernate | lib/fmj/src/net/sf/fmj/media/codec/audio/ulaw/Encoder.java | 5114 | package net.sf.fmj.media.codec.audio.ulaw;
import java.util.logging.Logger;
import javax.media.Buffer;
import javax.media.Format;
import javax.media.format.AudioFormat;
import net.sf.fmj.codegen.MediaCGUtils;
import net.sf.fmj.media.AbstractCodec;
import net.sf.fmj.utility.LoggerSingleton;
/**
*
* @author Ken Larson
*
*/
public class Encoder extends AbstractCodec
{
private static final Logger logger = LoggerSingleton.logger;
public String getName()
{
return "ULAW Encoder";
}
public Encoder()
{
super();
this.inputFormats = new Format[] {
new AudioFormat(AudioFormat.LINEAR, -1.0, 16, 1, -1, AudioFormat.SIGNED, 16, -1.0, Format.byteArray),
//new AudioFormat(AudioFormat.LINEAR, -1.0, 8, 1, -1, AudioFormat.SIGNED, 8, -1.0, Format.byteArray)
// using 8 bit input is kind of silly, since the whole point of ulaw is to encode 16 bits as 8 bits.
// the quality will be bad, and we are better off using a rate converter to do all of the rate conversion at once.
};
// TODO: if force AudioFormat.LITTLE_ENDIAN, codecs leading up to this seem to freeze up or something.
}
// TODO: move to base class?
protected Format[] outputFormats = new Format[] {new AudioFormat(AudioFormat.ULAW, -1.0, 8, 1, -1, AudioFormat.SIGNED, 8, -1.0, Format.byteArray)};
public Format[] getSupportedOutputFormats(Format input)
{
if (input == null)
return outputFormats;
else
{
if (!(input instanceof AudioFormat))
{ logger.warning(this.getClass().getSimpleName() + ".getSupportedOutputFormats: input format does not match, returning format array of {null} for " + input); // this can cause an NPE in JMF if it ever happens.
return new Format[] {null};
}
final AudioFormat inputCast = (AudioFormat) input;
if (!inputCast.getEncoding().equals(AudioFormat.LINEAR) ||
(inputCast.getSampleSizeInBits() != 16 && inputCast.getSampleSizeInBits() != Format.NOT_SPECIFIED) ||
(inputCast.getChannels() != 1 && inputCast.getChannels() != Format.NOT_SPECIFIED) ||
(inputCast.getSigned() != AudioFormat.SIGNED && inputCast.getSigned() != Format.NOT_SPECIFIED) ||
(inputCast.getFrameSizeInBits() != 16 && inputCast.getFrameSizeInBits() != Format.NOT_SPECIFIED) ||
(inputCast.getDataType() != null && inputCast.getDataType() != Format.byteArray)
)
{
logger.warning(this.getClass().getSimpleName() + ".getSupportedOutputFormats: input format does not match, returning format array of {null} for " + input); // this can cause an NPE in JMF if it ever happens.
return new Format[] {null};
}
final AudioFormat result = new AudioFormat(AudioFormat.ULAW, inputCast.getSampleRate(), 8,
1, -1, AudioFormat.SIGNED, 8, // endian-ness irrelevant for 8 bits
inputCast.getFrameRate(), Format.byteArray);
return new Format[] {result};
}
}
public void open()
{
}
public void close()
{
}
private static final boolean TRACE = false;
public int process(Buffer inputBuffer, Buffer outputBuffer)
{
if (TRACE) dump("input ", inputBuffer);
if (!checkInputBuffer(inputBuffer))
{
return BUFFER_PROCESSED_FAILED;
}
if (isEOM(inputBuffer))
{
propagateEOM(outputBuffer); // TODO: what about data? can there be any?
return BUFFER_PROCESSED_OK;
}
final AudioFormat inputAudioFormat = (AudioFormat) inputBuffer.getFormat();
byte[] outputBufferData = (byte []) outputBuffer.getData();
final int requiredOutputBufferLength = inputBuffer.getLength() / 2;
if (outputBufferData == null || outputBufferData.length < requiredOutputBufferLength)
{ outputBufferData = new byte[requiredOutputBufferLength];
outputBuffer.setData(outputBufferData);
}
if (!inputAudioFormat.equals(inputFormat))
throw new RuntimeException("Incorrect inpout format");
if (inputAudioFormat.getEndian() == -1)
throw new RuntimeException("Unspecified endian-ness"); // TODO: check in setInputFormat
final boolean bigEndian = inputAudioFormat.getEndian() == AudioFormat.BIG_ENDIAN;
MuLawEncoderUtil.muLawEncode(bigEndian, (byte []) inputBuffer.getData(), inputBuffer.getOffset(), inputBuffer.getLength(), outputBufferData);
outputBuffer.setLength(requiredOutputBufferLength);
outputBuffer.setOffset(0);
outputBuffer.setFormat(outputFormat);
final int result = BUFFER_PROCESSED_OK;
if (TRACE)
{ dump("input ", inputBuffer);
dump("output", outputBuffer);
System.out.println("Result=" + MediaCGUtils.plugInResultToStr(result));
}
return result;
}
public Format setInputFormat(Format arg0)
{
// TODO: force sample size, etc
if (TRACE) System.out.println("setInputFormat: " + MediaCGUtils.formatToStr(arg0));
return super.setInputFormat(arg0);
}
public Format setOutputFormat(Format arg0)
{
if (TRACE) System.out.println("setOutputFormat: " + MediaCGUtils.formatToStr(arg0));
return super.setOutputFormat(arg0);
}
}
| agpl-3.0 |
objective-solutions/taskboard | application/src/test/java/objective/taskboard/followup/TemplateServiceTest.java | 3089 | /*-
* [LICENSE]
* Taskboard
* - - -
* Copyright (C) 2015 - 2016 Objective Solutions
* - - -
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* [/LICENSE]
*/
package objective.taskboard.followup;
import static java.util.Arrays.asList;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import objective.taskboard.followup.data.Template;
import objective.taskboard.repository.TemplateRepository;
@RunWith(SpringRunner.class)
@DataJpaTest
@ContextConfiguration(classes = TemplateServiceTest.Configuration.class)
public class TemplateServiceTest {
@EntityScan(
basePackageClasses = {Template.class})
public static class Configuration {
@Bean
public JpaRepositoryFactoryBean<TemplateRepository, Template, Long> templateRepository() {
return new JpaRepositoryFactoryBean<>(TemplateRepository.class);
}
@Bean
public TemplateService templateService() {
return new DefaultTemplateService();
}
}
@Autowired
private TemplateService templateService;
@Test
public void givenTemplate_whenGetTemplates_thenReturnOneResult() {
// given
repositoryHasTemplate();
// when
List<Template> result = templateService.getTemplates();
// then
assertThat(result, hasSize(1));
}
@Test
public void givenNoTemplate_whenGetTemplates_thenReturnNoResults() {
// when
List<Template> result = templateService.getTemplates();
// then
assertThat(result, hasSize(0));
}
private void repositoryHasTemplate() {
String templateName = "Test Template";
String templatePath = "test-path";
try {
templateService.saveTemplate(templateName, asList("Role"), templatePath);
} catch (IOException e) {
e.printStackTrace();
}
}
} | agpl-3.0 |
dbenrosen/EtherPay | ethereumj-core/src/test/java/org/ethereum/util/ByteUtilTest.java | 16475 | package org.ethereum.util;
import org.junit.Assert;
import org.junit.Test;
import org.spongycastle.util.BigIntegers;
import org.spongycastle.util.encoders.Hex;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
public class ByteUtilTest {
@Test
public void testAppendByte() {
byte[] bytes = "tes".getBytes();
byte b = 0x74;
Assert.assertArrayEquals("test".getBytes(), ByteUtil.appendByte(bytes, b));
}
@Test
public void testBigIntegerToBytes() {
byte[] expecteds = new byte[]{(byte) 0xff, (byte) 0xec, 0x78};
BigInteger b = BigInteger.valueOf(16772216);
byte[] actuals = ByteUtil.bigIntegerToBytes(b);
assertArrayEquals(expecteds, actuals);
}
@Test
public void testBigIntegerToBytesSign() {
{
BigInteger b = BigInteger.valueOf(-2);
byte[] actuals = ByteUtil.bigIntegerToBytesSigned(b, 8);
assertArrayEquals(Hex.decode("fffffffffffffffe"), actuals);
}
{
BigInteger b = BigInteger.valueOf(2);
byte[] actuals = ByteUtil.bigIntegerToBytesSigned(b, 8);
assertArrayEquals(Hex.decode("0000000000000002"), actuals);
}
{
BigInteger b = BigInteger.valueOf(0);
byte[] actuals = ByteUtil.bigIntegerToBytesSigned(b, 8);
assertArrayEquals(Hex.decode("0000000000000000"), actuals);
}
{
BigInteger b = new BigInteger("eeeeeeeeeeeeee", 16);
byte[] actuals = ByteUtil.bigIntegerToBytesSigned(b, 8);
assertArrayEquals(Hex.decode("00eeeeeeeeeeeeee"), actuals);
}
{
BigInteger b = new BigInteger("eeeeeeeeeeeeeeee", 16);
byte[] actuals = ByteUtil.bigIntegerToBytesSigned(b, 8);
assertArrayEquals(Hex.decode("eeeeeeeeeeeeeeee"), actuals);
}
}
@Test
public void testBigIntegerToBytesNegative() {
byte[] expecteds = new byte[]{(byte) 0xff, 0x0, 0x13, (byte) 0x88};
BigInteger b = BigInteger.valueOf(-16772216);
byte[] actuals = ByteUtil.bigIntegerToBytes(b);
assertArrayEquals(expecteds, actuals);
}
@Test
public void testBigIntegerToBytesZero() {
byte[] expecteds = new byte[]{0x00};
BigInteger b = BigInteger.ZERO;
byte[] actuals = ByteUtil.bigIntegerToBytes(b);
assertArrayEquals(expecteds, actuals);
}
@Test
public void testToHexString() {
assertEquals("", ByteUtil.toHexString(null));
}
@Test
public void testCalcPacketLength() {
byte[] test = new byte[]{0x0f, 0x10, 0x43};
byte[] expected = new byte[]{0x00, 0x00, 0x00, 0x03};
assertArrayEquals(expected, ByteUtil.calcPacketLength(test));
}
@Test
public void testByteArrayToInt() {
assertEquals(0, ByteUtil.byteArrayToInt(null));
assertEquals(0, ByteUtil.byteArrayToInt(new byte[0]));
// byte[] x = new byte[] { 5,1,7,0,8 };
// long start = System.currentTimeMillis();
// for (int i = 0; i < 100000000; i++) {
// ByteArray.read32bit(x, 0);
// }
// long end = System.currentTimeMillis();
// System.out.println(end - start + "ms");
//
// long start1 = System.currentTimeMillis();
// for (int i = 0; i < 100000000; i++) {
// new BigInteger(1, x).intValue();
// }
// long end1 = System.currentTimeMillis();
// System.out.println(end1 - start1 + "ms");
}
@Test
public void testNumBytes() {
String test1 = "0";
String test2 = "1";
String test3 = "1000000000"; //3B9ACA00
int expected1 = 1;
int expected2 = 1;
int expected3 = 4;
assertEquals(expected1, ByteUtil.numBytes(test1));
assertEquals(expected2, ByteUtil.numBytes(test2));
assertEquals(expected3, ByteUtil.numBytes(test3));
}
@Test
public void testStripLeadingZeroes() {
byte[] test1 = null;
byte[] test2 = new byte[]{};
byte[] test3 = new byte[]{0x00};
byte[] test4 = new byte[]{0x00, 0x01};
byte[] test5 = new byte[]{0x00, 0x00, 0x01};
byte[] expected1 = null;
byte[] expected2 = new byte[]{0};
byte[] expected3 = new byte[]{0};
byte[] expected4 = new byte[]{0x01};
byte[] expected5 = new byte[]{0x01};
assertArrayEquals(expected1, ByteUtil.stripLeadingZeroes(test1));
assertArrayEquals(expected2, ByteUtil.stripLeadingZeroes(test2));
assertArrayEquals(expected3, ByteUtil.stripLeadingZeroes(test3));
assertArrayEquals(expected4, ByteUtil.stripLeadingZeroes(test4));
assertArrayEquals(expected5, ByteUtil.stripLeadingZeroes(test5));
}
@Test
public void testMatchingNibbleLength1() {
// a larger than b
byte[] a = new byte[]{0x00, 0x01};
byte[] b = new byte[]{0x00};
int result = ByteUtil.matchingNibbleLength(a, b);
assertEquals(1, result);
}
@Test
public void testMatchingNibbleLength2() {
// b larger than a
byte[] a = new byte[]{0x00};
byte[] b = new byte[]{0x00, 0x01};
int result = ByteUtil.matchingNibbleLength(a, b);
assertEquals(1, result);
}
@Test
public void testMatchingNibbleLength3() {
// a and b the same length equal
byte[] a = new byte[]{0x00};
byte[] b = new byte[]{0x00};
int result = ByteUtil.matchingNibbleLength(a, b);
assertEquals(1, result);
}
@Test
public void testMatchingNibbleLength4() {
// a and b the same length not equal
byte[] a = new byte[]{0x01};
byte[] b = new byte[]{0x00};
int result = ByteUtil.matchingNibbleLength(a, b);
assertEquals(0, result);
}
@Test
public void testNiceNiblesOutput_1() {
byte[] test = {7, 0, 7, 5, 7, 0, 7, 0, 7, 9};
String result = "\\x07\\x00\\x07\\x05\\x07\\x00\\x07\\x00\\x07\\x09";
assertEquals(result, ByteUtil.nibblesToPrettyString(test));
}
@Test
public void testNiceNiblesOutput_2() {
byte[] test = {7, 0, 7, 0xf, 7, 0, 0xa, 0, 7, 9};
String result = "\\x07\\x00\\x07\\x0f\\x07\\x00\\x0a\\x00\\x07\\x09";
assertEquals(result, ByteUtil.nibblesToPrettyString(test));
}
@Test(expected = NullPointerException.class)
public void testMatchingNibbleLength5() {
// a == null
byte[] a = null;
byte[] b = new byte[]{0x00};
ByteUtil.matchingNibbleLength(a, b);
}
@Test(expected = NullPointerException.class)
public void testMatchingNibbleLength6() {
// b == null
byte[] a = new byte[]{0x00};
byte[] b = null;
ByteUtil.matchingNibbleLength(a, b);
}
@Test
public void testMatchingNibbleLength7() {
// a or b is empty
byte[] a = new byte[0];
byte[] b = new byte[]{0x00};
int result = ByteUtil.matchingNibbleLength(a, b);
assertEquals(0, result);
}
/**
* This test shows the difference between iterating over,
* and comparing byte[] vs BigInteger value.
*
* Results indicate that the former has ~15x better performance.
* Therefore this is used in the Miner.mine() method.
*/
@Test
public void testIncrementPerformance() {
boolean testEnabled = false;
if (testEnabled) {
byte[] counter1 = new byte[4];
byte[] max = ByteBuffer.allocate(4).putInt(Integer.MAX_VALUE).array();
long start1 = System.currentTimeMillis();
while (ByteUtil.increment(counter1)) {
if (FastByteComparisons.compareTo(counter1, 0, 4, max, 0, 4) == 0) {
break;
}
}
System.out.println(System.currentTimeMillis() - start1 + "ms to reach: " + Hex.toHexString(counter1));
BigInteger counter2 = BigInteger.ZERO;
long start2 = System.currentTimeMillis();
while (true) {
if (counter2.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) == 0) {
break;
}
counter2 = counter2.add(BigInteger.ONE);
}
System.out.println(System.currentTimeMillis() - start2 + "ms to reach: " + Hex.toHexString(BigIntegers.asUnsignedByteArray(4, counter2)));
}
}
@Test
public void firstNonZeroByte_1() {
byte[] data = Hex.decode("0000000000000000000000000000000000000000000000000000000000000000");
int result = ByteUtil.firstNonZeroByte(data);
assertEquals(-1, result);
}
@Test
public void firstNonZeroByte_2() {
byte[] data = Hex.decode("0000000000000000000000000000000000000000000000000000000000332211");
int result = ByteUtil.firstNonZeroByte(data);
assertEquals(29, result);
}
@Test
public void firstNonZeroByte_3() {
byte[] data = Hex.decode("2211009988776655443322110099887766554433221100998877665544332211");
int result = ByteUtil.firstNonZeroByte(data);
assertEquals(0, result);
}
@Test
public void setBitTest() {
/*
Set on
*/
byte[] data = ByteBuffer.allocate(4).putInt(0).array();
int posBit = 24;
int expected = 16777216;
int result = -1;
byte[] ret = ByteUtil.setBit(data, posBit, 1);
result = ByteUtil.byteArrayToInt(ret);
assertTrue(expected == result);
posBit = 25;
expected = 50331648;
ret = ByteUtil.setBit(data, posBit, 1);
result = ByteUtil.byteArrayToInt(ret);
assertTrue(expected == result);
posBit = 2;
expected = 50331652;
ret = ByteUtil.setBit(data, posBit, 1);
result = ByteUtil.byteArrayToInt(ret);
assertTrue(expected == result);
/*
Set off
*/
posBit = 24;
expected = 33554436;
ret = ByteUtil.setBit(data, posBit, 0);
result = ByteUtil.byteArrayToInt(ret);
assertTrue(expected == result);
posBit = 25;
expected = 4;
ret = ByteUtil.setBit(data, posBit, 0);
result = ByteUtil.byteArrayToInt(ret);
assertTrue(expected == result);
posBit = 2;
expected = 0;
ret = ByteUtil.setBit(data, posBit, 0);
result = ByteUtil.byteArrayToInt(ret);
assertTrue(expected == result);
}
@Test
public void getBitTest() {
byte[] data = ByteBuffer.allocate(4).putInt(0).array();
ByteUtil.setBit(data, 24, 1);
ByteUtil.setBit(data, 25, 1);
ByteUtil.setBit(data, 2, 1);
List<Integer> found = new ArrayList<>();
for (int i = 0; i < (data.length * 8); i++) {
int res = ByteUtil.getBit(data, i);
if (res == 1)
if (i != 24 && i != 25 && i != 2)
assertTrue(false);
else
found.add(i);
else {
if (i == 24 || i == 25 || i == 2)
assertTrue(false);
}
}
if (found.size() != 3)
assertTrue(false);
assertTrue(found.get(0) == 2);
assertTrue(found.get(1) == 24);
assertTrue(found.get(2) == 25);
}
@Test
public void numToBytesTest() {
byte[] bytes = ByteUtil.intToBytesNoLeadZeroes(-1);
assertArrayEquals(bytes, Hex.decode("ffffffff"));
bytes = ByteUtil.intToBytesNoLeadZeroes(1);
assertArrayEquals(bytes, Hex.decode("01"));
bytes = ByteUtil.intToBytesNoLeadZeroes(255);
assertArrayEquals(bytes, Hex.decode("ff"));
bytes = ByteUtil.intToBytesNoLeadZeroes(256);
assertArrayEquals(bytes, Hex.decode("0100"));
bytes = ByteUtil.intToBytesNoLeadZeroes(0);
assertArrayEquals(bytes, new byte[0]);
bytes = ByteUtil.intToBytes(-1);
assertArrayEquals(bytes, Hex.decode("ffffffff"));
bytes = ByteUtil.intToBytes(1);
assertArrayEquals(bytes, Hex.decode("00000001"));
bytes = ByteUtil.intToBytes(255);
assertArrayEquals(bytes, Hex.decode("000000ff"));
bytes = ByteUtil.intToBytes(256);
assertArrayEquals(bytes, Hex.decode("00000100"));
bytes = ByteUtil.intToBytes(0);
assertArrayEquals(bytes, Hex.decode("00000000"));
bytes = ByteUtil.longToBytesNoLeadZeroes(-1);
assertArrayEquals(bytes, Hex.decode("ffffffffffffffff"));
bytes = ByteUtil.longToBytesNoLeadZeroes(1);
assertArrayEquals(bytes, Hex.decode("01"));
bytes = ByteUtil.longToBytesNoLeadZeroes(255);
assertArrayEquals(bytes, Hex.decode("ff"));
bytes = ByteUtil.longToBytesNoLeadZeroes(1L << 32);
assertArrayEquals(bytes, Hex.decode("0100000000"));
bytes = ByteUtil.longToBytesNoLeadZeroes(0);
assertArrayEquals(bytes, new byte[0]);
bytes = ByteUtil.longToBytes(-1);
assertArrayEquals(bytes, Hex.decode("ffffffffffffffff"));
bytes = ByteUtil.longToBytes(1);
assertArrayEquals(bytes, Hex.decode("0000000000000001"));
bytes = ByteUtil.longToBytes(255);
assertArrayEquals(bytes, Hex.decode("00000000000000ff"));
bytes = ByteUtil.longToBytes(256);
assertArrayEquals(bytes, Hex.decode("0000000000000100"));
bytes = ByteUtil.longToBytes(0);
assertArrayEquals(bytes, Hex.decode("0000000000000000"));
}
@Test
public void testHexStringToBytes() {
{
String str = "0000";
byte[] actuals = ByteUtil.hexStringToBytes(str);
byte[] expected = new byte[] {0, 0};
assertArrayEquals(expected, actuals);
}
{
String str = "0x0000";
byte[] actuals = ByteUtil.hexStringToBytes(str);
byte[] expected = new byte[] {0, 0};
assertArrayEquals(expected, actuals);
}
{
String str = "0x45a6";
byte[] actuals = ByteUtil.hexStringToBytes(str);
byte[] expected = new byte[] {69, -90};
assertArrayEquals(expected, actuals);
}
{
String str = "1963093cee500c081443e1045c40264b670517af";
byte[] actuals = ByteUtil.hexStringToBytes(str);
byte[] expected = Hex.decode(str);
assertArrayEquals(expected, actuals);
}
{
String str = "0x"; // Empty
byte[] actuals = ByteUtil.hexStringToBytes(str);
byte[] expected = new byte[] {};
assertArrayEquals(expected, actuals);
}
{
String str = "0"; // Same as 0x00
byte[] actuals = ByteUtil.hexStringToBytes(str);
byte[] expected = new byte[] {0};
assertArrayEquals(expected, actuals);
}
{
String str = "0x00"; // This case shouldn't be empty array
byte[] actuals = ByteUtil.hexStringToBytes(str);
byte[] expected = new byte[] {0};
assertArrayEquals(expected, actuals);
}
{
String str = "0xd"; // Should work with odd length, adding leading 0
byte[] actuals = ByteUtil.hexStringToBytes(str);
byte[] expected = new byte[] {13};
assertArrayEquals(expected, actuals);
}
{
String str = "0xd0d"; // Should work with odd length, adding leading 0
byte[] actuals = ByteUtil.hexStringToBytes(str);
byte[] expected = new byte[] {13, 13};
assertArrayEquals(expected, actuals);
}
}
@Test
public void testIpConversion() {
String ip1 = "0.0.0.0";
byte[] ip1Bytes = ByteUtil.hostToBytes(ip1);
assertEquals(ip1, ByteUtil.bytesToIp(ip1Bytes));
String ip2 = "35.36.37.138";
byte[] ip2Bytes = ByteUtil.hostToBytes(ip2);
assertEquals(ip2, ByteUtil.bytesToIp(ip2Bytes));
String ip3 = "255.255.255.255";
byte[] ip3Bytes = ByteUtil.hostToBytes(ip3);
assertEquals(ip3, ByteUtil.bytesToIp(ip3Bytes));
// Fallback case
String ip4 = "255.255.255.256";
byte[] ip4Bytes = ByteUtil.hostToBytes(ip4);
assertEquals("0.0.0.0", ByteUtil.bytesToIp(ip4Bytes));
}
}
| agpl-3.0 |
1fechner/FeatureExtractor | sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-core/src/main/java/org/hibernate/tuple/Property.java | 605 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.tuple;
/**
* Defines the basic contract of a Property within the runtime metamodel.
*
* @author Steve Ebersole
*
* @deprecated Use the direct {@link Attribute} hierarchy
*/
@Deprecated
public interface Property extends Attribute {
/**
* @deprecated DOM4j entity mode is no longer supported
*/
@Deprecated
public String getNode();
}
| lgpl-2.1 |
Dyrcona/marc4j | src/org/marc4j/util/DiffColorize.java | 9391 | package org.marc4j.util;
public class DiffColorize
{
static class ReturnStructure {
int lcs = 0;
double similarity = 0;
int distance = 0;
String s1;
String s2;
}
public static ReturnStructure stringSimilarity(String s1, String s2, String h1s, String h1e, String h2s, String h2e, int maxOffset)
{
int c = 0;
int offset1 = 0;
int offset2 = 0;
int lcs = 0;
// These two strings will contain the "highlighted" version
StringBuffer _s1 = new StringBuffer(s1.length() * 3);
StringBuffer _s2 = new StringBuffer(s2.length() * 3);
// These characters will surround differences in the strings
// (Inserted into _s1 and _s2)
ReturnStructure return_struct = new ReturnStructure();
// If both strings are empty
if (s1.trim().length() == 0 && s2.trim().length() == 0)
{
return_struct.lcs = 0;
return_struct.similarity = 1;
return_struct.distance = 0;
return_struct.s1 = "";
return_struct.s2 = "";
return return_struct;
}
// If s2 is empty, but s1 isn't
if (s1.trim().length() > 0 && s2.trim().length() == 0)
{
return_struct.lcs = 0;
return_struct.similarity = 0;
return_struct.distance = s1.length();
return_struct.s1 = h1s + s1 + h1e;
return_struct.s2 = "";
return return_struct;
}
// If s1 is empty, but s2 isn't
else if (s1.trim().length() == 0 && s2.trim().length() > 0)
{
return_struct.lcs = 0;
return_struct.similarity = 0;
return_struct.distance = s2.length();
return_struct.s1 = "";
return_struct.s2 = h2s + s2 + h2e;
return return_struct;
}
// Examine the strings, one character at a time, anding at the shortest string
// The offset adjusts for extra characters in either string.
while ((c + offset1 < s1.length()) && (c + offset2 < s2.length()))
{
// Pull the next characters out of s1 and s2
String next_s1 = substring(s1, c + offset1, (c == 0 ? 3 : 1)); // First time through check the first three
String next_s2 = substring(s2, c + offset2, (c == 0 ? 3 : 1)); // First time through check the first three
// If they are equal
if (next_s1.compareTo(next_s2) == 0)
{
// Our longeset Common String just got one bigger
lcs = lcs + 1;
// Append the characters onto the "highlighted" version
_s1.append(substring(next_s1, 0, 1));
_s2.append(substring(next_s2, 0, 1));
}
// The next two characters did not match
// Now we will go into a sub-loop while we attempt to
// find our place again. We will only search as long as
// our maxOffset allows us to.
else
{
// Don't reset the offsets, just back them up so you
// have a point of reference
int old_offset1 = offset1;
int old_offset2 = offset2;
String _s1_deviation = "";
String _s2_deviation = "";
// Loop for as long as allowed by our offset
// to see if we can match up again
for (int i = 0; i < maxOffset; i = i+1)
{
next_s1 = substring(s1, c + offset1 + i, 3); // Increments each time through.
int len_next_s1 = next_s1.length();
String bookmarked_s1 = substring(s1, c + offset1, 3); // stays the same
next_s2 = substring(s2, c + offset2 + i, 3); // Increments each time through.
int len_next_s2 = next_s2.length();
String bookmarked_s2 = substring(s2, c + offset2, 3); // stays the same
// If we reached the end of both of the strings
if(next_s1.length() == 0 && next_s2.length() == 0)
{
// Quit
break;
}
// These variables keep track of how far we have deviated in the
// string while trying to find our match again.
_s1_deviation = _s1_deviation + substring(next_s1, 0, 1);
_s2_deviation = _s2_deviation + substring(next_s2, 0, 1);
// It looks like s1 has a match down the line which fits
// where we left off in s2
if (next_s1.equals(bookmarked_s2))
{
// s1 is now offset THIS far from s2
offset1 = offset1+i;
// Our longeset Common String just got bigger
lcs = lcs + 1;
// Now that we match again, break to the main loop
break;
}
// It looks like s2 has a match down the line which fits
// where we left off in s1
if (next_s2.equals(bookmarked_s1))
{
// s2 is now offset THIS far from s1
offset2 = offset2+i;
// Our longeset Common String just got bigger
lcs = lcs + 1;
// Now that we match again, break to the main loop
break;
}
}
//This is the number of inserted characters were found
int added_offset1 = offset1 - old_offset1;
int added_offset2 = offset2 - old_offset2;
// We reached our maxoffset and couldn't match up the strings
if(added_offset1 == 0 && added_offset2 == 0)
{
_s1.append(h1s).append(substring(_s1_deviation, 0, added_offset1+1)).append(h1e);
_s2.append(h2s).append(substring(_s2_deviation, 0, added_offset2+1)).append(h2e);
}
// s2 had extra characters
else if(added_offset1 == 0 && added_offset2 > 0)
{
_s1.append(substring(_s1_deviation, 0, 1));
_s2.append(h2s).append(substring(_s2_deviation, 0, added_offset2)).append(h2e).append(substring(_s2_deviation, _s2_deviation.length()-1, _s2_deviation.length()));
}
// s1 had extra characters
else if(added_offset1 > 0 && added_offset2 == 0)
{
_s1.append(h1s).append(substring(_s1_deviation, 0, added_offset1)).append(h1e).append(substring(_s1_deviation, _s1_deviation.length()-1, _s1_deviation.length()));
_s2.append(substring(_s2_deviation, 0, 1));
}
}
c = c+1;
}
// Anything left at the end of s1 is extra
if(c + offset1 < s1.length())
{
_s1.append(h1s).append(substring(s1, (s1.length() - (s1.length()-(c + offset1))), s1.length())).append(h1e);
}
// Anything left at the end of s2 is extra
if(c + offset2 < s2.length())
{
_s2.append(h2s).append(substring(s2, (s2.length() - (s2.length()-(c + offset2))), s2.length())).append(h2e);
}
// Distance is the average string length minus the longest common string
int distance = (s1.length() + s2.length())/2 - lcs;
// Whcih string was longest?
int maxLen = (s1.length() > s2.length() ? s1.length() : s2.length());
// Similarity is the distance divided by the max length
double similarity = (maxLen == 0) ? 1 : 1-(distance/maxLen);
// Return what we found.
return_struct.lcs = lcs;
return_struct.similarity = similarity;
return_struct.distance = distance;
// return_struct.s1 = _s1.toString(); // "highlighted" version
// return_struct.s2 = _s2.toString(); // "highlighted" version
return_struct.s1 = _s1.toString().replace(h1e+h1s, "").replace("[ESC]", "\u001b"); // "highlighted" version
return_struct.s2 = _s2.toString().replace(h2e+h2s, "").replace("[ESC]", "\u001b"); // "highlighted" version
return return_struct;
}
private static String substring(String str, int offset, int length)
{
if (offset >= str.length()) return("");
if (offset+length >= str.length()) return(str.substring(offset));
return(str.substring(offset, offset+length));
}
public static void main(String args[])
{
ReturnStructure rs;
rs = stringSimilarity("The rain in Spain stays mainly on the plains", "The rain in Madrid stays totally on the plains", "<<", ">>", "<<", ">>", 10);
System.out.println(rs.s1);
System.out.println(rs.s2);
}
}
| lgpl-2.1 |
another-dave/checkstyle | src/main/java/com/puppycrawl/tools/checkstyle/api/AuditEvent.java | 4360 | ////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2015 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.api;
import java.util.EventObject;
/**
* Raw event for audit.
* <p>
* <i>
* I'm not very satisfied about the design of this event since there are
* optional methods that will return null in most of the case. This will
* need some work to clean it up especially if we want to introduce
* a more sequential reporting action rather than a packet error
* reporting. This will allow for example to follow the process quickly
* in an interface or a servlet (yep, that's cool to run a check via
* a web interface in a source repository ;-)
* </i>
* </p>
*
* @author <a href="mailto:stephane.bailliez@wanadoo.fr">Stephane Bailliez</a>
* @see AuditListener
*/
public final class AuditEvent
extends EventObject {
/** Record a version. */
private static final long serialVersionUID = -3774725606973812736L;
/** filename event associated with **/
private final String fileName;
/** message associated with the event **/
private final LocalizedMessage message;
/**
* Creates a new instance.
* @param source the object that created the event
*/
public AuditEvent(Object source) {
this(source, null);
}
/**
* Creates a new <code>AuditEvent</code> instance.
* @param src source of the event
* @param fileName file associated with the event
*/
public AuditEvent(Object src, String fileName) {
this(src, fileName, null);
}
/**
* Creates a new <code>AuditEvent</code> instance.
*
* @param src source of the event
* @param fileName file associated with the event
* @param message the actual message
*/
public AuditEvent(Object src, String fileName, LocalizedMessage message) {
super(src);
this.fileName = fileName;
this.message = message;
}
/**
* @return the file name currently being audited or null if there is
* no relation to a file.
*/
public String getFileName() {
return fileName;
}
/**
* return the line number on the source file where the event occurred.
* This may be 0 if there is no relation to a file content.
* @return an integer representing the line number in the file source code.
*/
public int getLine() {
return message.getLineNo();
}
/**
* return the message associated to the event.
* @return the event message
*/
public String getMessage() {
return message.getMessage();
}
/** @return the column associated with the message **/
public int getColumn() {
return message.getColumnNo();
}
/** @return the audit event severity level **/
public SeverityLevel getSeverityLevel() {
return message == null
? SeverityLevel.INFO
: message.getSeverityLevel();
}
/**
* @return the identifier of the module that generated the event. Can return
* null.
*/
public String getModuleId() {
return message.getModuleId();
}
/** @return the name of the source for the message **/
public String getSourceName() {
return message.getSourceName();
}
/** @return the localized message **/
public LocalizedMessage getLocalizedMessage() {
return message;
}
}
| lgpl-2.1 |
Sable/polyglot | tools/pth/src/polyglot/pth/AbstractTest.java | 2154 | /*
* Author : Stephen Chong
* Created: Nov 21, 2003
*/
package polyglot.pth;
import java.util.Date;
/**
*
*/
public abstract class AbstractTest implements Test {
protected String name;
protected String description;
protected boolean success = false;
protected boolean hasRun = false;
protected String failureMessage = null;
protected TestResult testResult;
protected OutputController output;
public AbstractTest(String name) {
this.name = name;
}
public void setOutputController(OutputController output) {
this.output = output;
}
public final boolean run() {
preRun();
this.success = this.runTest();
this.hasRun = true;
Date lastSuccess = null;
if (this.getTestResult() != null) {
lastSuccess = this.getTestResult().dateLastSuccess;
}
this.setTestResult(this.createTestResult(lastSuccess));
postRun();
return success();
}
protected abstract boolean runTest();
protected void preRun() {
output.startTest(this);
}
protected void postRun() {
output.finishTest(this, null);
}
protected TestResult createTestResult(Date lastSuccess) {
Date lastRun = new Date();
if (this.success()) {
lastSuccess = lastRun;
}
return new TestResult(this, lastRun, lastSuccess);
}
public boolean success() {
return success;
}
public String getFailureMessage() {
return failureMessage;
}
public void setFailureMessage(String failureMessage) {
this.failureMessage= failureMessage;
}
public String getDescription() {
return description;
}
public String getName() {
return name;
}
public void setDescription(String string) {
description = string;
}
public void setName(String string) {
name = string;
}
public TestResult getTestResult() {
return testResult;
}
public void setTestResult(TestResult tr) {
testResult = tr;
}
}
| lgpl-2.1 |
skyvers/skyve | skyve-ext/src/main/java/org/skyve/impl/bizport/DataFileExportField.java | 807 | package org.skyve.impl.bizport;
public class DataFileExportField {
private String fieldTitle;
private String bindingExpression;
public String getFieldTitle() {
return fieldTitle;
}
public void setFieldTitle(String fieldTitle) {
this.fieldTitle = fieldTitle;
}
public String getBindingExpression() {
return bindingExpression;
}
public void setBindingExpression(String bindingExpression) {
if(bindingExpression!=null && bindingExpression.startsWith("{") && bindingExpression.endsWith("}")) {
this.bindingExpression = bindingExpression.substring(1, bindingExpression.length()-1);
} else {
this.bindingExpression = bindingExpression;
}
}
public DataFileExportField(String fieldTitle, String binding) {
this.fieldTitle = fieldTitle;
this.bindingExpression = binding;
}
}
| lgpl-2.1 |
atricore/josso1 | components/josso-spring-security-v2/src/main/java/org/josso/spring/acegi/JOSSOUserDetailsService.java | 4092 | /*
* JOSSO: Java Open Single Sign-On
*
* Copyright 2004-2009, Atricore, Inc.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*
*/
package org.josso.spring.acegi;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.userdetails.User;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UserDetailsService;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.josso.gateway.GatewayServiceLocator;
import org.josso.gateway.identity.SSORole;
import org.josso.gateway.identity.SSOUser;
import org.josso.gateway.identity.exceptions.NoSuchUserException;
import org.josso.gateway.identity.exceptions.SSOIdentityException;
import org.josso.gateway.identity.service.SSOIdentityManagerService;
/**
* Date: Sep 28, 2007
* Time: 10:23:22 AM
*
* @author <a href="mailto:sgonzalez@josso.org">Gianluca Brigandi</a>
*/
public class JOSSOUserDetailsService implements UserDetailsService {
private static final Log logger = LogFactory.getLog(JOSSOUserDetailsService.class);
private GatewayServiceLocator _gsl;
private SSOIdentityManagerService _im;
/**
* This implementation will retrieve user details from JOSSO services.
*/
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, org.springframework.dao.DataAccessException {
try {
// TODO : Test ACEGI with multiple security domains !!!
// TODO : Get requester (partner app id!)
SSOUser user = getIdentityManager().findUser(null, null, username);
SSORole[] roles = _im.findRolesBySSOSessionId(null, username);
return toUserDetails(user, roles);
} catch (NoSuchUserException e) {
logger.error(e.getMessage(), e);
throw new UsernameNotFoundException(e.getMessage(), e);
} catch (SSOIdentityException e) {
logger.error(e.getMessage(), e);
throw new UsernameNotFoundException(e.getMessage(), e);
}
}
/**
* This addapts JOSSO user informatio to ACEGI user details.
* <p/>
* Some SSO properties retrieved by JOSSO could be mapped to specific user detail information
* like account disabled, by subclasses.
*/
protected UserDetails toUserDetails(SSOUser user, SSORole[] roles) {
GrantedAuthority[] authorities = new GrantedAuthority[roles.length];
for (int i = 0; i < roles.length; i++) {
SSORole role = roles[i];
authorities[i] = new GrantedAuthorityImpl(role.getName());
}
UserDetails ud = new User(user.getName(), "NOT AVAILABLE UNDER JOSSO", true, true,
true, true, authorities);
return ud;
}
public GatewayServiceLocator getGatewayServiceLocator() {
return _gsl;
}
public void setGatewayServiceLocator(GatewayServiceLocator gsl) {
this._gsl = gsl;
}
public SSOIdentityManagerService getIdentityManager() {
if (_im == null) {
try {
_im = _gsl.getSSOIdentityManager();
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
return _im;
}
}
| lgpl-2.1 |
xwiki-contrib/sankoreorg | plugins/lucene/src/main/java/com/xpn/xwiki/plugin/lucene/textextraction/PlainTextExtractor.java | 867 | /*
* Copyright 2004 Outerthought bvba and Schaubroeck nv
*
* 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.xpn.xwiki.plugin.lucene.textextraction;
public class PlainTextExtractor implements MimetypeTextExtractor
{
public String getText(byte[] data) throws Exception
{
return new String(data);
}
}
| lgpl-2.1 |
Qingbao/PasswdManagerAndroid | src/noconflict/org/bouncycastle/util/encoders/Translator.java | 589 | package noconflict.org.bouncycastle.util.encoders;
/**
* general interface for an translator.
*/
public interface Translator
{
/**
* size of the output block on encoding produced by getDecodedBlockSize()
* bytes.
*/
public int getEncodedBlockSize();
public int encode(byte[] in, int inOff, int length, byte[] out, int outOff);
/**
* size of the output block on decoding produced by getEncodedBlockSize()
* bytes.
*/
public int getDecodedBlockSize();
public int decode(byte[] in, int inOff, int length, byte[] out, int outOff);
}
| lgpl-2.1 |
xwiki-contrib/sankoreorg | xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/plugin/userdirectory/UserDirectoryPluginAPI.java | 5259 | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*
*/
package com.xpn.xwiki.plugin.userdirectory;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.api.Api;
import java.util.List;
public class UserDirectoryPluginAPI extends Api {
UserDirectoryPlugin userDir;
public UserDirectoryPluginAPI(UserDirectoryPlugin userDirectory, XWikiContext context) {
super(context);
this.userDir = userDirectory;
}
public Group addGroup(XWikiContext context) throws XWikiException {
return userDir.addGroup(context);
}
public void updateGroup(XWikiContext context) throws XWikiException {
userDir.updateGroup(context);
}
public boolean groupExist(String name, XWikiContext context) throws XWikiException {
return userDir.groupExist(name, context);
}
public Group getGroup(String space, String name, XWikiContext context) throws XWikiException {
return userDir.getGroup(space, name, context);
}
public Group getGroup(String name, XWikiContext context) throws XWikiException {
return userDir.getGroup(name, context);
}
public List getAllGroupsPageName(XWikiContext context) throws XWikiException {
return userDir.getAllGroupsPageName(context);
}
public List getAllGroups(XWikiContext context) throws XWikiException {
return userDir.getAllGroups(context);
}
public List getAllGroups(String orderBy, XWikiContext context) throws XWikiException {
return userDir.getAllGroups(orderBy, context);
}
public List getMembers(String grpPage, XWikiContext context) throws XWikiException {
return userDir.getMembers(grpPage, context);
}
public List getUnactivatedMembers(String grpPage, XWikiContext context) throws XWikiException {
return userDir.getUnactivatedMembers(grpPage, context);
}
public boolean addParentGroup(String childGroupName, String parentGroupName, XWikiContext context) throws XWikiException {
return userDir.addParentGroup(childGroupName, parentGroupName, context);
}
public boolean removeParentGroup(String childGroupName, String parentGroupName, XWikiContext context) throws XWikiException {
return userDir.removeParentGroup(childGroupName, parentGroupName, context);
}
public List getParentGroups(String grpName, XWikiContext context) throws XWikiException {
return userDir.getParentGroups(grpName, context);
}
public String inviteToGroup(String name, String firstName, String email, String group, XWikiContext context) throws XWikiException {
return userDir.inviteToGroup(name, firstName, email, group, context);
}
public void addUserToGroup(String userPage, String group, XWikiContext context) throws XWikiException {
userDir.addUserToGroup(userPage, group, context);
}
public String getUserName(String userPage, XWikiContext context) throws XWikiException {
return userDir.getUserName(userPage, context);
}
public String getUserEmail(String userPage, XWikiContext context) throws XWikiException {
return userDir.getUserEmail(userPage, context);
}
public List getUsersDocumentName(String grpPage, XWikiContext context) throws XWikiException {
return userDir.getUsersDocumentName(grpPage, context);
}
public List getUsersDocument(String grpPage, XWikiContext context) throws XWikiException {
return userDir.getUsersDocument(grpPage, context);
}
public boolean removeMemberships(String userPage, String grpPage, XWikiContext context) throws XWikiException {
return userDir.removeMemberships(userPage, grpPage, context);
}
public void sendDeactivationEMail(String userPage, String grpPage, XWikiContext context) throws XWikiException {
userDir.sendDeactivationEMail(userPage, grpPage, context);
}
public List getUserMemberships(String userPage, XWikiContext context) throws XWikiException {
return userDir.getUserMemberships(userPage, context);
}
public boolean deactivateAccount(String userPage, XWikiContext context) throws XWikiException {
return userDir.deactivateAccount(userPage, context);
}
public void resendInvitation(String userPage, XWikiContext context) throws XWikiException {
userDir.resendInvitation(userPage, context);
}
}
| lgpl-2.1 |
MjAbuz/exist | test/src/org/exist/deadlocks/GetReleaseBrokerDeadlocks.java | 5228 | /*
* eXist Open Source Native XML Database
* Copyright (C) 2012 The eXist Project
* http://exist-db.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* $Id$
*/
package org.exist.deadlocks;
import static org.junit.Assert.*;
import java.util.Map;
import java.util.Random;
import org.exist.Database;
import org.exist.security.Subject;
import org.exist.storage.BrokerPool;
import org.exist.storage.DBBroker;
import org.exist.util.Configuration;
import org.exist.xquery.FunctionFactory;
import org.junit.Ignore;
import org.junit.Test;
/**
* @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a>
*
*/
public class GetReleaseBrokerDeadlocks {
private static Random rd = new Random();
@Test
@Ignore
public void exterServiceMode() {
try {
Configuration config = new Configuration();
config.setProperty(FunctionFactory.PROPERTY_DISABLE_DEPRECATED_FUNCTIONS, new Boolean(false));
BrokerPool.configure(1, 5, config);
Database db = BrokerPool.getInstance();
Thread thread = new Thread(new EnterServiceMode());
DBBroker broker = null;
try {
broker = db.get(null);
thread.start();
Thread.sleep(1000);
} finally {
db.release(broker);
}
Thread.sleep(1000);
assertFalse(thread.isAlive());
} catch (Exception e) {
fail(e.getMessage());
}
}
class EnterServiceMode implements Runnable {
@Override
public void run() {
try {
BrokerPool db = BrokerPool.getInstance();
Subject subject = db.getSecurityManager().getSystemSubject();
try {
db.enterServiceMode(subject);
//do something
Thread.sleep(100);
} finally {
db.exitServiceMode(subject);
}
} catch (Exception e) {
fail(e.getMessage());
}
}
}
@Test
@Ignore
public void testingGetReleaseCycle() {
boolean debug = false;
try {
Configuration config = new Configuration();
config.setProperty(FunctionFactory.PROPERTY_DISABLE_DEPRECATED_FUNCTIONS, new Boolean(false));
BrokerPool.configure(1, 5, config);
Database db = BrokerPool.getInstance();
Thread thread;
for (int i = 0; i < 1000; i++) {
thread = new Thread(new GetRelease());
thread.start();
Thread.sleep(rd.nextInt(250));
if (ex != null) {
ex.printStackTrace();
fail(ex.getMessage());
}
if (debug && db.countActiveBrokers() == 20) {
Map<Thread, StackTraceElement[]> stackTraces = Thread.getAllStackTraces();
StringBuilder sb = new StringBuilder();
sb.append("************************************************\n");
sb.append("************************************************\n");
for (Map.Entry<Thread, StackTraceElement[]> entry : stackTraces.entrySet()) {
StackTraceElement[] stacks = entry.getValue();
sb.append("THREAD: ");
sb.append(entry.getKey().getName());
sb.append("\n");
for (int n = 0; n < stacks.length; n++) {
sb.append(" ");
sb.append(stacks[n]);
sb.append("\n");
}
}
if (stackTraces.isEmpty())
sb.append("No threads.");
// System.out.println(sb.toString());
}
}
while (db.countActiveBrokers() > 0) {
Thread.sleep(100);
}
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
private static Throwable ex = null;
class GetRelease implements Runnable {
@Override
public void run() {
try {
BrokerPool db = BrokerPool.getInstance();
Subject subject = db.getSecurityManager().getSystemSubject();
DBBroker broker = null;
try {
broker = db.get(subject);
//do something
Thread.sleep(rd.nextInt(5000));
try {
assertEquals(broker, db.get(null));
//do something
Thread.sleep(rd.nextInt(5000));
} finally {
db.release(broker);
}
} finally {
db.release(broker);
}
} catch (Throwable e) {
ex = e;
}
}
}
} | lgpl-2.1 |
SuperUnitato/UnLonely | build/tmp/recompileMc/sources/net/minecraft/client/renderer/entity/RenderIronGolem.java | 1642 | package net.minecraft.client.renderer.entity;
import net.minecraft.client.model.ModelIronGolem;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.entity.layers.LayerIronGolemFlower;
import net.minecraft.entity.monster.EntityIronGolem;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class RenderIronGolem extends RenderLiving<EntityIronGolem>
{
private static final ResourceLocation IRON_GOLEM_TEXTURES = new ResourceLocation("textures/entity/iron_golem.png");
public RenderIronGolem(RenderManager renderManagerIn)
{
super(renderManagerIn, new ModelIronGolem(), 0.5F);
this.addLayer(new LayerIronGolemFlower(this));
}
/**
* Returns the location of an entity's texture. Doesn't seem to be called unless you call Render.bindEntityTexture.
*/
protected ResourceLocation getEntityTexture(EntityIronGolem entity)
{
return IRON_GOLEM_TEXTURES;
}
protected void applyRotations(EntityIronGolem entityLiving, float p_77043_2_, float p_77043_3_, float partialTicks)
{
super.applyRotations(entityLiving, p_77043_2_, p_77043_3_, partialTicks);
if ((double)entityLiving.limbSwingAmount >= 0.01D)
{
float f = 13.0F;
float f1 = entityLiving.limbSwing - entityLiving.limbSwingAmount * (1.0F - partialTicks) + 6.0F;
float f2 = (Math.abs(f1 % 13.0F - 6.5F) - 3.25F) / 3.25F;
GlStateManager.rotate(6.5F * f2, 0.0F, 0.0F, 1.0F);
}
}
} | lgpl-2.1 |
aleitamar/cucumber-reporting | src/main/java/net/masterthought/cucumber/json/Hook.java | 1050 | package net.masterthought.cucumber.json;
import net.masterthought.cucumber.json.support.Resultsable;
import net.masterthought.cucumber.json.support.Status;
public class Hook implements Resultsable {
// Start: attributes from JSON file report
private final Result result = null;
private final Match match = null;
// foe Ruby reports
private final Embedding[] embeddings = new Embedding[0];
// End: attributes from JSON file report
private Status status;
@Override
public Result getResult() {
return result;
}
@Override
public Status getStatus() {
return status;
}
@Override
public Match getMatch() {
return match;
}
public Embedding[] getEmbeddings() {
return embeddings;
}
public void setMedaData() {
calculateStatus();
}
private void calculateStatus() {
if (result == null) {
status = Status.MISSING;
} else {
status = Status.toStatus(result.getStatus());
}
}
}
| lgpl-2.1 |
pbondoer/xwiki-platform | xwiki-platform-core/xwiki-platform-rendering/xwiki-platform-rendering-macros/xwiki-platform-rendering-macro-script/src/main/java/org/xwiki/rendering/internal/macro/script/AbstractScriptCheckerListener.java | 3349 | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.rendering.internal.macro.script;
import java.util.Collections;
import java.util.List;
import org.xwiki.observation.EventListener;
import org.xwiki.observation.event.CancelableEvent;
import org.xwiki.observation.event.Event;
import org.xwiki.script.event.ScriptEvaluatingEvent;
import org.xwiki.rendering.macro.script.ScriptMacroParameters;
import org.xwiki.rendering.transformation.MacroTransformationContext;
/**
* Abstract base class for listeners that need to perform some checks just before a script macro is executed. Subclasses
* must implement {@link #check(CancelableEvent, MacroTransformationContext, ScriptMacroParameters)} that allows
* them to avoid casting and checking for the right event type.
*
* @version $Id$
* @since 2.5M1
*/
public abstract class AbstractScriptCheckerListener implements EventListener
{
/**
* {@inheritDoc}
* <p>
* This implementation returns a singleton list with a {@link org.xwiki.script.event.ScriptEvaluatingEvent}.
* </p>
*
* @see org.xwiki.observation.EventListener#getEvents()
*/
@Override
public List<Event> getEvents()
{
return Collections.singletonList((Event) new ScriptEvaluatingEvent());
}
/**
* {@inheritDoc}
* <p>
* This implementation casts the arguments to the correct type and calls
* {@link #check(CancelableEvent, MacroTransformationContext, ScriptMacroParameters)}.
* </p>
*
* @see org.xwiki.observation.EventListener#onEvent(Event, java.lang.Object, java.lang.Object)
*/
@Override
public void onEvent(Event event, Object source, Object data)
{
if (!(event instanceof ScriptEvaluatingEvent)) {
return;
}
if ((source == null || source instanceof MacroTransformationContext)
&& (data == null || data instanceof ScriptMacroParameters)) {
check((CancelableEvent) event, (MacroTransformationContext) source, (ScriptMacroParameters) data);
}
}
/**
* This method is called when an {@link org.xwiki.script.event.ScriptEvaluatingEvent} is received.
*
* @param event the received event
* @param context current transformation context
* @param parameters parameters of the script macro about to be executed
*/
protected abstract void check(CancelableEvent event, MacroTransformationContext context,
ScriptMacroParameters parameters);
}
| lgpl-2.1 |
abbeyj/sonarqube | plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/MultilineIssuesSensor.java | 8168 | /*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.xoo.rule;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Table;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.sonar.api.batch.fs.FilePredicates;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.InputFile.Type;
import org.sonar.api.batch.fs.TextPointer;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.api.batch.sensor.issue.NewIssueLocation;
import org.sonar.api.rule.RuleKey;
import org.sonar.xoo.Xoo;
public class MultilineIssuesSensor implements Sensor {
public static final String RULE_KEY = "MultilineIssue";
private static final Pattern START_ISSUE_PATTERN = Pattern.compile("\\{xoo-start-issue:([0-9]+)\\}");
private static final Pattern END_ISSUE_PATTERN = Pattern.compile("\\{xoo-end-issue:([0-9]+)\\}");
private static final Pattern START_FLOW_PATTERN = Pattern.compile("\\{xoo-start-flow:([0-9]+):([0-9]+):([0-9]+)\\}");
private static final Pattern END_FLOW_PATTERN = Pattern.compile("\\{xoo-end-flow:([0-9]+):([0-9]+):([0-9]+)\\}");
@Override
public void describe(SensorDescriptor descriptor) {
descriptor
.name("Multiline Issues")
.onlyOnLanguages(Xoo.KEY)
.createIssuesForRuleRepositories(XooRulesDefinition.XOO_REPOSITORY);
}
@Override
public void execute(SensorContext context) {
FileSystem fs = context.fileSystem();
FilePredicates p = fs.predicates();
for (InputFile file : fs.inputFiles(p.and(p.hasLanguages(Xoo.KEY), p.hasType(Type.MAIN)))) {
createIssues(file, context);
}
}
private static void createIssues(InputFile file, SensorContext context) {
Map<Integer, TextPointer> startIssuesPositions = Maps.newHashMap();
Map<Integer, TextPointer> endIssuesPositions = Maps.newHashMap();
Map<Integer, Table<Integer, Integer, TextPointer>> startFlowsPositions = Maps.newHashMap();
Map<Integer, Table<Integer, Integer, TextPointer>> endFlowsPositions = Maps.newHashMap();
parseIssues(file, context, startIssuesPositions, endIssuesPositions);
parseFlows(file, context, startFlowsPositions, endFlowsPositions);
createIssues(file, context, startIssuesPositions, endIssuesPositions, startFlowsPositions, endFlowsPositions);
}
private static void parseFlows(InputFile file, SensorContext context, Map<Integer, Table<Integer, Integer, TextPointer>> startFlowsPositions,
Map<Integer, Table<Integer, Integer, TextPointer>> endFlowsPositions) {
int currentLine = 0;
try {
for (String lineStr : Files.readAllLines(file.path(), context.fileSystem().encoding())) {
currentLine++;
Matcher m = START_FLOW_PATTERN.matcher(lineStr);
while (m.find()) {
Integer issueId = Integer.parseInt(m.group(1));
Integer issueFlowId = Integer.parseInt(m.group(2));
Integer issueFlowNum = Integer.parseInt(m.group(3));
TextPointer newPointer = file.newPointer(currentLine, m.end());
if (!startFlowsPositions.containsKey(issueId)) {
startFlowsPositions.put(issueId, HashBasedTable.<Integer, Integer, TextPointer>create());
}
startFlowsPositions.get(issueId).row(issueFlowId).put(issueFlowNum, newPointer);
}
m = END_FLOW_PATTERN.matcher(lineStr);
while (m.find()) {
Integer issueId = Integer.parseInt(m.group(1));
Integer issueFlowId = Integer.parseInt(m.group(2));
Integer issueFlowNum = Integer.parseInt(m.group(3));
TextPointer newPointer = file.newPointer(currentLine, m.start());
if (!endFlowsPositions.containsKey(issueId)) {
endFlowsPositions.put(issueId, HashBasedTable.<Integer, Integer, TextPointer>create());
}
endFlowsPositions.get(issueId).row(issueFlowId).put(issueFlowNum, newPointer);
}
}
} catch (IOException e) {
throw new IllegalStateException("Unable to read file", e);
}
}
private static void createIssues(InputFile file, SensorContext context, Map<Integer, TextPointer> startPositions,
Map<Integer, TextPointer> endPositions, Map<Integer, Table<Integer, Integer, TextPointer>> startFlowsPositions,
Map<Integer, Table<Integer, Integer, TextPointer>> endFlowsPositions) {
RuleKey ruleKey = RuleKey.of(XooRulesDefinition.XOO_REPOSITORY, RULE_KEY);
for (Map.Entry<Integer, TextPointer> entry : startPositions.entrySet()) {
NewIssue newIssue = context.newIssue().forRule(ruleKey);
Integer issueId = entry.getKey();
NewIssueLocation primaryLocation = newIssue.newLocation()
.on(file)
.at(file.newRange(entry.getValue(), endPositions.get(issueId)));
newIssue.at(primaryLocation.message("Primary location"));
if (startFlowsPositions.containsKey(issueId)) {
Table<Integer, Integer, TextPointer> flows = startFlowsPositions.get(issueId);
for (Map.Entry<Integer, Map<Integer, TextPointer>> flowEntry : flows.rowMap().entrySet()) {
Integer flowId = flowEntry.getKey();
List<NewIssueLocation> flowLocations = Lists.newArrayList();
List<Integer> flowNums = Lists.newArrayList(flowEntry.getValue().keySet());
Collections.sort(flowNums);
for (Integer flowNum : flowNums) {
TextPointer start = flowEntry.getValue().get(flowNum);
TextPointer end = endFlowsPositions.get(issueId).row(flowId).get(flowNum);
NewIssueLocation newLocation = newIssue.newLocation()
.on(file)
.at(file.newRange(start, end))
.message("Flow step #" + flowNum);
flowLocations.add(newLocation);
}
if (flowLocations.size() == 1) {
newIssue.addLocation(flowLocations.get(0));
} else {
newIssue.addFlow(flowLocations);
}
}
}
newIssue.save();
}
}
private static void parseIssues(InputFile file, SensorContext context, Map<Integer, TextPointer> startPositions,
Map<Integer, TextPointer> endPositions) {
int currentLine = 0;
try {
for (String lineStr : Files.readAllLines(file.path(), context.fileSystem().encoding())) {
currentLine++;
Matcher m = START_ISSUE_PATTERN.matcher(lineStr);
while (m.find()) {
Integer issueId = Integer.parseInt(m.group(1));
TextPointer newPointer = file.newPointer(currentLine, m.end());
startPositions.put(issueId, newPointer);
}
m = END_ISSUE_PATTERN.matcher(lineStr);
while (m.find()) {
Integer issueId = Integer.parseInt(m.group(1));
TextPointer newPointer = file.newPointer(currentLine, m.start());
endPositions.put(issueId, newPointer);
}
}
} catch (IOException e) {
throw new IllegalStateException("Unable to read file", e);
}
}
}
| lgpl-3.0 |
FoxelBox/zOLD_FoxBukkit | src/main/java/com/foxelbox/foxbukkit/transmute/PaintingShape.java | 2270 | /**
* This file is part of FoxBukkit.
*
* FoxBukkit is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FoxBukkit 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 FoxBukkit. If not, see <http://www.gnu.org/licenses/>.
*/
package com.foxelbox.foxbukkit.transmute;
import net.minecraft.server.v1_8_R3.*;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
public class PaintingShape extends EntityShape {
static {
yOffsets[9] = 1.62;
yawOffsets[9] = 180;
}
private String paintingName = "Kebab";
public PaintingShape(Transmute transmute, Entity entity, int mobType) {
super(transmute, entity, mobType);
dropping = true;
}
@Override
public void createTransmutedEntity() {
super.createTransmutedEntity();
}
@Override
protected Packet createSpawnPacket() {
Location location = entity.getLocation();
final PacketPlayOutSpawnEntityPainting p25 = new PacketPlayOutSpawnEntityPainting();
p25.a = entityId; // v1_7_R1
p25.b = new BlockPosition(location.getBlockX(), location.getBlockY() + yOffset, location.getBlockZ());
p25.c = EnumDirection.DOWN;
p25.d = paintingName; // v1_7_R1
return p25;
}
public void setPaintingName(String paintingName) {
this.paintingName = paintingName;
deleteEntity();
createTransmutedEntity();
}
public String getPaintingName() {
return paintingName;
}
@Override
public boolean onOutgoingPacket(Player ply, int packetID, Packet packet) {
if (!super.onOutgoingPacket(ply, packetID, packet))
return false;
switch (packetID) {
//case 30:
//case 31:
case 32:
case 33:
return false;
case 34:
PacketPlayOutEntityTeleport p34 = (PacketPlayOutEntityTeleport) packet;
p34.e = (byte) -p34.e; // v1_7_R1
return true;
}
return true;
}
}
| lgpl-3.0 |
HATB0T/RuneCraftery | forge/mcp/src/minecraft/net/minecraft/logging/LogFormatter.java | 1532 | package net.minecraft.logging;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
class LogFormatter extends Formatter
{
private SimpleDateFormat field_98228_b;
final LogAgent field_98229_a;
private LogFormatter(LogAgent par1LogAgent)
{
this.field_98229_a = par1LogAgent;
this.field_98228_b = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
public String format(LogRecord par1LogRecord)
{
StringBuilder stringbuilder = new StringBuilder();
stringbuilder.append(this.field_98228_b.format(Long.valueOf(par1LogRecord.getMillis())));
if (LogAgent.func_98237_a(this.field_98229_a) != null)
{
stringbuilder.append(LogAgent.func_98237_a(this.field_98229_a));
}
stringbuilder.append(" [").append(par1LogRecord.getLevel().getName()).append("] ");
stringbuilder.append(this.formatMessage(par1LogRecord));
stringbuilder.append('\n');
Throwable throwable = par1LogRecord.getThrown();
if (throwable != null)
{
StringWriter stringwriter = new StringWriter();
throwable.printStackTrace(new PrintWriter(stringwriter));
stringbuilder.append(stringwriter.toString());
}
return stringbuilder.toString();
}
LogFormatter(LogAgent par1LogAgent, LogAgentEmptyAnon par2LogAgentEmptyAnon)
{
this(par1LogAgent);
}
}
| lgpl-3.0 |
MesquiteProject/MesquiteArchive | trunk/Mesquite Project/Source/mesquite/consensus/lib/BasicTreeConsenser.java | 6740 | /* Mesquite source code. Copyright 1997-2011 W. Maddison and D. Maddison.
Version 2.75, September 2011.
Disclaimer: The Mesquite source code is lengthy and we are few. There are no doubt inefficiencies and goofs in this code.
The commenting leaves much to be desired. Please approach this source code with the spirit of helping out.
Perhaps with your help we can be more than a few, and make Mesquite better.
Mesquite is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
Mesquite's web site is http://mesquiteproject.org
This source code and its compiled class files are free and modifiable under the terms of
GNU Lesser General Public License. (http://www.gnu.org/copyleft/lesser.html)
*/
package mesquite.consensus.lib;
import java.awt.Button;
import java.awt.Choice;
import java.awt.Label;
import mesquite.lib.duties.*;
import mesquite.lib.*;
public abstract class BasicTreeConsenser extends IncrementalConsenser {
protected static final int ASIS=0;
protected static final int ROOTED =1;
protected static final int UNROOTED=2;
protected int rooting = ASIS; // controls and preferences and snapshot should be in subclass
protected BipartitionVector bipartitions=null;
protected int treeNumber = 0;
boolean preferencesSet = false;
/*.................................................................................................................*/
public boolean startJob(String arguments, Object condition, boolean hiredByName) {
bipartitions = new BipartitionVector();
loadPreferences();
if (!MesquiteThread.isScripting())
if (!queryOptions())
return false;
return true;
}
/*.................................................................................................................*/
public void processMorePreferences (String tag, String content) {
}
/*.................................................................................................................*/
public void processSingleXMLPreference (String tag, String content) {
if ("rooting".equalsIgnoreCase(tag))
rooting = MesquiteInteger.fromString(content);
processMorePreferences(tag, content);
preferencesSet = true;
}
/*.................................................................................................................*/
public String prepareMorePreferencesForXML () {
return "";
}
/*.................................................................................................................*/
public String preparePreferencesForXML () {
StringBuffer buffer = new StringBuffer(200);
StringUtil.appendXMLTag(buffer, 2, "rooting", rooting);
buffer.append(prepareMorePreferencesForXML());
preferencesSet = true;
return buffer.toString();
}
public void queryOptionsSetup(ExtensibleDialog dialog) {
}
/*.................................................................................................................*/
public void queryOptionsProcess(ExtensibleDialog dialog) {
}
/*.................................................................................................................*/
public boolean queryOptions() {
MesquiteInteger buttonPressed = new MesquiteInteger(1);
ExtensibleDialog dialog = new ExtensibleDialog(containerOfModule(), getName() + " Options",buttonPressed); //MesquiteTrunk.mesquiteTrunk.containerOfModule()
dialog.addLabel(getName() + " Options");
String helpString = "Please choose the options for consensus trees. ";
dialog.appendToHelpString(helpString);
queryOptionsSetup(dialog);
String[] rootingStrings = {"As specified in first tree", "Rooted", "Unrooted"};
Choice rootingChoice = dialog.addPopUpMenu("Treat trees as rooted or unrooted:", rootingStrings, 0);
//TextArea PAUPOptionsField = queryFilesDialog.addTextArea(PAUPOptions, 20);
dialog.completeAndShowDialog(true);
if (buttonPressed.getValue()==0) {
queryOptionsProcess(dialog);
int choiceValue = rootingChoice.getSelectedIndex();
if (choiceValue>=0)
rooting = choiceValue;
storePreferences();
}
dialog.dispose();
return (buttonPressed.getValue()==0);
}
/*.................................................................................................................*/
/*.................................................................................................................*/
public void reset(Taxa taxa){
if (bipartitions==null)
bipartitions = new BipartitionVector();
else
bipartitions.removeAllElements(); // clean bipartition table
bipartitions.setTaxa(taxa);
bipartitions.zeroFrequencies();
initialize();
}
public abstract void addTree(Tree t);
public abstract Tree getConsensus();
/*.................................................................................................................*/
public void initialize() {
}
/*.................................................................................................................*/
public void afterConsensus() {
}
/*.................................................................................................................*/
//ASSUMES TREES HAVE ALL THE SAME TAXA
/*.................................................................................................................*/
public Tree consense(Trees list){
Taxa taxa = list.getTaxa();
reset(taxa);
ProgressIndicator progIndicator=null;
//progIndicator = new ProgressIndicator(getProject(),getName(), "", list.size(), true);
if (progIndicator!=null){
progIndicator.start();
}
// if (MesquiteTrunk.debugMode)
// logln("\n Consensus Tree Calculations");
MesquiteTimer timer = new MesquiteTimer();
timer.start();
logln("");
for (treeNumber = 0; treeNumber < list.size(); treeNumber++){
if (treeNumber==0) {
switch (rooting) {
case ASIS:
bipartitions.setRooted(list.getTree(0).getRooted());
break;
case ROOTED:
bipartitions.setRooted(true);
break;
case UNROOTED:
bipartitions.setRooted(false);
break;
}
}
addTree(list.getTree(treeNumber));
if (treeNumber%100==0)
log(".");
if (progIndicator!=null) {
progIndicator.setText("Processing tree " + (treeNumber+1));
progIndicator.spin();
if (progIndicator.isAborted())
break;
}
// if (MesquiteTrunk.debugMode)
// logln(" tree: " + (treeNumber+1)+ ", bipartitions: " + bipartitions.size() + ", memory: " + MesquiteTrunk.getMaxAvailableMemory());
}
Tree t = getConsensus();
double time = 1.0*timer.timeSinceLast()/1000.0;
if (progIndicator!=null)
progIndicator.goAway();
// afterConsensus();
logln("\n" + list.size() + " trees processed in " + time + " seconds");
return t;
}
}
| lgpl-3.0 |
fge/json-schema-validator-demo | src/main/java/com/github/fge/jsonschema/load/SampleLoader.java | 623 | package com.github.fge.jsonschema.load;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.github.fge.jackson.JacksonUtils;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
@Produces("application/json;charset=utf-8")
public abstract class SampleLoader
{
protected static final JsonNodeFactory FACTORY = JacksonUtils.nodeFactory();
@GET
public final Response getSample()
{
return Response.ok().entity(loadSample().toString()).build();
}
protected abstract JsonNode loadSample();
}
| lgpl-3.0 |
OpenCorrelate/red5load | red5/src/main/java/org/red5/server/api/IScope.java | 6784 | package org.red5.server.api;
/*
* RED5 Open Source Flash Server - http://www.osflash.org/red5
*
* Copyright (c) 2006-2009 by respective authors (see below). All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation; either version 2.1 of the License, or (at your option) any later
* version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along
* with this library; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import org.red5.server.api.service.IServiceHandlerProvider;
import org.red5.server.api.statistics.IScopeStatistics;
import org.springframework.core.io.support.ResourcePatternResolver;
/**
* The scope object.
*
* A stateful object shared between a group of clients connected to the same
* <tt>context path</tt>. Scopes are arranged in hierarchical way, so its possible for
* a scope to have a parent and children scopes. If a client connects to a scope then they are
* also connected to its parent scope. The scope object is used to access
* resources, shared object, streams, etc. That is, scope are general option for grouping things
* in application.
*
* The following are all names for scopes: application, room, place, lobby.
*
* @author The Red5 Project (red5@osflash.org)
* @author Luke Hubbard (luke@codegent.com)
*/
public interface IScope extends IBasicScope, ResourcePatternResolver,
IServiceHandlerProvider {
/**
* ID constant
*/
public static final String ID = "red5.scope";
/**
* Type constant
*/
public static final String TYPE = "scope";
/**
* Scope separator
*/
public static final String SEPARATOR = ":";
/**
* Check to see if this scope has a child scope matching a given name.
*
* @param name the name of the child scope
* @return <code>true</code> if a child scope exists, otherwise
* <code>false</code>
*/
public boolean hasChildScope(String name);
/**
* Checks whether scope has a child scope with given name and type
*
* @param type Child scope type
* @param name Child scope name
* @return <code>true</code> if a child scope exists, otherwise
* <code>false</code>
*/
public boolean hasChildScope(String type, String name);
/**
* Creates child scope with name given and returns success value. Returns
* <code>true</code> on success, <code>false</code> if given scope
* already exists among children.
*
* @param name New child scope name
* @return <code>true</code> if child scope was successfully creates,
* <code>false</code> otherwise
*/
public boolean createChildScope(String name);
/**
* Adds scope as a child scope. Returns <code>true</code> on success,
* <code>false</code> if given scope is already a child of current.
*
* @param scope Scope given
* @return <code>true</code> if child scope was successfully added,
* <code>false</code> otherwise
*/
public boolean addChildScope(IBasicScope scope);
/**
* Removes scope from the children scope list. Returns <code>false</code>
* if given scope isn't a child of the current scope.
*
* @param scope Scope given
*/
public void removeChildScope(IBasicScope scope);
/**
* Get a set of the child scope names.
*
* @return set containing child scope names
*/
public Iterator<String> getScopeNames();
public Iterator<String> getBasicScopeNames(String type);
/**
* Get a child scope by name.
*
* @param name Name of the child scope
* @return the child scope, or null if no scope is found
* @param type Child scope type
*/
public IBasicScope getBasicScope(String type, String name);
/**
* Return scope by name
* @param name Scope name
* @return Scope with given name
*/
public IScope getScope(String name);
/**
* Get a set of connected clients. You can get the connections by passing
* the scope to the clients {@link IClient#getConnections()} method.
*
* @return Set containing all connected clients
* @see org.red5.server.api.IClient#getConnections(IScope)
*/
public Set<IClient> getClients();
/**
* Get a connection iterator. You can call remove, and the connection will
* be closed.
*
* @return Iterator holding all connections
*/
public Collection<Set<IConnection>> getConnections();
/**
* Lookup connections.
*
* @param client object
* @return Set of connection objects (readonly)
*/
public Set<IConnection> lookupConnections(IClient client);
/**
* Returns scope context
*
* @return Scope context
*/
public IContext getContext();
/**
* Checks whether scope has handler or not.
*
* @return <code>true</code> if scope has a handler, <code>false</code>
* otherwise
*/
public boolean hasHandler();
/**
* Return handler of the scope
*
* @return Scope handler
*/
public IScopeHandler getHandler();
/**
* Return context path.
*
* @return Context path
*/
public String getContextPath();
/**
* Adds given connection to the scope
*
* @param conn Given connection
* @return <code>true</code> on success, <code>false</code> if given
* connection already belongs to this scope
*/
public boolean connect(IConnection conn);
/**
* Add given connection to the scope, overloaded for parameters pass case.
* @param conn Given connection
* @param params Parameters passed
* @return <code>true</code> on success, <code>false</code> if given
* connection already belongs to this scope
*/
public boolean connect(IConnection conn, Object[] params);
/**
* Removes given connection from list of scope connections. This disconnects
* all clients of given connection from the scope.
*
* @param conn Connection given
*/
public void disconnect(IConnection conn);
/**
* Return statistics informations about the scope.
*
* @return the statistics
*/
public IScopeStatistics getStatistics();
}
| lgpl-3.0 |
jspresso/jspresso-ce | remote/components/src/main/java/org/jspresso/framework/gui/remote/RDecimalComponent.java | 1853 | /*
* Copyright (c) 2005-2016 Vincent Vandenschrick. All rights reserved.
*
* This file is part of the Jspresso framework.
*
* Jspresso is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Jspresso 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 Jspresso. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jspresso.framework.gui.remote;
/**
* A remote number field component.
*
* @author Vincent Vandenschrick
*/
public abstract class RDecimalComponent extends RNumericComponent {
private static final long serialVersionUID = -1920811347497629751L;
private int maxFractionDigit;
/**
* Constructs a new {@code RIntegerField} instance.
*
* @param guid
* the guid.
*/
public RDecimalComponent(String guid) {
super(guid);
}
/**
* Constructs a new {@code RDecimalComponent} instance. Only used for
* serialization support.
*/
public RDecimalComponent() {
// For serialization support
}
/**
* Gets the maxFractionDigit.
*
* @return the maxFractionDigit.
*/
public int getMaxFractionDigit() {
return maxFractionDigit;
}
/**
* Sets the maxFractionDigit.
*
* @param maxFractionDigit
* the maxFractionDigit to set.
*/
public void setMaxFractionDigit(int maxFractionDigit) {
this.maxFractionDigit = maxFractionDigit;
}
}
| lgpl-3.0 |
simeshev/parabuild-ci | src/org/parabuild/ci/versioncontrol/StarTeamCheckoutCommandParameters.java | 1169 | /*
* Parabuild CI licenses this file to You under the LGPL 2.1
* (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/lgpl-3.0.txt
*
* 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.parabuild.ci.versioncontrol;
import java.util.*;
import org.parabuild.ci.object.*;
/**
*
*/
final class StarTeamCheckoutCommandParameters extends StarTeamCommandParameters {
private byte eolConversion = SourceControlSetting.STARTEAM_EOL_ON;
private Date date = null;
public byte getEolConversion() {
return eolConversion;
}
public void setEolConversion(final byte eolConversion) {
this.eolConversion = eolConversion;
}
public Date getDate() {
return date;
}
public void setDate(final Date date) {
this.date = (Date)date.clone();
}
}
| lgpl-3.0 |
JKatzwinkel/bts | org.bbaw.bts.ui.main/src/org/bbaw/bts/ui/main/toolbar/UserToolcontrol.java | 7556 | package org.bbaw.bts.ui.main.toolbar;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;
import org.bbaw.bts.btsmodel.BTSObject;
import org.bbaw.bts.btsmodel.BTSUser;
import org.bbaw.bts.btsviewmodel.BtsviewmodelFactory;
import org.bbaw.bts.btsviewmodel.TreeNodeWrapper;
import org.bbaw.bts.core.commons.BTSCoreConstants;
import org.bbaw.bts.ui.resources.BTSResourceProvider;
import org.eclipse.e4.core.contexts.IEclipseContext;
import org.eclipse.e4.core.di.annotations.Optional;
import org.eclipse.e4.ui.di.UISynchronize;
import org.eclipse.e4.ui.services.IStylingEngine;
import org.eclipse.emf.edit.provider.ComposedAdapterFactory;
import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
public class UserToolcontrol {
@Inject
private BTSResourceProvider resourceProvider;
@Inject
private UISynchronize sync;
@Inject
private IStylingEngine engine;
@Inject
private IEclipseContext context;
private BTSUser authenticatedUser;
private String userContextRole;
private ComposedAdapterFactory factory = new ComposedAdapterFactory(
ComposedAdapterFactory.Descriptor.Registry.INSTANCE);
private AdapterFactoryLabelProvider labelProvider = new AdapterFactoryLabelProvider(
factory);
private Label userLabel;
private Composite composite;
private Label mayEditLabel;
private Label roleLabel;
private Boolean userMayEdit;
private Boolean userMayTranscribe;
@PostConstruct
public void postConstruct(Composite composite) {
this.composite = composite;
composite.setLayout(new GridLayout(6, false));
engine.setClassname(composite, "MToolBar");
Label l = new Label(composite, SWT.None);
l.setImage(labelProvider.getImage(authenticatedUser));
l.setLayoutData(new GridData());
l.pack();
userLabel = new Label(composite, SWT.None);
userLabel.setLayoutData(new GridData());
((GridData) userLabel.getLayoutData()).horizontalSpan = 2;
if(authenticatedUser == null)
{
Object o = context.get(BTSCoreConstants.AUTHENTICATED_USER);
if (o != null && o instanceof BTSUser)
{
authenticatedUser = (BTSUser) o;
}
}
if (authenticatedUser != null) {
userLabel.setText(labelProvider.getText(authenticatedUser));
} else {
userLabel.setText("No User logged in");
}
userLabel.pack();
mayEditLabel = new Label(composite, SWT.None);
mayEditLabel.setLayoutData(new GridData());
((GridData) mayEditLabel.getLayoutData()).horizontalSpan = 1;
if (userMayEdit != null && userMayEdit.booleanValue()) {
mayEditLabel.setImage(resourceProvider.getImage(
Display.getDefault(), BTSResourceProvider.IMG_EDIT));
} else if (userMayTranscribe != null
&& userMayTranscribe.booleanValue()) {
mayEditLabel
.setImage(resourceProvider.getImage(Display.getDefault(),
BTSResourceProvider.IMG_HIEROGLYPHETW));
} else {
mayEditLabel
.setImage(resourceProvider.getImage(Display.getDefault(),
BTSResourceProvider.IMG_EDIT_DISABLED));
}
mayEditLabel.pack();
Label l2 = new Label(composite, SWT.None);
l2.setImage(resourceProvider.getImage(Display.getDefault(),
BTSResourceProvider.IMG_USERROLE));
l2.setLayoutData(new GridData());
l2.pack();
roleLabel = new Label(composite, SWT.None);
roleLabel.setLayoutData(new GridData());
((GridData) roleLabel.getLayoutData()).horizontalSpan = 1;
if (userContextRole != null) {
roleLabel.setText(userContextRole + " ");
} else {
roleLabel.setText("No Role" + " ");
}
roleLabel.pack();
composite.layout();
composite.pack();
}
/**
* @param authenticatedUser
* the authenticatedUser to set
*/
@Inject
@Optional
public void setAuthenticatedUser(
@Named(BTSCoreConstants.AUTHENTICATED_USER) BTSUser authenticatedUser) {
if (authenticatedUser != null
&& !authenticatedUser.equals(this.authenticatedUser)) {
this.authenticatedUser = authenticatedUser;
if (userLabel != null) {
if (authenticatedUser != null) {
userLabel.setText(labelProvider.getText(authenticatedUser));
}
userLabel.pack();
composite.layout();
composite.pack();
}
}
}
/**
* @param userContextRole
* the userContextRole to set
*/
@Inject
@Optional
public void setUserContextRole(
@Named(BTSCoreConstants.CORE_EXPRESSION_USER_CONTEXT_ROLE) final String userContextRole) {
if (userContextRole != null
&& !userContextRole.equals(this.userContextRole)) {
this.userContextRole = userContextRole;
sync.asyncExec(new Runnable() {
@Override
public void run() {
if (roleLabel != null && !roleLabel.isDisposed()) {
if (userContextRole != null) {
roleLabel.setText(userContextRole);
}
roleLabel.pack();
composite.layout();
composite.pack();
}
}
});
}
}
/**
* @param userMayEdit
* the userMayEdit to set
*/
@Inject
@Optional
public void setUserMayEdit(
@Named(BTSCoreConstants.CORE_EXPRESSION_MAY_EDIT) final Boolean userMayEdit) {
if (userMayEdit != null && userMayEdit != this.userMayEdit) {
this.userMayEdit = userMayEdit;
sync.asyncExec(new Runnable() {
@Override
public void run() {
if (mayEditLabel != null) {
if (userMayEdit != null && userMayEdit.booleanValue()) {
mayEditLabel.setImage(resourceProvider.getImage(
Display.getDefault(),
BTSResourceProvider.IMG_EDIT));
} else if (userMayTranscribe != null
&& userMayTranscribe.booleanValue()) {
mayEditLabel.setImage(resourceProvider.getImage(
Display.getDefault(),
BTSResourceProvider.IMG_HIEROGLYPHETW));
} else {
mayEditLabel.setImage(resourceProvider.getImage(
Display.getDefault(),
BTSResourceProvider.IMG_EDIT_DISABLED));
}
mayEditLabel.pack();
composite.layout();
composite.pack();
}
}
});
}
}
/**
* @param userMayTranscribe
* the userMayTranscribe to set
*/
@Inject
@Optional
public void setUserMayTranscribe(
@Named(BTSCoreConstants.CORE_EXPRESSION_MAY_TRANSCRIBE) final Boolean userMayTranscribe) {
if (userMayTranscribe != null
&& userMayTranscribe != this.userMayTranscribe) {
this.userMayTranscribe = userMayTranscribe;
sync.asyncExec(new Runnable() {
@Override
public void run() {
if (mayEditLabel != null) {
if (userMayEdit != null && userMayEdit.booleanValue()) {
mayEditLabel.setImage(resourceProvider.getImage(
Display.getDefault(),
BTSResourceProvider.IMG_EDIT));
} else if (userMayTranscribe != null
&& userMayTranscribe.booleanValue()) {
mayEditLabel.setImage(resourceProvider.getImage(
Display.getDefault(),
BTSResourceProvider.IMG_HIEROGLYPHETW));
} else {
mayEditLabel.setImage(resourceProvider.getImage(
Display.getDefault(),
BTSResourceProvider.IMG_EDIT_DISABLED));
}
mayEditLabel.pack();
composite.layout();
composite.pack();
}
}
});
}
}
}
| lgpl-3.0 |
SergiyKolesnikov/fuji | examples/Prevayler/Replication/org/prevayler/foundation/network/NetworkClientObjectReceiverImpl.java | 2209 | package org.prevayler.foundation.network;
import java.io.IOException;
import de.ovgu.cide.jakutil.*;
public class NetworkClientObjectReceiverImpl implements ObjectReceiver {
/**
* our connection to the network
*/
private ObjectSocket _provider;
/**
* the upper layer who we give what we receive to
*/
private ObjectReceiver _client;
private volatile boolean _closing;
public NetworkClientObjectReceiverImpl( String ipAddress, int port, ObjectReceiver client) throws IOException {
this(new ObjectSocketImpl(ipAddress,port),client);
}
public NetworkClientObjectReceiverImpl( ObjectSocket objectSocket, Service service) throws IOException {
_provider=objectSocket;
_client=service.serverFor(this);
startReading();
}
public NetworkClientObjectReceiverImpl( ObjectSocket objectSocket, ObjectReceiver client){
_provider=objectSocket;
_client=client;
startReading();
}
/**
* Create a reader thread
*/
private void startReading(){
Thread reader=new Thread(){
public void run(){
while (!_closing) receiveFromNetwork();
}
}
;
reader.setName("Prevayler Network Client Receiver");
reader.setDaemon(true);
reader.start();
}
/**
* When something is read give it to our client, also give it the exception
*/
private void receiveFromNetwork(){
try {
Object object=_provider.readObject();
passToClient(object);
}
catch ( Exception ex) {
closeDown();
if (_closing) {
return;
}
passToClient(ex);
}
}
private void closeDown(){
try {
close();
}
catch ( IOException ignorable) {
}
try {
_client.close();
}
catch ( IOException neverThrown) {
}
}
private void passToClient( Object object){
try {
_client.receive(object);
}
catch ( IOException unExpected) {
unExpected.printStackTrace();
}
}
/**
* Receive an object from prevayler client to be sent to the network
*/
public void receive( Object object) throws IOException {
_provider.writeObject(object);
}
public void close() throws IOException {
_closing=true;
_provider.close();
}
}
| lgpl-3.0 |
liblouis/liblouis-java | src/test/java/org/liblouis/TableResolverTest.java | 1308 | package org.liblouis;
import java.io.File;
import java.net.URL;
import java.util.Collections;
import java.util.Set;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.liblouis.Louis.asFile;
import static org.liblouis.Louis.asURL;
public class TableResolverTest {
@Test
public void testMagicTokenTable() throws Exception {
Translator translator = new Translator("<FOOBAR>");
assertEquals(
"foobar",
translator.translate("foobar", null, null, null).getBraille());
}
@Test
public void testIncludeMagicTokenTable() throws Exception {
Translator translator = new Translator("tables/include_magic_token");
assertEquals(
"foobar",
translator.translate("foobar", null, null, null).getBraille());
}
public TableResolverTest() {
final File testRootDir = asFile(this.getClass().getResource("/"));
Louis.setTableResolver(new TableResolver() {
public URL resolve(String table, URL base) {
if (table == null)
return null;
File tableFile = new File(testRootDir, table);
if (tableFile.exists())
return asURL(tableFile);
if (table.equals("<FOOBAR>"))
return resolve("tables/foobar.cti", null);
return null;
}
public Set<String> list() {
return Collections.emptySet();
}
}
);
}
}
| lgpl-3.0 |
h3xstream/find-sec-bugs | findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/injection/script/SpelViewDetector.java | 2037 | /**
* Find Security Bugs
* Copyright (c) Philippe Arteau, All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library.
*/
package com.h3xstream.findsecbugs.injection.script;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.Priorities;
import edu.umd.cs.findbugs.bcel.OpcodeStackDetector;
import static org.apache.bcel.Const.INVOKESPECIAL;
/**
* Detect a pattern that was found in multiple Spring components.
*
* https://gosecure.net/2018/05/15/beware-of-the-magic-spell-part-1-cve-2018-1273/
* http://gosecure.net/2018/05/17/beware-of-the-magic-spell-part-2-cve-2018-1260/
*/
public class SpelViewDetector extends OpcodeStackDetector {
private BugReporter bugReporter;
public SpelViewDetector(BugReporter bugReporter) {
this.bugReporter = bugReporter;
}
@Override
public void sawOpcode(int seen) {
//printOpCode(seen);
if(seen == INVOKESPECIAL) {
String methodName = getNameConstantOperand();
String className = getClassConstantOperand();
if (methodName.equals("<init>") && className.toLowerCase().endsWith("spelview")) { //Constructor named SpelView()
bugReporter.reportBug(new BugInstance(this, "SPEL_INJECTION", Priorities.NORMAL_PRIORITY) //
.addClass(this).addMethod(this).addSourceLine(this).addString("SpelView()"));
}
}
}
}
| lgpl-3.0 |
Albloutant/Galacticraft | dependencies/gregtechmod/api/world/GT_Worldgen.java | 1664 | package gregtechmod.api.world;
import gregtechmod.api.GregTech_API;
import java.util.Random;
import net.minecraft.world.World;
import net.minecraft.world.chunk.IChunkProvider;
public abstract class GT_Worldgen {
public final String mWorldGenName;
public GT_Worldgen(String aName, boolean aDefault) {
mWorldGenName = aName;
if (GregTech_API.sWorldgenFile.add("worldgen", mWorldGenName, aDefault)) {
GregTech_API.sWorldgenList.add(this);
}
}
/**
* @param aWorld The World Object
* @param aRandom The Random Generator to use
* @param aBiome The Name of the Biome (always != null)
* @param aDimensionType The Type of Worldgeneration to add. -1 = Nether, 0 = Overworld, +1 = End
* @param aChunkX xCoord of the Chunk
* @param aChunkZ zCoord of the Chunk
* @return if the Worldgeneration has been successfully completed
*/
public boolean executeWorldgen(World aWorld, Random aRandom, String aBiome, int aDimensionType, int aChunkX, int aChunkZ, IChunkProvider aChunkGenerator, IChunkProvider aChunkProvider) {
return false;
}
/**
* @param aWorld The World Object
* @param aRandom The Random Generator to use
* @param aBiome The Name of the Biome (always != null)
* @param aDimensionType The Type of Worldgeneration to add. -1 = Nether, 0 = Overworld, +1 = End
* @param aChunkX xCoord of the Chunk
* @param aChunkZ zCoord of the Chunk
* @return if the Worldgeneration has been successfully completed
*/
public boolean executeCavegen(World aWorld, Random aRandom, String aBiome, int aDimensionType, int aChunkX, int aChunkZ, IChunkProvider aChunkGenerator, IChunkProvider aChunkProvider) {
return false;
}
}
| lgpl-3.0 |
JKatzwinkel/bts | org.bbaw.bts.model/src/org/bbaw/bts/btsmodel/util/BtsmodelSwitch.java | 37200 | /**
* This file is part of Berlin Text System.
*
* The software Berlin Text System serves as a client user interface for working with
* text corpus data. See: aaew.bbaw.de
*
* The software Berlin Text System was developed at the Berlin-Brandenburg Academy
* of Sciences and Humanities, Jägerstr. 22/23, D-10117 Berlin.
* www.bbaw.de
*
* Copyright (C) 2013-2015 Berlin-Brandenburg Academy
* of Sciences and Humanities
*
* The software Berlin Text System was developed by @author: Christoph Plutte.
*
* Berlin Text System is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Berlin Text System 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 Berlin Text System.
* If not, see <http://www.gnu.org/licenses/lgpl-3.0.html>.
*/
package org.bbaw.bts.btsmodel.util;
import java.util.Map;
import org.bbaw.bts.btsmodel.*;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.util.Switch;
/**
* <!-- begin-user-doc -->
* The <b>Switch</b> for the model's inheritance hierarchy.
* It supports the call {@link #doSwitch(EObject) doSwitch(object)}
* to invoke the <code>caseXXX</code> method for each class of the model,
* starting with the actual class of the object
* and proceeding up the inheritance hierarchy
* until a non-null result is returned,
* which is the result of the switch.
* <!-- end-user-doc -->
* @see org.bbaw.bts.btsmodel.BtsmodelPackage
* @generated
*/
public class BtsmodelSwitch<T> extends Switch<T> {
/**
* The cached model package
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected static BtsmodelPackage modelPackage;
/**
* Creates an instance of the switch.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BtsmodelSwitch() {
if (modelPackage == null) {
modelPackage = BtsmodelPackage.eINSTANCE;
}
}
/**
* Checks whether this is a switch for the given package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @parameter ePackage the package in question.
* @return whether this is a switch for the given package.
* @generated
*/
@Override
protected boolean isSwitchFor(EPackage ePackage) {
return ePackage == modelPackage;
}
/**
* Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the first non-null result returned by a <code>caseXXX</code> call.
* @generated
*/
@Override
protected T doSwitch(int classifierID, EObject theEObject) {
switch (classifierID) {
case BtsmodelPackage.ADMINISTRATIV_DATA_OBJECT: {
AdministrativDataObject administrativDataObject = (AdministrativDataObject)theEObject;
T result = caseAdministrativDataObject(administrativDataObject);
if (result == null) result = caseBTSObservableObject(administrativDataObject);
if (result == null) result = caseBTSIdentifiableItem(administrativDataObject);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.BTS_OBJECT: {
BTSObject btsObject = (BTSObject)theEObject;
T result = caseBTSObject(btsObject);
if (result == null) result = caseAdministrativDataObject(btsObject);
if (result == null) result = caseBTSDBBaseObject(btsObject);
if (result == null) result = caseBTSNamedTypedObject(btsObject);
if (result == null) result = caseBTSObservableObject(btsObject);
if (result == null) result = caseBTSIdentifiableItem(btsObject);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.BTS_USER: {
BTSUser btsUser = (BTSUser)theEObject;
T result = caseBTSUser(btsUser);
if (result == null) result = caseBTSObject(btsUser);
if (result == null) result = caseAdministrativDataObject(btsUser);
if (result == null) result = caseBTSDBBaseObject(btsUser);
if (result == null) result = caseBTSNamedTypedObject(btsUser);
if (result == null) result = caseBTSObservableObject(btsUser);
if (result == null) result = caseBTSIdentifiableItem(btsUser);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.BTS_COMMENT: {
BTSComment btsComment = (BTSComment)theEObject;
T result = caseBTSComment(btsComment);
if (result == null) result = caseBTSObject(btsComment);
if (result == null) result = caseAdministrativDataObject(btsComment);
if (result == null) result = caseBTSDBBaseObject(btsComment);
if (result == null) result = caseBTSNamedTypedObject(btsComment);
if (result == null) result = caseBTSObservableObject(btsComment);
if (result == null) result = caseBTSIdentifiableItem(btsComment);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.BTS_INTER_TEXT_REFERENCE: {
BTSInterTextReference btsInterTextReference = (BTSInterTextReference)theEObject;
T result = caseBTSInterTextReference(btsInterTextReference);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.BTS_TRANSLATION: {
BTSTranslation btsTranslation = (BTSTranslation)theEObject;
T result = caseBTSTranslation(btsTranslation);
if (result == null) result = caseBTSIdentifiableItem(btsTranslation);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.BTS_DATE: {
BTSDate btsDate = (BTSDate)theEObject;
T result = caseBTSDate(btsDate);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.BTS_RELATION: {
BTSRelation btsRelation = (BTSRelation)theEObject;
T result = caseBTSRelation(btsRelation);
if (result == null) result = caseBTSIdentifiableItem(btsRelation);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.BTS_CONFIGURATION: {
BTSConfiguration btsConfiguration = (BTSConfiguration)theEObject;
T result = caseBTSConfiguration(btsConfiguration);
if (result == null) result = caseBTSConfig(btsConfiguration);
if (result == null) result = caseBTSObject(btsConfiguration);
if (result == null) result = caseAdministrativDataObject(btsConfiguration);
if (result == null) result = caseBTSDBBaseObject(btsConfiguration);
if (result == null) result = caseBTSNamedTypedObject(btsConfiguration);
if (result == null) result = caseBTSObservableObject(btsConfiguration);
if (result == null) result = caseBTSIdentifiableItem(btsConfiguration);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.BTSDB_BASE_OBJECT: {
BTSDBBaseObject btsdbBaseObject = (BTSDBBaseObject)theEObject;
T result = caseBTSDBBaseObject(btsdbBaseObject);
if (result == null) result = caseBTSIdentifiableItem(btsdbBaseObject);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.BTS_REVISION: {
BTSRevision btsRevision = (BTSRevision)theEObject;
T result = caseBTSRevision(btsRevision);
if (result == null) result = caseBTSIdentifiableItem(btsRevision);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.BTS_TIMESPAN: {
BTSTimespan btsTimespan = (BTSTimespan)theEObject;
T result = caseBTSTimespan(btsTimespan);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.BTS_EXTERNAL_REFERENCE: {
BTSExternalReference btsExternalReference = (BTSExternalReference)theEObject;
T result = caseBTSExternalReference(btsExternalReference);
if (result == null) result = caseBTSIdentifiableItem(btsExternalReference);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.BTS_REFERENCABLE_ITEM: {
BTSReferencableItem btsReferencableItem = (BTSReferencableItem)theEObject;
T result = caseBTSReferencableItem(btsReferencableItem);
if (result == null) result = caseBTSObject(btsReferencableItem);
if (result == null) result = caseAdministrativDataObject(btsReferencableItem);
if (result == null) result = caseBTSDBBaseObject(btsReferencableItem);
if (result == null) result = caseBTSNamedTypedObject(btsReferencableItem);
if (result == null) result = caseBTSObservableObject(btsReferencableItem);
if (result == null) result = caseBTSIdentifiableItem(btsReferencableItem);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.BTS_TRANSLATIONS: {
BTSTranslations btsTranslations = (BTSTranslations)theEObject;
T result = caseBTSTranslations(btsTranslations);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.BTS_CONFIG_ITEM: {
BTSConfigItem btsConfigItem = (BTSConfigItem)theEObject;
T result = caseBTSConfigItem(btsConfigItem);
if (result == null) result = caseBTSConfig(btsConfigItem);
if (result == null) result = caseBTSObservableObject(btsConfigItem);
if (result == null) result = caseBTSIdentifiableItem(btsConfigItem);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.BTS_PASSPORT_EDITOR_CONFIG: {
BTSPassportEditorConfig btsPassportEditorConfig = (BTSPassportEditorConfig)theEObject;
T result = caseBTSPassportEditorConfig(btsPassportEditorConfig);
if (result == null) result = caseBTSIdentifiableItem(btsPassportEditorConfig);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.BTS_USER_GROUP: {
BTSUserGroup btsUserGroup = (BTSUserGroup)theEObject;
T result = caseBTSUserGroup(btsUserGroup);
if (result == null) result = caseBTSObject(btsUserGroup);
if (result == null) result = caseAdministrativDataObject(btsUserGroup);
if (result == null) result = caseBTSDBBaseObject(btsUserGroup);
if (result == null) result = caseBTSNamedTypedObject(btsUserGroup);
if (result == null) result = caseBTSObservableObject(btsUserGroup);
if (result == null) result = caseBTSIdentifiableItem(btsUserGroup);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.BTS_CONFIG: {
BTSConfig btsConfig = (BTSConfig)theEObject;
T result = caseBTSConfig(btsConfig);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.BTS_OBSERVABLE_OBJECT: {
BTSObservableObject btsObservableObject = (BTSObservableObject)theEObject;
T result = caseBTSObservableObject(btsObservableObject);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.BTS_PROJECT: {
BTSProject btsProject = (BTSProject)theEObject;
T result = caseBTSProject(btsProject);
if (result == null) result = caseBTSObject(btsProject);
if (result == null) result = caseAdministrativDataObject(btsProject);
if (result == null) result = caseBTSDBBaseObject(btsProject);
if (result == null) result = caseBTSNamedTypedObject(btsProject);
if (result == null) result = caseBTSObservableObject(btsProject);
if (result == null) result = caseBTSIdentifiableItem(btsProject);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.BTSDB_CONNECTION: {
BTSDBConnection btsdbConnection = (BTSDBConnection)theEObject;
T result = caseBTSDBConnection(btsdbConnection);
if (result == null) result = caseBTSIdentifiableItem(btsdbConnection);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.BTS_WORKFLOW_RULE: {
BTSWorkflowRule btsWorkflowRule = (BTSWorkflowRule)theEObject;
T result = caseBTSWorkflowRule(btsWorkflowRule);
if (result == null) result = caseBTSIdentifiableItem(btsWorkflowRule);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.BTS_OPERATOR: {
BTSOperator btsOperator = (BTSOperator)theEObject;
T result = caseBTSOperator(btsOperator);
if (result == null) result = caseBTSWorkflowRuleItem(btsOperator);
if (result == null) result = caseBTSObservableObject(btsOperator);
if (result == null) result = caseBTSIdentifiableItem(btsOperator);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.BTS_WORKFLOW_RULE_ITEM: {
BTSWorkflowRuleItem btsWorkflowRuleItem = (BTSWorkflowRuleItem)theEObject;
T result = caseBTSWorkflowRuleItem(btsWorkflowRuleItem);
if (result == null) result = caseBTSObservableObject(btsWorkflowRuleItem);
if (result == null) result = caseBTSIdentifiableItem(btsWorkflowRuleItem);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.DB_LEASE: {
DBLease dbLease = (DBLease)theEObject;
T result = caseDBLease(dbLease);
if (result == null) result = caseBTSDBBaseObject(dbLease);
if (result == null) result = caseBTSIdentifiableItem(dbLease);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.BTS_PROJECT_DB_COLLECTION: {
BTSProjectDBCollection btsProjectDBCollection = (BTSProjectDBCollection)theEObject;
T result = caseBTSProjectDBCollection(btsProjectDBCollection);
if (result == null) result = caseBTSIdentifiableItem(btsProjectDBCollection);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.BTS_IDENTIFIABLE_ITEM: {
BTSIdentifiableItem btsIdentifiableItem = (BTSIdentifiableItem)theEObject;
T result = caseBTSIdentifiableItem(btsIdentifiableItem);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.BTSDB_COLLECTION_ROLE_DESC: {
BTSDBCollectionRoleDesc btsdbCollectionRoleDesc = (BTSDBCollectionRoleDesc)theEObject;
T result = caseBTSDBCollectionRoleDesc(btsdbCollectionRoleDesc);
if (result == null) result = caseBTSIdentifiableItem(btsdbCollectionRoleDesc);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.USER_ACTION_COUNTER: {
UserActionCounter userActionCounter = (UserActionCounter)theEObject;
T result = caseUserActionCounter(userActionCounter);
if (result == null) result = caseBTSDBBaseObject(userActionCounter);
if (result == null) result = caseBTSIdentifiableItem(userActionCounter);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.STRING_TO_STRING_LIST_MAP: {
@SuppressWarnings("unchecked") Map.Entry<String, EList<String>> stringToStringListMap = (Map.Entry<String, EList<String>>)theEObject;
T result = caseStringToStringListMap(stringToStringListMap);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.STRING_TO_STRING_MAP: {
Map stringToStringMap = (Map)theEObject;
T result = caseStringToStringMap(stringToStringMap);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.BTSID_RESERVATION_OBJECT: {
BTSIDReservationObject btsidReservationObject = (BTSIDReservationObject)theEObject;
T result = caseBTSIDReservationObject(btsidReservationObject);
if (result == null) result = caseBTSDBBaseObject(btsidReservationObject);
if (result == null) result = caseBTSIdentifiableItem(btsidReservationObject);
if (result == null) result = defaultCase(theEObject);
return result;
}
case BtsmodelPackage.BTS_NAMED_TYPED_OBJECT: {
BTSNamedTypedObject btsNamedTypedObject = (BTSNamedTypedObject)theEObject;
T result = caseBTSNamedTypedObject(btsNamedTypedObject);
if (result == null) result = caseBTSIdentifiableItem(btsNamedTypedObject);
if (result == null) result = defaultCase(theEObject);
return result;
}
default: return defaultCase(theEObject);
}
}
/**
* Returns the result of interpreting the object as an instance of '<em>Administrativ Data Object</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Administrativ Data Object</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseAdministrativDataObject(AdministrativDataObject object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>BTS Object</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>BTS Object</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseBTSObject(BTSObject object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>BTS User</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>BTS User</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseBTSUser(BTSUser object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>BTS Comment</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>BTS Comment</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseBTSComment(BTSComment object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>BTS Inter Text Reference</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>BTS Inter Text Reference</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseBTSInterTextReference(BTSInterTextReference object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>BTS Translation</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>BTS Translation</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseBTSTranslation(BTSTranslation object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>BTS Date</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>BTS Date</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseBTSDate(BTSDate object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>BTS Relation</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>BTS Relation</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseBTSRelation(BTSRelation object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>BTS Configuration</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>BTS Configuration</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseBTSConfiguration(BTSConfiguration object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>BTSDB Base Object</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>BTSDB Base Object</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseBTSDBBaseObject(BTSDBBaseObject object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>BTS Revision</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>BTS Revision</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseBTSRevision(BTSRevision object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>BTS Timespan</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>BTS Timespan</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseBTSTimespan(BTSTimespan object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>BTS External Reference</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>BTS External Reference</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseBTSExternalReference(BTSExternalReference object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>BTS Referencable Item</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>BTS Referencable Item</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseBTSReferencableItem(BTSReferencableItem object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>BTS Translations</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>BTS Translations</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseBTSTranslations(BTSTranslations object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>BTS Config Item</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>BTS Config Item</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseBTSConfigItem(BTSConfigItem object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>BTS Passport Editor Config</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>BTS Passport Editor Config</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseBTSPassportEditorConfig(BTSPassportEditorConfig object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>BTS User Group</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>BTS User Group</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseBTSUserGroup(BTSUserGroup object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>BTS Config</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>BTS Config</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseBTSConfig(BTSConfig object)
{
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>BTS Observable Object</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>BTS Observable Object</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseBTSObservableObject(BTSObservableObject object)
{
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>BTS Project</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>BTS Project</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseBTSProject(BTSProject object)
{
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>BTSDB Connection</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>BTSDB Connection</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseBTSDBConnection(BTSDBConnection object)
{
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>BTS Workflow Rule</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>BTS Workflow Rule</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseBTSWorkflowRule(BTSWorkflowRule object)
{
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>BTS Operator</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>BTS Operator</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseBTSOperator(BTSOperator object)
{
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>BTS Workflow Rule Item</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>BTS Workflow Rule Item</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseBTSWorkflowRuleItem(BTSWorkflowRuleItem object)
{
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>DB Lease</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>DB Lease</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseDBLease(DBLease object)
{
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>BTS Project DB Collection</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>BTS Project DB Collection</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseBTSProjectDBCollection(BTSProjectDBCollection object)
{
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>BTS Identifiable Item</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>BTS Identifiable Item</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseBTSIdentifiableItem(BTSIdentifiableItem object)
{
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>BTSDB Collection Role Desc</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>BTSDB Collection Role Desc</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseBTSDBCollectionRoleDesc(BTSDBCollectionRoleDesc object)
{
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>User Action Counter</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>User Action Counter</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseUserActionCounter(UserActionCounter object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>String To String List Map</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>String To String List Map</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseStringToStringListMap(Map.Entry<String, EList<String>> object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>String To String Map</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>String To String Map</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseStringToStringMap(Map object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>BTSID Reservation Object</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>BTSID Reservation Object</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseBTSIDReservationObject(BTSIDReservationObject object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>BTS Named Typed Object</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>BTS Named Typed Object</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseBTSNamedTypedObject(BTSNamedTypedObject object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>EObject</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch, but this is the last case anyway.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>EObject</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject)
* @generated
*/
@Override
public T defaultCase(EObject object) {
return null;
}
} //BtsmodelSwitch
| lgpl-3.0 |
philjord/tools | Tools/src/tools/io/ESMByteConvert.java | 1857 | package tools.io;
public class ESMByteConvert
{
public static float extractFloat(byte[] bytes, int start)
{
return Float.intBitsToFloat(((bytes[start + 3] & 0xff) << 24) | ((bytes[start + 2] & 0xff) << 16)
| ((bytes[start + 1] & 0xff) << 8) | (bytes[start + 0] & 0xff));
}
public static byte extractByte(byte[] bytes, int start)
{
return bytes[start];
}
public static short extractUnsignedByte(byte[] bytes, int start)
{
return byteToUnsigned(bytes[start]);
}
public static short byteToUnsigned(byte in)
{
return (short) (in & 0xFF);
}
public static int extractInt(byte[] bytes, int start)
{
return ((bytes[start + 3] & 0xff) << 24) | ((bytes[start + 2] & 0xff) << 16) | ((bytes[start + 1] & 0xff) << 8)
| (bytes[start + 0] & 0xff);
}
public static int extractInt64(byte[] bytes, int start)
{
return ((bytes[start + 7] & 0xff) << 56) | ((bytes[start + 6] & 0xff) << 48) | ((bytes[start + 5] & 0xff) << 40)
| ((bytes[start + 4] & 0xff) << 32) | ((bytes[start + 3] & 0xff) << 24) | ((bytes[start + 2] & 0xff) << 16)
| ((bytes[start + 1] & 0xff) << 8) | (bytes[start + 0] & 0xff);
}
//NOTE returns an int for now as it is unsigned short
public static int extractShort(byte[] bytes, int start)
{
return ((bytes[start + 1] & 0xff) << 8) | (bytes[start + 0] & 0xff);
}
public static void insertFloat(byte[] bytes, float f, int start)
{
/*return Float.intBitsToFloat(
((bytes[start + 3] & 0xff) << 24)
| ((bytes[start + 2] & 0xff) << 16)
| ((bytes[start + 1] & 0xff) << 8)
| (bytes[start + 0] & 0xff));*/
int bits = Float.floatToRawIntBits(f);
bytes[start + 3] = (byte) (bits >> 24);
bytes[start + 2] = (byte) (bits >> 16);
bytes[start + 1] = (byte) (bits >> 8);
bytes[start + 0] = (byte) (bits >> 0);
}
}
| lgpl-3.0 |
nativelibs4java/JNAerator | jnaerator-runtime/src/main/java/com/ochafik/lang/jnaerator/runtime/globals/GlobalNativeSize.java | 1454 | /*
Copyright (c) 2009-2013 Olivier Chafik, All Rights Reserved
This file is part of JNAerator (http://jnaerator.googlecode.com/).
JNAerator is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
JNAerator 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 JNAerator. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ochafik.lang.jnaerator.runtime.globals;
import com.ochafik.lang.jnaerator.runtime.NativeSize;
import com.ochafik.lang.jnaerator.runtime.NativeSizeByReference;
import com.sun.jna.NativeLibrary;
public class GlobalNativeSize extends GlobalPrimitive<NativeSizeByReference> {
public GlobalNativeSize(NativeLibrary library, String... symbols) {
super(library, NativeSizeByReference.class, symbols);
}
public NativeSize get() {
return getValue().getValue();
}
public void set(int v) {
getValue().setValue(new NativeSize(v));
}
public void set(long v) {
getValue().setValue(new NativeSize(v));
}
public void set(NativeSize v) {
getValue().setValue(v);
}
}
| lgpl-3.0 |
AdoptOpenJDK/mjprof | src/main/java/com/performizeit/mjprof/plugins/mappers/singlethread/stackframe/FileNameEliminator.java | 1821 | /*
This file is part of mjprof.
mjprof is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
mjprof 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 mjprof. If not, see <http://www.gnu.org/licenses/>.
*/
package com.performizeit.mjprof.plugins.mappers.singlethread.stackframe;
import com.performizeit.mjprof.api.Plugin;
import com.performizeit.mjprof.model.Profile;
import com.performizeit.mjprof.parser.ThreadInfo;
import com.performizeit.mjprof.plugins.mappers.singlethread.SingleThreadMapperBase;
import java.util.HashMap;
@SuppressWarnings("unused")
@Plugin(name = "-fn", params = {},
description = "Eliminates file name and line from stack frames")
public class FileNameEliminator extends SingleThreadMapperBase {
public FileNameEliminator() {
}
@Override
public ThreadInfo map(ThreadInfo threadInfo) {
HashMap<String, Object> mtd = threadInfo.cloneMetaData();
Profile jss = (Profile) threadInfo.getVal("stack");
jss.visit((sf, level) -> {
if (sf.getStackFrame() == null) return;
sf.setStackFrame(eliminatePackage(sf.getStackFrame()));
});
return threadInfo;
}
public static String eliminatePackage(String stackFrame) {
StackFrame sf = new StackFrame(stackFrame);
sf.setLineNum("");
sf.setFileName("");
return sf.toString();
}
}
| lgpl-3.0 |
SleepyTrousers/EnderIO | enderio-conduits/src/main/java/crazypants/enderio/powertools/machine/capbank/BlockCapBank.java | 17957 | package crazypants.enderio.powertools.machine.capbank;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.enderio.core.api.client.gui.IAdvancedTooltipProvider;
import com.enderio.core.client.handlers.SpecialTooltipHandler;
import com.enderio.core.common.util.NNList;
import com.enderio.core.common.util.NullHelper;
import com.enderio.core.common.vecmath.Vector3d;
import crazypants.enderio.api.IModObject;
import crazypants.enderio.base.BlockEio;
import crazypants.enderio.base.gui.handler.IEioGuiHandler;
import crazypants.enderio.base.integration.baubles.BaublesUtil;
import crazypants.enderio.base.lang.LangPower;
import crazypants.enderio.base.machine.modes.IoMode;
import crazypants.enderio.base.paint.IPaintable;
import crazypants.enderio.base.paint.render.PaintHelper;
import crazypants.enderio.base.render.IBlockStateWrapper;
import crazypants.enderio.base.render.ICustomSubItems;
import crazypants.enderio.base.render.IHaveTESR;
import crazypants.enderio.base.render.ISmartRenderAwareBlock;
import crazypants.enderio.base.render.pipeline.BlockStateWrapperBase;
import crazypants.enderio.base.render.property.EnumMergingBlockRenderMode;
import crazypants.enderio.base.render.property.IOMode;
import crazypants.enderio.base.render.registry.SmartModelAttacher;
import crazypants.enderio.base.render.registry.TextureRegistry;
import crazypants.enderio.base.render.registry.TextureRegistry.TextureSupplier;
import crazypants.enderio.base.tool.ToolUtil;
import crazypants.enderio.powertools.machine.capbank.network.ICapBankNetwork;
import crazypants.enderio.powertools.machine.capbank.network.NetworkUtil;
import crazypants.enderio.powertools.machine.capbank.render.CapBankBlockRenderMapper;
import crazypants.enderio.powertools.machine.capbank.render.CapBankItemRenderMapper;
import crazypants.enderio.powertools.machine.capbank.render.CapBankRenderer;
import crazypants.enderio.util.Prep;
import net.minecraft.block.Block;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.state.BlockFaceShape;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.particle.ParticleManager;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class BlockCapBank extends BlockEio<TileCapBank>
implements IEioGuiHandler.WithPos, IAdvancedTooltipProvider, ISmartRenderAwareBlock, IHaveTESR, ICustomSubItems, IPaintable.ISolidBlockPaintableBlock {
public static BlockCapBank create(@Nonnull IModObject modObject) {
BlockCapBank res = new BlockCapBank(modObject);
res.init();
return res;
}
private static final TextureSupplier gaugeIcon = TextureRegistry.registerTexture("blocks/capacitor_bank_overlays");
private static final TextureSupplier infoPanelIcon = TextureRegistry.registerTexture("blocks/cap_bank_info_panel");
protected BlockCapBank(@Nonnull IModObject modObject) {
super(modObject);
setHardness(2.0F);
setLightOpacity(255);
setDefaultState(getBlockState().getBaseState().withProperty(EnumMergingBlockRenderMode.RENDER, EnumMergingBlockRenderMode.AUTO)
.withProperty(CapBankType.KIND, CapBankType.NONE));
setShape(mkShape(BlockFaceShape.SOLID));
}
@Override
public BlockItemCapBank createBlockItem(@Nonnull IModObject modObject) {
return modObject.apply(new BlockItemCapBank(this));
}
@Override
protected void init() {
super.init();
SmartModelAttacher.register(this, EnumMergingBlockRenderMode.RENDER, EnumMergingBlockRenderMode.DEFAULTS, EnumMergingBlockRenderMode.AUTO);
}
@Override
protected @Nonnull BlockStateContainer createBlockState() {
return new BlockStateContainer(this, new IProperty[] { EnumMergingBlockRenderMode.RENDER, CapBankType.KIND });
}
@Override
public @Nonnull IBlockState getStateFromMeta(int meta) {
return getDefaultState().withProperty(CapBankType.KIND, CapBankType.getTypeFromMeta(meta));
}
@Override
public int getMetaFromState(@Nonnull IBlockState state) {
return CapBankType.getMetaFromType(state.getValue(CapBankType.KIND));
}
@Override
public @Nonnull IBlockState getActualState(@Nonnull IBlockState state, @Nonnull IBlockAccess worldIn, @Nonnull BlockPos pos) {
return state.withProperty(EnumMergingBlockRenderMode.RENDER, EnumMergingBlockRenderMode.AUTO);
}
@Override
@SideOnly(Side.CLIENT)
public @Nonnull IBlockState getExtendedState(@Nonnull IBlockState state, @Nonnull IBlockAccess world, @Nonnull BlockPos pos) {
CapBankBlockRenderMapper renderMapper = new CapBankBlockRenderMapper(state, world, pos);
IBlockStateWrapper blockStateWrapper = new BlockStateWrapperBase(state, world, pos, renderMapper);
blockStateWrapper.addCacheKey(state.getValue(CapBankType.KIND));
blockStateWrapper.addCacheKey(renderMapper);
TileCapBank tileEntity = getTileEntitySafe(world, pos);
if (tileEntity != null) {
for (EnumFacing face : EnumFacing.values()) {
blockStateWrapper.addCacheKey(tileEntity.getIoMode(NullHelper.notnullJ(face, "Enum.values()")));
blockStateWrapper.addCacheKey(tileEntity.getDisplayType(face));
}
}
blockStateWrapper.bakeModel();
return blockStateWrapper;
}
@Override
@SideOnly(Side.CLIENT)
public @Nonnull BlockRenderLayer getBlockLayer() {
return BlockRenderLayer.CUTOUT;
}
@Override
@Nonnull
public NNList<ItemStack> getSubItems() {
return getSubItems(this, CapBankType.values().length - 1);
}
@Override
@SideOnly(Side.CLIENT)
public void getSubBlocks(@Nonnull CreativeTabs p_149666_2_, @Nonnull NonNullList<ItemStack> list) {
for (CapBankType type : CapBankType.types()) {
if (type.isCreative()) {
list.add(BlockItemCapBank.createItemStackWithPower(CapBankType.getMetaFromType(type), type.getMaxEnergyStored() / 2));
} else {
list.add(BlockItemCapBank.createItemStackWithPower(CapBankType.getMetaFromType(type), 0));
list.add(BlockItemCapBank.createItemStackWithPower(CapBankType.getMetaFromType(type), type.getMaxEnergyStored()));
}
}
}
@Override
public int damageDropped(@Nonnull IBlockState st) {
return getMetaFromState(st);
}
@Override
@SideOnly(Side.CLIENT)
public void addCommonEntries(@Nonnull ItemStack itemstack, @Nullable EntityPlayer entityplayer, @Nonnull List<String> list, boolean flag) {
}
@Override
@SideOnly(Side.CLIENT)
public void addBasicEntries(@Nonnull ItemStack itemstack, @Nullable EntityPlayer entityplayer, @Nonnull List<String> list, boolean flag) {
list.add(LangPower.RF(BlockItemCapBank.getStoredEnergyForItem(itemstack), CapBankType.getTypeFromMeta(itemstack.getItemDamage()).getMaxEnergyStored()));
}
@Override
@SideOnly(Side.CLIENT)
public void addDetailedEntries(@Nonnull ItemStack itemstack, @Nullable EntityPlayer entityplayer, @Nonnull List<String> list, boolean flag) {
SpecialTooltipHandler.addDetailedTooltipFromResources(list, itemstack);
}
@Override
public boolean onBlockActivated(@Nonnull World world, @Nonnull BlockPos pos, @Nonnull IBlockState state, @Nonnull EntityPlayer entityPlayer,
@Nonnull EnumHand hand, @Nonnull EnumFacing faceHit, float hitX, float hitY, float hitZ) {
TileCapBank tcb = getTileEntity(world, pos);
if (tcb == null) {
return false;
}
if (entityPlayer.isSneaking() && Prep.isInvalid(entityPlayer.getHeldItem(hand)) && faceHit.getFrontOffsetY() == 0) {
InfoDisplayType newDisplayType = tcb.getDisplayType(faceHit).next();
if (newDisplayType == InfoDisplayType.NONE) {
tcb.setDefaultIoMode(faceHit);
} else {
tcb.setIoMode(faceHit, IoMode.DISABLED);
}
tcb.setDisplayType(faceHit, newDisplayType);
return true;
}
if (!entityPlayer.isSneaking() && ToolUtil.isToolEquipped(entityPlayer, hand)) {
IoMode ioMode = tcb.getIoMode(faceHit);
if (faceHit.getFrontOffsetY() == 0) {
if (ioMode == IoMode.DISABLED) {
InfoDisplayType newDisplayType = tcb.getDisplayType(faceHit).next();
tcb.setDisplayType(faceHit, newDisplayType);
if (newDisplayType == InfoDisplayType.NONE) {
tcb.toggleIoModeForFace(faceHit);
}
} else {
tcb.toggleIoModeForFace(faceHit);
}
} else {
tcb.toggleIoModeForFace(faceHit);
}
if (!world.isRemote) {
world.notifyNeighborsOfStateChange(pos, this, true);
}
world.notifyBlockUpdate(pos, state, state, 3);
return true;
}
return super.onBlockActivated(world, pos, state, entityPlayer, hand, faceHit, hitX, hitY, hitZ);
}
@Override
protected boolean openGui(@Nonnull World world, @Nonnull BlockPos pos, @Nonnull EntityPlayer entityPlayer, @Nonnull EnumFacing side) {
return openGui(world, pos, entityPlayer, side, baublesToGuiId(BaublesUtil.instance().getBaubles(entityPlayer)));
}
private static int baublesToGuiId(IInventory baubles) {
if (baubles != null && baubles.getSizeInventory() == 4) {
return 4;
} else if (baubles != null && baubles.getSizeInventory() == 7) {
return 7;
} else {
return 0;
}
}
@Override
@Nullable
public Container getServerGuiElement(@Nonnull EntityPlayer player, @Nonnull World world, @Nonnull BlockPos pos, @Nullable EnumFacing facing, int param1) {
TileCapBank te = getTileEntity(world, pos);
if (te != null) {
return new ContainerCapBank(player.inventory, te);
}
return null;
}
@Override
@Nullable
@SideOnly(Side.CLIENT)
public GuiScreen getClientGuiElement(@Nonnull EntityPlayer player, @Nonnull World world, @Nonnull BlockPos pos, @Nullable EnumFacing facing, int param1) {
TileCapBank te = getTileEntity(world, pos);
if (te != null) {
return new GuiCapBank(player, player.inventory, te, new ContainerCapBank(player.inventory, te));
}
return null;
}
@Override
public boolean isSideSolid(@Nonnull IBlockState bs, @Nonnull IBlockAccess world, @Nonnull BlockPos pos, @Nonnull EnumFacing side) {
return true;
}
@Override
public boolean isOpaqueCube(@Nonnull IBlockState bs) {
return false;
}
@Override
@SideOnly(Side.CLIENT)
@Deprecated
public boolean shouldSideBeRendered(@Nonnull IBlockState bs, @Nonnull IBlockAccess par1IBlockAccess, @Nonnull BlockPos pos, @Nonnull EnumFacing side) {
Block i1 = par1IBlockAccess.getBlockState(pos.offset(side)).getBlock();
return i1 == this ? false : super.shouldSideBeRendered(bs, par1IBlockAccess, pos, side);
}
@SideOnly(Side.CLIENT)
public static @Nonnull TextureAtlasSprite getGaugeIcon() {
return gaugeIcon.get(TextureAtlasSprite.class);
}
@SideOnly(Side.CLIENT)
public static @Nonnull TextureAtlasSprite getInfoPanelIcon() {
return infoPanelIcon.get(TextureAtlasSprite.class);
}
@Override
@Deprecated
public void neighborChanged(@Nonnull IBlockState state, @Nonnull World world, @Nonnull BlockPos pos, @Nonnull Block neighborBlock,
@Nonnull BlockPos neighborPos) {
if (world.isRemote) {
return;
}
TileCapBank te = getTileEntity(world, pos);
if (te != null) {
te.onNeighborBlockChange(neighborBlock);
}
}
@Override
public void onBlockPlaced(@Nonnull World world, @Nonnull BlockPos pos, @Nonnull IBlockState state, @Nonnull EntityLivingBase player,
@Nonnull TileCapBank te) {
super.onBlockPlaced(world, pos, state, player, te);
boolean neigbours = NetworkUtil.hasNeigbours(te);
if (!neigbours) {
int heading = MathHelper.floor(player.rotationYaw * 4.0F / 360.0F + 0.5D) & 3;
EnumFacing dir = getDirForHeading(heading);
te.setDisplayType(dir, InfoDisplayType.LEVEL_BAR);
} else {
boolean modifiedDisplayType;
modifiedDisplayType = setDisplayToVerticalFillBar(te, getTileEntity(world, pos.down()));
modifiedDisplayType |= setDisplayToVerticalFillBar(te, getTileEntity(world, pos.up()));
if (modifiedDisplayType) {
te.validateDisplayTypes();
}
}
if (world.isRemote) {
return;
}
world.notifyBlockUpdate(pos, state, state, 3);
}
protected boolean setDisplayToVerticalFillBar(TileCapBank cb, TileCapBank capBank) {
boolean modifiedDisplayType = false;
if (capBank != null) {
for (EnumFacing dir : EnumFacing.VALUES) {
if (dir.getFrontOffsetY() == 0 && capBank.getDisplayType(dir) == InfoDisplayType.LEVEL_BAR && capBank.getType() == cb.getType()) {
cb.setDisplayType(dir, InfoDisplayType.LEVEL_BAR);
modifiedDisplayType = true;
}
}
}
return modifiedDisplayType;
}
protected EnumFacing getDirForHeading(int heading) {
switch (heading) {
case 0:
return EnumFacing.values()[2];
case 1:
return EnumFacing.values()[5];
case 2:
return EnumFacing.values()[3];
case 3:
default:
return EnumFacing.values()[4];
}
}
@Override
@SideOnly(Side.CLIENT)
@Deprecated
public @Nonnull AxisAlignedBB getSelectedBoundingBox(@Nonnull IBlockState bs, @Nonnull World world, @Nonnull BlockPos pos) {
TileCapBank tr = getTileEntity(world, pos);
if (tr == null) {
return super.getSelectedBoundingBox(bs, world, pos);
}
ICapBankNetwork network = tr.getNetwork();
if (!tr.getType().isMultiblock() || network == null) {
return super.getSelectedBoundingBox(bs, world, pos);
}
Vector3d min = new Vector3d(Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE);
Vector3d max = new Vector3d(-Double.MAX_VALUE, -Double.MAX_VALUE, -Double.MAX_VALUE);
for (TileCapBank bc : network.getMembers()) {
int x = bc.getPos().getX();
int y = bc.getPos().getY();
int z = bc.getPos().getZ();
min.x = Math.min(min.x, x);
max.x = Math.max(max.x, x + 1);
min.y = Math.min(min.y, y);
max.y = Math.max(max.y, y + 1);
min.z = Math.min(min.z, z);
max.z = Math.max(max.z, z + 1);
}
return new AxisAlignedBB(min.x, min.y, min.z, max.x, max.y, max.z);
}
@Override
public boolean hasComparatorInputOverride(@Nonnull IBlockState bs) {
return true;
}
@Override
public int getComparatorInputOverride(@Nonnull IBlockState bs, @Nonnull World world, @Nonnull BlockPos pos) {
TileCapBank te = getTileEntity(world, pos);
if (te != null) {
return te.getComparatorOutput();
}
return 0;
}
@Override
@SideOnly(Side.CLIENT)
public @Nonnull CapBankItemRenderMapper getItemRenderMapper() {
return CapBankItemRenderMapper.instance;
}
@SideOnly(Side.CLIENT)
public @Nonnull IOMode.EnumIOMode mapIOMode(InfoDisplayType displayType, IoMode mode) {
switch (displayType) {
case IO:
return IOMode.EnumIOMode.CAPACITORBANK;
case LEVEL_BAR:
switch (mode) {
case NONE:
return IOMode.EnumIOMode.CAPACITORBANK;
case PULL:
return IOMode.EnumIOMode.CAPACITORBANKINPUTSMALL;
case PUSH:
return IOMode.EnumIOMode.CAPACITORBANKOUTPUTSMALL;
case PUSH_PULL:
return IOMode.EnumIOMode.CAPACITORBANK;
case DISABLED:
return IOMode.EnumIOMode.CAPACITORBANKLOCKEDSMALL;
}
case NONE:
switch (mode) {
case NONE:
return IOMode.EnumIOMode.CAPACITORBANK;
case PULL:
return IOMode.EnumIOMode.CAPACITORBANKINPUT;
case PUSH:
return IOMode.EnumIOMode.CAPACITORBANKOUTPUT;
case PUSH_PULL:
return IOMode.EnumIOMode.CAPACITORBANK;
case DISABLED:
return IOMode.EnumIOMode.CAPACITORBANKLOCKED;
}
}
throw new RuntimeException("Hey, leave our enums alone!");
}
@Override
@SideOnly(Side.CLIENT)
public void bindTileEntitySpecialRenderer() {
ClientRegistry.bindTileEntitySpecialRenderer(TileCapBank.class, new CapBankRenderer(this));
}
@Override
public boolean canConnectRedstone(@Nonnull IBlockState state, @Nonnull IBlockAccess world, @Nonnull BlockPos pos, @Nullable EnumFacing side) {
return true;
}
// ///////////////////////////////////////////////////////////////////////
// PAINT START
// ///////////////////////////////////////////////////////////////////////
@Override
public boolean canRenderInLayer(@Nonnull IBlockState state, @Nonnull BlockRenderLayer layer) {
return true;
}
@SideOnly(Side.CLIENT)
@Override
public boolean addHitEffects(@Nonnull IBlockState state, @Nonnull World world, @Nonnull RayTraceResult target, @Nonnull ParticleManager effectRenderer) {
return PaintHelper.addHitEffects(state, world, target, effectRenderer);
}
@SideOnly(Side.CLIENT)
@Override
public boolean addDestroyEffects(@Nonnull World world, @Nonnull BlockPos pos, @Nonnull ParticleManager effectRenderer) {
return PaintHelper.addDestroyEffects(world, pos, effectRenderer);
}
// ///////////////////////////////////////////////////////////////////////
// PAINT END
// ///////////////////////////////////////////////////////////////////////
}
| unlicense |
Narcisse/ProjetIntegrateur | src/vue/Attributs/Vie.java | 842 | package vue.Attributs;
import vue.Attributs.Attribut;
import java.util.ArrayList;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import vue.ElementsPrincipauxDuJeu.Carte;
import vue.ElementsPrincipauxDuJeu.Ennemi;
import vue.ElementsPrincipauxDuJeu.Joueur;
/**
*
* @author Guillaume
*/
public class Vie extends Attribut {
double rare;
int augmenteVie = 25;
public Vie(Carte uneCarte) throws SlickException {
super(uneCarte);
super.setImage(new Image("data/sprites/objet/Vie.png", false, Image.FILTER_NEAREST));
}
public void action() {
}
public void action(Joueur unJoueur) {
unJoueur.addHP(augmenteVie);
}
public void action(Ennemi unEnnemi) {
}
public void action(ArrayList uneListe) {
}
}
| unlicense |
AnonymousProductions/MineFantasy2 | src/main/java/mods/battlegear2/api/core/InventorySlotType.java | 308 | package mods.battlegear2.api.core;
/**
* Created by GotoLink on 24/04/2014.
*/
public enum InventorySlotType {
/**
* The main inventory space
*/
MAIN,
/**
* The armor inventory space
*/
ARMOR,
/**
* The inventory space added by battlegear
*/
BATTLE
}
| apache-2.0 |
seeburger-ag/seeburger-vfs2 | vfs2provider-digestarc/src/main/java/com/seeburger/vfs2/provider/digestarc/DarcTree.java | 17664 | /*
* DarcTree.java
*
* created at 2013-09-16 by Bernd Eckenfels <b.eckenfels@seeburger.de>
*
* Copyright (c) SEEBURGER AG, Germany. All Rights Reserved.
*/
package com.seeburger.vfs2.provider.digestarc;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.security.DigestInputStream;
import java.security.DigestOutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;
import org.apache.commons.vfs2.FileContent;
import org.apache.commons.vfs2.FileNotFolderException;
import org.apache.commons.vfs2.FileObject;
public class DarcTree
{
static final Charset ASCII = Charset.forName("ASCII");
DarcTree.Directory root;
public DarcTree()
{
this.root = new Directory(new HashMap<String, Entry>());
}
/** Read the root directory of this tree from InputStream. */
public DarcTree(InputStream is, String expectedHash) throws IOException
{
//System.out.println("Initiating DarcTree from hash " + expectedHash);
root = new Directory(new DataInputStream(is), expectedHash);
}
public Entry resolveName(String name, BlobStorageProvider provider) throws IOException
{
if (name.equals("/"))
return root;
String[] parts = name.split("/");
Entry me = root;
for(int i=1;i<parts.length;i++)
{
Entry child;
try
{
child = me.getChild(parts[i], provider);
}
catch (FileNotFolderException fne)
{
throw new FileNotFolderException(name + " (pos " + (i-1) + ")"); // TODO intermediate
}
if (child == null)
{
return null; // if file or parent does not exist
}
me = child;
}
return me;
}
/** Adds a mutable parent, and adds this path to it.
* @throws IOException */
public void createFolder(String name, BlobStorageProvider provider) throws IOException
{
String[] parts = name.split("/");
Entry me = root;
for(int i=1;i<parts.length;i++)
{
Entry child;
try
{
child = me.getChild(parts[i], provider);
}
catch (FileNotFolderException fnf)
{
throw new FileNotFolderException(name + " (pos " + (i-1) + ")"); // TODO intermediate
}
if (child == null)
{
// me is the last existing entry
Directory parentDir = (Directory)me;
Directory newChild = null;
for(int j=i;j<parts.length;j++)
{
newChild = new Directory(new HashMap<String, Entry>());
parentDir.addDirectory(parts[j], newChild, provider);
parentDir = newChild;
}
return;
}
me = child;
}
}
public void addFile(String name, String hash, long length, BlobStorageProvider provider) throws IOException
{
if (name.equals("/"))
throw new RuntimeException("Cannot overwrite root.");
String[] parts = name.split("/");
Entry me = root;
Entry child = root;
for(int i=1;i<parts.length-1;i++)
{
try
{
child = me.getChild(parts[i], provider);
}
catch (FileNotFolderException fnf)
{
throw new FileNotFolderException(name + " (pos " + (i-1) + ")"); // TODO intermediate
}
if (child == null)
{
// me is the last existing entry
Directory parentDir = (Directory)me;
Directory newChild = null;
for(int j=i;j<parts.length-1;j++)
{
newChild = new Directory(new HashMap<String, Entry>());
parentDir.addDirectory(parts[j], newChild, provider);
parentDir = newChild;
}
child = parentDir;
break;
}
me = child;
}
// child is the parent of the file
((Directory)child).addFile(parts[parts.length-1], length, hash, provider);
}
public void delete(String name, BlobStorageProvider provider) throws IOException
{
if (name.equals("/"))
throw new RuntimeException("Cannot delete root.");
String[] parts = name.split("/");
Entry me = root;
Entry child = root;
for(int i=1;i<parts.length;i++)
{
me = child;
try
{
child = me.getChild(parts[i], provider);
}
catch (FileNotFolderException fnf)
{
throw new FileNotFolderException(name + " (pos " + (i-1) + ")"); // TODO intermediate
}
if (child == null)
{
throw new RuntimeException("Not found " + name);
}
}
((Directory)me).removeChild(parts[parts.length-1], provider);
}
abstract class Entry
{
String hash;
long size;
abstract Entry getChild(String string, BlobStorageProvider provider) throws IOException;
abstract String getHash();
}
class File extends Entry
{
File(long size, String string)
{
this.size = size;
this.hash = string;
}
@Override
String getHash()
{
return hash;
}
@Override
Entry getChild(String name, BlobStorageProvider provider) throws IOException
{
throw new FileNotFolderException(name); // This exception will be replace with same but proper arg(s)
}
long getSize()
{
return size;
}
}
class Directory extends Entry
{
private static final byte DIRECTORY_MARKER = 'D';
private static final byte FILE_MARKER = 'F';
Map<String, Entry> content;
boolean modified;
Directory(String hash)
{
this.content = null;
this.hash = hash;
this.modified = false;
}
Directory(DataInputStream dis, String expectedHash) throws IOException
{
this.content = readFromStream(dis, expectedHash);
this.hash = expectedHash;
this.modified = false;
}
Directory(Map<String, Entry> content)
{
this.content = content;
this.hash = null;
this.modified = true;
}
public String[] getChildrenNames(BlobStorageProvider provider) throws IOException
{
materializeContent(provider);
Set<String> keys = content.keySet();
return keys.toArray(new String[keys.size()]);
}
public void addFile(String name, long length, String hash, BlobStorageProvider provider) throws IOException
{
materializeContent(provider);
Entry file = new File(length, hash);
content.put(name, file);
modified = true;
}
public void removeChild(String name, BlobStorageProvider provider) throws IOException
{
materializeContent(provider);
Entry entry = content.remove(name);
if (entry != null)
modified = true;
}
public void addDirectory(String name, Directory newChild, BlobStorageProvider provider) throws IOException
{
materializeContent(provider);
modified = true;
content.put(name, newChild);
}
Entry getChild(String name, BlobStorageProvider provider) throws IOException
{
materializeContent(provider);
return content.get(name); // might be null
}
String writeToStream(OutputStream target) throws IOException
{
// First we create a in-memory buffer
ByteArrayOutputStream bos = new ByteArrayOutputStream(content.size() * 30);
DataOutputStream out = new DataOutputStream(bos);
ArrayList<String> names = new ArrayList<String>(content.keySet());
Collections.sort(names);
for(String name : names)
{
Entry e = content.get(name);
if (e instanceof Directory)
{
out.writeByte(DIRECTORY_MARKER);
out.writeByte(1); // record format version (1=plain)
out.writeUTF(name);
out.writeUTF(e.getHash());
}
else if (e instanceof File)
{
File f = (File)e;
out.writeByte(FILE_MARKER);
out.writeByte(1);
out.writeUTF(name);
out.writeLong(f.getSize());
out.writeUTF(f.getHash());
}
}
out.close();
byte[] buf = bos.toByteArray(); bos = null;
OutputStream cout = new DeflaterOutputStream(target);
DigestOutputStream digester = new DigestOutputStream(cout, getDigester());
// then we write it all to a compressed stream
DataOutputStream dout = new DataOutputStream(digester);
dout.writeBytes("seetree ");
String size = String.valueOf(buf.length);
dout.writeBytes(size);
dout.writeByte(0);
dout.write(buf);
dout.close();
return asHex(digester.getMessageDigest().digest());
}
@Override
String getHash()
{
return hash;
}
private void materializeContent(BlobStorageProvider provider) throws IOException
{
if (content != null)
return;
FileObject dir = provider.resolveFileHash(hash);
try
{
FileContent fileContent = dir.getContent();
InputStream is = fileContent.getInputStream();
content = readFromStream(is, hash);
} finally {
dir.close();
}
}
/** Read directory from stream and compare the hash.
* @throws IOException */
private Map<String, Entry> readFromStream(InputStream is, String expectedHash) throws IOException
{
InflaterInputStream inflated = new InflaterInputStream(is);
DigestInputStream digester = new DigestInputStream(inflated, getDigester());
DataInputStream dis = new DataInputStream(digester);
readHeader(dis, "seetree");
Map<String, Entry> newContent = new HashMap<String, Entry>(20);
while(true)
{
int type = dis.read();
if (type == -1)
{
break;
}
switch(type)
{
case DIRECTORY_MARKER:
byte ver = dis.readByte();
if (ver != 1)
throw new IOException("Directory Entry with version " + (int)ver +" is unknown");
String name = dis.readUTF();
String hash = dis.readUTF();
Entry entry = new Directory(hash);
newContent.put(name, entry);
break;
case FILE_MARKER:
ver = dis.readByte();
if (ver != 1)
throw new IOException("File Entry with version " + (int)ver +" is unknown");
name = dis.readUTF();
size = dis.readLong();
hash = dis.readUTF();
entry = new File(size, hash);
newContent.put(name, entry);
break;
default:
throw new IOException("Unknown record identifier " + type);
}
} // end while
dis.close();
String digest = asHex(digester.getMessageDigest().digest());
if (expectedHash != null && !expectedHash.equals(digest))
{
throw new IOException("While readig file with expected hash=" + expectedHash + " we read corrupted data with hash=" + digest);
}
return newContent;
}
/**
* Read and verify the tree header
*
* @throws IOException if reading failed or header was malformed.
*/
private long readHeader(InputStream in, String expectedType) throws IOException
{
int typeLen = expectedType.length() + 1;
byte[] buf = new byte[typeLen + 19 + 1]; // "tree <long digits>\0"
try
{
DarcFileUtil.readFully(in, buf, 0, typeLen);
}
catch (EOFException eof)
{
throw new IOException("Malformed tree header. Cannot read magic=" + expectedType, eof);
}
int i;
for(i=typeLen;i<buf.length;i++)
{
int c = in.read();
if (c == -1)
{
throw new IOException("Malformed tree header. EOF while reading header at pos=" + i);
}
buf[i] = (byte)c;
// length is \0 terminated
if (c == 0)
{
break;
}
}
if (i == buf.length)
{
throw new IOException("Malformed tree header, no NUL byte till pos=" + i);
}
final String header = new String(buf, 0, i, ASCII);
if (!header.startsWith(expectedType+" "))
{
throw new IOException("Malformed tree header. Expecting=" + expectedType + " found=" + header); // TODO: hex
}
String sizeString = header.substring(typeLen);
try
{
return Long.parseLong(sizeString);
}
catch (NumberFormatException nfe)
{
throw new IOException("Malformed tree header, cannot parse length argument=" + sizeString, nfe);
}
}
@Override
public String toString()
{
return "Directory@" + hashCode() + "[mod=" + modified + ",hash=" + hash + ",\ncont=" + content + "]";
}
}
public MessageDigest getDigester()
{
try
{
return MessageDigest.getInstance("SHA1");
}
catch (NoSuchAlgorithmException e)
{
throw new RuntimeException("Cannot resolve SHA1 hash.", e);
}
}
public static String asHex(byte[] bytes)
{
char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
char[] result = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int i = bytes[j] & 0xFF;
result[j*2] = hexArray[i >> 4];
result[j*2 + 1] = hexArray[i & 0xf];
}
return new String(result);
}
public String commitChanges(BlobStorageProvider provider) throws IOException
{
// depth-first search to write out all dirty directories
return writeChange(root, provider);
}
private String writeChange(Directory dir, BlobStorageProvider provider) throws IOException
{
Map<String, Entry> content = dir.content;
if (content == null)
{
content = Collections.emptyMap();
}
Set<java.util.Map.Entry<String, Entry>> childrens = content.entrySet();
for(java.util.Map.Entry<String, Entry> e : childrens)
{
Entry ent = e.getValue();
// traverse all directories (not only dirty ones as they might have dirty childs)
if (ent instanceof Directory)
{
Directory dir2 = (Directory)ent;
String oldHash = dir2.getHash();
String hash = writeChange(dir2, provider);
// if hash is recalculated we see if if affects current dir
if (hash != null)
{
if (oldHash == null || !oldHash.equals(hash))
{
dir.modified = true; // write out this parent as well as child hash changed
}
}
}
}
if (dir.modified)
{
OutputStream os = provider.getTempStream();
String hash = dir.writeToStream(os);
os.close();
provider.storeTempBlob(os, hash);
dir.hash = hash;
dir.modified = false;
return hash;
}
return null;
}
@Override
public String toString()
{
return super.toString() + "{" + root + "}";
}
} | apache-2.0 |
lsmall/flowable-engine | modules/flowable-cxf/src/test/java/org/flowable/engine/impl/webservice/AbstractWebServiceTaskTest.java | 1620 | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flowable.engine.impl.webservice;
import org.apache.cxf.endpoint.Server;
import org.flowable.engine.impl.test.AbstractFlowableTestCase;
import org.flowable.engine.impl.test.PluggableFlowableExtension;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.extension.ExtendWith;
/**
* An abstract class for unit test of web-service task
*
* @author <a href="mailto:gnodet@gmail.com">Guillaume Nodet</a>
* @author Christophe DENEUX
*/
@Tag("webservice")
@Tag("pluggable")
@ExtendWith(MockWebServiceExtension.class)
@ExtendWith(PluggableFlowableExtension.class)
public abstract class AbstractWebServiceTaskTest extends AbstractFlowableTestCase {
public static final String WEBSERVICE_MOCK_ADDRESS = "http://localhost:63081/webservicemock";
protected WebServiceMock webServiceMock;
protected Server server;
@BeforeEach
protected void setUp(WebServiceMock webServiceMock, Server server) {
this.webServiceMock = webServiceMock;
this.server = server;
}
}
| apache-2.0 |
chetanmeh/jackrabbit-oak | oak-auth-ldap/src/main/java/org/apache/jackrabbit/oak/security/authentication/ldap/impl/LdapIdentityProvider.java | 36971 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.oak.security.authentication.ldap.impl;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.jcr.Credentials;
import javax.jcr.SimpleCredentials;
import javax.net.ssl.SSLContext;
import javax.security.auth.login.LoginException;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.apache.directory.api.ldap.codec.controls.search.pagedSearch.PagedResultsDecorator;
import org.apache.directory.api.ldap.model.constants.SchemaConstants;
import org.apache.directory.api.ldap.model.cursor.CursorException;
import org.apache.directory.api.ldap.model.cursor.SearchCursor;
import org.apache.directory.api.ldap.model.entry.Attribute;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.entry.Value;
import org.apache.directory.api.ldap.model.exception.LdapAuthenticationException;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.exception.LdapInvalidAttributeValueException;
import org.apache.directory.api.ldap.model.message.Response;
import org.apache.directory.api.ldap.model.message.ResultCodeEnum;
import org.apache.directory.api.ldap.model.message.SearchRequest;
import org.apache.directory.api.ldap.model.message.SearchRequestImpl;
import org.apache.directory.api.ldap.model.message.SearchResultDone;
import org.apache.directory.api.ldap.model.message.SearchResultEntry;
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.api.ldap.model.message.controls.PagedResults;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.api.ldap.model.name.Rdn;
import org.apache.directory.ldap.client.api.AbstractPoolableLdapConnectionFactory;
import org.apache.directory.ldap.client.api.DefaultLdapConnectionValidator;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapConnectionConfig;
import org.apache.directory.ldap.client.api.LdapConnectionPool;
import org.apache.directory.ldap.client.api.LookupLdapConnectionValidator;
import org.apache.directory.ldap.client.api.NoVerificationTrustManager;
import org.apache.directory.ldap.client.api.ValidatingPoolableLdapConnectionFactory;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.ConfigurationPolicy;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Service;
import org.apache.jackrabbit.commons.iterator.AbstractLazyIterator;
import org.apache.jackrabbit.oak.commons.DebugTimer;
import org.apache.jackrabbit.oak.spi.security.ConfigurationParameters;
import org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalGroup;
import org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalIdentity;
import org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalIdentityException;
import org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalIdentityProvider;
import org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalIdentityRef;
import org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalUser;
import org.apache.jackrabbit.oak.spi.security.authentication.external.PrincipalNameResolver;
import org.apache.jackrabbit.util.Text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* {@code LdapIdentityProvider} implements an external identity provider that reads users and groups from an ldap
* source.
*
* Please refer to {@link LdapProviderConfig} for configuration options.
*/
@Component(
// note that the metatype information is generated from LdapProviderConfig
policy = ConfigurationPolicy.REQUIRE
)
@Service
public class LdapIdentityProvider implements ExternalIdentityProvider, PrincipalNameResolver {
/**
* default logger
*/
private static final Logger log = LoggerFactory.getLogger(LdapIdentityProvider.class);
/**
* internal configuration
*/
private LdapProviderConfig config;
/**
* the connection pool with connections authenticated with the bind DN
*/
private LdapConnectionPool adminPool;
/**
* admin connection factory
*/
private AbstractPoolableLdapConnectionFactory adminConnectionFactory;
/**
* the connection pool with unbound connections
*/
private UnboundLdapConnectionPool userPool;
/**
* user connection factory
*/
private PoolableUnboundConnectionFactory userConnectionFactory;
/**
* SSL protocols (initialized on init)
*/
private String[] enabledSSLProtocols;
/**
* Default constructor for OSGi
*/
@SuppressWarnings("UnusedDeclaration")
public LdapIdentityProvider() {
}
/**
* Constructor for non-OSGi cases.
* @param config the configuration
*/
public LdapIdentityProvider(@Nonnull LdapProviderConfig config) {
this.config = config;
init();
}
//----------------------------------------------------< SCR integration >---
@SuppressWarnings("UnusedDeclaration")
@Activate
private void activate(Map<String, Object> properties) {
ConfigurationParameters cfg = ConfigurationParameters.of(properties);
config = LdapProviderConfig.of(cfg);
init();
}
@SuppressWarnings("UnusedDeclaration")
@Deactivate
private void deactivate() {
close();
}
/**
* Closes this provider and releases the internal pool. This should be called by Non-OSGi users of this provider.
*/
public void close() {
if (adminPool != null) {
try {
adminPool.close();
} catch (Exception e) {
log.warn("Error while closing LDAP connection pool", e);
}
adminPool = null;
}
if (userPool != null) {
try {
userPool.close();
} catch (Exception e) {
log.warn("Error while closing LDAP connection pool", e);
}
userPool = null;
}
}
//----------------------------------------------< PrincipalNameResolver >---
@Nonnull
@Override
public String fromExternalIdentityRef(@Nonnull ExternalIdentityRef externalIdentityRef) throws ExternalIdentityException {
if (!isMyRef(externalIdentityRef)) {
throw new ExternalIdentityException("Foreign IDP " + externalIdentityRef.getString());
}
return externalIdentityRef.getId();
}
//-------------------------------------------< ExternalIdentityProvider >---
@Nonnull
@Override
public String getName() {
return config.getName();
}
@Override
public ExternalIdentity getIdentity(@Nonnull ExternalIdentityRef ref) throws ExternalIdentityException {
if (!isMyRef(ref)) {
return null;
}
LdapConnection connection = connect();
try {
String userIdAttr = config.getUserConfig().getIdAttribute();
String groupIdAttr = config.getGroupConfig().getIdAttribute();
String[] ca = config.getCustomAttributes();
Entry entry;
if (ca.length == 0) {
entry = connection.lookup(ref.getId(), SchemaConstants.ALL_USER_ATTRIBUTES);
}
else {
List<String> attributes = new ArrayList<>(Arrays.asList(ca));
attributes.add("objectClass");
attributes.add(userIdAttr);
attributes.add(groupIdAttr);
String[] attributeArray = new String[attributes.size()];
attributes.toArray(attributeArray);
entry = connection.lookup(ref.getId(), attributeArray);
}
if (entry == null) {
return null;
} else if (entry.hasObjectClass(config.getUserConfig().getObjectClasses())) {
return createUser(entry, null);
} else if (entry.hasObjectClass(config.getGroupConfig().getObjectClasses())) {
return createGroup(entry, null);
} else {
log.warn("referenced identity is neither user or group: {}", ref.getString());
return null;
}
} catch (LdapException e) {
throw lookupFailedException(e, null);
} finally {
disconnect(connection);
}
}
@Override
public ExternalUser getUser(@Nonnull String userId) throws ExternalIdentityException {
DebugTimer timer = new DebugTimer();
LdapConnection connection = connect();
timer.mark("connect");
try {
Entry entry = getEntry(connection, config.getUserConfig(), userId, config.getCustomAttributes());
timer.mark("lookup");
if (log.isDebugEnabled()) {
log.debug("getUser({}) {}", userId, timer.getString());
}
if (entry != null) {
return createUser(entry, userId);
} else {
return null;
}
} catch (LdapException e) {
throw lookupFailedException(e, timer);
} catch (CursorException e) {
throw lookupFailedException(e, timer);
} finally {
disconnect(connection);
}
}
@Override
public ExternalGroup getGroup(@Nonnull String name) throws ExternalIdentityException {
DebugTimer timer = new DebugTimer();
LdapConnection connection = connect();
timer.mark("connect");
try {
Entry entry = getEntry(connection, config.getGroupConfig(), name, config.getCustomAttributes());
timer.mark("lookup");
if (log.isDebugEnabled()) {
log.debug("getGroup({}) {}", name, timer.getString());
}
if (entry != null) {
return createGroup(entry, name);
} else {
return null;
}
} catch (LdapException e) {
throw lookupFailedException(e, timer);
} catch (CursorException e) {
throw lookupFailedException(e, timer);
} finally {
disconnect(connection);
}
}
@Nonnull
@Override
public Iterator<ExternalUser> listUsers() throws ExternalIdentityException {
try {
final Iterator<Entry> iter = getEntryIterator(config.getUserConfig());
return new AbstractLazyIterator<ExternalUser>() {
@Override
protected ExternalUser getNext() {
while (iter.hasNext()) {
try {
return createUser(iter.next(), null);
} catch (LdapInvalidAttributeValueException e) {
log.warn("Error while creating external user object", e);
}
}
return null;
}
};
} catch (LdapException e) {
throw lookupFailedException(e, null);
} catch (CursorException e) {
throw lookupFailedException(e, null);
}
}
@Nonnull
@Override
public Iterator<ExternalGroup> listGroups() throws ExternalIdentityException {
try {
final Iterator<Entry> iter = getEntryIterator(config.getGroupConfig());
return new AbstractLazyIterator<ExternalGroup>() {
@Override
protected ExternalGroup getNext() {
while (iter.hasNext()) {
try {
return createGroup(iter.next(), null);
} catch (LdapInvalidAttributeValueException e) {
log.warn("Error while creating external user object", e);
}
}
return null;
}
};
} catch (LdapException e) {
throw lookupFailedException(e, null);
} catch (CursorException e) {
throw lookupFailedException(e, null);
}
}
@Override
public ExternalUser authenticate(@Nonnull Credentials credentials) throws ExternalIdentityException, LoginException {
if (!(credentials instanceof SimpleCredentials)) {
log.debug("LDAP IDP can only authenticate SimpleCredentials.");
return null;
}
final SimpleCredentials creds = (SimpleCredentials) credentials;
final ExternalUser user = getUser(creds.getUserID());
if (user != null) {
// OAK-2078: check for non-empty passwords to avoid anonymous bind on weakly configured servers
// see http://tools.ietf.org/html/rfc4513#section-5.1.1 for details.
if (creds.getPassword().length == 0) {
throw new LoginException("Refusing to authenticate against LDAP server: Empty passwords not allowed.");
}
// authenticate
LdapConnection connection = null;
try {
DebugTimer timer = new DebugTimer();
if (userPool == null) {
connection = userConnectionFactory.makeObject();
} else {
connection = userPool.getConnection();
}
timer.mark("connect");
connection.bind(user.getExternalId().getId(), new String(creds.getPassword()));
timer.mark("bind");
if (log.isDebugEnabled()) {
log.debug("authenticate({}) {}", user.getId(), timer.getString());
}
} catch (LdapAuthenticationException e) {
throw new LoginException("Unable to authenticate against LDAP server: " + e.getMessage());
} catch (Exception e) {
throw new ExternalIdentityException("Error while binding user credentials", e);
} finally {
if (connection != null) {
try {
if (userPool == null) {
userConnectionFactory.destroyObject(connection);
} else {
userPool.releaseConnection(connection);
}
} catch (Exception e) {
// ignore
}
}
}
}
return user;
}
//-----------------------------------------------------------< internal >---
/**
* Collects the declared (direct) groups of an identity
* @param ref reference to the identity
* @return map of identities where the key is the DN of the LDAP entity
*/
Map<String, ExternalIdentityRef> getDeclaredGroupRefs(ExternalIdentityRef ref) throws ExternalIdentityException {
if (!isMyRef(ref)) {
return Collections.emptyMap();
}
String searchFilter = config.getMemberOfSearchFilter(ref.getId());
LdapConnection connection = null;
SearchCursor searchCursor = null;
try {
// Create the SearchRequest object
SearchRequest req = new SearchRequestImpl();
req.setScope(SearchScope.SUBTREE);
String idAttribute = config.getGroupConfig().getIdAttribute();
req.addAttributes(idAttribute == null? SchemaConstants.NO_ATTRIBUTE : idAttribute);
req.setTimeLimit((int) config.getSearchTimeout());
req.setBase(new Dn(config.getGroupConfig().getBaseDN()));
req.setFilter(searchFilter);
if (log.isDebugEnabled()) {
log.debug("getDeclaredGroupRefs: using SearchRequest {}.", req);
}
Map<String, ExternalIdentityRef> groups = new HashMap<String, ExternalIdentityRef>();
DebugTimer timer = new DebugTimer();
connection = connect();
timer.mark("connect");
searchCursor = connection.search(req);
timer.mark("search");
while (searchCursor.next()) {
Response response = searchCursor.get();
if (response instanceof SearchResultEntry) {
Entry resultEntry = ((SearchResultEntry) response).getEntry();
ExternalIdentityRef groupRef = new ExternalIdentityRef(resultEntry.getDn().toString(), this.getName());
groups.put(groupRef.getId(), groupRef);
}
}
timer.mark("iterate");
if (log.isDebugEnabled()) {
log.debug("getDeclaredGroupRefs: search below {} with {} found {} entries. {}",
config.getGroupConfig().getBaseDN(), searchFilter, groups.size(), timer.getString());
}
return groups;
} catch (Exception e) {
log.error("Error during ldap membership search." ,e);
throw new ExternalIdentityException("Error during ldap membership search.", e);
} finally {
if (searchCursor != null) {
try {
searchCursor.close();
} catch (IOException e) {
log.warn("Failed to close search cursor.", e);
}
}
disconnect(connection);
}
}
/**
* Collects the declared (direct) members of a group
* @param ref the reference to the group
* @return map of identity refers
* @throws ExternalIdentityException if an error occurs
*/
Map<String, ExternalIdentityRef> getDeclaredMemberRefs(ExternalIdentityRef ref) throws ExternalIdentityException {
if (!isMyRef(ref)) {
return Collections.emptyMap();
}
LdapConnection connection = null;
try {
Map<String, ExternalIdentityRef> members = new HashMap<String, ExternalIdentityRef>();
DebugTimer timer = new DebugTimer();
connection = connect();
timer.mark("connect");
Entry entry = connection.lookup(ref.getId());
timer.mark("lookup");
Attribute attr = entry.get(config.getGroupMemberAttribute());
if (attr == null) {
log.warn("LDAP group does not have configured attribute: {}", config.getGroupMemberAttribute());
} else {
for (Value value: attr) {
ExternalIdentityRef memberRef = new ExternalIdentityRef(value.getString(), this.getName());
members.put(memberRef.getId(), memberRef);
}
}
timer.mark("iterate");
if (log.isDebugEnabled()) {
log.debug("members lookup of {} found {} members. {}", ref.getId(), members.size(), timer.getString());
}
return members;
} catch (Exception e) {
String msg = "Error during ldap group members lookup.";
log.error(msg ,e);
throw new ExternalIdentityException(msg, e);
} finally {
disconnect(connection);
}
}
//------------------------------------------------------------< private >---
/**
* Initializes the ldap identity provider.
*/
private void init() {
if (adminConnectionFactory != null) {
throw new IllegalStateException("Provider already initialized.");
}
// make sure the JVM supports the TLSv1.1
try {
enabledSSLProtocols = null;
SSLContext.getInstance("TLSv1.1");
} catch (NoSuchAlgorithmException e) {
log.warn("JDK does not support TLSv1.1. Disabling it.");
enabledSSLProtocols = new String[]{"TLSv1"};
}
// setup admin connection pool
LdapConnectionConfig cc = createConnectionConfig();
String bindDN = config.getBindDN();
if (bindDN != null && !bindDN.isEmpty()) {
cc.setName(bindDN);
cc.setCredentials(config.getBindPassword());
}
adminConnectionFactory = new ValidatingPoolableLdapConnectionFactory(cc);
if (config.getAdminPoolConfig().lookupOnValidate()) {
adminConnectionFactory.setValidator(new LookupLdapConnectionValidator());
} else {
adminConnectionFactory.setValidator(new DefaultLdapConnectionValidator());
}
if (config.getAdminPoolConfig().getMaxActive() != 0) {
adminPool = new LdapConnectionPool(adminConnectionFactory);
adminPool.setTestOnBorrow(true);
adminPool.setMaxActive(config.getAdminPoolConfig().getMaxActive());
adminPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
}
// setup unbound connection pool. let's create a new version of the config
cc = createConnectionConfig();
userConnectionFactory = new PoolableUnboundConnectionFactory(cc);
if (config.getUserPoolConfig().lookupOnValidate()) {
userConnectionFactory.setValidator(new UnboundLookupConnectionValidator());
} else {
userConnectionFactory.setValidator(new UnboundConnectionValidator());
}
if (config.getUserPoolConfig().getMaxActive() != 0) {
userPool = new UnboundLdapConnectionPool(userConnectionFactory);
userPool.setTestOnBorrow(true);
userPool.setMaxActive(config.getUserPoolConfig().getMaxActive());
userPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
}
log.info("LdapIdentityProvider initialized: {}", config);
}
/**
* Creates a new connection config based on the config.
* @return the connection config.
*/
@Nonnull
private LdapConnectionConfig createConnectionConfig() {
LdapConnectionConfig cc = new LdapConnectionConfig();
cc.setLdapHost(config.getHostname());
cc.setLdapPort(config.getPort());
cc.setUseSsl(config.useSSL());
cc.setUseTls(config.useTLS());
// todo: implement better trustmanager/keystore management (via sling/felix)
if (config.noCertCheck()) {
cc.setTrustManagers(new NoVerificationTrustManager());
}
if (enabledSSLProtocols != null) {
cc.setEnabledProtocols(enabledSSLProtocols);
}
return cc;
}
@CheckForNull
private Entry getEntry(@Nonnull LdapConnection connection, @Nonnull LdapProviderConfig.Identity idConfig, @Nonnull String id, @Nonnull String[] customAttributes)
throws CursorException, LdapException {
String searchFilter = idConfig.getSearchFilter(id);
// Create the SearchRequest object
SearchRequest req = new SearchRequestImpl();
req.setScope(SearchScope.SUBTREE);
if (customAttributes.length == 0) {
req.addAttributes(SchemaConstants.ALL_USER_ATTRIBUTES);
} else {
req.addAttributes(customAttributes);
}
req.setTimeLimit((int) config.getSearchTimeout());
req.setBase(new Dn(idConfig.getBaseDN()));
req.setFilter(searchFilter);
if (log.isDebugEnabled()) {
log.debug("getEntry: using SearchRequest {}.", req);
}
// Process the request
SearchCursor searchCursor = null;
Entry resultEntry = null;
try {
searchCursor = connection.search(req);
while (searchCursor.next()) {
if (resultEntry != null) {
log.warn("search for {} returned more than one entry. discarding additional ones.", searchFilter);
} else {
// process the SearchResultEntry
Response response = searchCursor.get();
if (response instanceof SearchResultEntry) {
resultEntry = ((SearchResultEntry) response).getEntry();
}
}
}
} finally {
if (searchCursor != null) {
try {
searchCursor.close();
} catch (IOException e) {
log.warn("Failed to close search cursor.", e);
}
}
}
if (log.isDebugEnabled()) {
if (resultEntry == null) {
log.debug("getEntry: search below {} with {} found 0 entries.", idConfig.getBaseDN(), searchFilter);
} else {
log.debug("getEntry: search below {} with {} found {}", idConfig.getBaseDN(), searchFilter, resultEntry.getDn());
}
}
return resultEntry;
}
@Nonnull
private SearchResultIterator getEntryIterator(@Nonnull LdapProviderConfig.Identity idConfig) throws LdapException, CursorException, ExternalIdentityException {
StringBuilder filter = new StringBuilder();
int num = 0;
for (String objectClass: idConfig.getObjectClasses()) {
num++;
filter.append("(objectclass=")
.append(LdapProviderConfig.encodeFilterValue(objectClass))
.append(')');
}
String extraFilter = idConfig.getExtraFilter();
if (extraFilter != null && !extraFilter.isEmpty()) {
num++;
filter.append(extraFilter);
}
String searchFilter = num > 1
? "(&" + filter + ')'
: filter.toString();
return new SearchResultIterator(searchFilter, idConfig);
}
private final class SearchResultIterator implements Iterator<Entry> {
private final String searchFilter;
private final LdapProviderConfig.Identity idConfig;
private byte[] cookie;
private List page = Collections.emptyList();
private boolean searchComplete;
private int pos = -1;
public SearchResultIterator(
@Nonnull String searchFilter,
@Nonnull LdapProviderConfig.Identity idConfig) throws LdapException, CursorException, ExternalIdentityException {
this.searchFilter = searchFilter;
this.idConfig = idConfig;
findNextEntry();
}
//-------------------------------------------------------< Iterator >---
@Override
public boolean hasNext() {
return pos >= 0;
}
@Override
public Entry next() {
if (hasNext()) {
try {
Entry entry = (Entry) page.get(pos);
findNextEntry();
return entry;
} catch (LdapException e) {
log.error("Error while performing LDAP search", e);
} catch (CursorException e) {
log.error("Error while performing LDAP search", e);
} catch (ExternalIdentityException e) {
log.error("Error while performing LDAP search", e);
}
}
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
//-------------------------------------------------------< internal >---
private SearchRequest createSearchRequest(LdapConnection connection, byte[] cookie, @Nonnull String[] userAttributes) throws LdapException {
SearchRequest req = new SearchRequestImpl();
req.setScope(SearchScope.SUBTREE);
if (userAttributes.length == 0) {
req.addAttributes(SchemaConstants.ALL_USER_ATTRIBUTES);
} else {
req.addAttributes(userAttributes);
}
req.setTimeLimit((int) config.getSearchTimeout());
req.setBase(new Dn(idConfig.getBaseDN()));
req.setFilter(searchFilter);
PagedResults pagedSearchControl = new PagedResultsDecorator(connection.getCodecService());
// do paged searches (OAK-2874)
pagedSearchControl.setSize(1000);
pagedSearchControl.setCookie(cookie);
req.addControl(pagedSearchControl);
return req;
}
private boolean loadNextPage() throws ExternalIdentityException, LdapException, CursorException {
if (searchComplete) {
return false;
}
SearchCursor searchCursor = null;
DebugTimer timer = new DebugTimer();
LdapConnection connection = connect();
timer.mark("connect");
page = new ArrayList<Entry>();
try {
SearchRequest req = createSearchRequest(connection, cookie, config.getCustomAttributes());
if (log.isDebugEnabled()) {
log.debug("loadNextPage: using SearchRequest {}.", req);
}
searchCursor = connection.search(req);
while (searchCursor.next()) {
Response response = searchCursor.get();
if (response instanceof SearchResultEntry) {
Entry resultEntry = ((SearchResultEntry) response).getEntry();
page.add(resultEntry);
if (log.isDebugEnabled()) {
log.debug("loadNextPage: search below {} with {} found {}", idConfig.getBaseDN(), searchFilter, resultEntry.getDn());
}
}
}
SearchResultDone done = searchCursor.getSearchResultDone();
cookie = null;
if (done.getLdapResult().getResultCode() != ResultCodeEnum.UNWILLING_TO_PERFORM) {
PagedResults ctrl = (PagedResults) done.getControl(PagedResults.OID);
if (ctrl != null) {
cookie = ctrl.getCookie();
}
}
searchComplete = cookie == null;
timer.mark("lookup");
return !page.isEmpty();
} finally {
if (searchCursor != null) {
try {
searchCursor.close();
} catch (IOException e) {
log.warn("Failed to close search cursor.", e);
}
}
disconnect(connection);
}
}
private void findNextEntry() throws LdapException, CursorException, ExternalIdentityException {
if (pos == -1 && !loadNextPage()) {
return;
}
if (pos + 1 == page.size()) {
pos = -1;
page = Collections.emptyList();
if (!loadNextPage()) {
return;
}
}
pos++;
}
}
@Nonnull
private ExternalUser createUser(@Nonnull Entry entry, @CheckForNull String id)
throws LdapInvalidAttributeValueException {
ExternalIdentityRef ref = new ExternalIdentityRef(entry.getDn().getName(), this.getName());
if (id == null) {
String idAttribute = config.getUserConfig().getIdAttribute();
Attribute attr = entry.get(idAttribute);
if (attr == null) {
throw new LdapInvalidAttributeValueException(ResultCodeEnum.CONSTRAINT_VIOLATION,
"no value found for attribute '" + idAttribute + "' for entry " + entry);
}
id = attr.getString();
}
String path = config.getUserConfig().makeDnPath()
? createDNPath(entry.getDn())
: null;
LdapUser user = new LdapUser(this, ref, id, path);
Map<String, Object> props = user.getProperties();
applyAttributes(props, entry);
return user;
}
@Nonnull
private ExternalGroup createGroup(@Nonnull Entry entry, @CheckForNull String name)
throws LdapInvalidAttributeValueException {
ExternalIdentityRef ref = new ExternalIdentityRef(entry.getDn().getName(), this.getName());
if (name == null) {
String idAttribute = config.getGroupConfig().getIdAttribute();
Attribute attr = entry.get(idAttribute);
if (attr == null) {
throw new LdapInvalidAttributeValueException(ResultCodeEnum.CONSTRAINT_VIOLATION,
"no value found for attribute '" + idAttribute + "' for entry " + entry);
}
name = attr.getString();
}
String path = config.getGroupConfig().makeDnPath()
? createDNPath(entry.getDn())
: null;
LdapGroup group = new LdapGroup(this, ref, name, path);
Map<String, Object> props = group.getProperties();
applyAttributes(props, entry);
return group;
}
private void applyAttributes(Map<String, Object> props, Entry entry)
throws LdapInvalidAttributeValueException {
for (Attribute attr: entry.getAttributes()) {
if (attr.isHumanReadable()) {
final Object propValue;
// for multivalue properties, store as collection
if (attr.size() > 1) {
List<String> values = new ArrayList<String>();
for (Value<?> value : attr) {
values.add(value.getString());
}
propValue = values;
} else {
propValue = attr.getString();
}
props.put(attr.getId(), propValue);
}
}
}
@Nonnull
private LdapConnection connect() throws ExternalIdentityException {
try {
if (adminPool == null) {
return adminConnectionFactory.makeObject();
} else {
return adminPool.getConnection();
}
} catch (Exception e) {
String msg = "Error while connecting to the ldap server.";
log.error(msg, e);
throw new ExternalIdentityException(msg, e);
}
}
private void disconnect(@Nullable LdapConnection connection) {
try {
if (connection != null) {
if (adminPool == null) {
adminConnectionFactory.destroyObject(connection);
} else {
adminPool.releaseConnection(connection);
}
}
} catch (Exception e) {
log.warn("Error while disconnecting from the ldap server.", e);
}
}
private boolean isMyRef(@Nonnull ExternalIdentityRef ref) {
final String refProviderName = ref.getProviderName();
return refProviderName == null || refProviderName.isEmpty() || getName().equals(refProviderName);
}
/**
* Makes the intermediate path of an DN by splitting along the RDNs
* @param dn the dn of the identity
* @return the intermediate path or {@code null} if disabled by config
*/
private static String createDNPath(Dn dn) {
StringBuilder path = new StringBuilder();
for (Rdn rnd: dn.getRdns()) {
if (path.length() > 0) {
path.append('/');
}
path.append(Text.escapeIllegalJcrChars(rnd.toString()));
}
return path.toString();
}
private static ExternalIdentityException lookupFailedException(@Nonnull Exception e, @CheckForNull DebugTimer timer) {
String msg = "Error during ldap lookup. ";
log.error(msg + ((timer != null) ? timer.getString() : ""), e);
return new ExternalIdentityException(msg, e);
}
} | apache-2.0 |
glub/ftpswrap | src/com/glub/secureftp/common/PEMConverter.java | 2139 |
//*****************************************************************************
//*
//* (c) Copyright 2003. Glub Tech, Incorporated. All Rights Reserved.
//*
//* $Id: PEMConverter.java 39 2009-05-11 22:50:09Z gary $
//*
//*****************************************************************************
package com.glub.secureftp.common;
import java.io.*;
public class PEMConverter {
public static void main( String args[] ) throws Exception {
new PEMConverter( args );
}
public PEMConverter( String args[] ) throws Exception {
doIt(args);
}
private void doIt( String args[] ) throws Exception {
String inFile = null;
String outFile = null;
if ( args.length < 1 ) {
System.out.println( "usage: PEMConverter <file.pem>" );
System.exit( 1 );
}
try {
inFile = args[0];
outFile = args[0];
if ( !inFile.toLowerCase().endsWith(".pem") ) {
System.out.println( "The file must end with .pem" );
System.exit( 1 );
}
}
catch (ArrayIndexOutOfBoundsException aiobe) {
System.out.println( "The file must end with .pem");
System.exit( 1 );
}
catch ( StringIndexOutOfBoundsException siobe ) {
System.out.println( "The file must end with .pem" );
System.exit( 1 );
}
File in = new File(inFile);
outFile =
in.getName().substring( 0, in.getName().lastIndexOf(".") ) + ".der";
PEMInputStream pis = null;
try {
pis = new PEMInputStream(new FileInputStream(in));
}
catch (FileNotFoundException fnf) {
System.err.println( fnf.getMessage() );
System.exit( 1 );
}
String curDir = System.getProperty("user.dir");
File out = new File(curDir, outFile);
FileOutputStream fos = new FileOutputStream( out );
System.out.print("Converting from PEM to DER... ");
do {
int i = pis.read();
if (i != -1) {
fos.write(i);
}
else {
System.out.println("done.");
System.out.println("DER file written to: " + out);
pis.close();
fos.close();
return;
}
} while (true);
}
}
| apache-2.0 |
ua-eas/ksd-kc5.2.1-rice2.3.6-ua | rice-middleware/kns/src/main/java/org/kuali/rice/kns/web/comparator/NumericCellComparator.java | 1494 | /**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.kns.web.comparator;
import org.displaytag.model.Cell;
import org.kuali.rice.krad.comparator.NumericValueComparator;
import java.io.Serializable;
import java.util.Comparator;
public class NumericCellComparator implements Comparator, Serializable {
static final long serialVersionUID = 3449202365486147519L;
public int compare(Object o1, Object o2) {
// null guard. non-null value is greater. equal if both are null
if (null == o1 || null == o2) {
return (null == o1 && null == o2) ? 0 : ((null == o1) ? -1 : 1);
}
String numericCompare1 = CellComparatorHelper.getSanitizedStaticValue((Cell) o1);
String numericCompare2 = CellComparatorHelper.getSanitizedStaticValue((Cell) o2);
return NumericValueComparator.getInstance().compare(numericCompare1, numericCompare2);
}
}
| apache-2.0 |
majinkai/pinpoint | profiler/src/test/java/com/navercorp/pinpoint/profiler/instrument/classloading/JarProfilerPluginClassInjectorTest.java | 4765 | /*
* Copyright 2017 NAVER Corp.
*
* 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.navercorp.pinpoint.profiler.instrument.classloading;
import com.navercorp.pinpoint.bootstrap.classloader.PinpointClassLoaderFactory;
import com.navercorp.pinpoint.common.plugin.JarPlugin;
import com.navercorp.pinpoint.common.plugin.Plugin;
import com.navercorp.pinpoint.common.util.ClassLoaderUtils;
import com.navercorp.pinpoint.common.util.CodeSourceUtils;
import com.navercorp.pinpoint.profiler.plugin.PluginConfig;
import com.navercorp.pinpoint.profiler.plugin.PluginPackageFilter;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.util.Collections;
import java.util.List;
import java.util.jar.JarFile;
/**
* @author Woonduk Kang(emeroad)
*/
public class JarProfilerPluginClassInjectorTest {
public static final String CONTEXT_TYPE_MATCH_CLASS_LOADER = "org.springframework.context.support.ContextTypeMatchClassLoader";
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private static final String LOG4_IMPL = "org.slf4j.impl";
@Test
public void testInjectClass() throws Exception {
final Plugin plugin = getMockPlugin("org.slf4j.impl.Log4jLoggerAdapter");
final ClassLoader contextTypeMatchClassLoader = createContextTypeMatchClassLoader(new URL[]{plugin.getURL()});
final PluginPackageFilter pluginPackageFilter = new PluginPackageFilter(Collections.singletonList(LOG4_IMPL));
PluginConfig pluginConfig = new PluginConfig(plugin, pluginPackageFilter);
logger.debug("pluginConfig:{}", pluginConfig);
PlainClassLoaderHandler injector = new PlainClassLoaderHandler(pluginConfig);
final Class<?> loggerClass = injector.injectClass(contextTypeMatchClassLoader, logger.getClass().getName());
logger.debug("ClassLoader{}", loggerClass.getClassLoader());
Assert.assertEquals("check className", loggerClass.getName(), "org.slf4j.impl.Log4jLoggerAdapter");
Assert.assertEquals("check ClassLoader", loggerClass.getClassLoader().getClass().getName(), CONTEXT_TYPE_MATCH_CLASS_LOADER);
}
private ClassLoader createContextTypeMatchClassLoader(URL[] urlArray) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, java.lang.reflect.InvocationTargetException {
final ClassLoader classLoader = this.getClass().getClassLoader();
final Class<ClassLoader> aClass = (Class<ClassLoader>) classLoader.loadClass(CONTEXT_TYPE_MATCH_CLASS_LOADER);
final Constructor<ClassLoader> constructor = aClass.getConstructor(ClassLoader.class);
constructor.setAccessible(true);
List<String> lib = Collections.singletonList(LOG4_IMPL);
ClassLoader testClassLoader = PinpointClassLoaderFactory.createClassLoader(this.getClass().getName(), urlArray, ClassLoader.getSystemClassLoader(), lib);
final ClassLoader contextTypeMatchClassLoader = constructor.newInstance(testClassLoader);
logger.debug("cl:{}",contextTypeMatchClassLoader);
// final Method excludePackage = aClass.getMethod("excludePackage", String.class);
// ReflectionUtils.invokeMethod(excludePackage, contextTypeMatchClassLoader, "org.slf4j");
return contextTypeMatchClassLoader;
}
private Plugin getMockPlugin(String className) throws IOException {
ClassLoader cl = ClassLoaderUtils.getDefaultClassLoader();
Class<?> clazz = null;
try {
clazz = cl.loadClass(className);
} catch (ClassNotFoundException ex) {
throw new RuntimeException(className + " class not found. Caused by:" + ex.getMessage(), ex);
}
return getMockPlugin(clazz);
}
private Plugin<?> getMockPlugin(Class<?> clazz) throws IOException {
final URL location = CodeSourceUtils.getCodeLocation(clazz);
logger.debug("url:{}", location);
JarFile jarFile = new JarFile(location.getPath());
return new JarPlugin<Object>(location, jarFile, Collections.emptyList(), Collections.<String>emptyList());
}
} | apache-2.0 |
kidaa/isis | core/metamodel/src/main/java/org/apache/isis/core/metamodel/interactions/CollectionAddToContext.java | 2298 | /*
* 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.isis.core.metamodel.interactions;
import org.apache.isis.applib.Identifier;
import org.apache.isis.applib.events.CollectionAddToEvent;
import org.apache.isis.core.commons.authentication.AuthenticationSession;
import org.apache.isis.core.metamodel.adapter.ObjectAdapter;
import org.apache.isis.core.metamodel.consent.InteractionContextType;
import org.apache.isis.core.metamodel.consent.InteractionInvocationMethod;
import org.apache.isis.core.metamodel.deployment.DeploymentCategory;
/**
* See {@link InteractionContext} for overview; analogous to
* {@link CollectionAddToEvent}.
*/
public class CollectionAddToContext extends ValidityContext<CollectionAddToEvent> implements ProposedHolder {
private final ObjectAdapter proposed;
public CollectionAddToContext(DeploymentCategory deploymentCategory, final AuthenticationSession session, final InteractionInvocationMethod invocationMethod, final ObjectAdapter target, final Identifier id, final ObjectAdapter proposed) {
super(InteractionContextType.COLLECTION_ADD_TO, deploymentCategory, session, invocationMethod, id, target);
this.proposed = proposed;
}
@Override
public ObjectAdapter getProposed() {
return proposed;
}
@Override
public CollectionAddToEvent createInteractionEvent() {
return new CollectionAddToEvent(ObjectAdapter.Util.unwrap(getTarget()), getIdentifier(), ObjectAdapter.Util.unwrap(getProposed()));
}
}
| apache-2.0 |
ueshin/apache-tez | tez-mapreduce/src/main/java/org/apache/hadoop/mapreduce/split/TezGroupedSplitsInputFormat.java | 7876 | /**
* 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.mapreduce.split;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.classification.InterfaceAudience.Public;
import org.apache.hadoop.classification.InterfaceStability.Evolving;
import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.InputFormat;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.tez.common.ReflectionUtils;
import org.apache.tez.dag.api.TezException;
import org.apache.tez.dag.api.TezUncheckedException;
import com.google.common.base.Preconditions;
/**
* An InputFormat that provides a generic grouping around
* the splits of a real InputFormat
*/
@Public
@Evolving
public class TezGroupedSplitsInputFormat<K, V> extends InputFormat<K, V>
implements Configurable{
private static final Logger LOG = LoggerFactory.getLogger(TezGroupedSplitsInputFormat.class);
InputFormat<K, V> wrappedInputFormat;
int desiredNumSplits = 0;
Configuration conf;
SplitSizeEstimator estimator;
SplitLocationProvider locationProvider;
public TezGroupedSplitsInputFormat() {
}
public void setInputFormat(InputFormat<K, V> wrappedInputFormat) {
this.wrappedInputFormat = wrappedInputFormat;
if (LOG.isDebugEnabled()) {
LOG.debug("wrappedInputFormat: " + wrappedInputFormat.getClass().getName());
}
}
public void setDesiredNumberOfSplits(int num) {
Preconditions.checkArgument(num >= 0);
this.desiredNumSplits = num;
if (LOG.isDebugEnabled()) {
LOG.debug("desiredNumSplits: " + desiredNumSplits);
}
}
public void setSplitSizeEstimator(SplitSizeEstimator estimator) {
Preconditions.checkArgument(estimator != null);
this.estimator = estimator;
if (LOG.isDebugEnabled()) {
LOG.debug("Split size estimator : " + estimator);
}
}
public void setSplitLocationProvider(SplitLocationProvider locationProvider) {
Preconditions.checkArgument(locationProvider != null);
this.locationProvider = locationProvider;
if (LOG.isDebugEnabled()) {
LOG.debug("Split location provider : " + locationProvider);
}
}
@Override
public List<InputSplit> getSplits(JobContext context) throws IOException,
InterruptedException {
List<InputSplit> originalSplits = wrappedInputFormat.getSplits(context);
TezMapReduceSplitsGrouper grouper = new TezMapReduceSplitsGrouper();
String wrappedInputFormatName = wrappedInputFormat.getClass().getName();
return grouper
.getGroupedSplits(conf, originalSplits, desiredNumSplits, wrappedInputFormatName, estimator,
locationProvider);
}
@Override
public RecordReader<K, V> createRecordReader(InputSplit split,
TaskAttemptContext context) throws IOException, InterruptedException {
TezGroupedSplit groupedSplit = (TezGroupedSplit) split;
try {
initInputFormatFromSplit(groupedSplit);
} catch (TezException e) {
throw new IOException(e);
}
return new TezGroupedSplitsRecordReader(groupedSplit, context);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
void initInputFormatFromSplit(TezGroupedSplit split) throws TezException {
if (wrappedInputFormat == null) {
Class<? extends InputFormat> clazz = (Class<? extends InputFormat>)
getClassFromName(split.wrappedInputFormatName);
try {
wrappedInputFormat = org.apache.hadoop.util.ReflectionUtils.newInstance(clazz, conf);
} catch (Exception e) {
throw new TezException(e);
}
}
}
static Class<?> getClassFromName(String name) throws TezException {
return ReflectionUtils.getClazz(name);
}
public class TezGroupedSplitsRecordReader extends RecordReader<K, V> {
TezGroupedSplit groupedSplit;
TaskAttemptContext context;
int idx = 0;
long progress;
RecordReader<K, V> curReader;
public TezGroupedSplitsRecordReader(TezGroupedSplit split,
TaskAttemptContext context) throws IOException {
this.groupedSplit = split;
this.context = context;
}
public void initialize(InputSplit split,
TaskAttemptContext context) throws IOException, InterruptedException {
if (this.groupedSplit != split) {
throw new TezUncheckedException("Splits dont match");
}
if (this.context != context) {
throw new TezUncheckedException("Contexts dont match");
}
initNextRecordReader();
}
public boolean nextKeyValue() throws IOException, InterruptedException {
while ((curReader == null) || !curReader.nextKeyValue()) {
// false return finishes. true return loops back for nextKeyValue()
if (!initNextRecordReader()) {
return false;
}
}
return true;
}
public K getCurrentKey() throws IOException, InterruptedException {
return curReader.getCurrentKey();
}
public V getCurrentValue() throws IOException, InterruptedException {
return curReader.getCurrentValue();
}
public void close() throws IOException {
if (curReader != null) {
curReader.close();
curReader = null;
}
}
protected boolean initNextRecordReader() throws IOException {
if (curReader != null) {
curReader.close();
curReader = null;
if (idx > 0) {
try {
progress += groupedSplit.wrappedSplits.get(idx-1).getLength();
} catch (InterruptedException e) {
throw new TezUncheckedException(e);
}
}
}
// if all chunks have been processed, nothing more to do.
if (idx == groupedSplit.wrappedSplits.size()) {
return false;
}
// get a record reader for the idx-th chunk
try {
curReader = wrappedInputFormat.createRecordReader(
groupedSplit.wrappedSplits.get(idx), context);
curReader.initialize(groupedSplit.wrappedSplits.get(idx), context);
} catch (Exception e) {
throw new RuntimeException (e);
}
idx++;
return true;
}
/**
* return progress based on the amount of data processed so far.
*/
public float getProgress() throws IOException, InterruptedException {
long subprogress = 0; // bytes processed in current split
if (null != curReader) {
// idx is always one past the current subsplit's true index.
subprogress = (long) (curReader.getProgress() * groupedSplit.wrappedSplits
.get(idx - 1).getLength());
}
return Math.min(1.0f, (progress + subprogress)/(float)(groupedSplit.getLength()));
}
}
@Override
public void setConf(Configuration conf) {
this.conf = conf;
}
@Override
public Configuration getConf() {
return conf;
}
}
| apache-2.0 |
srowhani/migrate-app | app/src/main/java/com/dankideacentral/dic/view/WeightedNodeRenderer.java | 36111 | package com.dankideacentral.dic.view;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.MessageQueue;
import android.util.Log;
import android.view.animation.DecelerateInterpolator;
import com.dankideacentral.dic.model.TweetNode;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.maps.android.MarkerManager;
import com.google.maps.android.clustering.Cluster;
import com.google.maps.android.clustering.ClusterItem;
import com.google.maps.android.clustering.ClusterManager;
import com.google.maps.android.clustering.view.ClusterRenderer;
import com.google.maps.android.geometry.Point;
import com.google.maps.android.projection.SphericalMercatorProjection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import static com.google.maps.android.clustering.algo.NonHierarchicalDistanceBasedAlgorithm.MAX_DISTANCE_AT_ZOOM;
/**
* The default view for a ClusterManager. Markers are animated in and out of clusters.
*/
public abstract class WeightedNodeRenderer<T extends ClusterItem> implements ClusterRenderer<T> {
private static final String TAG = "WeightedNodeRenderer";
private static final boolean SHOULD_ANIMATE = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
private final GoogleMap mMap;
private final ClusterManager<T> mClusterManager;
private final float mDensity;
/**
* Sends a notification to the user.
* Abstract as algorithm is not concerned with how this is done.
*/
public abstract void sendUserNotification();
/**
* Markers that are currently on the map.
*/
private Set<MarkerWithPosition> mMarkers = Collections.newSetFromMap(
new ConcurrentHashMap<MarkerWithPosition, Boolean>());
/**
* Markers for single ClusterItems.
*/
private MarkerCache<T> mMarkerCache = new MarkerCache<T>();
/**
* If cluster size is less than this size, display individual markers.
*/
private int mMinClusterSize = 20;
/**
* The currently displayed set of clusters.
*/
private Set<? extends Cluster<T>> mClusters;
/**
* Lookup between markers and the associated cluster.
*/
private Map<Marker, Cluster<T>> mMarkerToCluster = new HashMap<Marker, Cluster<T>>();
private Map<Cluster<T>, Marker> mClusterToMarker = new HashMap<Cluster<T>, Marker>();
/**
* The target zoom level for the current set of clusters.
*/
private float mZoom;
private final ViewModifier mViewModifier = new ViewModifier();
private ClusterManager.OnClusterClickListener<T> mClickListener;
private ClusterManager.OnClusterInfoWindowClickListener<T> mInfoWindowClickListener;
private ClusterManager.OnClusterItemClickListener<T> mItemClickListener;
private ClusterManager.OnClusterItemInfoWindowClickListener<T> mItemInfoWindowClickListener;
public WeightedNodeRenderer(Context context, GoogleMap map, ClusterManager<T> clusterManager) {
mMap = map;
mDensity = context.getResources().getDisplayMetrics().density;
mClusterManager = clusterManager;
}
@Override
public void onAdd() {
mClusterManager.getMarkerCollection().setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
return mItemClickListener != null && mItemClickListener.onClusterItemClick(mMarkerCache.get(marker));
}
});
mClusterManager.getMarkerCollection().setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
@Override
public void onInfoWindowClick(Marker marker) {
if (mItemInfoWindowClickListener != null) {
mItemInfoWindowClickListener.onClusterItemInfoWindowClick(mMarkerCache.get(marker));
}
}
});
mClusterManager.getClusterMarkerCollection().setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
return mClickListener != null && mClickListener.onClusterClick(mMarkerToCluster.get(marker));
}
});
mClusterManager.getClusterMarkerCollection().setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
@Override
public void onInfoWindowClick(Marker marker) {
if (mInfoWindowClickListener != null) {
mInfoWindowClickListener.onClusterInfoWindowClick(mMarkerToCluster.get(marker));
}
}
});
}
@Override
public void onRemove() {
mClusterManager.getMarkerCollection().setOnMarkerClickListener(null);
mClusterManager.getClusterMarkerCollection().setOnMarkerClickListener(null);
}
public int getMinClusterSize() {
return mMinClusterSize;
}
public void setMinClusterSize(int minClusterSize) {
mMinClusterSize = minClusterSize;
}
/**
* ViewModifier ensures only one re-rendering of the view occurs at a time, and schedules
* re-rendering, which is performed by the RenderTask.
*/
@SuppressLint("HandlerLeak")
private class ViewModifier extends Handler {
private static final int RUN_TASK = 0;
private static final int TASK_FINISHED = 1;
private boolean mViewModificationInProgress = false;
private RenderTask mNextClusters = null;
@Override
public void handleMessage(Message msg) {
if (msg.what == TASK_FINISHED) {
mViewModificationInProgress = false;
if (mNextClusters != null) {
// Run the task that was queued up.
sendEmptyMessage(RUN_TASK);
}
return;
}
removeMessages(RUN_TASK);
if (mViewModificationInProgress) {
// Busy - wait for the callback.
return;
}
if (mNextClusters == null) {
// Nothing to do.
return;
}
Projection projection = mMap.getProjection();
if (projection == null) {
// Without a map projection we can't render clusters.
return;
}
RenderTask renderTask;
synchronized (this) {
renderTask = mNextClusters;
mNextClusters = null;
mViewModificationInProgress = true;
}
renderTask.setCallback(new Runnable() {
@Override
public void run() {
sendEmptyMessage(TASK_FINISHED);
}
});
renderTask.setProjection(projection);
renderTask.setMapZoom(mMap.getCameraPosition().zoom);
new Thread(renderTask).start();
}
public void queue(Set<? extends Cluster<T>> clusters) {
synchronized (this) {
// Overwrite any pending cluster tasks - we don't care about intermediate states.
mNextClusters = new RenderTask(clusters);
}
sendEmptyMessage(RUN_TASK);
}
}
/**
* Determine whether the cluster should be rendered as individual markers or a cluster.
*/
protected boolean shouldRenderAsCluster(Cluster<T> cluster) {
return cluster.getSize() >= mMinClusterSize;
}
/**
* Transforms the current view (represented by WeightedNodeRenderer.mClusters and WeightedNodeRenderer.mZoom) to a
* new zoom level and set of clusters.
* <p/>
* This must be run off the UI thread. Work is coordinated in the RenderTask, then queued up to
* be executed by a MarkerModifier.
* <p/>
* There are three stages for the render:
* <p/>
* 1. Markers are added to the map
* <p/>
* 2. Markers are animated to their final position
* <p/>
* 3. Any old markers are removed from the map
* <p/>
* When zooming in, markers are animated out from the nearest existing cluster. When zooming
* out, existing clusters are animated to the nearest new cluster.
*/
private class RenderTask implements Runnable {
final Set<? extends Cluster<T>> clusters;
private Runnable mCallback;
private Projection mProjection;
private SphericalMercatorProjection mSphericalMercatorProjection;
private float mMapZoom;
private RenderTask(Set<? extends Cluster<T>> clusters) {
this.clusters = clusters;
}
/**
* A callback to be run when all work has been completed.
*
* @param callback
*/
public void setCallback(Runnable callback) {
mCallback = callback;
}
public void setProjection(Projection projection) {
this.mProjection = projection;
}
public void setMapZoom(float zoom) {
this.mMapZoom = zoom;
this.mSphericalMercatorProjection = new SphericalMercatorProjection(256 * Math.pow(2, Math.min(zoom, mZoom)));
}
@SuppressLint("NewApi")
public void run() {
if (clusters.equals(WeightedNodeRenderer.this.mClusters)) {
mCallback.run();
return;
}
final MarkerModifier markerModifier = new MarkerModifier();
final float zoom = mMapZoom;
final boolean zoomingIn = zoom > mZoom;
final float zoomDelta = zoom - mZoom;
final Set<MarkerWithPosition> markersToRemove = mMarkers;
final LatLngBounds visibleBounds = mProjection.getVisibleRegion().latLngBounds;
// TODO: Add some padding, so that markers can animate in from off-screen.
// Find all of the existing clusters that are on-screen. These are candidates for
// markers to animate from.
List<Point> existingClustersOnScreen = null;
if (WeightedNodeRenderer.this.mClusters != null && SHOULD_ANIMATE) {
existingClustersOnScreen = new ArrayList<Point>();
for (Cluster<T> c : WeightedNodeRenderer.this.mClusters) {
if (shouldRenderAsCluster(c) && visibleBounds.contains(c.getPosition())) {
Point point = mSphericalMercatorProjection.toPoint(c.getPosition());
existingClustersOnScreen.add(point);
}
}
}
// Create the new markers and animate them to their new positions.
final Set<MarkerWithPosition> newMarkers = Collections.newSetFromMap(
new ConcurrentHashMap<MarkerWithPosition, Boolean>());
for (Cluster<T> c : clusters) {
boolean onScreen = visibleBounds.contains(c.getPosition());
if (zoomingIn && onScreen && SHOULD_ANIMATE) {
Point point = mSphericalMercatorProjection.toPoint(c.getPosition());
Point closest = findClosestCluster(existingClustersOnScreen, point);
if (closest != null) {
LatLng animateTo = mSphericalMercatorProjection.toLatLng(closest);
markerModifier.add(true, new CreateMarkerTask(c, newMarkers, animateTo));
} else {
markerModifier.add(true, new CreateMarkerTask(c, newMarkers, null));
}
} else {
markerModifier.add(onScreen, new CreateMarkerTask(c, newMarkers, null));
}
}
// Wait for all markers to be added.
markerModifier.waitUntilFree();
// Don't remove any markers that were just added. This is basically anything that had
// a hit in the MarkerCache.
markersToRemove.removeAll(newMarkers);
// Find all of the new clusters that were added on-screen. These are candidates for
// markers to animate from.
List<Point> newClustersOnScreen = null;
if (SHOULD_ANIMATE) {
newClustersOnScreen = new ArrayList<Point>();
for (Cluster<T> c : clusters) {
if (shouldRenderAsCluster(c) && visibleBounds.contains(c.getPosition())) {
Point p = mSphericalMercatorProjection.toPoint(c.getPosition());
newClustersOnScreen.add(p);
}
}
}
// Remove the old markers, animating them into clusters if zooming out.
for (final MarkerWithPosition marker : markersToRemove) {
boolean onScreen = visibleBounds.contains(marker.position);
// Don't animate when zooming out more than 3 zoom levels.
// TODO: drop animation based on speed of device & number of markers to animate.
if (!zoomingIn && zoomDelta > -3 && onScreen && SHOULD_ANIMATE) {
final Point point = mSphericalMercatorProjection.toPoint(marker.position);
final Point closest = findClosestCluster(newClustersOnScreen, point);
if (closest != null) {
LatLng animateTo = mSphericalMercatorProjection.toLatLng(closest);
markerModifier.animateThenRemove(marker, marker.position, animateTo);
} else {
markerModifier.remove(true, marker.marker);
}
} else {
markerModifier.remove(onScreen, marker.marker);
}
}
markerModifier.waitUntilFree();
mMarkers = newMarkers;
WeightedNodeRenderer.this.mClusters = clusters;
mZoom = zoom;
mCallback.run();
}
}
@Override
public void onClustersChanged(Set<? extends Cluster<T>> clusters) {
mViewModifier.queue(clusters);
}
@Override
public void setOnClusterClickListener(ClusterManager.OnClusterClickListener<T> listener) {
mClickListener = listener;
}
@Override
public void setOnClusterInfoWindowClickListener(ClusterManager.OnClusterInfoWindowClickListener<T> listener) {
mInfoWindowClickListener = listener;
}
@Override
public void setOnClusterItemClickListener(ClusterManager.OnClusterItemClickListener<T> listener) {
mItemClickListener = listener;
}
@Override
public void setOnClusterItemInfoWindowClickListener(ClusterManager.OnClusterItemInfoWindowClickListener<T> listener) {
mItemInfoWindowClickListener = listener;
}
private static double distanceSquared(Point a, Point b) {
return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);
}
private static Point findClosestCluster(List<Point> markers, Point point) {
if (markers == null || markers.isEmpty()) return null;
// TODO: make this configurable.
double minDistSquared = MAX_DISTANCE_AT_ZOOM * MAX_DISTANCE_AT_ZOOM;
Point closest = null;
for (Point candidate : markers) {
double dist = distanceSquared(candidate, point);
if (dist < minDistSquared) {
closest = candidate;
minDistSquared = dist;
}
}
return closest;
}
/**
* Handles all markerWithPosition manipulations on the map. Work (such as adding, removing, or
* animating a markerWithPosition) is performed while trying not to block the rest of the app's
* UI.
*/
@SuppressLint("HandlerLeak")
private class MarkerModifier extends Handler implements MessageQueue.IdleHandler {
private static final int BLANK = 0;
private final Lock lock = new ReentrantLock();
private final Condition busyCondition = lock.newCondition();
private Queue<CreateMarkerTask> mCreateMarkerTasks = new LinkedList<CreateMarkerTask>();
private Queue<CreateMarkerTask> mOnScreenCreateMarkerTasks = new LinkedList<CreateMarkerTask>();
private Queue<Marker> mRemoveMarkerTasks = new LinkedList<Marker>();
private Queue<Marker> mOnScreenRemoveMarkerTasks = new LinkedList<Marker>();
private Queue<AnimationTask> mAnimationTasks = new LinkedList<AnimationTask>();
/**
* Whether the idle listener has been added to the UI thread's MessageQueue.
*/
private boolean mListenerAdded;
private MarkerModifier() {
super(Looper.getMainLooper());
}
/**
* Creates markers for a cluster some time in the future.
*
* @param priority whether this operation should have priority.
*/
public void add(boolean priority, CreateMarkerTask c) {
lock.lock();
sendEmptyMessage(BLANK);
if (priority) {
mOnScreenCreateMarkerTasks.add(c);
} else {
mCreateMarkerTasks.add(c);
}
lock.unlock();
}
/**
* Removes a markerWithPosition some time in the future.
*
* @param priority whether this operation should have priority.
* @param m the markerWithPosition to remove.
*/
public void remove(boolean priority, Marker m) {
lock.lock();
sendEmptyMessage(BLANK);
if (priority) {
mOnScreenRemoveMarkerTasks.add(m);
} else {
mRemoveMarkerTasks.add(m);
}
lock.unlock();
}
/**
* Animates a markerWithPosition some time in the future.
*
* @param marker the markerWithPosition to animate.
* @param from the position to animate from.
* @param to the position to animate to.
*/
public void animate(MarkerWithPosition marker, LatLng from, LatLng to) {
lock.lock();
mAnimationTasks.add(new AnimationTask(marker, from, to));
lock.unlock();
}
/**
* Animates a markerWithPosition some time in the future, and removes it when the animation
* is complete.
*
* @param marker the markerWithPosition to animate.
* @param from the position to animate from.
* @param to the position to animate to.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void animateThenRemove(MarkerWithPosition marker, LatLng from, LatLng to) {
lock.lock();
AnimationTask animationTask = new AnimationTask(marker, from, to);
animationTask.removeOnAnimationComplete(mClusterManager.getMarkerManager());
mAnimationTasks.add(animationTask);
lock.unlock();
}
@Override
public void handleMessage(Message msg) {
if (!mListenerAdded) {
Looper.myQueue().addIdleHandler(this);
mListenerAdded = true;
}
removeMessages(BLANK);
lock.lock();
try {
// Perform up to 10 tasks at once.
// Consider only performing 10 remove tasks, not adds and animations.
// Removes are relatively slow and are much better when batched.
for (int i = 0; i < 10; i++) {
performNextTask();
}
if (!isBusy()) {
mListenerAdded = false;
Looper.myQueue().removeIdleHandler(this);
// Signal any other threads that are waiting.
busyCondition.signalAll();
} else {
// Sometimes the idle queue may not be called - schedule up some work regardless
// of whether the UI thread is busy or not.
// TODO: try to remove this.
sendEmptyMessageDelayed(BLANK, 10);
}
} finally {
lock.unlock();
}
}
/**
* Perform the next task. Prioritise any on-screen work.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void performNextTask() {
if (!mOnScreenRemoveMarkerTasks.isEmpty()) {
removeMarker(mOnScreenRemoveMarkerTasks.poll());
} else if (!mAnimationTasks.isEmpty()) {
mAnimationTasks.poll().perform();
} else if (!mOnScreenCreateMarkerTasks.isEmpty()) {
mOnScreenCreateMarkerTasks.poll().perform(this);
} else if (!mCreateMarkerTasks.isEmpty()) {
mCreateMarkerTasks.poll().perform(this);
} else if (!mRemoveMarkerTasks.isEmpty()) {
removeMarker(mRemoveMarkerTasks.poll());
}
}
private void removeMarker(Marker m) {
Cluster<T> cluster = mMarkerToCluster.get(m);
mClusterToMarker.remove(cluster);
mMarkerCache.remove(m);
mMarkerToCluster.remove(m);
mClusterManager.getMarkerManager().remove(m);
}
/**
* @return true if there is still work to be processed.
*/
public boolean isBusy() {
try {
lock.lock();
return !(mCreateMarkerTasks.isEmpty() && mOnScreenCreateMarkerTasks.isEmpty() &&
mOnScreenRemoveMarkerTasks.isEmpty() && mRemoveMarkerTasks.isEmpty() &&
mAnimationTasks.isEmpty()
);
} finally {
lock.unlock();
}
}
/**
* Blocks the calling thread until all work has been processed.
*/
public void waitUntilFree() {
while (isBusy()) {
// Sometimes the idle queue may not be called - schedule up some work regardless
// of whether the UI thread is busy or not.
// TODO: try to remove this.
sendEmptyMessage(BLANK);
lock.lock();
try {
if (isBusy()) {
busyCondition.await();
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
}
}
@Override
public boolean queueIdle() {
// When the UI is not busy, schedule some work.
sendEmptyMessage(BLANK);
return true;
}
}
/**
* A cache of markers representing individual ClusterItems.
*/
private static class MarkerCache<T> {
private Map<T, Marker> mCache = new HashMap<T, Marker>();
private Map<Marker, T> mCacheReverse = new HashMap<Marker, T>();
public Marker get(T item) {
return mCache.get(item);
}
public T get(Marker m) {
return mCacheReverse.get(m);
}
public void put(T item, Marker m) {
mCache.put(item, m);
mCacheReverse.put(m, item);
}
public void remove(Marker m) {
T item = mCacheReverse.get(m);
mCacheReverse.remove(m);
mCache.remove(item);
}
}
/**
* Called before the marker for a ClusterItem is added to the map.
*/
protected void onBeforeClusterItemRendered(T item, MarkerOptions markerOptions) {
}
/**
* Called after the marker for a Cluster has been added to the map.
*/
protected void onClusterRendered(Cluster<T> cluster, Marker marker) {
}
/**
* Called after the marker for a ClusterItem has been added to the map.
*/
protected void onClusterItemRendered(T clusterItem, Marker marker) {
}
/**
* Get the marker from a ClusterItem
* @param clusterItem ClusterItem which you will obtain its marker
* @return a marker from a ClusterItem or null if it does not exists
*/
public Marker getMarker(T clusterItem) {
return mMarkerCache.get(clusterItem);
}
/**
* Get the ClusterItem from a marker
* @param marker which you will obtain its ClusterItem
* @return a ClusterItem from a marker or null if it does not exists
*/
public T getClusterItem(Marker marker) {
return mMarkerCache.get(marker);
}
/**
* Get the marker from a Cluster
* @param cluster which you will obtain its marker
* @return a marker from a cluster or null if it does not exists
*/
public Marker getMarker(Cluster<T> cluster) {
return mClusterToMarker.get(cluster);
}
/**
* Get the Cluster from a marker
* @param marker which you will obtain its Cluster
* @return a Cluster from a marker or null if it does not exists
*/
public Cluster<T> getCluster(Marker marker) {
return mMarkerToCluster.get(marker);
}
/**
* Creates markerWithPosition(s) for a particular cluster, animating it if necessary.
*/
private class CreateMarkerTask {
private final Cluster<T> cluster;
private final Set<MarkerWithPosition> newMarkers;
private final LatLng animateFrom;
/**
* @param c the cluster to render.
* @param markersAdded a collection of markers to append any created markers.
* @param animateFrom the location to animate the markerWithPosition from, or null if no
* animation is required.
*/
public CreateMarkerTask(Cluster<T> c, Set<MarkerWithPosition> markersAdded, LatLng animateFrom) {
this.cluster = c;
this.newMarkers = markersAdded;
this.animateFrom = animateFrom;
}
/**
* Renders a cluster object.
* @param markerModifier
*/
private void perform(final MarkerModifier markerModifier) {
// Don't show small clusters. Render the markers inside, instead.
if (!shouldRenderAsCluster(cluster)) {
for (T item : cluster.getItems()) {
Marker marker = mMarkerCache.get(item);
MarkerWithPosition markerWithPosition;
if (marker == null) {
MarkerOptions markerOptions = new MarkerOptions();
if (animateFrom != null) {
markerOptions.position(animateFrom);
} else {
markerOptions.position(item.getPosition());
}
onBeforeClusterItemRendered(item, markerOptions);
marker = mClusterManager.getMarkerCollection().addMarker(markerOptions);
markerWithPosition = new MarkerWithPosition(marker);
mMarkerCache.put(item, marker);
if (animateFrom != null) {
markerModifier.animate(markerWithPosition, animateFrom, item.getPosition());
}
} else {
markerWithPosition = new MarkerWithPosition(marker);
}
onClusterItemRendered(item, marker);
newMarkers.add(markerWithPosition);
}
return;
}
MarkerOptions markerOptions = new MarkerOptions().
position(animateFrom == null ? cluster.getPosition() : animateFrom);
new AsyncTask<MarkerOptions, Void, MarkerOptions> () {
@Override
protected MarkerOptions doInBackground(MarkerOptions... params) {
Log.v(TAG, "AsyncTask - Getting image");
MarkerOptions markerOptions = params[0];
TweetNode mNode = null;
Iterator<T> items = cluster.getItems().iterator();
int clusterSize = 0;
while (items.hasNext()) {
TweetNode currentNode = (TweetNode) items.next();
if (mNode == null)
mNode = currentNode;
if (mNode.getSize() < currentNode.getSize()) {
mNode = currentNode;
}
clusterSize += currentNode.getSize();
}
Log.v("Cluster - Identifier", cluster.hashCode() + "");
Log.v("Cluster - Popular Node" + mNode, "Coolest user here");
Log.v("Cluster - clusterSize", clusterSize + "");
Bitmap mIcon = mNode.getIcon();
int mScale = Math.max(0, (int) Math.ceil(Math.log(clusterSize)));
// TODO: Implement proper scaling and colouring of nodes.
mIcon = Bitmap.createScaledBitmap(mIcon, mIcon.getWidth() + 40 + mScale, mIcon.getHeight() + 40 + mScale, true);
// mIcon = cfilter(mIcon, mScale % 255, 255, 255);
BitmapDescriptor descriptor = BitmapDescriptorFactory.fromBitmap(mIcon);
markerOptions.anchor(.5f, .5f);
markerOptions.icon(descriptor);
markerOptions.title(mNode.getStatus().getUser().getName());
return markerOptions;
}
@Override
protected void onPostExecute(MarkerOptions markerOptions) {
super.onPostExecute(markerOptions);
Marker marker = mClusterManager.getClusterMarkerCollection().addMarker(markerOptions);
mMarkerToCluster.put(marker, cluster);
mClusterToMarker.put(cluster, marker);
MarkerWithPosition markerWithPosition = new MarkerWithPosition(marker);
if (animateFrom != null) {
markerModifier.animate(markerWithPosition, animateFrom, cluster.getPosition());
}
onClusterRendered(cluster, marker);
newMarkers.add(markerWithPosition);
sendUserNotification();
}
}.execute(markerOptions);
}
}
private Bitmap cfilter(Bitmap src, double red, double green, double blue) {
red /= 100;
green /= 100;
blue /= 100;
// image size
int width = src.getWidth();
int height = src.getHeight();
// create output bitmap
Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig());
// color information
int A, R, G, B;
int pixel;
// scan through all pixels
for(int x = 0; x < width; ++x) {
for(int y = 0; y < height; ++y) {
// get pixel color
pixel = src.getPixel(x, y);
// apply filtering on each channel R, G, B
A = Color.alpha(pixel);
R = (int)(Color.red(pixel) * red);
G = (int)(Color.green(pixel) * green);
B = (int)(Color.blue(pixel) * blue);
// set new color pixel to output bitmap
bmOut.setPixel(x, y, Color.argb(A, R, G, B));
}
}
src.recycle();
src = null;
// return final image
return bmOut;
}
/**
* A Marker and its position. Marker.getPosition() must be called from the UI thread, so this
* object allows lookup from other threads.
*/
private static class MarkerWithPosition {
private final Marker marker;
private LatLng position;
private MarkerWithPosition(Marker marker) {
this.marker = marker;
position = marker.getPosition();
}
@Override
public boolean equals(Object other) {
if (other instanceof MarkerWithPosition) {
return marker.equals(((MarkerWithPosition) other).marker);
}
return false;
}
@Override
public int hashCode() {
return marker.hashCode();
}
}
private static final TimeInterpolator ANIMATION_INTERP = new DecelerateInterpolator();
/**
* Animates a markerWithPosition from one position to another. TODO: improve performance for
* slow devices (e.g. Nexus S).
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
private class AnimationTask extends AnimatorListenerAdapter implements ValueAnimator.AnimatorUpdateListener {
private final MarkerWithPosition markerWithPosition;
private final Marker marker;
private final LatLng from;
private final LatLng to;
private boolean mRemoveOnComplete;
private MarkerManager mMarkerManager;
private AnimationTask(MarkerWithPosition markerWithPosition, LatLng from, LatLng to) {
this.markerWithPosition = markerWithPosition;
this.marker = markerWithPosition.marker;
this.from = from;
this.to = to;
}
public void perform() {
ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1);
valueAnimator.setInterpolator(ANIMATION_INTERP);
valueAnimator.addUpdateListener(this);
valueAnimator.addListener(this);
valueAnimator.start();
}
@Override
public void onAnimationEnd(Animator animation) {
if (mRemoveOnComplete) {
Cluster<T> cluster = mMarkerToCluster.get(marker);
mClusterToMarker.remove(cluster);
mMarkerCache.remove(marker);
mMarkerToCluster.remove(marker);
mMarkerManager.remove(marker);
}
markerWithPosition.position = to;
}
public void removeOnAnimationComplete(MarkerManager markerManager) {
mMarkerManager = markerManager;
mRemoveOnComplete = true;
}
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
float fraction = valueAnimator.getAnimatedFraction();
double lat = (to.latitude - from.latitude) * fraction + from.latitude;
double lngDelta = to.longitude - from.longitude;
// Take the shortest path across the 180th meridian.
if (Math.abs(lngDelta) > 180) {
lngDelta -= Math.signum(lngDelta) * 360;
}
double lng = lngDelta * fraction + from.longitude;
LatLng position = new LatLng(lat, lng);
marker.setPosition(position);
}
}
} | apache-2.0 |
kod3r/graphhopper | core/src/main/java/com/graphhopper/reader/dem/CGIARProvider.java | 11886 | /*
* Licensed to Peter Karich under one or more contributor license
* agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* Peter Karich licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the
* License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.graphhopper.reader.dem;
import com.graphhopper.storage.DAType;
import com.graphhopper.storage.DataAccess;
import com.graphhopper.storage.Directory;
import com.graphhopper.storage.GHDirectory;
import com.graphhopper.util.Downloader;
import com.graphhopper.util.Helper;
import java.awt.image.Raster;
import java.io.*;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.xmlgraphics.image.codec.tiff.TIFFDecodeParam;
import org.apache.xmlgraphics.image.codec.tiff.TIFFImageDecoder;
import org.apache.xmlgraphics.image.codec.util.SeekableStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Elevation data from CGIAR project http://srtm.csi.cgiar.org/ 'PROCESSED SRTM DATA VERSION 4.1'.
* Every file covers a region of 5x5 degree. License granted for all people using GraphHopper:
* http://graphhopper.com/public/license/CGIAR.txt
* <p/>
* Every zip contains readme.txt with the necessary information e.g.:
* <ol>
* <li>
* All GeoTiffs with 6000 x 6000 pixels.
* </li>
* </ol>
* <p/>
* @author NopMap
* @author Peter Karich
*/
public class CGIARProvider implements ElevationProvider
{
private static final int WIDTH = 6000;
private Downloader downloader = new Downloader("GraphHopper CGIARReader").setTimeout(10000);
private final Logger logger = LoggerFactory.getLogger(getClass());
private final Map<String, HeightTile> cacheData = new HashMap<String, HeightTile>();
private File cacheDir = new File("/tmp/cgiar");
// for alternatives see #346
private String baseUrl = "http://srtm.csi.cgiar.org/SRT-ZIP/SRTM_V41/SRTM_Data_GeoTiff";
private Directory dir;
private DAType daType = DAType.MMAP;
final double precision = 1e7;
private final double invPrecision = 1 / precision;
private final int degree = 5;
private boolean calcMean = false;
private boolean autoRemoveTemporary = true;
@Override
public void setCalcMean( boolean eleCalcMean )
{
calcMean = eleCalcMean;
}
/**
* Creating temporary files can take a long time as we need to unpack tiff as well as to fill
* our DataAccess object, so this option can be used to disable the default clear mechanism via
* specifying 'false'.
*/
public void setAutoRemoveTemporaryFiles( boolean autoRemoveTemporary )
{
this.autoRemoveTemporary = autoRemoveTemporary;
}
public void setDownloader( Downloader downloader )
{
this.downloader = downloader;
}
@Override
public ElevationProvider setCacheDir( File cacheDir )
{
if (cacheDir.exists() && !cacheDir.isDirectory())
throw new IllegalArgumentException("Cache path has to be a directory");
try
{
this.cacheDir = cacheDir.getCanonicalFile();
} catch (IOException ex)
{
throw new RuntimeException(ex);
}
return this;
}
protected File getCacheDir()
{
return cacheDir;
}
@Override
public ElevationProvider setBaseURL( String baseUrl )
{
if (baseUrl == null || baseUrl.isEmpty())
throw new IllegalArgumentException("baseUrl cannot be empty");
this.baseUrl = baseUrl;
return this;
}
@Override
public ElevationProvider setDAType( DAType daType )
{
this.daType = daType;
return this;
}
@Override
public double getEle( double lat, double lon )
{
// no data we can avoid the trouble
if (lat > 60 || lat < -60)
return 0;
lat = (int) (lat * precision) / precision;
lon = (int) (lon * precision) / precision;
String name = getFileName(lat, lon);
HeightTile demProvider = cacheData.get(name);
if (demProvider == null)
{
if (!cacheDir.exists())
cacheDir.mkdirs();
int minLat = down(lat);
int minLon = down(lon);
// less restrictive against boundary checking
demProvider = new HeightTile(minLat, minLon, WIDTH, degree * precision, degree);
demProvider.setCalcMean(calcMean);
cacheData.put(name, demProvider);
DataAccess heights = getDirectory().find(name + ".gh");
demProvider.setHeights(heights);
boolean loadExisting = false;
try
{
loadExisting = heights.loadExisting();
} catch (Exception ex)
{
logger.warn("cannot load " + name + ", error:" + ex.getMessage());
}
if (!loadExisting)
{
String tifName = name + ".tif";
String zippedURL = baseUrl + "/" + name + ".zip";
File file = new File(cacheDir, new File(zippedURL).getName());
// get zip file if not already in cacheDir - unzip later and in-memory only!
if (!file.exists())
{
try
{
for (int i = 0; i < 3; i++)
{
try
{
downloader.downloadFile(zippedURL, file.getAbsolutePath());
break;
} catch (SocketTimeoutException ex)
{
// just try again after a little nap
Thread.sleep(2000);
continue;
} catch (IOException ex)
{
demProvider.setSeaLevel(true);
// use small size on disc and in-memory
heights.setSegmentSize(100).create(10).
flush();
return 0;
}
}
} catch (Exception ex)
{
throw new RuntimeException(ex);
}
}
// short == 2 bytes
heights.create(2 * WIDTH * WIDTH);
// logger.info("start decoding");
// decode tiff data
Raster raster;
SeekableStream ss = null;
try
{
InputStream is = new FileInputStream(file);
ZipInputStream zis = new ZipInputStream(is);
// find tif file in zip
ZipEntry entry = zis.getNextEntry();
while (entry != null && !entry.getName().equals(tifName))
{
entry = zis.getNextEntry();
}
ss = SeekableStream.wrapInputStream(zis, true);
TIFFImageDecoder imageDecoder = new TIFFImageDecoder(ss, new TIFFDecodeParam());
raster = imageDecoder.decodeAsRaster();
} catch (Exception e)
{
throw new RuntimeException("Can't decode " + tifName, e);
} finally
{
if (ss != null)
Helper.close(ss);
}
// logger.info("start converting to our format");
final int height = raster.getHeight();
final int width = raster.getWidth();
int x = 0, y = 0;
try
{
for (y = 0; y < height; y++)
{
for (x = 0; x < width; x++)
{
short val = (short) raster.getPixel(x, y, (int[]) null)[0];
if (val < -1000 || val > 12000)
val = Short.MIN_VALUE;
heights.setShort(2 * (y * WIDTH + x), val);
}
}
heights.flush();
// TODO remove tifName and zip?
} catch (Exception ex)
{
throw new RuntimeException("Problem at x:" + x + ", y:" + y, ex);
}
} // loadExisting
}
if (demProvider.isSeaLevel())
return 0;
return demProvider.getHeight(lat, lon);
}
int down( double val )
{
// 'rounding' to closest 5
int intVal = (int) (val / degree) * degree;
if (!(val >= 0 || intVal - val < invPrecision))
intVal = intVal - degree;
return intVal;
}
protected String getFileName( double lat, double lon )
{
lon = 1 + (180 + lon) / degree;
int lonInt = (int) lon;
lat = 1 + (60 - lat) / degree;
int latInt = (int) lat;
if (Math.abs(latInt - lat) < invPrecision / degree)
latInt--;
// replace String.format as it seems to be slow
// String.format("srtm_%02d_%02d", lonInt, latInt);
String str = "srtm_";
str += lonInt < 10 ? "0" : "";
str += lonInt;
str += latInt < 10 ? "_0" : "_";
str += latInt;
return str;
}
@Override
public void release()
{
cacheData.clear();
// for memory mapped type we create temporary unpacked files which should be removed
if (autoRemoveTemporary && dir != null)
dir.clear();
}
@Override
public String toString()
{
return "CGIAR";
}
private Directory getDirectory()
{
if (dir != null)
return dir;
logger.info(this.toString() + " Elevation Provider, from: " + baseUrl + ", to: " + cacheDir + ", as: " + daType);
return dir = new GHDirectory(cacheDir.getAbsolutePath(), daType);
}
public static void main( String[] args )
{
CGIARProvider provider = new CGIARProvider();
System.out.println(provider.getEle(46, -20));
// 337.0
System.out.println(provider.getEle(49.949784, 11.57517));
// 453.0
System.out.println(provider.getEle(49.968668, 11.575127));
// 447.0
System.out.println(provider.getEle(49.968682, 11.574842));
// 3131
System.out.println(provider.getEle(-22.532854, -65.110474));
// 123
System.out.println(provider.getEle(38.065392, -87.099609));
// 1615
System.out.println(provider.getEle(40, -105.2277023));
System.out.println(provider.getEle(39.99999999, -105.2277023));
System.out.println(provider.getEle(39.9999999, -105.2277023));
// 1617
System.out.println(provider.getEle(39.999999, -105.2277023));
// 0
System.out.println(provider.getEle(29.840644, -42.890625));
}
}
| apache-2.0 |
difi/sikker-digital-post-java-klient | src/main/java/no/difi/sdp/client2/internal/Environment.java | 92 | package no.difi.sdp.client2.internal;
public enum Environment {
PRODUCTION,
TEST
}
| apache-2.0 |
jexp/idea2 | plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/actions/actionVisibility/CvsActionVisibility.java | 5924 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.cvsSupport2.actions.actionVisibility;
import com.intellij.cvsSupport2.actions.cvsContext.CvsContext;
import com.intellij.cvsSupport2.actions.cvsContext.CvsContextWrapper;
import com.intellij.cvsSupport2.actions.cvsContext.CvsLightweightFile;
import com.intellij.cvsSupport2.application.CvsEntriesManager;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* author: lesya
*/
public class CvsActionVisibility {
private boolean myCanBePerformedOnFile = true;
private boolean myCanBePerformedOnDirectory = true;
private boolean myCanBePerformedOnSeveralFiles = false;
private final boolean myExpectedCvsAsActiveVcs = true;
private final List myConditions = new ArrayList();
private boolean myCanBePerformedOnLocallyDeletedFile = false;
private boolean myCanBePerformedOnCvsLightweightFile = false;
public static interface Condition{
boolean isPerformedOn(CvsContext context);
}
public void addCondition(Condition condition){
myConditions.add(condition);
}
public boolean isVisible(CvsContext context){
if (!myExpectedCvsAsActiveVcs) return true;
return context.cvsIsActive();
}
public boolean isEnabled(CvsContext context){
boolean result = (context.cvsIsActive() || !myExpectedCvsAsActiveVcs)
&& hasSuitableType(context);
if (!result) return false;
for (Iterator each = myConditions.iterator(); each.hasNext();) {
Condition condition = (Condition) each.next();
if (!condition.isPerformedOn(context)) return false;
}
return true;
}
public void shouldNotBePerformedOnFile() {
myCanBePerformedOnFile = false;
}
public void shouldNotBePerformedOnDirectory() {
myCanBePerformedOnDirectory = false;
}
public void canBePerformedOnSeveralFiles() {
myCanBePerformedOnSeveralFiles = true;
}
private boolean hasSuitableType(CvsContext context) {
File[] selectedIOFiles = context.getSelectedIOFiles();
VirtualFile[] selectedFiles = context.getSelectedFiles();
CvsLightweightFile[] lightweightFiles = context.getSelectedLightweightFiles();
if (selectedFiles == null) selectedFiles = VirtualFile.EMPTY_ARRAY;
if (selectedIOFiles == null) selectedIOFiles = new File[0];
if (lightweightFiles == null) lightweightFiles = new CvsLightweightFile[0];
if ((selectedFiles.length ==0 && lightweightFiles.length == 0) && !myCanBePerformedOnLocallyDeletedFile) return false;
if ((selectedFiles.length ==0 && selectedIOFiles.length == 0) && !myCanBePerformedOnCvsLightweightFile) return false;
int selectedFileCount = selectedFiles.length + selectedIOFiles.length + lightweightFiles.length;
if (selectedFileCount == 0) return false;
if (selectedFileCount > 1 && !myCanBePerformedOnSeveralFiles) return false;
if (containsFileFromUnsupportedFileSystem(selectedFiles)) return false;
if ((containsDirectory(selectedFiles) || containsDirectory(selectedIOFiles)) && !myCanBePerformedOnDirectory) return false;
if ((containsFile(selectedFiles) || containsFile(selectedIOFiles)) && !myCanBePerformedOnFile) return false;
return true;
}
private boolean containsFileFromUnsupportedFileSystem(VirtualFile[] selectedFiles) {
for (int i = 0; i < selectedFiles.length; i++) {
VirtualFile selectedFile = selectedFiles[i];
if (!selectedFile.isInLocalFileSystem()) return true;
}
return false;
}
private boolean containsFile(VirtualFile[] selectedFiles) {
for (int i = 0; i < selectedFiles.length; i++) {
VirtualFile selectedFile = selectedFiles[i];
if (!selectedFile.isDirectory()) return true;
}
return false;
}
private boolean containsDirectory(VirtualFile[] selectedFiles) {
for (int i = 0; i < selectedFiles.length; i++) {
VirtualFile selectedFile = selectedFiles[i];
if (selectedFile.isDirectory()) return true;
}
return false;
}
private boolean containsDirectory(File[] selectedFiles) {
for (int i = 0; i < selectedFiles.length; i++) {
File selectedFile = selectedFiles[i];
if (selectedFile.isDirectory()) return true;
}
return false;
}
private boolean containsFile(File[] selectedFiles) {
for (int i = 0; i < selectedFiles.length; i++) {
File selectedFile = selectedFiles[i];
if (selectedFile.isFile()) return true;
}
return false;
}
public void canBePerformedOnLocallyDeletedFile() {
myCanBePerformedOnLocallyDeletedFile = true;
}
public void applyToEvent(AnActionEvent e) {
if (!CvsEntriesManager.getInstance().isActive()) {
final Presentation presentation = e.getPresentation();
presentation.setVisible(false);
presentation.setEnabled(false);
return;
}
CvsContext cvsContext = CvsContextWrapper.createInstance(e);
Presentation presentation = e.getPresentation();
presentation.setEnabled(isEnabled(cvsContext));
presentation.setVisible(isVisible(cvsContext));
}
public void canBePerformedOnCvsLightweightFile() {
myCanBePerformedOnCvsLightweightFile = true;
}
}
| apache-2.0 |
fanlehai/CodePractice | java/src/main/java/com/fanlehai/java/enumtest/RoShamBo2.java | 1280 | //: enumerated/RoShamBo2.java
// Switching one enum on another.
package com.fanlehai.java.enumtest;
import static com.fanlehai.java.enumtest.Outcome.*;
public enum RoShamBo2 implements Competitor<RoShamBo2> {
PAPER(DRAW, LOSE, WIN),
SCISSORS(WIN, DRAW, LOSE),
ROCK(LOSE, WIN, DRAW);
private Outcome vPAPER, vSCISSORS, vROCK;
RoShamBo2(Outcome paper, Outcome scissors, Outcome rock) {
this.vPAPER = paper;
this.vSCISSORS = scissors;
this.vROCK = rock;
}
public Outcome compete(RoShamBo2 it) {
switch (it) {
default:
case PAPER:
return vPAPER;
case SCISSORS:
return vSCISSORS;
case ROCK:
return vROCK;
}
}
public static void main(String[] args) {
RoShamBo.play(RoShamBo2.class, 20);
}
} /* Output:
ROCK vs. ROCK: DRAW
SCISSORS vs. ROCK: LOSE
SCISSORS vs. ROCK: LOSE
SCISSORS vs. ROCK: LOSE
PAPER vs. SCISSORS: LOSE
PAPER vs. PAPER: DRAW
PAPER vs. SCISSORS: LOSE
ROCK vs. SCISSORS: WIN
SCISSORS vs. SCISSORS: DRAW
ROCK vs. SCISSORS: WIN
SCISSORS vs. PAPER: WIN
SCISSORS vs. PAPER: WIN
ROCK vs. PAPER: LOSE
ROCK vs. SCISSORS: WIN
SCISSORS vs. ROCK: LOSE
PAPER vs. SCISSORS: LOSE
SCISSORS vs. PAPER: WIN
SCISSORS vs. PAPER: WIN
SCISSORS vs. PAPER: WIN
SCISSORS vs. PAPER: WIN
*///:~
| apache-2.0 |
qitsrc/qit | qit-jaxrs/src/main/java/qit/jaxrs/QitApplication.java | 617 | package qit.jaxrs;
import javax.json.stream.JsonGenerator;
import javax.ws.rs.ApplicationPath;
import org.glassfish.jersey.jsonp.JsonProcessingFeature;
import org.glassfish.jersey.server.ResourceConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ApplicationPath("api")
public class QitApplication extends ResourceConfig {
Logger log = LoggerFactory.getLogger(QitApplication.class);
public QitApplication() {
super();
register(JsonProcessingFeature.class);
packages("qit.jaxrs");
property(JsonGenerator.PRETTY_PRINTING, true);
log.info("JAX-RS application initialized as /api");
}
}
| apache-2.0 |
jason-rhodes/bridgepoint | src/org.xtuml.bp.ui.text.test/src/org/xtuml/bp/ui/text/test/ParseAllOnModelReloadTest.java | 5688 | //=====================================================================
//
//File: $RCSfile: ParseAllOnModelReloadTest.java,v $
//Version: $Revision: 1.10 $
//Modified: $Date: 2013/05/10 06:02:35 $
//
//(c) Copyright 2005-2014 by Mentor Graphics Corp. All rights reserved.
//
//=====================================================================
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//=====================================================================
package org.xtuml.bp.ui.text.test;
import java.io.File;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.swt.widgets.Display;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.xtuml.bp.core.CorePlugin;
import org.xtuml.bp.core.StateMachineState_c;
import org.xtuml.bp.core.common.ClassQueryInterface_c;
import org.xtuml.bp.core.common.PersistableModelComponent;
import org.xtuml.bp.core.common.PersistenceManager;
import org.xtuml.bp.test.TestUtil;
import org.xtuml.bp.test.common.OrderedRunner;
import org.xtuml.bp.test.common.TestingUtilities;
import org.xtuml.bp.test.common.TextEditorUtils;
import org.xtuml.bp.ui.text.TextPlugin;
/**
* Holds tests pertaining to the parse-all action that occurs
* when a model is reloaded from disk.
*/
@RunWith(OrderedRunner.class)
public class ParseAllOnModelReloadTest extends UITextTest
{
public ParseAllOnModelReloadTest() throws CoreException {
super();
}
/**
* Constructor.
*/
// public ParseAllOnModelReloadTest(String name) throws CoreException
// {
// super(null, name);
// }
@Before
public void setUp() throws Exception {
super.setUp();
loadProject("small");
}
/**
* For issue 863. Tests that a parse-all occurs when a model is reloaded
* from disk due to its having changed outside of Eclipse.
*/
@Test
public void testParseAllOccursOnModelReload() throws Exception
{
// ensure the parse on resource change preference is enabled
CorePlugin.enableParseAllOnResourceChange();
StateMachineState_c state = StateMachineState_c.
StateMachineStateInstance(modelRoot, new ClassQueryInterface_c() {
@Override
public boolean evaluate(Object candidate) {
return ((StateMachineState_c) candidate).getName().equals("first");
}
});
PersistenceManager manager = PersistenceManager.getDefaultInstance();
PersistableModelComponent component = manager.getComponent(state);
IPath componentPath = component.getContainingDirectoryPath();
IProject project = getProject();
// check that there are no problems associated with an activity
// that we know will have problems when the bad version of the
// model is loaded, below
IWorkspace workspace = TextPlugin.getWorkspace();
IFile placeholder = workspace.getRoot().getFile(
componentPath.append("A__first.oal"));
assertTrue("Activity file which should have no errors has problem markers",
TextEditorUtils.getMarkers(placeholder).length == 0);
// copy over the model's file with a version of the same model
// that has problems
File badModelFile = new File(m_workspace_path + "/models/pre_716_files/InstanceStateMachine.xtuml");
TestingUtilities.importFile(workspace.getRoot().getFolder(componentPath),
badModelFile);
// alert Eclipse to the file's being changed, so it reloads the model,
// which should also cause a parse-all
try {
project.refreshLocal(IFile.DEPTH_INFINITE, new NullProgressMonitor());
} catch (CoreException e) {
TextPlugin.logError("Could not refresh copied-over model file", e);
}
// while we haven't reached a timeout limit, and the problem
// markers for the activity which we know has errors have yet
// to appear
int loops = 0;
while (loops++ < 10 && TextEditorUtils.getMarkers(placeholder).length == 0) {
// dispatch pending events (which likely includes the running of
// the above-mentioned parse itself)
while (Display.getCurrent().readAndDispatch());
// sleep a bit, to wait for the parse to create the markers
TestUtil.sleep(300);
}
// check that there are problems associated with an activity
// in the bad version of the model that is known to have errors
assertTrue("Activity file which has errors has no problem markers",
TextEditorUtils.getMarkers(placeholder).length > 0);
}
}
| apache-2.0 |
apache/sis | core/sis-referencing/src/test/java/org/apache/sis/internal/referencing/provider/ProvidersTest.java | 13089 | /*
* 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.sis.internal.referencing.provider;
import java.util.Map;
import java.util.HashMap;
import java.util.IdentityHashMap;
import org.opengis.util.GenericName;
import org.opengis.metadata.Identifier;
import org.opengis.parameter.GeneralParameterDescriptor;
import org.opengis.parameter.ParameterDescriptorGroup;
import org.opengis.referencing.operation.OperationMethod;
import org.apache.sis.referencing.operation.DefaultOperationMethod;
import org.apache.sis.parameter.DefaultParameterDescriptor;
import org.apache.sis.test.DependsOn;
import org.apache.sis.test.TestCase;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Tests {@link Providers} and some consistency rules of all providers defined in this package.
*
* @author Martin Desruisseaux (Geomatys)
* @version 1.2
* @since 0.6
* @module
*/
@DependsOn({
org.apache.sis.referencing.operation.DefaultOperationMethodTest.class,
AffineTest.class,
LongitudeRotationTest.class,
MapProjectionTest.class
})
public final strictfp class ProvidersTest extends TestCase {
/**
* Returns all providers to test.
*/
private static Class<?>[] methods() {
return new Class<?>[] {
Affine.class,
AxisOrderReversal.class,
AxisOrderReversal3D.class,
GeographicOffsets.class,
GeographicOffsets2D.class,
GeographicAndVerticalOffsets.class,
VerticalOffset.class,
LongitudeRotation.class,
CoordinateFrameRotation.class,
CoordinateFrameRotation2D.class,
CoordinateFrameRotation3D.class,
PositionVector7Param.class,
PositionVector7Param2D.class,
PositionVector7Param3D.class,
GeocentricTranslation.class,
GeocentricTranslation2D.class,
GeocentricTranslation3D.class,
GeographicToGeocentric.class,
GeocentricToGeographic.class,
Geographic3Dto2D.class,
Geographic2Dto3D.class,
Molodensky.class,
AbridgedMolodensky.class,
PseudoPlateCarree.class,
Equirectangular.class,
Mercator1SP.class,
Mercator2SP.class,
MercatorSpherical.class,
PseudoMercator.class,
RegionalMercator.class,
MillerCylindrical.class,
LambertConformal1SP.class,
LambertConformal2SP.class,
LambertConformalWest.class,
LambertConformalBelgium.class,
LambertConformalMichigan.class,
LambertCylindricalEqualArea.class,
LambertCylindricalEqualAreaSpherical.class,
AlbersEqualArea.class,
TransverseMercator.class,
TransverseMercatorSouth.class,
CassiniSoldner.class,
HyperbolicCassiniSoldner.class,
PolarStereographicA.class,
PolarStereographicB.class,
PolarStereographicC.class,
PolarStereographicNorth.class,
PolarStereographicSouth.class,
ObliqueStereographic.class,
ObliqueMercator.class,
ObliqueMercatorCenter.class,
ObliqueMercatorTwoPoints.class,
ObliqueMercatorTwoPointsCenter.class,
Orthographic.class,
ModifiedAzimuthalEquidistant.class,
AzimuthalEquidistantSpherical.class,
ZonedTransverseMercator.class,
SatelliteTracking.class,
Sinusoidal.class,
Polyconic.class,
Mollweide.class,
SouthPoleRotation.class,
NorthPoleRotation.class,
NTv2.class,
NTv1.class,
NADCON.class,
FranceGeocentricInterpolation.class,
MolodenskyInterpolation.class,
Interpolation1D.class,
Wraparound.class
};
}
/**
* Returns the subset of {@link #methods()} which are expected to support
* {@link AbstractProvider#redimension(int, int)}, not including map projections.
*/
private static Class<?>[] redimensionables() {
return new Class<?>[] {
Affine.class,
LongitudeRotation.class,
GeographicOffsets.class,
GeographicOffsets2D.class,
GeographicAndVerticalOffsets.class,
CoordinateFrameRotation2D.class,
CoordinateFrameRotation3D.class,
PositionVector7Param2D.class,
PositionVector7Param3D.class,
GeocentricTranslation2D.class,
GeocentricTranslation3D.class,
Geographic3Dto2D.class,
Geographic2Dto3D.class,
Molodensky.class,
AbridgedMolodensky.class,
FranceGeocentricInterpolation.class
};
}
/**
* Ensures that every parameter instance is unique. Actually this test is not strong requirement.
* This is only for sharing existing resources by avoiding unnecessary objects duplication.
*
* @throws ReflectiveOperationException if the instantiation of a service provider failed.
*/
@Test
public void ensureParameterUniqueness() throws ReflectiveOperationException {
final Map<GeneralParameterDescriptor, String> groupNames = new IdentityHashMap<>();
final Map<GeneralParameterDescriptor, GeneralParameterDescriptor> parameters = new HashMap<>();
final Map<Object, Object> namesAndIdentifiers = new HashMap<>();
for (final Class<?> c : methods()) {
final OperationMethod method = (OperationMethod) c.getConstructor((Class[]) null).newInstance((Object[]) null);
final ParameterDescriptorGroup group = method.getParameters();
final String operationName = group.getName().getCode();
for (final GeneralParameterDescriptor param : group.descriptors()) {
assertFalse("Parameter declared twice in the same group.",
operationName.equals(groupNames.put(param, operationName)));
/*
* Ensure uniqueness of the parameter descriptor as a whole.
*/
final Identifier name = param.getName();
Object existing = parameters.put(param, param);
if (existing != null && existing != param) {
fail("Parameter “" + name.getCode() + "” defined in “" + operationName + '”'
+ " was already defined in “" + groupNames.get(existing) + "”."
+ " The same instance could be shared.");
}
/*
* Ensure uniqueness of each name and identifier.
*/
existing = namesAndIdentifiers.put(name, name);
if (existing != null && existing != name) {
fail("The name of parameter “" + name.getCode() + "” defined in “" + operationName + '”'
+ " was already defined elsewhere. The same instance could be shared.");
}
for (final GenericName alias : param.getAlias()) {
existing = namesAndIdentifiers.put(alias, alias);
if (existing != null && existing != alias) {
fail("Alias “" + alias + "” of parameter “" + name.getCode() + "” defined in “" + operationName + '”'
+ " was already defined elsewhere. The same instance could be shared.");
}
}
for (final Identifier id : param.getIdentifiers()) {
existing = namesAndIdentifiers.put(id, id);
if (existing != null && existing != id) {
fail("Identifier “" + id + "” of parameter “" + name.getCode() + "” defined in “" + operationName + '”'
+ " was already defined elsewhere. The same instance could be shared.");
}
}
}
}
}
/**
* Tests {@link AbstractProvider#redimension(int, int)} on all providers managed by {@link Providers}.
*/
@Test
public void testRedimension() {
final Map<Class<?>,Boolean> redimensionables = new HashMap<>(100);
for (final Class<?> type : methods()) {
assertNull(type.getName(), redimensionables.put(type, Boolean.FALSE));
}
for (final Class<?> type : redimensionables()) {
assertEquals(type.getName(), Boolean.FALSE, redimensionables.put(type, Boolean.TRUE));
}
final Providers providers = new Providers();
for (final OperationMethod method : providers) {
if (method instanceof ProviderMock) {
continue; // Skip the methods that were defined only for test purpose.
}
final int sourceDimensions = method.getSourceDimensions();
final int targetDimensions = method.getTargetDimensions();
final Boolean isRedimensionable = redimensionables.get(method.getClass());
assertNotNull(method.getClass().getName(), isRedimensionable);
if (isRedimensionable) {
for (int newSource = 2; newSource <= 3; newSource++) {
for (int newTarget = 2; newTarget <= 3; newTarget++) {
final OperationMethod redim = ((DefaultOperationMethod) method).redimension(newSource, newTarget);
assertEquals("sourceDimensions", newSource, redim.getSourceDimensions().intValue());
assertEquals("targetDimensions", newTarget, redim.getTargetDimensions().intValue());
if (!(method instanceof Affine)) {
if (newSource == sourceDimensions && newTarget == targetDimensions) {
assertSame("When asking the original number of dimensions, expected the original instance.", method, redim);
} else {
assertNotSame("When asking a different number of dimensions, expected a different instance.", method, redim);
}
assertSame("When asking the original number of dimensions, expected the original instance.",
method, ((DefaultOperationMethod) redim).redimension(sourceDimensions, targetDimensions));
}
}
}
} else if (method instanceof MapProjection) {
final OperationMethod proj3D = ((MapProjection) method).redimension(sourceDimensions ^ 1, targetDimensions ^ 1);
assertNotSame("redimension(3,3) should return a new method.", method, proj3D);
assertSame("redimension(2,2) should give back the original method.", method,
((DefaultOperationMethod) proj3D).redimension(sourceDimensions, targetDimensions));
assertSame("Value of redimension(3,3) should have been cached.", proj3D,
((MapProjection) method).redimension(sourceDimensions ^ 1, targetDimensions ^ 1));
} else try {
((DefaultOperationMethod) method).redimension(sourceDimensions ^ 1, targetDimensions ^ 1);
fail("Type " + method.getClass().getName() + " is not in our list of redimensionable methods.");
} catch (IllegalArgumentException e) {
final String message = e.getMessage();
assertTrue(message, message.contains(method.getName().getCode()));
}
}
}
/**
* Tests the description provided in some parameters.
*/
@Test
public void testDescription() {
assertFalse(((DefaultParameterDescriptor<Double>) SatelliteTracking.SATELLITE_ORBIT_INCLINATION).getDescription().length() == 0);
assertFalse(((DefaultParameterDescriptor<Double>) SatelliteTracking.SATELLITE_ORBITAL_PERIOD ).getDescription().length() == 0);
assertFalse(((DefaultParameterDescriptor<Double>) SatelliteTracking.ASCENDING_NODE_PERIOD ).getDescription().length() == 0);
}
}
| apache-2.0 |
betfair/cougar | cougar-framework/cougar-api/src/main/java/com/betfair/cougar/api/security/InvalidCredentialsException.java | 1565 | /*
* Copyright 2014, The Sporting Exchange Limited
*
* 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.betfair.cougar.api.security;
/**
* Exception to be thrown when an IdentityResolver can't resolve credentials into an
* identity (for example because the credentials are not valid).
*/
public class InvalidCredentialsException extends Exception {
// Optional custom fault code to be included in the exception
private CredentialFaultCode cfc;
public InvalidCredentialsException(String message) {
super(message);
}
public InvalidCredentialsException(String message, Throwable cause) {
super(message, cause);
}
public InvalidCredentialsException(String message, CredentialFaultCode cfc) {
super(message);
this.cfc = cfc;
}
public InvalidCredentialsException(String message, Throwable cause, CredentialFaultCode cfc) {
super(message, cause);
this.cfc = cfc;
}
public CredentialFaultCode getCredentialFaultCode() {
return cfc;
}
}
| apache-2.0 |
GJRTimmer/vaadin4spring | addons/sidebar/src/main/java/org/vaadin/spring/sidebar/annotation/SideBarItem.java | 2647 | /*
* Copyright 2015 The original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.vaadin.spring.sidebar.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation is used to declare a {@link org.vaadin.spring.sidebar.components.AccordionSideBar} item that a user can click on.
* It can be placed on two types of beans:
* <ol>
* <li>{@link java.lang.Runnable}s - when the item is clicked, the runnable is executed</li>
* <li>{@link com.vaadin.navigator.View Views}s that are also annotated with {@link org.vaadin.spring.navigator.annotation.VaadinView VaadinView} - when the item is clicked, the {@link com.vaadin.navigator.Navigator navigator} navigates to the view.
* </ol>
* Please note that the annotated class must be a Spring-managed bean - only adding this annotation is not enough.
*
* @author Petter Holmström (petter@vaadin.com)
* @see org.vaadin.spring.sidebar.components.AccordionSideBar
* @see org.vaadin.spring.sidebar.annotation.SideBarSection
* @see org.vaadin.spring.sidebar.annotation.FontAwesomeIcon
* @see org.vaadin.spring.sidebar.annotation.ThemeIcon
* @see org.vaadin.spring.sidebar.annotation.LocalizedThemeIcon
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface SideBarItem {
/**
* The ID of the side bar section that this item belongs to.
*
* @see SideBarSection#id()
*/
String sectionId();
/**
* The caption of this item.
*
* @see #captionCode()
*/
String caption() default "";
/**
* The code to pass to the {@link org.vaadin.spring.i18n.I18N} instance to get the item caption.
* If this is an empty string, {@link #caption()} is used instead.
*
* @see org.vaadin.spring.i18n.I18N#get(String, Object...)
*/
String captionCode() default "";
/**
* The order of this item within its section. Items with a lower order are placed higher up in the list.
*/
int order() default Integer.MAX_VALUE;
}
| apache-2.0 |
Zooz/Zooz-Java | src/main/java/com/zooz/common/client/ecomm/beans/requests/AbstractAddPaymentMethodRequest.java | 4012 | package com.zooz.common.client.ecomm.beans.requests;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import com.zooz.common.client.ecomm.beans.Fingerprint;
import com.zooz.common.client.ecomm.beans.addpaymentmethod.beans.AbstractPaymentMethod;
import com.zooz.common.client.ecomm.beans.responses.AddPaymentMethodResponse;
import com.zooz.common.client.ecomm.beans.server.response.ZoozServerResponse;
import com.zooz.common.client.ecomm.control.CommonParameters;
import java.util.List;
/**
* Created by roykey on 10/13/15.
*/
public abstract class AbstractAddPaymentMethodRequest extends AbstractZoozRequest {
/**
* The token from "openPayment"/"getToken"
*/
@JsonProperty
protected String paymentToken;
/**
* The users e-mail address.
*/
@JsonProperty
protected String email;
/**
* The users payment method details.
*/
@JsonProperty
protected AbstractPaymentMethod paymentMethod;
/**
* The redirectUrl.
*/
@JsonProperty
protected String redirectUrl;
/**
* List of device fingerprints.
*/
@JsonProperty
protected List<Fingerprint> deviceFingerprint;
/**
* Instantiates a new Abstract add payment method request.
*
* @param paymentToken the payment token
* @param email the email
* @param paymentMethod the payment method
*/
protected AbstractAddPaymentMethodRequest(String paymentToken,String email, AbstractPaymentMethod paymentMethod) {
super(CommonParameters.addPaymentMethod);
this.paymentToken = paymentToken;
this.email = email;
this.paymentMethod = paymentMethod;
}
/**
* Gets the payment token.
*
* @return the payment token
*/
public String getPaymentToken() {
return paymentToken;
}
/**
* Sets the payment token.
*
* @param paymentToken the payment token
*/
public void setPaymentToken(String paymentToken) {
this.paymentToken = paymentToken;
}
/**
* Gets the email.
*
* @return the email
*/
public String getEmail() {
return email;
}
/**
* Sets the email.
*
* @param email the email
*/
public void setEmail(String email) {
this.email = email;
}
/**
* Gets the payment method.
*
* @return the payment method
*/
public AbstractPaymentMethod getPaymentMethod() {
return paymentMethod;
}
/**
* Sets the payment method.
*
* @param paymentMethod the payment method
*/
public void setPaymentMethod(AbstractPaymentMethod paymentMethod) {
this.paymentMethod = paymentMethod;
}
/**
* Gets the list of device fingerprints.
*
* @return device fingerprint
*/
public List<Fingerprint> getDeviceFingerprint() {
return deviceFingerprint;
}
/**
* Sets the list of device fingerprints.
*
* @param deviceFingerprint the device fingerprint
*/
public void setDeviceFingerprint(List<Fingerprint> deviceFingerprint) {
this.deviceFingerprint = deviceFingerprint;
}
/**
* Gets redirect url.
*
* @return the redirect url
*/
public String getRedirectUrl() {
return redirectUrl;
}
/**
* Sets redirect url.
*
* @param redirectUrl the redirect url
*/
public void setRedirectUrl(String redirectUrl) {
this.redirectUrl = redirectUrl;
}
/**
* Used to return the response type corresponding to the request.
*
* @return the corresponding response type.
*/
@Override
@JsonIgnore
public TypeReference<ZoozServerResponse<AddPaymentMethodResponse>> getResponseTypeReference() {
return new TypeReference<ZoozServerResponse<AddPaymentMethodResponse>>() {
};
}
}
| apache-2.0 |
hllorens/timeml-qa | src/test/java/com/cognitionis/timeml_qa/TimeMLQATest.java | 2472 | package com.cognitionis.timeml_qa;
import com.cognitionis.nlp_files.XMLFile;
import com.cognitionis.timeml_basickit.TML_file_utils;
import com.cognitionis.timeml_basickit.TimeML;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author hector
*/
public class TimeMLQATest {
public TimeMLQATest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of TMQA part ActionHandler
*/
@Test
public void testTimeMLQA_questions() throws Exception {
System.out.println("tmqa");
String input_file = this.getClass().getResource("/example2/little-file.tml").toURI().toString();
TimeGraphWrapper tg = null;
XMLFile nlpfile = new XMLFile(input_file, null);
if (!nlpfile.getClass().getSimpleName().equals("XMLFile")) {
throw new Exception("Requires XMLFile files as input. Found: " + nlpfile.getClass().getSimpleName());
}
if (!nlpfile.getExtension().equalsIgnoreCase("tml")) {
nlpfile.overrideExtension("tml");
}
if (!nlpfile.isWellFormatted()) {
throw new Exception("File: " + input_file + " is not a valid TimeML (.tml) XML file.");
}
TimeML tml = TML_file_utils.ReadTml2Object(nlpfile.getFile().getCanonicalPath());
tg = new TimeGraphWrapper(tml, "original_order");
if (tg == null) {
throw new Exception("Null TG wrapper.");
}
test_question( tg, "IS ei1 BEFORE ei2", "yes");
test_question( tg, "IS ei2 BEFORE ei1", "no");
test_question( tg, "IS ei1 BEFORE ei4", "yes");
test_question( tg, "IS ei1 BEFORE 1998-02-20", "yes");
// add more questions, complicate the file
}
public void test_question(TimeGraphWrapper tg, String question, String expected_answer){
String predicted_answer=TimeML_QA.answer_question(question,tg);
if(!predicted_answer.split(" ")[0].equals(expected_answer)){
System.err.println("ERROR: "+question+ " \n\t expected: "+expected_answer+" \n\t predicted:"+predicted_answer);
}
assertEquals(expected_answer, predicted_answer.split(" ")[0]);
}
}
| apache-2.0 |
apache/solr | solr/core/src/test/org/apache/solr/handler/MoreLikeThisHandlerTest.java | 9892 | /*
* 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.solr.handler;
import java.util.ArrayList;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.params.*;
import org.apache.solr.common.util.ContentStream;
import org.apache.solr.common.util.ContentStreamBase;
import org.apache.solr.core.SolrCore;
import org.apache.solr.request.LocalSolrQueryRequest;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.SolrQueryRequestBase;
import org.apache.solr.response.SolrQueryResponse;
import org.junit.BeforeClass;
import org.junit.Test;
/** TODO -- this needs to actually test the results/query etc */
public class MoreLikeThisHandlerTest extends SolrTestCaseJ4 {
@BeforeClass
public static void moreLikeThisBeforeClass() throws Exception {
initCore("solrconfig.xml", "schema.xml");
}
@Test
public void testInterface() throws Exception {
SolrCore core = h.getCore();
ModifiableSolrParams params = new ModifiableSolrParams();
assertU(
adoc(
"id",
"42",
"name",
"Tom Cruise",
"subword",
"Top Gun",
"subword",
"Risky Business",
"subword",
"The Color of Money",
"subword",
"Minority Report",
"subword",
"Days of Thunder",
"subword",
"Eyes Wide Shut",
"subword",
"Far and Away",
"foo_ti",
"10"));
assertU(
adoc(
"id",
"43",
"name",
"Tom Hanks",
"subword",
"The Green Mile",
"subword",
"Forest Gump",
"subword",
"Philadelphia Story",
"subword",
"Big",
"subword",
"Cast Away",
"foo_ti",
"10"));
assertU(
adoc(
"id",
"44",
"name",
"Harrison Ford",
"subword",
"Star Wars",
"subword",
"Indiana Jones",
"subword",
"Patriot Games",
"subword",
"Regarding Henry"));
assertU(
adoc(
"id",
"45",
"name",
"George Harrison",
"subword",
"Yellow Submarine",
"subword",
"Help",
"subword",
"Magical Mystery Tour",
"subword",
"Sgt. Peppers Lonley Hearts Club Band"));
assertU(
adoc(
"id",
"46",
"name",
"Nicole Kidman",
"subword",
"Batman",
"subword",
"Days of Thunder",
"subword",
"Eyes Wide Shut",
"subword",
"Far and Away"));
assertU(commit());
params.set(MoreLikeThisParams.MLT, "true");
params.set(MoreLikeThisParams.SIMILARITY_FIELDS, "name,subword");
params.set(MoreLikeThisParams.INTERESTING_TERMS, "details");
params.set(MoreLikeThisParams.MIN_TERM_FREQ, "1");
params.set(MoreLikeThisParams.MIN_DOC_FREQ, "1");
params.set("indent", "true");
// requires 'q' or a single content stream
SolrException ex =
expectThrows(
SolrException.class,
() -> {
try (MoreLikeThisHandler mlt = new MoreLikeThisHandler();
SolrQueryRequestBase req = new SolrQueryRequestBase(core, params) {}) {
mlt.handleRequestBody(req, new SolrQueryResponse());
}
});
assertEquals(ex.getMessage(), MoreLikeThisHandler.ERR_MSG_QUERY_OR_TEXT_REQUIRED);
assertEquals(ex.code(), SolrException.ErrorCode.BAD_REQUEST.code);
// requires a single content stream (more than one is not supported).
ex =
expectThrows(
SolrException.class,
() -> {
try (MoreLikeThisHandler mlt = new MoreLikeThisHandler();
SolrQueryRequestBase req = new SolrQueryRequestBase(core, params) {}) {
ArrayList<ContentStream> streams = new ArrayList<>(2);
streams.add(new ContentStreamBase.StringStream("hello"));
streams.add(new ContentStreamBase.StringStream("there"));
req.setContentStreams(streams);
mlt.handleRequestBody(req, new SolrQueryResponse());
}
});
assertEquals(ex.getMessage(), MoreLikeThisHandler.ERR_MSG_SINGLE_STREAM_ONLY);
assertEquals(ex.code(), SolrException.ErrorCode.BAD_REQUEST.code);
params.set(CommonParams.Q, "id:42");
try (SolrQueryRequest mltreq = new LocalSolrQueryRequest(core, params)) {
assertQ(
"morelikethis - tom cruise",
mltreq,
"//result/doc[1]/str[@name='id'][.='46']",
"//result/doc[2]/str[@name='id'][.='43']");
}
params.set(MoreLikeThisParams.BOOST, "true");
try (SolrQueryRequest mltreq = new LocalSolrQueryRequest(core, params)) {
assertQ(
"morelikethis - tom cruise",
mltreq,
"//result/doc[1]/str[@name='id'][.='46']",
"//result/doc[2]/str[@name='id'][.='43']");
}
params.set(CommonParams.Q, "id:44");
try (SolrQueryRequest mltreq = new LocalSolrQueryRequest(core, params)) {
assertQ("morelike this - harrison ford", mltreq, "//result/doc[1]/str[@name='id'][.='45']");
}
// test MoreLikeThis debug
params.set(CommonParams.DEBUG_QUERY, "true");
try (SolrQueryRequest mltreq = new LocalSolrQueryRequest(core, params)) {
assertQ(
"morelike this - harrison ford",
mltreq,
"//lst[@name='debug']/lst[@name='moreLikeThis']/lst[@name='44']/str[@name='rawMLTQuery']",
"//lst[@name='debug']/lst[@name='moreLikeThis']/lst[@name='44']/str[@name='boostedMLTQuery']",
"//lst[@name='debug']/lst[@name='moreLikeThis']/lst[@name='44']/str[@name='realMLTQuery']",
"//lst[@name='debug']/lst[@name='moreLikeThis']/lst[@name='44']/lst[@name='explain']/str[@name='45']");
}
// test that qparser plugins work
params.remove(CommonParams.DEBUG_QUERY);
params.set(CommonParams.Q, "{!field f=id}44");
try (SolrQueryRequest mltreq = new LocalSolrQueryRequest(core, params)) {
assertQ(mltreq, "//result/doc[1]/str[@name='id'][.='45']");
}
params.set(CommonParams.Q, "id:42");
params.set(MoreLikeThisParams.QF, "name^5.0 subword^0.1");
try (SolrQueryRequest mltreq = new LocalSolrQueryRequest(core, params)) {
assertQ(
"morelikethis with weights",
mltreq,
"//result/doc[1]/str[@name='id'][.='43']",
"//result/doc[2]/str[@name='id'][.='46']");
}
// test that qparser plugins work w/ the MoreLikeThisHandler
params.set(CommonParams.QT, "/mlt");
params.set(CommonParams.Q, "{!field f=id}44");
try (SolrQueryRequest mltreq = new LocalSolrQueryRequest(core, params)) {
assertQ(mltreq, "//result/doc[1]/str[@name='id'][.='45']");
}
// test that debugging works (test for MoreLikeThis*Handler*)
params.set(CommonParams.QT, "/mlt");
params.set(CommonParams.DEBUG_QUERY, "true");
try (SolrQueryRequest mltreq = new LocalSolrQueryRequest(core, params)) {
assertQ(
mltreq,
"//result/doc[1]/str[@name='id'][.='45']",
"//lst[@name='debug']/lst[@name='explain']");
}
}
@Test
public void testMultifieldSimilarity() throws Exception {
SolrCore core = h.getCore();
ModifiableSolrParams params = new ModifiableSolrParams();
assertU(adoc("id", "1", "name", "aaa bbb ccc", "subword", " zzz"));
assertU(adoc("id", "2", "name", " bbb ccc", "subword", " bbb zzz"));
assertU(adoc("id", "3", "name", " ccc", "subword", "aaa bbb zzz"));
assertU(adoc("id", "4", "name", " ccc", "subword", " bbb "));
assertU(commit());
params.set(CommonParams.QT, "/mlt");
params.set(MoreLikeThisParams.MLT, "true");
params.set(MoreLikeThisParams.SIMILARITY_FIELDS, "name,subword");
params.set(MoreLikeThisParams.INTERESTING_TERMS, "details");
params.set(MoreLikeThisParams.MIN_TERM_FREQ, "1");
params.set(MoreLikeThisParams.MIN_DOC_FREQ, "2");
params.set(MoreLikeThisParams.BOOST, true);
params.set("indent", "true");
try (SolrQueryRequestBase req = new SolrQueryRequestBase(core, params) {}) {
ArrayList<ContentStream> streams = new ArrayList<>(2);
streams.add(new ContentStreamBase.StringStream("bbb", "zzz"));
req.setContentStreams(streams);
// Make sure we have terms from both fields in the interestingTerms array and all documents
// have been retrieved as matching.
assertQ(
req,
"//lst[@name = 'interestingTerms']/float[@name = 'subword:bbb']",
"//lst[@name = 'interestingTerms']/float[@name = 'name:bbb']",
"//result[@name = 'response' and @numFound = '4']");
}
}
}
| apache-2.0 |
tiobe/closure-compiler | test/com/google/javascript/jscomp/ChromePassTest.java | 24468 | /*
* Copyright 2014 The Closure Compiler 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.javascript.jscomp;
import com.google.javascript.jscomp.CompilerOptions.LanguageMode;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests {@link ChromePass}. */
@RunWith(JUnit4.class)
public class ChromePassTest extends CompilerTestCase {
@Override
@Before
public void setUp() throws Exception {
super.setUp();
setLanguage(LanguageMode.ECMASCRIPT_2017, LanguageMode.ECMASCRIPT_2017);
}
@Override
protected CompilerPass getProcessor(Compiler compiler) {
return new ChromePass(compiler);
}
@Override
protected int getNumRepetitions() {
// This pass isn't idempotent and only runs once.
return 1;
}
@Test
public void testCrDefineCreatesObjectsForQualifiedName() {
test(
"cr.define('my.namespace.name', function() {\n" + " return {};\n" + "});",
"var my = my || {};\n"
+ "my.namespace = my.namespace || {};\n"
+ "my.namespace.name = my.namespace.name || {};\n"
+ "cr.define('my.namespace.name', function() {\n"
+ " return {};\n"
+ "});");
}
@Test
public void testChromePassIgnoresModules() {
testSame("export var x;");
}
@Test
public void testCrDefineAssignsExportedFunctionByQualifiedName() {
test(
"cr.define('namespace', function() {\n"
+ " function internalStaticMethod() {\n"
+ " alert(42);\n"
+ " }\n"
+ " return {\n"
+ " externalStaticMethod: internalStaticMethod\n"
+ " };\n"
+ "});",
"var namespace = namespace || {};\n"
+ "cr.define('namespace', function() {\n"
+ " namespace.externalStaticMethod = function internalStaticMethod() {\n"
+ " alert(42);\n"
+ " }\n"
+ " return {\n"
+ " externalStaticMethod: namespace.externalStaticMethod\n"
+ " };\n"
+ "});");
}
@Test
public void testCrDefineCopiesJSDocForExportedFunction() {
test(
"cr.define('namespace', function() {\n"
+ " /** I'm function's JSDoc */\n"
+ " function internalStaticMethod() {\n"
+ " alert(42);\n"
+ " }\n"
+ " return {\n"
+ " externalStaticMethod: internalStaticMethod\n"
+ " };\n"
+ "});",
"var namespace = namespace || {};\n"
+ "cr.define('namespace', function() {\n"
+ " /** I'm function's JSDoc */\n"
+ " namespace.externalStaticMethod = function internalStaticMethod() {\n"
+ " alert(42);\n"
+ " }\n"
+ " return {\n"
+ " externalStaticMethod: namespace.externalStaticMethod\n"
+ " };\n"
+ "});");
}
@Test
public void testCrDefineReassignsExportedVarByQualifiedName() {
test(
"cr.define('namespace', function() {\n"
+ " var internalStaticMethod = function() {\n"
+ " alert(42);\n"
+ " }\n"
+ " return {\n"
+ " externalStaticMethod: internalStaticMethod\n"
+ " };\n"
+ "});",
"var namespace = namespace || {};\n"
+ "cr.define('namespace', function() {\n"
+ " namespace.externalStaticMethod = function() {\n"
+ " alert(42);\n"
+ " }\n"
+ " return {\n"
+ " externalStaticMethod: namespace.externalStaticMethod\n"
+ " };\n"
+ "});");
}
@Test
public void testCrDefineExportsVarsWithoutAssignment() {
test(
"cr.define('namespace', function() {\n"
+ " var a;\n"
+ " return {\n"
+ " a: a\n"
+ " };\n"
+ "});\n",
"var namespace = namespace || {};\n"
+ "cr.define('namespace', function() {\n"
+ " namespace.a;\n"
+ " return {\n"
+ " a: namespace.a\n"
+ " };\n"
+ "});\n");
}
@Test
public void testCrDefineExportsVarsWithoutAssignmentWithJSDoc() {
test(
"cr.define('namespace', function() {\n"
+ " /** @type {number} */\n"
+ " var a;\n"
+ " return {\n"
+ " a: a\n"
+ " };\n"
+ "});\n",
"var namespace = namespace || {};\n"
+ "cr.define('namespace', function() {\n"
+ " /** @type {number} */\n"
+ " namespace.a;\n"
+ " return {\n"
+ " a: namespace.a\n"
+ " };\n"
+ "});\n");
}
@Test
public void testCrDefineCopiesJSDocForExportedVariable() {
test(
"cr.define('namespace', function() {\n"
+ " /** I'm function's JSDoc */\n"
+ " var internalStaticMethod = function() {\n"
+ " alert(42);\n"
+ " }\n"
+ " return {\n"
+ " externalStaticMethod: internalStaticMethod\n"
+ " };\n"
+ "});",
"var namespace = namespace || {};\n"
+ "cr.define('namespace', function() {\n"
+ " /** I'm function's JSDoc */\n"
+ " namespace.externalStaticMethod = function() {\n"
+ " alert(42);\n"
+ " }\n"
+ " return {\n"
+ " externalStaticMethod: namespace.externalStaticMethod\n"
+ " };\n"
+ "});");
}
@Test
public void testCrDefineDoesNothingWithNonExportedFunction() {
test(
"cr.define('namespace', function() {\n"
+ " function internalStaticMethod() {\n"
+ " alert(42);\n"
+ " }\n"
+ " return {};\n"
+ "});",
"var namespace = namespace || {};\n"
+ "cr.define('namespace', function() {\n"
+ " function internalStaticMethod() {\n"
+ " alert(42);\n"
+ " }\n"
+ " return {};\n"
+ "});");
}
@Test
public void testCrDefineDoesNothingWithNonExportedVar() {
test(
"cr.define('namespace', function() {\n"
+ " var a;\n"
+ " var b;\n"
+ " return {\n"
+ " a: a\n"
+ " };\n"
+ "});\n",
"var namespace = namespace || {};\n"
+ "cr.define('namespace', function() {\n"
+ " namespace.a;\n"
+ " var b;\n"
+ " return {\n"
+ " a: namespace.a\n"
+ " };\n"
+ "});\n");
}
@Test
public void testCrDefineDoesNothingWithExportedNotAName() {
test(
"cr.define('namespace', function() {\n"
+ " return {\n"
+ " a: 42\n"
+ " };\n"
+ "});\n",
"var namespace = namespace || {};\n"
+ "cr.define('namespace', function() {\n"
+ " return {\n"
+ " a: 42\n"
+ " };\n"
+ "});\n");
}
@Test
public void testCrDefineChangesReferenceToExportedFunction() {
test(
"cr.define('namespace', function() {\n"
+ " function internalStaticMethod() {\n"
+ " alert(42);\n"
+ " }\n"
+ " function letsUseIt() {\n"
+ " internalStaticMethod();\n"
+ " }\n"
+ " return {\n"
+ " externalStaticMethod: internalStaticMethod\n"
+ " };\n"
+ "});",
"var namespace = namespace || {};\n"
+ "cr.define('namespace', function() {\n"
+ " namespace.externalStaticMethod = function internalStaticMethod() {\n"
+ " alert(42);\n"
+ " }\n"
+ " function letsUseIt() {\n"
+ " namespace.externalStaticMethod();\n"
+ " }\n"
+ " return {\n"
+ " externalStaticMethod: namespace.externalStaticMethod\n"
+ " };\n"
+ "});");
}
@Test
public void testCrDefineConstEnum() {
test(
lines(
"cr.define('foo', function() {",
" /** ",
" * @enum {string}",
" */",
" const DangerType = {",
" NOT_DANGEROUS: 'NOT_DANGEROUS',",
" DANGEROUS: 'DANGEROUS',",
" };",
"",
" return {",
" DangerType: DangerType,",
" };",
"});"),
lines(
"var foo = foo || {};",
"cr.define('foo', function() {",
" /** @enum {string} */",
" foo.DangerType = {",
" NOT_DANGEROUS:'NOT_DANGEROUS',",
" DANGEROUS:'DANGEROUS',",
" };",
"",
" return {",
" DangerType: foo.DangerType",
" }",
"})",
""));
}
@Test
public void testCrDefineLetEnum() {
test(
lines(
"cr.define('foo', function() {",
" /** ",
" * @enum {string}",
" */",
" let DangerType = {",
" NOT_DANGEROUS: 'NOT_DANGEROUS',",
" DANGEROUS: 'DANGEROUS',",
" };",
"",
" return {",
" DangerType: DangerType,",
" };",
"});"),
lines(
"var foo = foo || {};",
"cr.define('foo', function() {",
" /** @enum {string} */",
" foo.DangerType = {",
" NOT_DANGEROUS:'NOT_DANGEROUS',",
" DANGEROUS:'DANGEROUS',",
" };",
"",
" return {",
" DangerType: foo.DangerType",
" }",
"})",
""));
}
@Test
public void testCrDefineWrongNumberOfArguments() {
testError(
"cr.define('namespace', function() { return {}; }, 'invalid argument')\n",
ChromePass.CR_DEFINE_WRONG_NUMBER_OF_ARGUMENTS);
}
@Test
public void testCrDefineInvalidFirstArgument() {
testError(
"cr.define(42, function() { return {}; })\n", ChromePass.CR_DEFINE_INVALID_FIRST_ARGUMENT);
}
@Test
public void testCrDefineInvalidSecondArgument() {
testError("cr.define('namespace', 42)\n", ChromePass.CR_DEFINE_INVALID_SECOND_ARGUMENT);
}
@Test
public void testCrDefineInvalidReturnInFunction() {
testError(
"cr.define('namespace', function() {})\n", ChromePass.CR_DEFINE_INVALID_RETURN_IN_FUNCTION);
}
@Test
public void testObjectDefinePropertyDefinesUnquotedProperty() {
test(
"Object.defineProperty(a.b, 'c', {});",
"Object.defineProperty(a.b, 'c', {});\n" + "/** @type {?} */\n" + "a.b.c;");
}
@Test
public void testCrDefinePropertyDefinesUnquotedPropertyWithStringTypeForPropertyKindAttr()
throws Exception {
test(
"cr.defineProperty(a.prototype, 'c', cr.PropertyKind.ATTR);",
"cr.defineProperty(a.prototype, 'c', cr.PropertyKind.ATTR);\n"
+ "/** @type {string} */\n"
+ "a.prototype.c;");
}
@Test
public void testCrDefinePropertyDefinesUnquotedPropertyWithBooleanTypeForPropertyKindBoolAttr()
throws Exception {
test(
"cr.defineProperty(a.prototype, 'c', cr.PropertyKind.BOOL_ATTR);",
"cr.defineProperty(a.prototype, 'c', cr.PropertyKind.BOOL_ATTR);\n"
+ "/** @type {boolean} */\n"
+ "a.prototype.c;");
}
@Test
public void testCrDefinePropertyDefinesUnquotedPropertyWithAnyTypeForPropertyKindJs()
throws Exception {
test(
"cr.defineProperty(a.prototype, 'c', cr.PropertyKind.JS);",
"cr.defineProperty(a.prototype, 'c', cr.PropertyKind.JS);\n"
+ "/** @type {?} */\n"
+ "a.prototype.c;");
}
@Test
public void testCrDefinePropertyDefinesUnquotedPropertyWithTypeInfoForPropertyKindJs()
throws Exception {
test(
lines(
// @type starts here.
"/** @type {!Object} */",
"cr.defineProperty(a.prototype, 'c', cr.PropertyKind.JS);"),
lines(
"cr.defineProperty(a.prototype, 'c', cr.PropertyKind.JS);",
// But gets moved here.
"/** @type {!Object} */",
"a.prototype.c;"));
}
@Test
public void testCrDefinePropertyDefinesUnquotedPropertyIgnoringJsDocWhenBoolAttrIsPresent()
throws Exception {
test(
lines(
// PropertyKind is used at runtime and is canonical. When it's specified, ignore @type.
"/** @type {!Object} */",
"cr.defineProperty(a.prototype, 'c', cr.PropertyKind.BOOL_ATTR);"),
lines(
"cr.defineProperty(a.prototype, 'c', cr.PropertyKind.BOOL_ATTR);",
// @type is now {boolean}. Earlier, manually-specified @type is ignored.
"/** @type {boolean} */",
"a.prototype.c;"));
}
@Test
public void testCrDefinePropertyDefinesUnquotedPropertyIgnoringJsDocWhenAttrIsPresent()
throws Exception {
test(
lines(
// PropertyKind is used at runtime and is canonical. When it's specified, ignore @type.
"/** @type {!Array} */",
"cr.defineProperty(a.prototype, 'c', cr.PropertyKind.ATTR);"),
lines(
"cr.defineProperty(a.prototype, 'c', cr.PropertyKind.ATTR);",
// @type is now {string}. Earlier, manually-specified @type is ignored.
"/** @type {string} */",
"a.prototype.c;"));
}
@Test
public void testCrDefinePropertyCalledWithouthThirdArgumentMeansCrPropertyKindJs()
throws Exception {
test(
"cr.defineProperty(a.prototype, 'c');",
"cr.defineProperty(a.prototype, 'c');\n" + "/** @type {?} */\n" + "a.prototype.c;");
}
@Test
public void testCrDefinePropertyDefinesUnquotedPropertyOnPrototypeWhenFunctionIsPassed()
throws Exception {
test(
"cr.defineProperty(a, 'c', cr.PropertyKind.JS);",
"cr.defineProperty(a, 'c', cr.PropertyKind.JS);\n"
+ "/** @type {?} */\n"
+ "a.prototype.c;");
}
@Test
public void testCrDefinePropertyInvalidPropertyKind() {
testError(
"cr.defineProperty(a.b, 'c', cr.PropertyKind.INEXISTENT_KIND);",
ChromePass.CR_DEFINE_PROPERTY_INVALID_PROPERTY_KIND);
}
@Test
public void testCrExportPath() {
test(
"cr.exportPath('a.b.c');",
"var a = a || {};\n"
+ "a.b = a.b || {};\n"
+ "a.b.c = a.b.c || {};\n"
+ "cr.exportPath('a.b.c');");
}
@Test
public void testCrDefineCreatesEveryObjectOnlyOnce() {
test(
"cr.define('a.b.c.d', function() {\n"
+ " return {};\n"
+ "});\n"
+ "cr.define('a.b.e.f', function() {\n"
+ " return {};\n"
+ "});",
"var a = a || {};\n"
+ "a.b = a.b || {};\n"
+ "a.b.c = a.b.c || {};\n"
+ "a.b.c.d = a.b.c.d || {};\n"
+ "cr.define('a.b.c.d', function() {\n"
+ " return {};\n"
+ "});\n"
+ "a.b.e = a.b.e || {};\n"
+ "a.b.e.f = a.b.e.f || {};\n"
+ "cr.define('a.b.e.f', function() {\n"
+ " return {};\n"
+ "});");
}
@Test
public void testCrDefineAndCrExportPathCreateEveryObjectOnlyOnce() {
test(
"cr.exportPath('a.b.c.d');\n"
+ "cr.define('a.b.e.f', function() {\n"
+ " return {};\n"
+ "});",
"var a = a || {};\n"
+ "a.b = a.b || {};\n"
+ "a.b.c = a.b.c || {};\n"
+ "a.b.c.d = a.b.c.d || {};\n"
+ "cr.exportPath('a.b.c.d');\n"
+ "a.b.e = a.b.e || {};\n"
+ "a.b.e.f = a.b.e.f || {};\n"
+ "cr.define('a.b.e.f', function() {\n"
+ " return {};\n"
+ "});");
}
@Test
public void testCrDefineDoesntRedefineCrVar() {
test(
"cr.define('cr.ui', function() {\n" + " return {};\n" + "});",
"cr.ui = cr.ui || {};\n" + "cr.define('cr.ui', function() {\n" + " return {};\n" + "});");
}
@Test
public void testCrDefineFunction() {
test(
lines(
"cr.define('settings', function() {",
" var x = 0;",
" function C() {}",
" return { C: C };",
"});"),
lines(
"var settings = settings || {};",
"cr.define('settings', function() {",
" var x = 0;",
" settings.C = function C() {};",
" return { C: settings.C };",
"});"));
}
@Test
public void testCrDefineClassStatement() {
test(
lines(
"cr.define('settings', function() {",
" var x = 0;",
" class C {}",
" return { C: C };",
"});"),
lines(
"var settings = settings || {};",
"cr.define('settings', function() {",
" var x = 0;",
" settings.C = class {}",
" return { C: settings.C };",
"});"));
}
@Test
public void testCrDefineClassExpression() {
test(
lines(
"cr.define('settings', function() {",
" var x = 0;",
" var C = class {}",
" return { C: C };",
"});"),
lines(
"var settings = settings || {};",
"cr.define('settings', function() {",
" var x = 0;",
" settings.C = class {}",
" return { C: settings.C };",
"});"));
}
@Test
public void testCrDefineClassWithInternalSelfReference() {
test(
lines(
"cr.define('settings', function() {",
" var x = 0;",
" class C {",
" static create() { return new C; }",
" }",
" return { C: C };",
"});"),
lines(
"var settings = settings || {};",
"cr.define('settings', function() {",
" var x = 0;",
" settings.C = class {",
" static create() { return new settings.C; }",
" }",
" return { C: settings.C };",
"});"));
}
@Test
public void testCrExportPathInvalidNumberOfArguments() {
testError("cr.exportPath();", ChromePass.CR_EXPORT_PATH_TOO_FEW_ARGUMENTS);
}
@Test
public void testCrMakePublicWorksOnOneMethodDefinedInPrototypeObject() {
test(
"/** @constructor */\n"
+ "function Class() {};\n"
+ "\n"
+ "Class.prototype = {\n"
+ " /** @return {number} */\n"
+ " method_: function() { return 42; }\n"
+ "};\n"
+ "\n"
+ "cr.makePublic(Class, ['method']);",
"/** @constructor */\n"
+ "function Class() {};\n"
+ "\n"
+ "Class.prototype = {\n"
+ " /** @return {number} */\n"
+ " method_: function() { return 42; }\n"
+ "};\n"
+ "\n"
+ "/** @return {number} */\n"
+ "Class.method;\n"
+ "\n"
+ "cr.makePublic(Class, ['method']);");
}
@Test
public void testCrMakePublicWorksOnTwoMethods() {
test(
"/** @constructor */\n"
+ "function Class() {}\n"
+ "\n"
+ "Class.prototype = {\n"
+ " /** @return {number} */\n"
+ " m1_: function() { return 42; },\n"
+ "\n"
+ " /** @return {string} */\n"
+ " m2_: function() { return ''; }\n"
+ "};\n"
+ "\n"
+ "cr.makePublic(Class, ['m1', 'm2']);",
"/** @constructor */\n"
+ "function Class() {}\n"
+ "\n"
+ "Class.prototype = {\n"
+ " /** @return {number} */\n"
+ " m1_: function() { return 42; },\n"
+ "\n"
+ " /** @return {string} */\n"
+ " m2_: function() { return ''; }\n"
+ "}\n"
+ "\n"
+ "/** @return {number} */\n"
+ "Class.m1;\n"
+ "\n"
+ "/** @return {string} */\n"
+ "Class.m2;\n"
+ "\n"
+ "cr.makePublic(Class, ['m1', 'm2']);");
}
@Test
public void testCrMakePublicRequiresMethodsToHaveJSDoc() {
testError(
"/** @constructor */\n"
+ "function Class() {}\n"
+ "\n"
+ "Class.prototype = {\n"
+ " method_: function() {}\n"
+ "}\n"
+ "\n"
+ "cr.makePublic(Class, ['method']);",
ChromePass.CR_MAKE_PUBLIC_HAS_NO_JSDOC);
}
@Test
public void testCrMakePublicDoesNothingWithMethodsNotInAPI() {
test(
"/** @constructor */\n"
+ "function Class() {}\n"
+ "\n"
+ "Class.prototype = {\n"
+ " method_: function() {}\n"
+ "}\n"
+ "\n"
+ "cr.makePublic(Class, []);",
"/** @constructor */\n"
+ "function Class() {}\n"
+ "\n"
+ "Class.prototype = {\n"
+ " method_: function() {}\n"
+ "}\n"
+ "\n"
+ "cr.makePublic(Class, []);");
}
@Test
public void testCrMakePublicRequiresExportedMethodToBeDeclared() {
testError(
"/** @constructor */\n"
+ "function Class() {}\n"
+ "\n"
+ "Class.prototype = {\n"
+ "}\n"
+ "\n"
+ "cr.makePublic(Class, ['method']);",
ChromePass.CR_MAKE_PUBLIC_MISSED_DECLARATION);
}
@Test
public void testCrMakePublicWorksOnOneMethodDefinedDirectlyOnPrototype() {
test(
"/** @constructor */\n"
+ "function Class() {}\n"
+ "\n"
+ "/** @return {number} */\n"
+ "Class.prototype.method_ = function() {};\n"
+ "\n"
+ "cr.makePublic(Class, ['method']);",
"/** @constructor */\n"
+ "function Class() {}\n"
+ "\n"
+ "/** @return {number} */\n"
+ "Class.prototype.method_ = function() {};\n"
+ "\n"
+ "/** @return {number} */\n"
+ "Class.method;\n"
+ "\n"
+ "cr.makePublic(Class, ['method']);");
}
@Test
public void testCrMakePublicWorksOnDummyDeclaration() {
test(
"/** @constructor */\n"
+ "function Class() {}\n"
+ "\n"
+ "/** @return {number} */\n"
+ "Class.prototype.method_;\n"
+ "\n"
+ "cr.makePublic(Class, ['method']);",
"/** @constructor */\n"
+ "function Class() {}\n"
+ "\n"
+ "/** @return {number} */\n"
+ "Class.prototype.method_;\n"
+ "\n"
+ "/** @return {number} */\n"
+ "Class.method;\n"
+ "\n"
+ "cr.makePublic(Class, ['method']);");
}
@Test
public void testCrMakePublicReportsInvalidSecondArgumentMissing() {
testError("cr.makePublic(Class);", ChromePass.CR_MAKE_PUBLIC_INVALID_SECOND_ARGUMENT);
}
@Test
public void testCrMakePublicReportsInvalidSecondArgumentNotAnArray() {
testError("cr.makePublic(Class, 42);", ChromePass.CR_MAKE_PUBLIC_INVALID_SECOND_ARGUMENT);
}
@Test
public void testCrMakePublicReportsInvalidSecondArgumentArrayWithNotAString() {
testError("cr.makePublic(Class, [42]);", ChromePass.CR_MAKE_PUBLIC_INVALID_SECOND_ARGUMENT);
}
}
| apache-2.0 |
Esjob-Cloud-DevOps/elastic-job | elastic-job-lite/elastic-job-lite-core/src/test/java/com/dangdang/ddframe/job/lite/fixture/LiteJsonConstants.java | 3156 | /*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package com.dangdang.ddframe.job.lite.fixture;
import com.dangdang.ddframe.job.executor.handler.impl.DefaultExecutorServiceHandler;
import com.dangdang.ddframe.job.executor.handler.impl.DefaultJobExceptionHandler;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class LiteJsonConstants {
private static final String JOB_PROPS_JSON = "{\"job_exception_handler\":\"" + DefaultJobExceptionHandler.class.getCanonicalName() + "\","
+ "\"executor_service_handler\":\"" + DefaultExecutorServiceHandler.class.getCanonicalName() + "\"}";
private static final String JOB_JSON = "{\"jobName\":\"test_job\",\"jobClass\":\"%s\",\"jobType\":\"SIMPLE\",\"cron\":\"0/1 * * * * ?\","
+ "\"shardingTotalCount\":3,\"shardingItemParameters\":\"\",\"jobParameter\":\"param\",\"failover\":%s,\"misfire\":false,\"description\":\"desc\","
+ "\"jobProperties\":" + JOB_PROPS_JSON + ",\"monitorExecution\":%s,\"maxTimeDiffSeconds\":%s,"
+ "\"monitorPort\":8888,\"jobShardingStrategyClass\":\"testClass\",\"disabled\":true,\"overwrite\":true, \"reconcileIntervalMinutes\": 15}";
private static final String DEFAULT_JOB_CLASS = "com.dangdang.ddframe.job.lite.fixture.TestSimpleJob";
private static final boolean DEFAULT_FAILOVER = true;
private static final boolean DEFAULT_MONITOR_EXECUTION = true;
private static final int DEFAULT_MAX_TIME_DIFF_SECONDS = 1000;
public static String getJobJson() {
return String.format(JOB_JSON, DEFAULT_JOB_CLASS, DEFAULT_FAILOVER, DEFAULT_MONITOR_EXECUTION, DEFAULT_MAX_TIME_DIFF_SECONDS);
}
public static String getJobJson(final String jobClass) {
return String.format(JOB_JSON, jobClass, DEFAULT_FAILOVER, DEFAULT_MONITOR_EXECUTION, DEFAULT_MAX_TIME_DIFF_SECONDS);
}
public static String getJobJson(final int maxTimeDiffSeconds) {
return String.format(JOB_JSON, DEFAULT_JOB_CLASS, DEFAULT_FAILOVER, DEFAULT_MONITOR_EXECUTION, maxTimeDiffSeconds);
}
public static String getJobJsonWithFailover(final boolean failover) {
return String.format(JOB_JSON, DEFAULT_JOB_CLASS, failover, DEFAULT_MONITOR_EXECUTION, DEFAULT_MAX_TIME_DIFF_SECONDS);
}
public static String getJobJsonWithMonitorExecution(final boolean monitorExecution) {
return String.format(JOB_JSON, DEFAULT_JOB_CLASS, DEFAULT_FAILOVER, monitorExecution, DEFAULT_MAX_TIME_DIFF_SECONDS);
}
}
| apache-2.0 |
apurtell/hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/test/GenericTestUtils.java | 33037 | /**
* 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.test;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.StringWriter;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.Enumeration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.impl.Log4JLogger;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.util.BlockingThreadPoolExecutorService;
import org.apache.hadoop.util.DurationInfo;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Time;
import org.apache.log4j.Appender;
import org.apache.log4j.Layout;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.WriterAppender;
import org.junit.Assert;
import org.junit.Assume;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.thirdparty.com.google.common.base.Joiner;
import org.apache.hadoop.util.Sets;
import static org.apache.hadoop.fs.contract.ContractTestUtils.createFile;
import static org.apache.hadoop.util.functional.CommonCallableSupplier.submit;
import static org.apache.hadoop.util.functional.CommonCallableSupplier.waitForCompletion;
/**
* Test provides some very generic helpers which might be used across the tests
*/
public abstract class GenericTestUtils {
public static final int EXECUTOR_THREAD_COUNT = 64;
private static final org.slf4j.Logger LOG =
LoggerFactory.getLogger(GenericTestUtils.class);
public static final String PREFIX = "file-";
private static final AtomicInteger sequence = new AtomicInteger();
/**
* system property for test data: {@value}
*/
public static final String SYSPROP_TEST_DATA_DIR = "test.build.data";
/**
* Default path for test data: {@value}
*/
public static final String DEFAULT_TEST_DATA_DIR =
"target" + File.separator + "test" + File.separator + "data";
/**
* The default path for using in Hadoop path references: {@value}
*/
public static final String DEFAULT_TEST_DATA_PATH = "target/test/data/";
/**
* Error string used in
* {@link GenericTestUtils#waitFor(Supplier, long, long)}.
*/
public static final String ERROR_MISSING_ARGUMENT =
"Input supplier interface should be initailized";
public static final String ERROR_INVALID_ARGUMENT =
"Total wait time should be greater than check interval time";
/**
* @deprecated use {@link #disableLog(org.slf4j.Logger)} instead
*/
@Deprecated
@SuppressWarnings("unchecked")
public static void disableLog(Log log) {
// We expect that commons-logging is a wrapper around Log4j.
disableLog((Log4JLogger) log);
}
@Deprecated
public static Logger toLog4j(org.slf4j.Logger logger) {
return LogManager.getLogger(logger.getName());
}
/**
* @deprecated use {@link #disableLog(org.slf4j.Logger)} instead
*/
@Deprecated
public static void disableLog(Log4JLogger log) {
log.getLogger().setLevel(Level.OFF);
}
/**
* @deprecated use {@link #disableLog(org.slf4j.Logger)} instead
*/
@Deprecated
public static void disableLog(Logger logger) {
logger.setLevel(Level.OFF);
}
public static void disableLog(org.slf4j.Logger logger) {
disableLog(toLog4j(logger));
}
/**
* @deprecated
* use {@link #setLogLevel(org.slf4j.Logger, org.slf4j.event.Level)} instead
*/
@Deprecated
@SuppressWarnings("unchecked")
public static void setLogLevel(Log log, Level level) {
// We expect that commons-logging is a wrapper around Log4j.
setLogLevel((Log4JLogger) log, level);
}
/**
* A helper used in log4j2 migration to accept legacy
* org.apache.commons.logging apis.
* <p>
* And will be removed after migration.
*
* @param log a log
* @param level level to be set
*/
@Deprecated
public static void setLogLevel(Log log, org.slf4j.event.Level level) {
setLogLevel(log, Level.toLevel(level.toString()));
}
/**
* @deprecated
* use {@link #setLogLevel(org.slf4j.Logger, org.slf4j.event.Level)} instead
*/
@Deprecated
public static void setLogLevel(Log4JLogger log, Level level) {
log.getLogger().setLevel(level);
}
/**
* @deprecated
* use {@link #setLogLevel(org.slf4j.Logger, org.slf4j.event.Level)} instead
*/
@Deprecated
public static void setLogLevel(Logger logger, Level level) {
logger.setLevel(level);
}
/**
* @deprecated
* use {@link #setLogLevel(org.slf4j.Logger, org.slf4j.event.Level)} instead
*/
@Deprecated
public static void setLogLevel(org.slf4j.Logger logger, Level level) {
setLogLevel(toLog4j(logger), level);
}
public static void setLogLevel(org.slf4j.Logger logger,
org.slf4j.event.Level level) {
setLogLevel(toLog4j(logger), Level.toLevel(level.toString()));
}
public static void setRootLogLevel(org.slf4j.event.Level level) {
setLogLevel(LogManager.getRootLogger(), Level.toLevel(level.toString()));
}
public static void setCurrentLoggersLogLevel(org.slf4j.event.Level level) {
for (Enumeration<?> loggers = LogManager.getCurrentLoggers();
loggers.hasMoreElements();) {
Logger logger = (Logger) loggers.nextElement();
logger.setLevel(Level.toLevel(level.toString()));
}
}
public static org.slf4j.event.Level toLevel(String level) {
return toLevel(level, org.slf4j.event.Level.DEBUG);
}
public static org.slf4j.event.Level toLevel(
String level, org.slf4j.event.Level defaultLevel) {
try {
return org.slf4j.event.Level.valueOf(level);
} catch (IllegalArgumentException e) {
return defaultLevel;
}
}
/**
* Extracts the name of the method where the invocation has happened
* @return String name of the invoking method
*/
public static String getMethodName() {
return Thread.currentThread().getStackTrace()[2].getMethodName();
}
/**
* Generates a process-wide unique sequence number.
* @return an unique sequence number
*/
public static int uniqueSequenceId() {
return sequence.incrementAndGet();
}
/**
* Creates a directory for the data/logs of the unit test.
* It first deletes the directory if it exists.
*
* @param testClass the unit test class.
* @return the Path of the root directory.
*/
public static File setupTestRootDir(Class<?> testClass) {
File testRootDir = getTestDir(testClass.getSimpleName());
if (testRootDir.exists()) {
FileUtil.fullyDelete(testRootDir);
}
testRootDir.mkdirs();
return testRootDir;
}
/**
* Get the (created) base directory for tests.
* @return the absolute directory
*/
public static File getTestDir() {
String prop = System.getProperty(SYSPROP_TEST_DATA_DIR, DEFAULT_TEST_DATA_DIR);
if (prop.isEmpty()) {
// corner case: property is there but empty
prop = DEFAULT_TEST_DATA_DIR;
}
File dir = new File(prop).getAbsoluteFile();
dir.mkdirs();
assertExists(dir);
return dir;
}
/**
* Get an uncreated directory for tests.
* @return the absolute directory for tests. Caller is expected to create it.
*/
public static File getTestDir(String subdir) {
return new File(getTestDir(), subdir).getAbsoluteFile();
}
/**
* Get an uncreated directory for tests with a randomized alphanumeric
* name. This is likely to provide a unique path for tests run in parallel
* @return the absolute directory for tests. Caller is expected to create it.
*/
public static File getRandomizedTestDir() {
return new File(getRandomizedTempPath());
}
/**
* Get a temp path. This may or may not be relative; it depends on what the
* {@link #SYSPROP_TEST_DATA_DIR} is set to. If unset, it returns a path
* under the relative path {@link #DEFAULT_TEST_DATA_PATH}
* @param subpath sub path, with no leading "/" character
* @return a string to use in paths
*/
public static String getTempPath(String subpath) {
String prop = (Path.WINDOWS) ? DEFAULT_TEST_DATA_PATH
: System.getProperty(SYSPROP_TEST_DATA_DIR, DEFAULT_TEST_DATA_PATH);
if (prop.isEmpty()) {
// corner case: property is there but empty
prop = DEFAULT_TEST_DATA_PATH;
}
if (!prop.endsWith("/")) {
prop = prop + "/";
}
return prop + subpath;
}
/**
* Get a temp path. This may or may not be relative; it depends on what the
* {@link #SYSPROP_TEST_DATA_DIR} is set to. If unset, it returns a path
* under the relative path {@link #DEFAULT_TEST_DATA_PATH}
* @return a string to use in paths
*/
public static String getRandomizedTempPath() {
return getTempPath(RandomStringUtils.randomAlphanumeric(10));
}
/**
* Assert that a given file exists.
*/
public static void assertExists(File f) {
Assert.assertTrue("File " + f + " should exist", f.exists());
}
/**
* List all of the files in 'dir' that match the regex 'pattern'.
* Then check that this list is identical to 'expectedMatches'.
* @throws IOException if the dir is inaccessible
*/
public static void assertGlobEquals(File dir, String pattern,
String ... expectedMatches) throws IOException {
Set<String> found = Sets.newTreeSet();
for (File f : FileUtil.listFiles(dir)) {
if (f.getName().matches(pattern)) {
found.add(f.getName());
}
}
Set<String> expectedSet = Sets.newTreeSet(
Arrays.asList(expectedMatches));
Assert.assertEquals("Bad files matching " + pattern + " in " + dir,
Joiner.on(",").join(expectedSet),
Joiner.on(",").join(found));
}
static final String E_NULL_THROWABLE = "Null Throwable";
static final String E_NULL_THROWABLE_STRING =
"Null Throwable.toString() value";
static final String E_UNEXPECTED_EXCEPTION = "but got unexpected exception";
/**
* Assert that an exception's <code>toString()</code> value
* contained the expected text.
* @param expectedText expected string
* @param t thrown exception
* @throws AssertionError if the expected string is not found
*/
public static void assertExceptionContains(String expectedText, Throwable t) {
assertExceptionContains(expectedText, t, "");
}
/**
* Assert that an exception's <code>toString()</code> value
* contained the expected text.
* @param expectedText expected string
* @param t thrown exception
* @param message any extra text for the string
* @throws AssertionError if the expected string is not found
*/
public static void assertExceptionContains(String expectedText,
Throwable t,
String message) {
Assert.assertNotNull(E_NULL_THROWABLE, t);
String msg = t.toString();
if (msg == null) {
throw new AssertionError(E_NULL_THROWABLE_STRING, t);
}
if (expectedText != null && !msg.contains(expectedText)) {
String prefix = org.apache.commons.lang3.StringUtils.isEmpty(message)
? "" : (message + ": ");
throw new AssertionError(
String.format("%s Expected to find '%s' %s: %s",
prefix, expectedText, E_UNEXPECTED_EXCEPTION,
StringUtils.stringifyException(t)),
t);
}
}
/**
* Wait for the specified test to return true. The test will be performed
* initially and then every {@code checkEveryMillis} until at least
* {@code waitForMillis} time has expired. If {@code check} is null or
* {@code waitForMillis} is less than {@code checkEveryMillis} this method
* will throw an {@link IllegalArgumentException}.
*
* @param check the test to perform
* @param checkEveryMillis how often to perform the test
* @param waitForMillis the amount of time after which no more tests will be
* performed
* @throws TimeoutException if the test does not return true in the allotted
* time
* @throws InterruptedException if the method is interrupted while waiting
*/
public static void waitFor(final Supplier<Boolean> check,
final long checkEveryMillis, final long waitForMillis)
throws TimeoutException, InterruptedException {
Objects.requireNonNull(check, ERROR_MISSING_ARGUMENT);
if (waitForMillis < checkEveryMillis) {
throw new IllegalArgumentException(ERROR_INVALID_ARGUMENT);
}
long st = Time.monotonicNow();
boolean result = check.get();
while (!result && (Time.monotonicNow() - st < waitForMillis)) {
Thread.sleep(checkEveryMillis);
result = check.get();
}
if (!result) {
throw new TimeoutException("Timed out waiting for condition. " +
"Thread diagnostics:\n" +
TimedOutTestsListener.buildThreadDiagnosticString());
}
}
/**
* Prints output to one {@link PrintStream} while copying to the other.
* <p>
* Closing the main {@link PrintStream} will NOT close the other.
*/
public static class TeePrintStream extends PrintStream {
private final PrintStream other;
public TeePrintStream(OutputStream main, PrintStream other) {
super(main);
this.other = other;
}
@Override
public void flush() {
super.flush();
other.flush();
}
@Override
public void write(byte[] buf, int off, int len) {
super.write(buf, off, len);
other.write(buf, off, len);
}
}
/**
* Capture output printed to {@link System#err}.
* <p>
* Usage:
* <pre>
* try (SystemErrCapturer capture = new SystemErrCapturer()) {
* ...
* // Call capture.getOutput() to get the output string
* }
* </pre>
*
* TODO: Add lambda support once Java 8 is common.
* <pre>
* SystemErrCapturer.withCapture(capture -> {
* ...
* })
* </pre>
*/
public static class SystemErrCapturer implements AutoCloseable {
final private ByteArrayOutputStream bytes;
final private PrintStream bytesPrintStream;
final private PrintStream oldErr;
public SystemErrCapturer() {
bytes = new ByteArrayOutputStream();
bytesPrintStream = new PrintStream(bytes);
oldErr = System.err;
System.setErr(new TeePrintStream(oldErr, bytesPrintStream));
}
public String getOutput() {
return bytes.toString();
}
@Override
public void close() throws Exception {
IOUtils.closeStream(bytesPrintStream);
System.setErr(oldErr);
}
}
public static class LogCapturer {
private StringWriter sw = new StringWriter();
private WriterAppender appender;
private Logger logger;
public static LogCapturer captureLogs(Log l) {
Logger logger = ((Log4JLogger)l).getLogger();
return new LogCapturer(logger);
}
public static LogCapturer captureLogs(org.slf4j.Logger logger) {
return new LogCapturer(toLog4j(logger));
}
private LogCapturer(Logger logger) {
this.logger = logger;
Appender defaultAppender = Logger.getRootLogger().getAppender("stdout");
if (defaultAppender == null) {
defaultAppender = Logger.getRootLogger().getAppender("console");
}
final Layout layout = (defaultAppender == null) ? new PatternLayout() :
defaultAppender.getLayout();
this.appender = new WriterAppender(layout, sw);
logger.addAppender(this.appender);
}
public String getOutput() {
return sw.toString();
}
public void stopCapturing() {
logger.removeAppender(appender);
}
public void clearOutput() {
sw.getBuffer().setLength(0);
}
}
/**
* Mockito answer helper that triggers one latch as soon as the
* method is called, then waits on another before continuing.
*/
public static class DelayAnswer implements Answer<Object> {
private final org.slf4j.Logger LOG;
private final CountDownLatch fireLatch = new CountDownLatch(1);
private final CountDownLatch waitLatch = new CountDownLatch(1);
private final CountDownLatch resultLatch = new CountDownLatch(1);
private final AtomicInteger fireCounter = new AtomicInteger(0);
private final AtomicInteger resultCounter = new AtomicInteger(0);
// Result fields set after proceed() is called.
private volatile Throwable thrown;
private volatile Object returnValue;
public DelayAnswer(org.slf4j.Logger log) {
this.LOG = log;
}
/**
* Wait until the method is called.
*/
public void waitForCall() throws InterruptedException {
fireLatch.await();
}
/**
* Tell the method to proceed.
* This should only be called after waitForCall()
*/
public void proceed() {
waitLatch.countDown();
}
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
LOG.info("DelayAnswer firing fireLatch");
fireCounter.getAndIncrement();
fireLatch.countDown();
try {
LOG.info("DelayAnswer waiting on waitLatch");
waitLatch.await();
LOG.info("DelayAnswer delay complete");
} catch (InterruptedException ie) {
throw new IOException("Interrupted waiting on latch", ie);
}
return passThrough(invocation);
}
protected Object passThrough(InvocationOnMock invocation) throws Throwable {
try {
Object ret = invocation.callRealMethod();
returnValue = ret;
return ret;
} catch (Throwable t) {
thrown = t;
throw t;
} finally {
resultCounter.incrementAndGet();
resultLatch.countDown();
}
}
/**
* After calling proceed(), this will wait until the call has
* completed and a result has been returned to the caller.
*/
public void waitForResult() throws InterruptedException {
resultLatch.await();
}
/**
* After the call has gone through, return any exception that
* was thrown, or null if no exception was thrown.
*/
public Throwable getThrown() {
return thrown;
}
/**
* After the call has gone through, return the call's return value,
* or null in case it was void or an exception was thrown.
*/
public Object getReturnValue() {
return returnValue;
}
public int getFireCount() {
return fireCounter.get();
}
public int getResultCount() {
return resultCounter.get();
}
}
/**
* An Answer implementation that simply forwards all calls through
* to a delegate.
*
* This is useful as the default Answer for a mock object, to create
* something like a spy on an RPC proxy. For example:
* <code>
* NamenodeProtocol origNNProxy = secondary.getNameNode();
* NamenodeProtocol spyNNProxy = Mockito.mock(NameNodeProtocol.class,
* new DelegateAnswer(origNNProxy);
* doThrow(...).when(spyNNProxy).getBlockLocations(...);
* ...
* </code>
*/
public static class DelegateAnswer implements Answer<Object> {
private final Object delegate;
private final org.slf4j.Logger log;
public DelegateAnswer(Object delegate) {
this(null, delegate);
}
public DelegateAnswer(org.slf4j.Logger log, Object delegate) {
this.log = log;
this.delegate = delegate;
}
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
try {
if (log != null) {
log.info("Call to " + invocation + " on " + delegate,
new Exception("TRACE"));
}
return invocation.getMethod().invoke(
delegate, invocation.getArguments());
} catch (InvocationTargetException ite) {
throw ite.getCause();
}
}
}
/**
* An Answer implementation which sleeps for a random number of milliseconds
* between 0 and a configurable value before delegating to the real
* implementation of the method. This can be useful for drawing out race
* conditions.
*/
public static class SleepAnswer implements Answer<Object> {
private final int minSleepTime;
private final int maxSleepTime;
private static Random r = new Random();
public SleepAnswer(int maxSleepTime) {
this(0, maxSleepTime);
}
public SleepAnswer(int minSleepTime, int maxSleepTime) {
this.minSleepTime = minSleepTime;
this.maxSleepTime = maxSleepTime;
}
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
boolean interrupted = false;
try {
Thread.sleep(r.nextInt(maxSleepTime - minSleepTime) + minSleepTime);
} catch (InterruptedException ie) {
interrupted = true;
}
try {
return invocation.callRealMethod();
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
}
public static void assertDoesNotMatch(String output, String pattern) {
Assert.assertFalse("Expected output to match /" + pattern + "/" +
" but got:\n" + output,
Pattern.compile(pattern).matcher(output).find());
}
public static void assertMatches(String output, String pattern) {
Assert.assertTrue("Expected output to match /" + pattern + "/" +
" but got:\n" + output,
Pattern.compile(pattern).matcher(output).find());
}
public static void assertValueNear(long expected, long actual, long allowedError) {
assertValueWithinRange(expected - allowedError, expected + allowedError, actual);
}
public static void assertValueWithinRange(long expectedMin, long expectedMax,
long actual) {
Assert.assertTrue("Expected " + actual + " to be in range (" + expectedMin + ","
+ expectedMax + ")", expectedMin <= actual && actual <= expectedMax);
}
/**
* Determine if there are any threads whose name matches the regex.
* @param pattern a Pattern object used to match thread names
* @return true if there is any thread that matches the pattern
*/
public static boolean anyThreadMatching(Pattern pattern) {
ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
ThreadInfo[] infos =
threadBean.getThreadInfo(threadBean.getAllThreadIds(), 20);
for (ThreadInfo info : infos) {
if (info == null)
continue;
if (pattern.matcher(info.getThreadName()).matches()) {
return true;
}
}
return false;
}
/**
* Assert that there are no threads running whose name matches the
* given regular expression.
* @param regex the regex to match against
*/
public static void assertNoThreadsMatching(String regex) {
Pattern pattern = Pattern.compile(regex);
if (anyThreadMatching(pattern)) {
Assert.fail("Leaked thread matches " + regex);
}
}
/**
* Periodically check and wait for any threads whose name match the
* given regular expression.
*
* @param regex the regex to match against.
* @param checkEveryMillis time (in milliseconds) between checks.
* @param waitForMillis total time (in milliseconds) to wait before throwing
* a time out exception.
* @throws TimeoutException
* @throws InterruptedException
*/
public static void waitForThreadTermination(String regex,
int checkEveryMillis, final int waitForMillis) throws TimeoutException,
InterruptedException {
final Pattern pattern = Pattern.compile(regex);
waitFor(new Supplier<Boolean>() {
@Override public Boolean get() {
return !anyThreadMatching(pattern);
}
}, checkEveryMillis, waitForMillis);
}
/**
* Skip test if native build profile of Maven is not activated.
* Sub-project using this must set 'runningWithNative' property to true
* in the definition of native profile in pom.xml.
*/
public static void assumeInNativeProfile() {
Assume.assumeTrue(
Boolean.parseBoolean(System.getProperty("runningWithNative", "false")));
}
/**
* Get the diff between two files.
*
* @param a
* @param b
* @return The empty string if there is no diff; the diff, otherwise.
*
* @throws IOException If there is an error reading either file.
*/
public static String getFilesDiff(File a, File b) throws IOException {
StringBuilder bld = new StringBuilder();
try (BufferedReader ra = new BufferedReader(
new InputStreamReader(new FileInputStream(a)));
BufferedReader rb = new BufferedReader(
new InputStreamReader(new FileInputStream(b)))) {
while (true) {
String la = ra.readLine();
String lb = rb.readLine();
if (la == null) {
if (lb != null) {
addPlusses(bld, ra);
}
break;
} else if (lb == null) {
if (la != null) {
addPlusses(bld, rb);
}
break;
}
if (!la.equals(lb)) {
bld.append(" - ").append(la).append("\n");
bld.append(" + ").append(lb).append("\n");
}
}
}
return bld.toString();
}
private static void addPlusses(StringBuilder bld, BufferedReader r)
throws IOException {
String l;
while ((l = r.readLine()) != null) {
bld.append(" + ").append(l).append("\n");
}
}
/**
* Formatted fail, via {@link String#format(String, Object...)}.
* @param format format string
* @param args argument list. If the last argument is a throwable, it
* is used as the inner cause of the exception
* @throws AssertionError with the formatted message
*/
public static void failf(String format, Object... args) {
String message = String.format(Locale.ENGLISH, format, args);
AssertionError error = new AssertionError(message);
int len = args.length;
if (len > 0 && args[len - 1] instanceof Throwable) {
error.initCause((Throwable) args[len - 1]);
}
throw error;
}
/**
* Conditional formatted fail, via {@link String#format(String, Object...)}.
* @param condition condition: if true the method fails
* @param format format string
* @param args argument list. If the last argument is a throwable, it
* is used as the inner cause of the exception
* @throws AssertionError with the formatted message
*/
public static void failif(boolean condition,
String format,
Object... args) {
if (condition) {
failf(format, args);
}
}
/**
* Retreive the max number of parallel test threads when running under maven.
* @return int number of threads
*/
public static int getTestsThreadCount() {
String propString = System.getProperty("testsThreadCount", "1");
int threadCount = 1;
if (propString != null) {
String trimProp = propString.trim();
if (trimProp.endsWith("C")) {
double multiplier = Double.parseDouble(
trimProp.substring(0, trimProp.length()-1));
double calculated = multiplier * ((double) Runtime
.getRuntime()
.availableProcessors());
threadCount = calculated > 0d ? Math.max((int) calculated, 1) : 0;
} else {
threadCount = Integer.parseInt(trimProp);
}
}
return threadCount;
}
/**
* Write the text to a file asynchronously. Logs the operation duration.
* @param fs filesystem
* @param path path
* @return future to the patch created.
*/
private static CompletableFuture<Path> put(FileSystem fs,
Path path, String text) {
return submit(EXECUTOR, () -> {
try (DurationInfo ignore =
new DurationInfo(LOG, false, "Creating %s", path)) {
createFile(fs, path, true, text.getBytes(StandardCharsets.UTF_8));
return path;
}
});
}
/**
* Build a set of files in a directory tree.
* @param fs filesystem
* @param destDir destination
* @param depth file depth
* @param fileCount number of files to create.
* @param dirCount number of dirs to create at each level
* @return the list of files created.
*/
public static List<Path> createFiles(final FileSystem fs,
final Path destDir,
final int depth,
final int fileCount,
final int dirCount) throws IOException {
return createDirsAndFiles(fs, destDir, depth, fileCount, dirCount,
new ArrayList<Path>(fileCount),
new ArrayList<Path>(dirCount));
}
/**
* Build a set of files in a directory tree.
* @param fs filesystem
* @param destDir destination
* @param depth file depth
* @param fileCount number of files to create.
* @param dirCount number of dirs to create at each level
* @param paths [out] list of file paths created
* @param dirs [out] list of directory paths created.
* @return the list of files created.
*/
public static List<Path> createDirsAndFiles(final FileSystem fs,
final Path destDir,
final int depth,
final int fileCount,
final int dirCount,
final List<Path> paths,
final List<Path> dirs) throws IOException {
buildPaths(paths, dirs, destDir, depth, fileCount, dirCount);
List<CompletableFuture<Path>> futures = new ArrayList<>(paths.size()
+ dirs.size());
// create directories. With dir marker retention, that adds more entries
// to cause deletion issues
try (DurationInfo ignore =
new DurationInfo(LOG, "Creating %d directories", dirs.size())) {
for (Path path : dirs) {
futures.add(submit(EXECUTOR, () ->{
fs.mkdirs(path);
return path;
}));
}
waitForCompletion(futures);
}
try (DurationInfo ignore =
new DurationInfo(LOG, "Creating %d files", paths.size())) {
for (Path path : paths) {
futures.add(put(fs, path, path.getName()));
}
waitForCompletion(futures);
return paths;
}
}
/**
* Recursive method to build up lists of files and directories.
* @param filePaths list of file paths to add entries to.
* @param dirPaths list of directory paths to add entries to.
* @param destDir destination directory.
* @param depth depth of directories
* @param fileCount number of files.
* @param dirCount number of directories.
*/
public static void buildPaths(final List<Path> filePaths,
final List<Path> dirPaths, final Path destDir, final int depth,
final int fileCount, final int dirCount) {
if (depth <= 0) {
return;
}
// create the file paths
for (int i = 0; i < fileCount; i++) {
String name = filenameOfIndex(i);
Path p = new Path(destDir, name);
filePaths.add(p);
}
for (int i = 0; i < dirCount; i++) {
String name = String.format("dir-%03d", i);
Path p = new Path(destDir, name);
dirPaths.add(p);
buildPaths(filePaths, dirPaths, p, depth - 1, fileCount, dirCount);
}
}
/**
* Given an index, return a string to use as the filename.
* @param i index
* @return name
*/
public static String filenameOfIndex(final int i) {
return String.format("%s%03d", PREFIX, i);
}
/**
* For submitting work.
*/
private static final BlockingThreadPoolExecutorService EXECUTOR =
BlockingThreadPoolExecutorService.newInstance(
EXECUTOR_THREAD_COUNT,
EXECUTOR_THREAD_COUNT * 2,
30, TimeUnit.SECONDS,
"test-operations");
} | apache-2.0 |
pdxrunner/geode | geode-core/src/main/java/org/apache/geode/cache/query/internal/types/ObjectTypeImpl.java | 2903 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.cache.query.internal.types;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.geode.DataSerializer;
import org.apache.geode.cache.query.types.ObjectType;
import org.apache.geode.internal.DataSerializableFixedID;
import org.apache.geode.internal.InternalDataSerializer;
import org.apache.geode.internal.Version;
/**
* Implementation of ObjectType
*
* @since GemFire 4.0
*/
public class ObjectTypeImpl implements ObjectType, DataSerializableFixedID {
private static final long serialVersionUID = 3327357282163564784L;
private Class clazz;
/**
* Empty constructor to satisfy <code>DataSerializer</code> requirements
*/
public ObjectTypeImpl() {}
/** Creates a new instance of ObjectTypeImpl */
public ObjectTypeImpl(Class clazz) {
this.clazz = clazz;
}
public ObjectTypeImpl(String className) throws ClassNotFoundException {
this.clazz = InternalDataSerializer.getCachedClass(className);
}
public Class resolveClass() {
return this.clazz;
}
public String getSimpleClassName() {
String cn = this.clazz.getName();
int i = cn.lastIndexOf('.');
return i < 0 ? cn : cn.substring(i + 1);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ObjectTypeImpl))
return false;
return this.clazz == ((ObjectTypeImpl) obj).clazz;
}
@Override
public int hashCode() {
return this.clazz.hashCode();
}
@Override
public String toString() {
return this.clazz.getName();
}
public boolean isCollectionType() {
return false;
}
public boolean isMapType() {
return false;
}
public boolean isStructType() {
return false;
}
public int getDSFID() {
return OBJECT_TYPE_IMPL;
}
public void fromData(DataInput in) throws IOException, ClassNotFoundException {
this.clazz = DataSerializer.readClass(in);
}
public void toData(DataOutput out) throws IOException {
DataSerializer.writeClass(this.clazz, out);
}
@Override
public Version[] getSerializationVersions() {
return null;
}
}
| apache-2.0 |
unsw-cse-soc/CoreDB | src/CoreDB-Relational Pluggin/Library/src/coredb/unit/Operation.java | 2041 | /**
*
*/
package coredb.unit;
/**
* @author sean
*
* @deprecated "Please use the SQLAtom class. This class will be removed from version 3.1"
*/
@Deprecated
public class Operation {
/**
* Available operations
* @deprecated "Please use the SQLAtom class. This class will be removed from version 3.1"
*/
@Deprecated
public static String E = " = "; //EQUAL
/**
* Available operations
* @deprecated "Please use the SQLAtom class. This class will be removed from version 3.1"
*/
@Deprecated
public static String NE = " != "; //NOT EQUAL
/**
* Available operations
* @deprecated "Please use the SQLAtom class. This class will be removed from version 3.1"
*/
@Deprecated
public static String NL = " < "; //NUMERICAL LESS
/**
* Available operations
* @deprecated "Please use the SQLAtom class. This class will be removed from version 3.1"
*/
@Deprecated
public static String NLE = " <= "; //NUMERICAL LESS or EQUAL
/**
* Available operations
* @deprecated "Please use the SQLAtom class. This class will be removed from version 3.1"
*/
@Deprecated
public static String NG = " > "; //NUMERICAL GREATER
/**
* Available operations
* @deprecated "Please use the SQLAtom class. This class will be removed from version 3.1"
*/
@Deprecated
public static String NGE = " >= "; //NUMERICAL GREATER OR EQUAL
/**
* Available operations
* @deprecated "Please use the SQLAtom class. This class will be removed from version 3.1"
*/
@Deprecated
public static String IS = " IS "; //IS
/**
* Available operations
* @deprecated "Please use the SQLAtom class. This class will be removed from version 3.1"
*/
@Deprecated
public static String LIKE = " LIKE "; //LIKE
/**
* Available operations
* @deprecated "Please use the SQLAtom class. This class will be removed from version 3.1"
*/
@Deprecated
public static String ISNOT = " IS NOT "; //IS NOT
} | apache-2.0 |