repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
OSEHRA/ISAAC | core/model/src/main/java/sh/isaac/model/semantic/types/DynamicByteArrayImpl.java | 3482 | /*
* 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.
*
* Contributions from 2013-2017 where performed either by US government
* employees, or under US Veterans Health Administration contracts.
*
* US Veterans Health Administration contributions by government employees
* are work of the U.S. Government and are not subject to copyright
* protection in the United States. Portions contributed by government
* employees are USGovWork (17USC §105). Not subject to copyright.
*
* Contribution by contractors to the US Veterans Health Administration
* during this period are contractually contributed under the
* Apache License, Version 2.0.
*
* See: https://www.usa.gov/government-works
*
* Contributions prior to 2013:
*
* Copyright (C) International Health Terminology Standards Development Organisation.
* Licensed under the Apache License, Version 2.0.
*
*/
package sh.isaac.model.semantic.types;
//~--- non-JDK imports --------------------------------------------------------
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import sh.isaac.api.component.semantic.version.dynamic.types.DynamicByteArray;
//~--- classes ----------------------------------------------------------------
/**
* {@link DynamicByteArrayImpl}.
*
* @author <a href="mailto:daniel.armbrust.list@gmail.com">Dan Armbrust</a>
*/
public class DynamicByteArrayImpl
extends DynamicDataImpl
implements DynamicByteArray {
/** The property. */
private ObjectProperty<byte[]> property;
//~--- constructors --------------------------------------------------------
/**
* Instantiates a new dynamic byte array impl.
*
* @param bytes the bytes
*/
public DynamicByteArrayImpl(byte[] bytes) {
super(bytes);
}
/**
* Instantiates a new dynamic byte array impl.
*
* @param data the data
* @param assemblageSequence the assemblage sequence
* @param columnNumber the column number
*/
protected DynamicByteArrayImpl(byte[] data, int assemblageSequence, int columnNumber) {
super(data, assemblageSequence, columnNumber);
}
//~--- get methods ---------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public byte[] getDataByteArray() {
return this.data;
}
/**
* {@inheritDoc}
*/
@Override
public ReadOnlyObjectProperty<byte[]> getDataByteArrayProperty() {
if (this.property == null) {
this.property = new SimpleObjectProperty<>(null, getName(), this.data);
}
return this.property;
}
/**
* {@inheritDoc}
*/
@Override
public Object getDataObject() {
return getDataByteArray();
}
/**
* {@inheritDoc}
*/
@Override
public ReadOnlyObjectProperty<?> getDataObjectProperty() {
return getDataByteArrayProperty();
}
}
| apache-2.0 |
boybeak/WowPaper | app/src/main/java/com/nulldreams/wowpaper/fragment/TagStyleFragment.java | 8280 | package com.nulldreams.wowpaper.fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.nulldreams.adapter.DelegateAdapter;
import com.nulldreams.adapter.DelegateParser;
import com.nulldreams.adapter.impl.LayoutImpl;
import com.nulldreams.base.fragment.AbsPagerFragment;
import com.nulldreams.wowpaper.R;
import com.nulldreams.wowpaper.adapter.delegate.TagStyleDelegate;
import com.nulldreams.wowpaper.adapter.delegate.TitleDelegate;
import com.nulldreams.wowpaper.manager.ApiManager;
import com.nulldreams.wowpaper.modules.Filter;
import com.nulldreams.wowpaper.modules.CategoryResult;
import com.nulldreams.wowpaper.modules.CollectionResult;
import com.nulldreams.wowpaper.modules.GroupResult;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Created by gaoyunfei on 2017/3/19.
*/
public class TagStyleFragment extends AbsPagerFragment implements SwipeRefreshLayout.OnRefreshListener{
private static final String TAG = TagStyleFragment.class.getSimpleName();
public static TagStyleFragment newInstance () {
return new TagStyleFragment();
}
private SwipeRefreshLayout mSrl;
private RecyclerView mRv;
private DelegateAdapter mAdapter;
private ArrayList<Filter> mCategories, mCollections, mGroups;
@Override
public CharSequence getTitle(Context context, Bundle bundle) {
return context.getString(R.string.title_tag_style);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_paper_list, null);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mSrl = (SwipeRefreshLayout)view.findViewById(R.id.paper_list_srl);
mSrl.setColorSchemeResources(R.color.colorAccent);
mSrl.setOnRefreshListener(this);
mRv = (RecyclerView)view.findViewById(R.id.paper_list_rv);
FlexboxLayoutManager layoutManager = new FlexboxLayoutManager();
layoutManager.setFlexDirection(FlexDirection.ROW);
layoutManager.setJustifyContent(JustifyContent.FLEX_START);
mRv.setLayoutManager(layoutManager);
mAdapter = new DelegateAdapter(getContext());
mRv.setAdapter(mAdapter);
if (savedInstanceState != null) {
mCategories = savedInstanceState.getParcelableArrayList("categories");
if (mCategories != null && !mCategories.isEmpty()) {
mAdapter.clear();
mAdapter.add(new TitleDelegate(getString(R.string.title_category)));
mAdapter.addAll(mCategories, new DelegateParser<Filter>() {
@Override
public LayoutImpl parse(DelegateAdapter adapter, Filter data) {
return new TagStyleDelegate(data).setStyle(TagStyleDelegate.STYLE_CATEGORY);
}
});
mAdapter.notifyDataSetChanged();
}
}
Log.v(TAG, "TAG onViewCreated");
if (mAdapter.isEmpty() && getUserVisibleHint() && !mSrl.isRefreshing()) {
Log.v(TAG, "TAG onViewCreated loadData");
mSrl.post(new Runnable() {
@Override
public void run() {
mSrl.setRefreshing(true);
loadData();
}
});
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
if (mCategories != null) {
outState.putParcelableArrayList("categories", mCategories);
}
super.onSaveInstanceState(outState);
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (mSrl.isRefreshing()) {
mSrl.setRefreshing(false);
}
mSrl.setOnRefreshListener(null);
Log.v(TAG, "TAG onDestroyView");
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && mAdapter != null && mAdapter.isEmpty() && !mSrl.isRefreshing()) {
Log.v(TAG, "TAG setUserVisibleHint");
mSrl.post(new Runnable() {
@Override
public void run() {
mSrl.setRefreshing(true);
loadData();
}
});
}
}
private void loadData () {
ApiManager.getInstance(getContext()).getCategories(new Callback<CategoryResult>() {
@Override
public void onResponse(Call<CategoryResult> call, Response<CategoryResult> response) {
if (mSrl.isRefreshing()) {
mSrl.setRefreshing(false);
}
mCategories = response.body().categories;
addDataList(getString(R.string.title_category), mCategories, TagStyleDelegate.STYLE_CATEGORY);
}
@Override
public void onFailure(Call<CategoryResult> call, Throwable t) {
if (mSrl.isRefreshing()) {
mSrl.setRefreshing(false);
}
Toast.makeText(getContext(), R.string.toast_load_data_failed, Toast.LENGTH_SHORT).show();
}
});
ApiManager.getInstance(getContext()).getCollections(new Callback<CollectionResult>() {
@Override
public void onResponse(Call<CollectionResult> call, Response<CollectionResult> response) {
if (mSrl.isRefreshing()) {
mSrl.setRefreshing(false);
}
mCategories = response.body().collections;
addDataList(getString(R.string.title_collection), mCategories, TagStyleDelegate.STYLE_COLLECTION);
}
@Override
public void onFailure(Call<CollectionResult> call, Throwable t) {
if (mSrl.isRefreshing()) {
mSrl.setRefreshing(false);
}
Toast.makeText(getContext(), R.string.toast_load_data_failed, Toast.LENGTH_SHORT).show();
}
});
ApiManager.getInstance(getContext()).getGroups(new Callback<GroupResult>() {
@Override
public void onResponse(Call<GroupResult> call, Response<GroupResult> response) {
if (mSrl.isRefreshing()) {
mSrl.setRefreshing(false);
}
mGroups = response.body().groups;
addDataList(getString(R.string.title_group), mGroups, TagStyleDelegate.STYLE_GROUP);
}
@Override
public void onFailure(Call<GroupResult> call, Throwable t) {
if (mSrl.isRefreshing()) {
mSrl.setRefreshing(false);
}
Toast.makeText(getContext(), R.string.toast_load_data_failed, Toast.LENGTH_SHORT).show();
}
});
}
private synchronized void addDataList (String title, List<Filter> categories, @TagStyleDelegate.Style final String style) {
if (categories == null || categories.isEmpty()) {
return;
}
mAdapter.add(new TitleDelegate(title));
mAdapter.addAll(categories, new DelegateParser<Filter>() {
@Override
public LayoutImpl parse(DelegateAdapter adapter, Filter data) {
return new TagStyleDelegate(data).setStyle(style);
}
});
mAdapter.notifyDataSetChanged();
}
@Override
public void onRefresh() {
mAdapter.clear();
mAdapter.notifyDataSetChanged();
loadData();
}
}
| apache-2.0 |
haoch/kylin | core-job/src/main/java/org/apache/kylin/job/JoinedFlatTable.java | 10795 | /*
* 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.kylin.job;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.kylin.cube.CubeSegment;
import org.apache.kylin.cube.model.CubeDesc;
import org.apache.kylin.cube.model.CubeJoinedFlatTableDesc;
import org.apache.kylin.job.engine.JobEngineConfig;
import org.apache.kylin.metadata.model.DataModelDesc;
import org.apache.kylin.metadata.model.IJoinedFlatTableDesc;
import org.apache.kylin.metadata.model.IntermediateColumnDesc;
import org.apache.kylin.metadata.model.JoinDesc;
import org.apache.kylin.metadata.model.LookupDesc;
import org.apache.kylin.metadata.model.PartitionDesc;
import org.apache.kylin.metadata.model.TblColRef;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* @author George Song (ysong1)
*
*/
public class JoinedFlatTable {
public static String getTableDir(IJoinedFlatTableDesc intermediateTableDesc, String storageDfsDir) {
return storageDfsDir + "/" + intermediateTableDesc.getTableName();
}
public static String generateCreateTableStatement(IJoinedFlatTableDesc intermediateTableDesc, String storageDfsDir) {
StringBuilder ddl = new StringBuilder();
ddl.append("CREATE EXTERNAL TABLE IF NOT EXISTS " + intermediateTableDesc.getTableName() + "\n");
ddl.append("(" + "\n");
for (int i = 0; i < intermediateTableDesc.getColumnList().size(); i++) {
IntermediateColumnDesc col = intermediateTableDesc.getColumnList().get(i);
if (i > 0) {
ddl.append(",");
}
ddl.append(colName(col.getCanonicalName()) + " " + getHiveDataType(col.getDataType()) + "\n");
}
ddl.append(")" + "\n");
ddl.append("ROW FORMAT DELIMITED FIELDS TERMINATED BY '\\177'" + "\n");
ddl.append("STORED AS SEQUENCEFILE" + "\n");
ddl.append("LOCATION '" + getTableDir(intermediateTableDesc, storageDfsDir) + "';").append("\n");
// ddl.append("TBLPROPERTIES ('serialization.null.format'='\\\\N')" +
// ";\n");
return ddl.toString();
}
public static String generateDropTableStatement(IJoinedFlatTableDesc intermediateTableDesc) {
StringBuilder ddl = new StringBuilder();
ddl.append("DROP TABLE IF EXISTS " + intermediateTableDesc.getTableName() + ";").append("\n");
return ddl.toString();
}
public static String generateInsertDataStatement(IJoinedFlatTableDesc intermediateTableDesc, JobEngineConfig engineConfig) throws IOException {
StringBuilder sql = new StringBuilder();
File hadoopPropertiesFile = new File(engineConfig.getHiveConfFilePath());
if (hadoopPropertiesFile.exists()) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
Document doc;
try {
builder = factory.newDocumentBuilder();
doc = builder.parse(hadoopPropertiesFile);
NodeList nl = doc.getElementsByTagName("property");
for (int i = 0; i < nl.getLength(); i++) {
String name = doc.getElementsByTagName("name").item(i).getFirstChild().getNodeValue();
String value = doc.getElementsByTagName("value").item(i).getFirstChild().getNodeValue();
if (name.equals("tmpjars") == false) {
sql.append("SET " + name + "=" + value + ";").append("\n");
}
}
} catch (ParserConfigurationException e) {
throw new IOException(e);
} catch (SAXException e) {
throw new IOException(e);
}
}
sql.append("INSERT OVERWRITE TABLE " + intermediateTableDesc.getTableName() + " " + generateSelectDataStatement(intermediateTableDesc) + ";").append("\n");
return sql.toString();
}
public static String generateSelectDataStatement(IJoinedFlatTableDesc intermediateTableDesc) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT" + "\n");
String tableAlias;
Map<String, String> tableAliasMap = buildTableAliasMap(intermediateTableDesc.getDataModel());
for (int i = 0; i < intermediateTableDesc.getColumnList().size(); i++) {
IntermediateColumnDesc col = intermediateTableDesc.getColumnList().get(i);
if (i > 0) {
sql.append(",");
}
tableAlias = tableAliasMap.get(col.getTableName());
sql.append(tableAlias + "." + col.getColumnName() + "\n");
}
appendJoinStatement(intermediateTableDesc, sql, tableAliasMap);
appendWhereStatement(intermediateTableDesc, sql, tableAliasMap);
return sql.toString();
}
private static Map<String, String> buildTableAliasMap(DataModelDesc dataModelDesc) {
Map<String, String> tableAliasMap = new HashMap<String, String>();
addTableAlias(dataModelDesc.getFactTable(), tableAliasMap);
for (LookupDesc lookupDesc : dataModelDesc.getLookups()) {
JoinDesc join = lookupDesc.getJoin();
if (join != null) {
addTableAlias(lookupDesc.getTable(), tableAliasMap);
}
}
return tableAliasMap;
}
// The table alias used to be "FACT_TABLE" and "LOOKUP_#", but that's too unpredictable
// for those who want to write a filter. (KYLIN-900)
// Also yet don't support joining the same table more than once, since table name is the map key.
private static void addTableAlias(String table, Map<String, String> tableAliasMap) {
String alias;
int cut = table.lastIndexOf('.');
if (cut < 0)
alias = table;
else
alias = table.substring(cut + 1);
tableAliasMap.put(table, alias);
}
private static void appendJoinStatement(IJoinedFlatTableDesc intermediateTableDesc, StringBuilder sql, Map<String, String> tableAliasMap) {
Set<String> dimTableCache = new HashSet<String>();
DataModelDesc dataModelDesc = intermediateTableDesc.getDataModel();
String factTableName = dataModelDesc.getFactTable();
String factTableAlias = tableAliasMap.get(factTableName);
sql.append("FROM " + factTableName + " as " + factTableAlias + " \n");
for (LookupDesc lookupDesc : dataModelDesc.getLookups()) {
JoinDesc join = lookupDesc.getJoin();
if (join != null && join.getType().equals("") == false) {
String joinType = join.getType().toUpperCase();
String dimTableName = lookupDesc.getTable();
if (!dimTableCache.contains(dimTableName)) {
TblColRef[] pk = join.getPrimaryKeyColumns();
TblColRef[] fk = join.getForeignKeyColumns();
if (pk.length != fk.length) {
throw new RuntimeException("Invalid join condition of lookup table:" + lookupDesc);
}
sql.append(joinType + " JOIN " + dimTableName + " as " + tableAliasMap.get(dimTableName) + "\n");
sql.append("ON ");
for (int i = 0; i < pk.length; i++) {
if (i > 0) {
sql.append(" AND ");
}
sql.append(factTableAlias + "." + fk[i].getName() + " = " + tableAliasMap.get(dimTableName) + "." + pk[i].getName());
}
sql.append("\n");
dimTableCache.add(dimTableName);
}
}
}
}
private static void appendWhereStatement(IJoinedFlatTableDesc intermediateTableDesc, StringBuilder sql, Map<String, String> tableAliasMap) {
if (!(intermediateTableDesc instanceof CubeJoinedFlatTableDesc)) {
return;//TODO: for now only cube segments support filter and partition
}
CubeJoinedFlatTableDesc desc = (CubeJoinedFlatTableDesc) intermediateTableDesc;
boolean hasCondition = false;
StringBuilder whereBuilder = new StringBuilder();
whereBuilder.append("WHERE");
CubeDesc cubeDesc = desc.getCubeDesc();
DataModelDesc model = cubeDesc.getModel();
if (model.getFilterCondition() != null && model.getFilterCondition().equals("") == false) {
whereBuilder.append(" (").append(model.getFilterCondition()).append(") ");
hasCondition = true;
}
CubeSegment cubeSegment = desc.getCubeSegment();
if (null != cubeSegment) {
PartitionDesc partDesc = model.getPartitionDesc();
long dateStart = cubeSegment.getDateRangeStart();
long dateEnd = cubeSegment.getDateRangeEnd();
if (!(dateStart == 0 && dateEnd == Long.MAX_VALUE)) {
whereBuilder.append(hasCondition ? " AND (" : " (");
whereBuilder.append(partDesc.getPartitionConditionBuilder().buildDateRangeCondition(partDesc, dateStart, dateEnd, tableAliasMap));
whereBuilder.append(")\n");
hasCondition = true;
}
}
if (hasCondition) {
sql.append(whereBuilder.toString());
}
}
private static String colName(String canonicalColName) {
return canonicalColName.replace(".", "_");
}
private static String getHiveDataType(String javaDataType) {
String hiveDataType = javaDataType.toLowerCase().startsWith("varchar") ? "string" : javaDataType;
hiveDataType = javaDataType.toLowerCase().startsWith("integer") ? "int" : hiveDataType;
return hiveDataType.toLowerCase();
}
}
| apache-2.0 |
muckleproject/muckle | src/test/org/sh/muckle/runtime/js/ReadFileTest.java | 3593 | package test.org.sh.muckle.runtime.js;
/*
* Copyright 2013 The Muckle Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.sh.muckle.runtime.js.IFileResolver;
import org.sh.muckle.runtime.js.ReadFile;
import test.org.sh.TempFileHelper;
public class ReadFileTest extends ScriptTestCase {
Mockery mocker;
IFileResolver res;
TempFileHelper helper;
File testRoot;
public void testReadNoFilePath(){
assertEquals("", runScript("readFile()"));
}
public void testReadNonExistantFile(){
try {
final File f = new File("NOT_HERE");
mocker.checking(new Expectations(){{
one(res).resolveName("NOT_HERE"); will(returnValue(f));
}});
runScript("readFile('NOT_HERE')");
fail();
}
catch(RuntimeException e){}
}
public void testReadEmptyFileDefaultEncoding() throws IOException{
final File f = helper.createFile(testRoot, "test", ".txt");
mocker.checking(new Expectations(){{
one(res).resolveName(f.getName()); will(returnValue(f));
}});
assertEquals("", runScript("readFile('" + f.getName() + "')"));
}
public void testReadFileDefaultEncoding() throws IOException{
final File f = helper.createFile(testRoot, "test", ".txt");
String contents = "some contents";
writeFile(f, contents.getBytes("utf-8"));
mocker.checking(new Expectations(){{
one(res).resolveName(f.getName()); will(returnValue(f));
}});
assertEquals(contents, runScript("readFile('" + f.getName() + "')"));
}
public void testReadFileBadEncoding() throws IOException{
try {
final File f = helper.createFile(testRoot, "test", ".txt");
String contents = "some contents";
writeFile(f, contents.getBytes("utf-8"));
mocker.checking(new Expectations(){{
one(res).resolveName(f.getName()); will(returnValue(f));
}});
runScript("readFile('" + f.getName() + "','BAD_ENCODING')");
fail();
}
catch(RuntimeException e){}
}
public void testReadFileWithEncoding() throws IOException{
final File f = helper.createFile(testRoot, "test", ".txt");
String contents = "some contents";
writeFile(f, contents.getBytes("utf-8"));
mocker.checking(new Expectations(){{
one(res).resolveName(f.getName()); will(returnValue(f));
}});
assertEquals(contents, runScript("readFile('" + f.getName() + "', 'utf-8')"));
}
//-------------------------------------------
void writeFile(File f, byte[] contents) throws IOException {
FileOutputStream fos = new FileOutputStream(f);
fos.write(contents);
fos.close();
}
protected void setUp() throws Exception {
super.setUp();
helper = new TempFileHelper();
testRoot = helper.createDir(this);
mocker = new Mockery();
res = mocker.mock(IFileResolver.class);
addToScope(new ReadFile(res), ReadFile.NAME);
}
protected void tearDown() throws Exception {
helper.cleanUp();
super.tearDown();
}
}
| apache-2.0 |
ctc-g/sinavi-jfw | validation/jfw-validation-core/src/main/java/jp/co/ctc_g/jse/core/validation/constraints/feature/equalssize/EqualsSizeValidatorForCollection.java | 1920 | /*
* Copyright (c) 2013 ITOCHU Techno-Solutions Corporation.
*
* 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 jp.co.ctc_g.jse.core.validation.constraints.feature.equalssize;
import java.util.Collection;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import jp.co.ctc_g.jse.core.validation.constraints.EqualsSize;
/**
* <p>
* このクラスは、{@link EqualsSize}バリデータの検証アルゴリズムを実装しています。
* </p>
* <p>
* {@link EqualsSize}バリデータの検証アルゴリズムは、検証対象のコレクションの要素数が指定されたサイズと同じかどうかを検証します。
* </p>
* @author ITOCHU Techno-Solutions Corporation.
* @see EqualsSize
*/
public class EqualsSizeValidatorForCollection implements ConstraintValidator<EqualsSize, Collection<?>> {
private int size;
/**
* デフォルトコンストラクタです。
*/
public EqualsSizeValidatorForCollection() {}
/**
* {@inheritDoc}
*/
@Override
public void initialize(EqualsSize constraint) {
this.size = constraint.value();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isValid(Collection<?> suspect, ConstraintValidatorContext context) {
if (suspect == null) return true;
return suspect.size() == size;
}
}
| apache-2.0 |
Java-Discord-Bot-System/JDA | src/main/java/net/dv8tion/jda/events/audio/AudioRegionChangeEvent.java | 1167 | /*
* Copyright 2015-2016 Austin Keener & Michael Ritter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.dv8tion.jda.events.audio;
import net.dv8tion.jda.JDA;
import net.dv8tion.jda.entities.Guild;
import net.dv8tion.jda.entities.VoiceChannel;
public class AudioRegionChangeEvent extends GenericAudioEvent
{
protected final VoiceChannel channel;
public AudioRegionChangeEvent(JDA api, VoiceChannel channel)
{
super(api, -1);
this.channel = channel;
}
public Guild getGuild()
{
return channel.getGuild();
}
public VoiceChannel getChannel()
{
return channel;
}
}
| apache-2.0 |
amdiaosi/nutzWx | nutzwx-app/src/main/java/net/wendal/base/annotation/SimpleCURD.java | 430 | package net.wendal.base.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Documented
public @interface SimpleCURD {
String[] cnd() default {};
String[] tableName() default {};
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-backup/src/main/java/com/amazonaws/services/backup/model/Condition.java | 13399 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.backup.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Contains an array of triplets made up of a condition type (such as <code>StringEquals</code>), a key, and a value.
* Used to filter resources using their tags and assign them to a backup plan. Case sensitive.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/backup-2018-11-15/Condition" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class Condition implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* An operation applied to a key-value pair used to assign resources to your backup plan. Condition only supports
* <code>StringEquals</code>. For more flexible assignment options, including <code>StringLike</code> and the
* ability to exclude resources from your backup plan, use <code>Conditions</code> (with an "s" on the end) for your
* <a href="https://docs.aws.amazon.com/aws-backup/latest/devguide/API_BackupSelection.html">
* <code>BackupSelection</code> </a>.
* </p>
*/
private String conditionType;
/**
* <p>
* The key in a key-value pair. For example, in the tag <code>Department: Accounting</code>, <code>Department</code>
* is the key.
* </p>
*/
private String conditionKey;
/**
* <p>
* The value in a key-value pair. For example, in the tag <code>Department: Accounting</code>,
* <code>Accounting</code> is the value.
* </p>
*/
private String conditionValue;
/**
* <p>
* An operation applied to a key-value pair used to assign resources to your backup plan. Condition only supports
* <code>StringEquals</code>. For more flexible assignment options, including <code>StringLike</code> and the
* ability to exclude resources from your backup plan, use <code>Conditions</code> (with an "s" on the end) for your
* <a href="https://docs.aws.amazon.com/aws-backup/latest/devguide/API_BackupSelection.html">
* <code>BackupSelection</code> </a>.
* </p>
*
* @param conditionType
* An operation applied to a key-value pair used to assign resources to your backup plan. Condition only
* supports <code>StringEquals</code>. For more flexible assignment options, including
* <code>StringLike</code> and the ability to exclude resources from your backup plan, use
* <code>Conditions</code> (with an "s" on the end) for your <a
* href="https://docs.aws.amazon.com/aws-backup/latest/devguide/API_BackupSelection.html">
* <code>BackupSelection</code> </a>.
* @see ConditionType
*/
public void setConditionType(String conditionType) {
this.conditionType = conditionType;
}
/**
* <p>
* An operation applied to a key-value pair used to assign resources to your backup plan. Condition only supports
* <code>StringEquals</code>. For more flexible assignment options, including <code>StringLike</code> and the
* ability to exclude resources from your backup plan, use <code>Conditions</code> (with an "s" on the end) for your
* <a href="https://docs.aws.amazon.com/aws-backup/latest/devguide/API_BackupSelection.html">
* <code>BackupSelection</code> </a>.
* </p>
*
* @return An operation applied to a key-value pair used to assign resources to your backup plan. Condition only
* supports <code>StringEquals</code>. For more flexible assignment options, including
* <code>StringLike</code> and the ability to exclude resources from your backup plan, use
* <code>Conditions</code> (with an "s" on the end) for your <a
* href="https://docs.aws.amazon.com/aws-backup/latest/devguide/API_BackupSelection.html">
* <code>BackupSelection</code> </a>.
* @see ConditionType
*/
public String getConditionType() {
return this.conditionType;
}
/**
* <p>
* An operation applied to a key-value pair used to assign resources to your backup plan. Condition only supports
* <code>StringEquals</code>. For more flexible assignment options, including <code>StringLike</code> and the
* ability to exclude resources from your backup plan, use <code>Conditions</code> (with an "s" on the end) for your
* <a href="https://docs.aws.amazon.com/aws-backup/latest/devguide/API_BackupSelection.html">
* <code>BackupSelection</code> </a>.
* </p>
*
* @param conditionType
* An operation applied to a key-value pair used to assign resources to your backup plan. Condition only
* supports <code>StringEquals</code>. For more flexible assignment options, including
* <code>StringLike</code> and the ability to exclude resources from your backup plan, use
* <code>Conditions</code> (with an "s" on the end) for your <a
* href="https://docs.aws.amazon.com/aws-backup/latest/devguide/API_BackupSelection.html">
* <code>BackupSelection</code> </a>.
* @return Returns a reference to this object so that method calls can be chained together.
* @see ConditionType
*/
public Condition withConditionType(String conditionType) {
setConditionType(conditionType);
return this;
}
/**
* <p>
* An operation applied to a key-value pair used to assign resources to your backup plan. Condition only supports
* <code>StringEquals</code>. For more flexible assignment options, including <code>StringLike</code> and the
* ability to exclude resources from your backup plan, use <code>Conditions</code> (with an "s" on the end) for your
* <a href="https://docs.aws.amazon.com/aws-backup/latest/devguide/API_BackupSelection.html">
* <code>BackupSelection</code> </a>.
* </p>
*
* @param conditionType
* An operation applied to a key-value pair used to assign resources to your backup plan. Condition only
* supports <code>StringEquals</code>. For more flexible assignment options, including
* <code>StringLike</code> and the ability to exclude resources from your backup plan, use
* <code>Conditions</code> (with an "s" on the end) for your <a
* href="https://docs.aws.amazon.com/aws-backup/latest/devguide/API_BackupSelection.html">
* <code>BackupSelection</code> </a>.
* @return Returns a reference to this object so that method calls can be chained together.
* @see ConditionType
*/
public Condition withConditionType(ConditionType conditionType) {
this.conditionType = conditionType.toString();
return this;
}
/**
* <p>
* The key in a key-value pair. For example, in the tag <code>Department: Accounting</code>, <code>Department</code>
* is the key.
* </p>
*
* @param conditionKey
* The key in a key-value pair. For example, in the tag <code>Department: Accounting</code>,
* <code>Department</code> is the key.
*/
public void setConditionKey(String conditionKey) {
this.conditionKey = conditionKey;
}
/**
* <p>
* The key in a key-value pair. For example, in the tag <code>Department: Accounting</code>, <code>Department</code>
* is the key.
* </p>
*
* @return The key in a key-value pair. For example, in the tag <code>Department: Accounting</code>,
* <code>Department</code> is the key.
*/
public String getConditionKey() {
return this.conditionKey;
}
/**
* <p>
* The key in a key-value pair. For example, in the tag <code>Department: Accounting</code>, <code>Department</code>
* is the key.
* </p>
*
* @param conditionKey
* The key in a key-value pair. For example, in the tag <code>Department: Accounting</code>,
* <code>Department</code> is the key.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Condition withConditionKey(String conditionKey) {
setConditionKey(conditionKey);
return this;
}
/**
* <p>
* The value in a key-value pair. For example, in the tag <code>Department: Accounting</code>,
* <code>Accounting</code> is the value.
* </p>
*
* @param conditionValue
* The value in a key-value pair. For example, in the tag <code>Department: Accounting</code>,
* <code>Accounting</code> is the value.
*/
public void setConditionValue(String conditionValue) {
this.conditionValue = conditionValue;
}
/**
* <p>
* The value in a key-value pair. For example, in the tag <code>Department: Accounting</code>,
* <code>Accounting</code> is the value.
* </p>
*
* @return The value in a key-value pair. For example, in the tag <code>Department: Accounting</code>,
* <code>Accounting</code> is the value.
*/
public String getConditionValue() {
return this.conditionValue;
}
/**
* <p>
* The value in a key-value pair. For example, in the tag <code>Department: Accounting</code>,
* <code>Accounting</code> is the value.
* </p>
*
* @param conditionValue
* The value in a key-value pair. For example, in the tag <code>Department: Accounting</code>,
* <code>Accounting</code> is the value.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Condition withConditionValue(String conditionValue) {
setConditionValue(conditionValue);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getConditionType() != null)
sb.append("ConditionType: ").append(getConditionType()).append(",");
if (getConditionKey() != null)
sb.append("ConditionKey: ").append(getConditionKey()).append(",");
if (getConditionValue() != null)
sb.append("ConditionValue: ").append(getConditionValue());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof Condition == false)
return false;
Condition other = (Condition) obj;
if (other.getConditionType() == null ^ this.getConditionType() == null)
return false;
if (other.getConditionType() != null && other.getConditionType().equals(this.getConditionType()) == false)
return false;
if (other.getConditionKey() == null ^ this.getConditionKey() == null)
return false;
if (other.getConditionKey() != null && other.getConditionKey().equals(this.getConditionKey()) == false)
return false;
if (other.getConditionValue() == null ^ this.getConditionValue() == null)
return false;
if (other.getConditionValue() != null && other.getConditionValue().equals(this.getConditionValue()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getConditionType() == null) ? 0 : getConditionType().hashCode());
hashCode = prime * hashCode + ((getConditionKey() == null) ? 0 : getConditionKey().hashCode());
hashCode = prime * hashCode + ((getConditionValue() == null) ? 0 : getConditionValue().hashCode());
return hashCode;
}
@Override
public Condition clone() {
try {
return (Condition) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.backup.model.transform.ConditionMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| apache-2.0 |
denisprotopopov/pentaho-kettle | plugins/kettle-xml-plugin/src/org/pentaho/di/trans/steps/getxmldata/GetXMLData.java | 37607 | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2016 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.trans.steps.getxmldata;
import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.GZIPInputStream;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.dom4j.Element;
import org.dom4j.ElementHandler;
import org.dom4j.ElementPath;
import org.dom4j.Namespace;
import org.dom4j.Node;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;
import org.dom4j.tree.AbstractNode;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.util.Utils;
import org.pentaho.di.core.ResultFile;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.fileinput.FileInputList;
import org.pentaho.di.core.row.RowDataUtil;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.row.value.ValueMetaFactory;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStep;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
/**
* Read XML files, parse them and convert them to rows and writes these to one or more output streams.
*
* @author Samatar,Brahim
* @since 20-06-2007
*/
public class GetXMLData extends BaseStep implements StepInterface {
private static Class<?> PKG = GetXMLDataMeta.class; // for i18n purposes, needed by Translator2!!
private GetXMLDataMeta meta;
private GetXMLDataData data;
private Object[] prevRow = null; // A pre-allocated spot for the previous row
public GetXMLData( StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta,
Trans trans ) {
super( stepMeta, stepDataInterface, copyNr, transMeta, trans );
}
protected boolean setDocument( String StringXML, FileObject file, boolean IsInXMLField, boolean readurl )
throws KettleException {
this.prevRow = buildEmptyRow(); // pre-allocate previous row
try {
SAXReader reader = new SAXReader();
data.stopPruning = false;
// Validate XML against specified schema?
if ( meta.isValidating() ) {
reader.setValidation( true );
reader.setFeature( "http://apache.org/xml/features/validation/schema", true );
} else {
// Ignore DTD declarations
reader.setEntityResolver( new IgnoreDTDEntityResolver() );
}
// Ignore comments?
if ( meta.isIgnoreComments() ) {
reader.setIgnoreComments( true );
}
if ( data.prunePath != null ) {
// when pruning is on: reader.read() below will wait until all is processed in the handler
if ( log.isDetailed() ) {
logDetailed( BaseMessages.getString( PKG, "GetXMLData.Log.StreamingMode.Activated" ) );
}
if ( data.PathValue.equals( data.prunePath ) ) {
// Edge case, but if true, there will only ever be one item in the list
data.an = new ArrayList<AbstractNode>( 1 ); // pre-allocate array and sizes
data.an.add( null );
}
reader.addHandler( data.prunePath, new ElementHandler() {
public void onStart( ElementPath path ) {
// do nothing here...
}
public void onEnd( ElementPath path ) {
if ( isStopped() ) {
// when a large file is processed and it should be stopped it is still reading the hole thing
// the only solution I see is to prune / detach the document and this will lead into a
// NPE or other errors depending on the parsing location - this will be treated in the catch part below
// any better idea is welcome
if ( log.isBasic() ) {
logBasic( BaseMessages.getString( PKG, "GetXMLData.Log.StreamingMode.Stopped" ) );
}
data.stopPruning = true;
path.getCurrent().getDocument().detach(); // trick to stop reader
return;
}
// process a ROW element
if ( log.isDebug() ) {
logDebug( BaseMessages.getString( PKG, "GetXMLData.Log.StreamingMode.StartProcessing" ) );
}
Element row = path.getCurrent();
try {
// Pass over the row instead of just the document. If
// if there's only one row, there's no need to
// go back to the whole document.
processStreaming( row );
} catch ( Exception e ) {
// catch the KettleException or others and forward to caller, e.g. when applyXPath() has a problem
throw new RuntimeException( e );
}
// prune the tree
row.detach();
if ( log.isDebug() ) {
logDebug( BaseMessages.getString( PKG, "GetXMLData.Log.StreamingMode.EndProcessing" ) );
}
}
} );
}
if ( IsInXMLField ) {
// read string to parse
data.document = reader.read( new StringReader( StringXML ) );
} else if ( readurl ) {
// read url as source
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod( StringXML );
method.addRequestHeader( "Accept-Encoding", "gzip" );
client.executeMethod( method );
Header contentEncoding = method.getResponseHeader( "Content-Encoding" );
if ( contentEncoding != null ) {
String acceptEncodingValue = contentEncoding.getValue();
if ( acceptEncodingValue.indexOf( "gzip" ) != -1 ) {
GZIPInputStream in = new GZIPInputStream( method.getResponseBodyAsStream() );
data.document = reader.read( in );
}
} else {
data.document = reader.read( method.getResponseBodyAsStream() );
}
} else {
// get encoding. By default UTF-8
String encoding = "UTF-8";
if ( !Utils.isEmpty( meta.getEncoding() ) ) {
encoding = meta.getEncoding();
}
InputStream is = KettleVFS.getInputStream( file );
try {
data.document = reader.read( is, encoding );
} finally {
BaseStep.closeQuietly( is );
}
}
if ( meta.isNamespaceAware() ) {
prepareNSMap( data.document.getRootElement() );
}
} catch ( Exception e ) {
if ( data.stopPruning ) {
// ignore error when pruning
return false;
} else {
throw new KettleException( e );
}
}
return true;
}
/**
* Process chunk of data in streaming mode. Called only by the handler when pruning is true. Not allowed in
* combination with meta.getIsInFields(), but could be redesigned later on.
*
*/
private void processStreaming( Element row ) throws KettleException {
data.document = row.getDocument();
if ( meta.isNamespaceAware() ) {
prepareNSMap( data.document.getRootElement() );
}
if ( log.isDebug() ) {
logDebug( BaseMessages.getString( PKG, "GetXMLData.Log.StreamingMode.ApplyXPath" ) );
}
// If the prune path and the path are the same, then
// we're processing one row at a time through here.
if ( data.PathValue.equals( data.prunePath ) ) {
data.an.set( 0, (AbstractNode) row );
data.nodesize = 1; // it's always just one row.
data.nodenr = 0;
if ( log.isDebug() ) {
logDebug( BaseMessages.getString( PKG, "GetXMLData.Log.StreamingMode.ProcessingRows" ) );
}
Object[] r = getXMLRowPutRowWithErrorhandling();
if ( !data.errorInRowButContinue ) { // do not put out the row but continue
putRowOut( r ); // false when limit is reached, functionality is there but we can not stop reading the hole file
// (slow but works)
}
data.nodesize = 0;
data.nodenr = 0;
return;
} else {
if ( !applyXPath() ) {
throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.UnableApplyXPath" ) );
}
}
// main loop through the data until limit is reached or transformation is stopped
// similar functionality like in BaseStep.runStepThread
if ( log.isDebug() ) {
logDebug( BaseMessages.getString( PKG, "GetXMLData.Log.StreamingMode.ProcessingRows" ) );
}
boolean cont = true;
while ( data.nodenr < data.nodesize && cont && !isStopped() ) {
Object[] r = getXMLRowPutRowWithErrorhandling();
if ( data.errorInRowButContinue ) {
continue; // do not put out the row but continue
}
cont = putRowOut( r ); // false when limit is reached, functionality is there but we can not stop reading the hole
// file (slow but works)
}
if ( log.isDebug() ) {
logDebug( BaseMessages.getString( PKG, "GetXMLData.Log.StreamingMode.FreeMemory" ) );
}
// free allocated memory
data.an.clear();
data.nodesize = data.an.size();
data.nodenr = 0;
}
public void prepareNSMap( Element l ) {
@SuppressWarnings( "unchecked" )
List<Namespace> namespacesList = l.declaredNamespaces();
for ( Namespace ns : namespacesList ) {
if ( ns.getPrefix().trim().length() == 0 ) {
data.NAMESPACE.put( "pre" + data.NSPath.size(), ns.getURI() );
String path = "";
Element element = l;
while ( element != null ) {
if ( element.getNamespacePrefix() != null && element.getNamespacePrefix().length() > 0 ) {
path = GetXMLDataMeta.N0DE_SEPARATOR + element.getNamespacePrefix() + ":" + element.getName() + path;
} else {
path = GetXMLDataMeta.N0DE_SEPARATOR + element.getName() + path;
}
element = element.getParent();
}
data.NSPath.add( path );
} else {
data.NAMESPACE.put( ns.getPrefix(), ns.getURI() );
}
}
@SuppressWarnings( "unchecked" )
List<Element> elementsList = l.elements();
for ( Element e : elementsList ) {
prepareNSMap( e );
}
}
/**
* Build an empty row based on the meta-data.
*
* @return empty row built
*/
private Object[] buildEmptyRow() {
return RowDataUtil.allocateRowData( data.outputRowMeta.size() );
}
private void handleMissingFiles() throws KettleException {
List<FileObject> nonExistantFiles = data.files.getNonExistantFiles();
if ( nonExistantFiles.size() != 0 ) {
String message = FileInputList.getRequiredFilesDescription( nonExistantFiles );
logError( BaseMessages.getString( PKG, "GetXMLData.Log.RequiredFilesTitle" ), BaseMessages.getString( PKG,
"GetXMLData.Log.RequiredFiles", message ) );
throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.RequiredFilesMissing", message ) );
}
List<FileObject> nonAccessibleFiles = data.files.getNonAccessibleFiles();
if ( nonAccessibleFiles.size() != 0 ) {
String message = FileInputList.getRequiredFilesDescription( nonAccessibleFiles );
logError( BaseMessages.getString( PKG, "GetXMLData.Log.RequiredFilesTitle" ), BaseMessages.getString( PKG,
"GetXMLData.Log.RequiredNotAccessibleFiles", message ) );
throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.RequiredNotAccessibleFilesMissing",
message ) );
}
}
private boolean ReadNextString() {
try {
// Grab another row ...
data.readrow = getRow();
if ( data.readrow == null ) {
// finished processing!
if ( log.isDetailed() ) {
logDetailed( BaseMessages.getString( PKG, "GetXMLData.Log.FinishedProcessing" ) );
}
return false;
}
if ( first ) {
first = false;
data.nrReadRow = getInputRowMeta().size();
data.inputRowMeta = getInputRowMeta();
data.outputRowMeta = data.inputRowMeta.clone();
meta.getFields( data.outputRowMeta, getStepname(), null, null, this, repository, metaStore );
// Get total previous fields
data.totalpreviousfields = data.inputRowMeta.size();
// Create convert meta-data objects that will contain Date & Number formatters
data.convertRowMeta = new RowMeta();
for ( ValueMetaInterface valueMeta : data.convertRowMeta.getValueMetaList() ) {
data.convertRowMeta
.addValueMeta( ValueMetaFactory.cloneValueMeta( valueMeta, ValueMetaInterface.TYPE_STRING ) );
}
// For String to <type> conversions, we allocate a conversion meta data row as well...
//
data.convertRowMeta = data.outputRowMeta.cloneToType( ValueMetaInterface.TYPE_STRING );
// Check is XML field is provided
if ( Utils.isEmpty( meta.getXMLField() ) ) {
logError( BaseMessages.getString( PKG, "GetXMLData.Log.NoField" ) );
throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.NoField" ) );
}
// cache the position of the field
if ( data.indexOfXmlField < 0 ) {
data.indexOfXmlField = getInputRowMeta().indexOfValue( meta.getXMLField() );
if ( data.indexOfXmlField < 0 ) {
// The field is unreachable !
logError( BaseMessages.getString( PKG, "GetXMLData.Log.ErrorFindingField", meta.getXMLField() ) );
throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Exception.CouldnotFindField", meta
.getXMLField() ) );
}
}
}
if ( meta.isInFields() ) {
// get XML field value
String Fieldvalue = getInputRowMeta().getString( data.readrow, data.indexOfXmlField );
if ( log.isDetailed() ) {
logDetailed( BaseMessages.getString( PKG, "GetXMLData.Log.XMLStream", meta.getXMLField(), Fieldvalue ) );
}
if ( meta.getIsAFile() ) {
FileObject file = null;
try {
// XML source is a file.
file = KettleVFS.getFileObject( Fieldvalue, getTransMeta() );
if ( meta.isIgnoreEmptyFile() && file.getContent().getSize() == 0 ) {
logBasic( BaseMessages.getString( PKG, "GetXMLData.Error.FileSizeZero", "" + file.getName() ) );
return ReadNextString();
}
// Open the XML document
if ( !setDocument( null, file, false, false ) ) {
throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.UnableCreateDocument" ) );
}
if ( !applyXPath() ) {
throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.UnableApplyXPath" ) );
}
addFileToResultFilesname( file );
if ( log.isDetailed() ) {
logDetailed( BaseMessages.getString( PKG, "GetXMLData.Log.LoopFileOccurences", "" + data.nodesize, file
.getName().getBaseName() ) );
}
} catch ( Exception e ) {
throw new KettleException( e );
} finally {
try {
if ( file != null ) {
file.close();
}
} catch ( Exception e ) {
// Ignore close errors
}
}
} else {
boolean url = false;
boolean xmltring = true;
if ( meta.isReadUrl() ) {
url = true;
xmltring = false;
}
// Open the XML document
if ( !setDocument( Fieldvalue, null, xmltring, url ) ) {
throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.UnableCreateDocument" ) );
}
// Apply XPath and set node list
if ( !applyXPath() ) {
throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.UnableApplyXPath" ) );
}
if ( log.isDetailed() ) {
logDetailed( BaseMessages.getString( PKG, "GetXMLData.Log.LoopFileOccurences", "" + data.nodesize ) );
}
}
}
} catch ( Exception e ) {
logError( BaseMessages.getString( PKG, "GetXMLData.Log.UnexpectedError", e.toString() ) );
stopAll();
logError( Const.getStackTracker( e ) );
setErrors( 1 );
return false;
}
return true;
}
private void addFileToResultFilesname( FileObject file ) throws Exception {
if ( meta.addResultFile() ) {
// Add this to the result file names...
ResultFile resultFile =
new ResultFile( ResultFile.FILE_TYPE_GENERAL, file, getTransMeta().getName(), getStepname() );
resultFile.setComment( BaseMessages.getString( PKG, "GetXMLData.Log.FileAddedResult" ) );
addResultFile( resultFile );
}
}
public String addNSPrefix( String path, String loopPath ) {
if ( data.NSPath.size() > 0 ) {
String fullPath = loopPath;
if ( !path.equals( fullPath ) ) {
for ( String tmp : path.split( GetXMLDataMeta.N0DE_SEPARATOR ) ) {
if ( tmp.equals( ".." ) ) {
fullPath = fullPath.substring( 0, fullPath.lastIndexOf( GetXMLDataMeta.N0DE_SEPARATOR ) );
} else {
fullPath += GetXMLDataMeta.N0DE_SEPARATOR + tmp;
}
}
}
int[] indexs = new int[fullPath.split( GetXMLDataMeta.N0DE_SEPARATOR ).length - 1];
java.util.Arrays.fill( indexs, -1 );
int length = 0;
for ( int i = 0; i < data.NSPath.size(); i++ ) {
if ( data.NSPath.get( i ).length() > length && fullPath.startsWith( data.NSPath.get( i ) ) ) {
java.util.Arrays.fill( indexs, data.NSPath.get( i ).split( GetXMLDataMeta.N0DE_SEPARATOR ).length - 2,
indexs.length, i );
length = data.NSPath.get( i ).length();
}
}
StringBuilder newPath = new StringBuilder();
String[] pathStrs = path.split( GetXMLDataMeta.N0DE_SEPARATOR );
for ( int i = 0; i < pathStrs.length; i++ ) {
String tmp = pathStrs[i];
if ( newPath.length() > 0 ) {
newPath.append( GetXMLDataMeta.N0DE_SEPARATOR );
}
if ( tmp.length() > 0 && !tmp.contains( ":" ) && !tmp.contains( "." ) && !tmp.contains( GetXMLDataMeta.AT ) ) {
int index = indexs[i + indexs.length - pathStrs.length];
if ( index >= 0 ) {
newPath.append( "pre" ).append( index ).append( ":" ).append( tmp );
} else {
newPath.append( tmp );
}
} else {
newPath.append( tmp );
}
}
return newPath.toString();
}
return path;
}
@SuppressWarnings( "unchecked" )
private boolean applyXPath() {
try {
XPath xpath = data.document.createXPath( data.PathValue );
if ( meta.isNamespaceAware() ) {
xpath = data.document.createXPath( addNSPrefix( data.PathValue, data.PathValue ) );
xpath.setNamespaceURIs( data.NAMESPACE );
}
// get nodes list
data.an = xpath.selectNodes( data.document );
data.nodesize = data.an.size();
data.nodenr = 0;
} catch ( Exception e ) {
logError( BaseMessages.getString( PKG, "GetXMLData.Log.ErrorApplyXPath", e.getMessage() ) );
return false;
}
return true;
}
private boolean openNextFile() {
try {
if ( data.filenr >= data.files.nrOfFiles() ) {
// finished processing!
if ( log.isDetailed() ) {
logDetailed( BaseMessages.getString( PKG, "GetXMLData.Log.FinishedProcessing" ) );
}
return false;
}
// get file
data.file = data.files.getFile( data.filenr );
data.filename = KettleVFS.getFilename( data.file );
// Add additional fields?
if ( meta.getShortFileNameField() != null && meta.getShortFileNameField().length() > 0 ) {
data.shortFilename = data.file.getName().getBaseName();
}
if ( meta.getPathField() != null && meta.getPathField().length() > 0 ) {
data.path = KettleVFS.getFilename( data.file.getParent() );
}
if ( meta.isHiddenField() != null && meta.isHiddenField().length() > 0 ) {
data.hidden = data.file.isHidden();
}
if ( meta.getExtensionField() != null && meta.getExtensionField().length() > 0 ) {
data.extension = data.file.getName().getExtension();
}
if ( meta.getLastModificationDateField() != null && meta.getLastModificationDateField().length() > 0 ) {
data.lastModificationDateTime = new Date( data.file.getContent().getLastModifiedTime() );
}
if ( meta.getUriField() != null && meta.getUriField().length() > 0 ) {
data.uriName = data.file.getName().getURI();
}
if ( meta.getRootUriField() != null && meta.getRootUriField().length() > 0 ) {
data.rootUriName = data.file.getName().getRootURI();
}
// Check if file is empty
long fileSize;
try {
fileSize = data.file.getContent().getSize();
} catch ( FileSystemException e ) {
fileSize = -1;
}
if ( meta.getSizeField() != null && meta.getSizeField().length() > 0 ) {
data.size = fileSize;
}
// Move file pointer ahead!
data.filenr++;
if ( meta.isIgnoreEmptyFile() && fileSize == 0 ) {
// log only basic as a warning (was before logError)
logBasic( BaseMessages.getString( PKG, "GetXMLData.Error.FileSizeZero", "" + data.file.getName() ) );
openNextFile();
} else {
if ( log.isDetailed() ) {
logDetailed( BaseMessages.getString( PKG, "GetXMLData.Log.OpeningFile", data.file.toString() ) );
}
// Open the XML document
if ( !setDocument( null, data.file, false, false ) ) {
if ( data.stopPruning ) {
return false; // ignore error when stopped while pruning
}
throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.UnableCreateDocument" ) );
}
// Apply XPath and set node list
if ( data.prunePath == null ) { // this was already done in processStreaming()
if ( !applyXPath() ) {
throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.UnableApplyXPath" ) );
}
}
addFileToResultFilesname( data.file );
if ( log.isDetailed() ) {
logDetailed( BaseMessages.getString( PKG, "GetXMLData.Log.FileOpened", data.file.toString() ) );
logDetailed( BaseMessages.getString( PKG, "GetXMLData.Log.LoopFileOccurences", "" + data.nodesize, data.file
.getName().getBaseName() ) );
}
}
} catch ( Exception e ) {
logError( BaseMessages.getString( PKG, "GetXMLData.Log.UnableToOpenFile", "" + data.filenr, data.file.toString(),
e.toString() ) );
stopAll();
setErrors( 1 );
return false;
}
return true;
}
public boolean processRow( StepMetaInterface smi, StepDataInterface sdi ) throws KettleException {
if ( first && !meta.isInFields() ) {
first = false;
data.files = meta.getFiles( this );
if ( !meta.isdoNotFailIfNoFile() && data.files.nrOfFiles() == 0 ) {
throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.NoFiles" ) );
}
handleMissingFiles();
// Create the output row meta-data
data.outputRowMeta = new RowMeta();
meta.getFields( data.outputRowMeta, getStepname(), null, null, this, repository, metaStore );
// Create convert meta-data objects that will contain Date & Number formatters
// For String to <type> conversions, we allocate a conversion meta data row as well...
//
data.convertRowMeta = data.outputRowMeta.cloneToType( ValueMetaInterface.TYPE_STRING );
}
// Grab a row
Object[] r = getXMLRow();
if ( data.errorInRowButContinue ) {
return true; // continue without putting the row out
}
if ( r == null ) {
setOutputDone(); // signal end to receiver(s)
return false; // end of data or error.
}
return putRowOut( r );
}
private boolean putRowOut( Object[] r ) throws KettleException {
if ( log.isRowLevel() ) {
logRowlevel( BaseMessages.getString( PKG, "GetXMLData.Log.ReadRow", data.outputRowMeta.getString( r ) ) );
}
incrementLinesInput();
data.rownr++;
putRow( data.outputRowMeta, r ); // copy row to output rowset(s);
if ( meta.getRowLimit() > 0 && data.rownr > meta.getRowLimit() ) {
// limit has been reached: stop now.
setOutputDone();
return false;
}
return true;
}
private Object[] getXMLRow() throws KettleException {
if ( !meta.isInFields() ) {
while ( ( data.nodenr >= data.nodesize || data.file == null ) ) {
if ( !openNextFile() ) {
data.errorInRowButContinue = false; // stop in all cases
return null;
}
}
}
return getXMLRowPutRowWithErrorhandling();
}
private Object[] getXMLRowPutRowWithErrorhandling() throws KettleException {
// Build an empty row based on the meta-data
Object[] r;
data.errorInRowButContinue = false;
try {
if ( meta.isInFields() ) {
while ( ( data.nodenr >= data.nodesize || data.readrow == null ) ) {
if ( !ReadNextString() ) {
return null;
}
if ( data.readrow == null ) {
return null;
}
}
}
r = processPutRow( data.an.get( data.nodenr ) );
} catch ( Exception e ) {
throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Error.UnableReadFile" ), e );
}
return r;
}
private Object[] processPutRow( AbstractNode node ) throws KettleException {
// Create new row...
Object[] outputRowData = buildEmptyRow();
// Create new row or clone
if ( meta.isInFields() ) {
System.arraycopy( data.readrow, 0, outputRowData, 0, data.nrReadRow );
}
try {
data.nodenr++;
// Read fields...
for ( int i = 0; i < data.nrInputFields; i++ ) {
// Get field
GetXMLDataField xmlDataField = meta.getInputFields()[i];
// Get the Path to look for
String XPathValue = xmlDataField.getXPath();
XPathValue = environmentSubstitute( XPathValue );
if ( xmlDataField.getElementType() == GetXMLDataField.ELEMENT_TYPE_ATTRIBUT ) {
// We have an attribute
// do we need to add leading @?
// Only put @ to the last element in path, not in front at all
int last = XPathValue.lastIndexOf( GetXMLDataMeta.N0DE_SEPARATOR );
if ( last > -1 ) {
last++;
String attribut = XPathValue.substring( last, XPathValue.length() );
if ( !attribut.startsWith( GetXMLDataMeta.AT ) ) {
XPathValue = XPathValue.substring( 0, last ) + GetXMLDataMeta.AT + attribut;
}
} else {
if ( !XPathValue.startsWith( GetXMLDataMeta.AT ) ) {
XPathValue = GetXMLDataMeta.AT + XPathValue;
}
}
}
if ( meta.isuseToken() ) {
// See if user use Token inside path field
// The syntax is : @_Fieldname-
// PDI will search for Fieldname value and replace it
// Fieldname must be defined before the current node
XPathValue = substituteToken( XPathValue, outputRowData );
if ( isDetailed() ) {
logDetailed( XPathValue );
}
}
// Get node value
String nodevalue;
// Handle namespaces
if ( meta.isNamespaceAware() ) {
XPath xpathField = node.createXPath( addNSPrefix( XPathValue, data.PathValue ) );
xpathField.setNamespaceURIs( data.NAMESPACE );
if ( xmlDataField.getResultType() == GetXMLDataField.RESULT_TYPE_VALUE_OF ) {
nodevalue = xpathField.valueOf( node );
} else {
// nodevalue=xpathField.selectSingleNode(node).asXML();
Node n = xpathField.selectSingleNode( node );
if ( n != null ) {
nodevalue = n.asXML();
} else {
nodevalue = "";
}
}
} else {
if ( xmlDataField.getResultType() == GetXMLDataField.RESULT_TYPE_VALUE_OF ) {
nodevalue = node.valueOf( XPathValue );
} else {
// nodevalue=node.selectSingleNode(XPathValue).asXML();
Node n = node.selectSingleNode( XPathValue );
if ( n != null ) {
nodevalue = n.asXML();
} else {
nodevalue = "";
}
}
}
// Do trimming
switch ( xmlDataField.getTrimType() ) {
case GetXMLDataField.TYPE_TRIM_LEFT:
nodevalue = Const.ltrim( nodevalue );
break;
case GetXMLDataField.TYPE_TRIM_RIGHT:
nodevalue = Const.rtrim( nodevalue );
break;
case GetXMLDataField.TYPE_TRIM_BOTH:
nodevalue = Const.trim( nodevalue );
break;
default:
break;
}
// Do conversions
//
ValueMetaInterface targetValueMeta = data.outputRowMeta.getValueMeta( data.totalpreviousfields + i );
ValueMetaInterface sourceValueMeta = data.convertRowMeta.getValueMeta( data.totalpreviousfields + i );
outputRowData[data.totalpreviousfields + i] = targetValueMeta.convertData( sourceValueMeta, nodevalue );
// Do we need to repeat this field if it is null?
if ( meta.getInputFields()[i].isRepeated() ) {
if ( data.previousRow != null && Utils.isEmpty( nodevalue ) ) {
outputRowData[data.totalpreviousfields + i] = data.previousRow[data.totalpreviousfields + i];
}
}
} // End of loop over fields...
int rowIndex = data.totalpreviousfields + data.nrInputFields;
// See if we need to add the filename to the row...
if ( meta.includeFilename() && !Utils.isEmpty( meta.getFilenameField() ) ) {
outputRowData[rowIndex++] = data.filename;
}
// See if we need to add the row number to the row...
if ( meta.includeRowNumber() && !Utils.isEmpty( meta.getRowNumberField() ) ) {
outputRowData[rowIndex++] = data.rownr;
}
// Possibly add short filename...
if ( meta.getShortFileNameField() != null && meta.getShortFileNameField().length() > 0 ) {
outputRowData[rowIndex++] = data.shortFilename;
}
// Add Extension
if ( meta.getExtensionField() != null && meta.getExtensionField().length() > 0 ) {
outputRowData[rowIndex++] = data.extension;
}
// add path
if ( meta.getPathField() != null && meta.getPathField().length() > 0 ) {
outputRowData[rowIndex++] = data.path;
}
// Add Size
if ( meta.getSizeField() != null && meta.getSizeField().length() > 0 ) {
outputRowData[rowIndex++] = data.size;
}
// add Hidden
if ( meta.isHiddenField() != null && meta.isHiddenField().length() > 0 ) {
outputRowData[rowIndex++] = Boolean.valueOf( data.path );
}
// Add modification date
if ( meta.getLastModificationDateField() != null && meta.getLastModificationDateField().length() > 0 ) {
outputRowData[rowIndex++] = data.lastModificationDateTime;
}
// Add Uri
if ( meta.getUriField() != null && meta.getUriField().length() > 0 ) {
outputRowData[rowIndex++] = data.uriName;
}
// Add RootUri
if ( meta.getRootUriField() != null && meta.getRootUriField().length() > 0 ) {
outputRowData[rowIndex] = data.rootUriName;
}
RowMetaInterface irow = getInputRowMeta();
if ( irow == null ) {
data.previousRow = outputRowData;
} else {
// clone to previously allocated array to make sure next step doesn't
// change it in between...
System.arraycopy( outputRowData, 0, this.prevRow, 0, outputRowData.length );
// Pick up everything else that needs a real deep clone
data.previousRow = irow.cloneRow( outputRowData, this.prevRow );
}
} catch ( Exception e ) {
if ( getStepMeta().isDoingErrorHandling() ) {
// Simply add this row to the error row
putError( data.outputRowMeta, outputRowData, 1, e.toString(), null, "GetXMLData001" );
data.errorInRowButContinue = true;
return null;
} else {
logError( e.toString() );
throw new KettleException( e.toString() );
}
}
return outputRowData;
}
public String substituteToken( String aString, Object[] outputRowData ) {
if ( aString == null ) {
return null;
}
StringBuilder buffer = new StringBuilder();
String rest = aString;
// search for closing string
int i = rest.indexOf( data.tokenStart );
while ( i > -1 ) {
int j = rest.indexOf( data.tokenEnd, i + data.tokenStart.length() );
// search for closing string
if ( j > -1 ) {
String varName = rest.substring( i + data.tokenStart.length(), j );
Object Value = varName;
for ( int k = 0; k < data.nrInputFields; k++ ) {
GetXMLDataField Tmp_xmlInputField = meta.getInputFields()[k];
if ( Tmp_xmlInputField.getName().equalsIgnoreCase( varName ) ) {
Value = "'" + outputRowData[data.totalpreviousfields + k] + "'";
}
}
buffer.append( rest.substring( 0, i ) );
buffer.append( Value );
rest = rest.substring( j + data.tokenEnd.length() );
} else {
// no closing tag found; end the search
buffer.append( rest );
rest = "";
}
// keep searching
i = rest.indexOf( data.tokenEnd );
}
buffer.append( rest );
return buffer.toString();
}
public boolean init( StepMetaInterface smi, StepDataInterface sdi ) {
meta = (GetXMLDataMeta) smi;
data = (GetXMLDataData) sdi;
if ( super.init( smi, sdi ) ) {
data.rownr = 1L;
data.nrInputFields = meta.getInputFields().length;
data.PathValue = environmentSubstitute( meta.getLoopXPath() );
if ( Utils.isEmpty( data.PathValue ) ) {
logError( BaseMessages.getString( PKG, "GetXMLData.Error.EmptyPath" ) );
return false;
}
if ( !data.PathValue.substring( 0, 1 ).equals( GetXMLDataMeta.N0DE_SEPARATOR ) ) {
data.PathValue = GetXMLDataMeta.N0DE_SEPARATOR + data.PathValue;
}
if ( log.isDetailed() ) {
logDetailed( BaseMessages.getString( PKG, "GetXMLData.Log.LoopXPath", data.PathValue ) );
}
data.prunePath = environmentSubstitute( meta.getPrunePath() );
if ( data.prunePath != null ) {
if ( Utils.isEmpty( data.prunePath.trim() ) ) {
data.prunePath = null;
} else {
// ensure a leading slash
if ( !data.prunePath.startsWith( GetXMLDataMeta.N0DE_SEPARATOR ) ) {
data.prunePath = GetXMLDataMeta.N0DE_SEPARATOR + data.prunePath;
}
// check if other conditions apply that do not allow pruning
if ( meta.isInFields() ) {
data.prunePath = null; // not possible by design, could be changed later on
}
}
}
return true;
}
return false;
}
public void dispose( StepMetaInterface smi, StepDataInterface sdi ) {
meta = (GetXMLDataMeta) smi;
data = (GetXMLDataData) sdi;
if ( data.file != null ) {
try {
data.file.close();
} catch ( Exception e ) {
// Ignore close errors
}
}
if ( data.an != null ) {
data.an.clear();
data.an = null;
}
if ( data.NAMESPACE != null ) {
data.NAMESPACE.clear();
data.NAMESPACE = null;
}
if ( data.NSPath != null ) {
data.NSPath.clear();
data.NSPath = null;
}
if ( data.readrow != null ) {
data.readrow = null;
}
if ( data.document != null ) {
data.document = null;
}
if ( data.fr != null ) {
BaseStep.closeQuietly( data.fr );
}
if ( data.is != null ) {
BaseStep.closeQuietly( data.is );
}
if ( data.files != null ) {
data.files = null;
}
super.dispose( smi, sdi );
}
}
| apache-2.0 |
JayanthyChengan/dataverse | src/test/java/edu/harvard/iq/dataverse/metrics/MetricsUtilTest.java | 7167 | package edu.harvard.iq.dataverse.metrics;
import edu.harvard.iq.dataverse.util.json.JsonUtil;
import java.util.ArrayList;
import java.util.List;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class MetricsUtilTest {
private static final long COUNT = 42l;
@Test
public void testCountToJson() {
// This constructor is just here for code coverage. :)
MetricsUtil metricsUtil = new MetricsUtil();
JsonObject jsonObject = MetricsUtil.countToJson(COUNT).build();
System.out.println(JsonUtil.prettyPrint(jsonObject));
assertEquals(COUNT, jsonObject.getJsonNumber("count").longValue());
}
@Test
public void testDataversesByCategoryToJson() {
List<Object[]> list = new ArrayList<>();
Object[] obj00 = {"RESEARCH_PROJECTS", 791l};
Object[] obj01 = {"RESEARCHERS", 745l};
Object[] obj02 = {"UNCATEGORIZED", 565l};
Object[] obj03 = {"ORGANIZATIONS_INSTITUTIONS", 250l};
Object[] obj04 = {"JOURNALS", 106l};
Object[] obj05 = {"RESEARCH_GROUP", 106l};
Object[] obj06 = {"TEACHING_COURSES", 20l};
Object[] obj07 = {"LABORATORY", 17l};
Object[] obj08 = {"DEPARTMENT", 7l};
list.add(obj00);
list.add(obj01);
list.add(obj02);
list.add(obj03);
list.add(obj04);
list.add(obj05);
list.add(obj06);
list.add(obj07);
list.add(obj08);
JsonArrayBuilder jab = MetricsUtil.dataversesByCategoryToJson(list);
JsonArray jsonArray = jab.build();
System.out.println(JsonUtil.prettyPrint(jsonArray));
JsonObject jsonObject = jsonArray.getJsonObject(8);
assertEquals("Department", jsonObject.getString("category"));
assertEquals(7, jsonObject.getInt("count"));
}
@Test
public void testDatasetsBySubjectToJson() {
List<Object[]> list = new ArrayList<>();
Object[] obj00 = {"Social Sciences", 24955l};
Object[] obj01 = {"Medicine, Health and Life Sciences", 2262l};
Object[] obj02 = {"Earth and Environmental Sciences", 1631l};
Object[] obj03 = {"Agricultural Sciences", 1187l};
Object[] obj04 = {"Other", 980l};
Object[] obj05 = {"Computer and Information Science", 888l};
Object[] obj06 = {"Arts and Humanities", 832l};
Object[] obj07 = {"Astronomy and Astrophysics", 353l};
Object[] obj08 = {"Business and Management", 346l};
Object[] obj09 = {"Law", 220l};
Object[] obj10 = {"Engineering", 203l};
Object[] obj11 = {"Mathematical Sciences", 123l};
Object[] obj12 = {"Chemistry", 116l};
Object[] obj13 = {"Physics", 98l};
list.add(obj00);
list.add(obj01);
list.add(obj02);
list.add(obj03);
list.add(obj04);
list.add(obj05);
list.add(obj06);
list.add(obj07);
list.add(obj08);
list.add(obj09);
list.add(obj10);
list.add(obj11);
list.add(obj12);
list.add(obj13);
JsonArrayBuilder jab = MetricsUtil.datasetsBySubjectToJson(list);
JsonArray jsonArray = jab.build();
System.out.println(JsonUtil.prettyPrint(jsonArray));
JsonObject jsonObject = jsonArray.getJsonObject(13);
assertEquals("Physics", jsonObject.getString("subject"));
assertEquals(98, jsonObject.getInt("count"));
}
@Test
public void testDataversesBySubjectToJson() {
List<Object[]> list = new ArrayList<>();
Object[] obj00 = {"Social Sciences", 24955l};
Object[] obj01 = {"Medicine, Health and Life Sciences", 2262l};
Object[] obj02 = {"Earth and Environmental Sciences", 1631l};
Object[] obj03 = {"Agricultural Sciences", 1187l};
Object[] obj04 = {"Other", 980l};
Object[] obj05 = {"Computer and Information Science", 888l};
Object[] obj06 = {"Arts and Humanities", 832l};
Object[] obj07 = {"Astronomy and Astrophysics", 353l};
Object[] obj08 = {"Business and Management", 346l};
Object[] obj09 = {"Law", 220l};
Object[] obj10 = {"Engineering", 203l};
Object[] obj11 = {"Mathematical Sciences", 123l};
Object[] obj12 = {"Chemistry", 116l};
Object[] obj13 = {"Physics", 98l};
list.add(obj00);
list.add(obj01);
list.add(obj02);
list.add(obj03);
list.add(obj04);
list.add(obj05);
list.add(obj06);
list.add(obj07);
list.add(obj08);
list.add(obj09);
list.add(obj10);
list.add(obj11);
list.add(obj12);
list.add(obj13);
JsonArrayBuilder jab = MetricsUtil.dataversesBySubjectToJson(list);
JsonArray jsonArray = jab.build();
System.out.println(JsonUtil.prettyPrint(jsonArray));
JsonObject jsonObject = jsonArray.getJsonObject(13);
assertEquals("Physics", jsonObject.getString("subject"));
assertEquals(98, jsonObject.getInt("count"));
}
@Test
public void testSanitizeHappyPath() throws Exception {
assertEquals("2018-04", MetricsUtil.sanitizeYearMonthUserInput("2018-04"));
}
@Test(expected = Exception.class)
public void testSanitizeJunk() throws Exception {
MetricsUtil.sanitizeYearMonthUserInput("junk");
}
@Test(expected = Exception.class)
public void testSanitizeFullIso() throws Exception {
MetricsUtil.sanitizeYearMonthUserInput("2018-01-01");
}
//Create JsonArray, turn into string and back into array to confirm data integrity
@Test
public void testStringToJsonArrayBuilder() {
System.out.println("testStringToJsonArrayBuilder");
List<Object[]> list = new ArrayList<>();
Object[] obj00 = {"Social Sciences", 24955l};
list.add(obj00);
JsonArray jsonArrayBefore = MetricsUtil.datasetsBySubjectToJson(list).build();
System.out.println(JsonUtil.prettyPrint(jsonArrayBefore));
JsonArray jsonArrayAfter = MetricsUtil.stringToJsonArrayBuilder(jsonArrayBefore.toString()).build();
System.out.println(JsonUtil.prettyPrint(jsonArrayAfter));
assertEquals(
jsonArrayBefore.getJsonObject(0).getString("subject"),
jsonArrayAfter.getJsonObject(0).getString("subject")
);
}
//Create JsonObject, turn into string and back into array to confirm data integrity
@Test
public void testStringToJsonObjectBuilder() {
System.out.println("testStringToJsonObjectBuilder");
JsonObject jsonObjBefore = Json.createObjectBuilder().add("Test", "result").build();
System.out.println(JsonUtil.prettyPrint(jsonObjBefore));
JsonObject jsonObjAfter = MetricsUtil.stringToJsonObjectBuilder(jsonObjBefore.toString()).build();
System.out.println(JsonUtil.prettyPrint(jsonObjAfter));
assertEquals(
jsonObjBefore.getString("Test"),
jsonObjAfter.getString("Test")
);
}
}
| apache-2.0 |
TheOverLordKotan/Build-Patterns | Abstract-Factory/src/main/java/model/concreteBusiness/DramaticEbook.java | 449 | package model.concreteBusiness;
import model.factories.Ebook;
public class DramaticEbook extends Ebook {
public DramaticEbook(String name, int pagesNumbers, Long value, Long sizeArchive) {
super(name, pagesNumbers, value, sizeArchive);
}
@Override
public void seeCharacteristics() {
System.out.println("Ebook Digital Dramatic "+name+"with" + pagesNumbers+"With price:" +value +"and Size:" +sizeArchive);
}
}
| apache-2.0 |
masonmei/apm-agent | rpc/src/main/java/com/baidu/oped/apm/rpc/codec/PacketDecoder.java | 7517 | /*
* Copyright 2014 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.baidu.oped.apm.rpc.codec;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baidu.oped.apm.rpc.client.WriteFailFutureListener;
import com.baidu.oped.apm.rpc.packet.ClientClosePacket;
import com.baidu.oped.apm.rpc.packet.ControlHandshakePacket;
import com.baidu.oped.apm.rpc.packet.ControlHandshakeResponsePacket;
import com.baidu.oped.apm.rpc.packet.PacketType;
import com.baidu.oped.apm.rpc.packet.PingPacket;
import com.baidu.oped.apm.rpc.packet.PongPacket;
import com.baidu.oped.apm.rpc.packet.RequestPacket;
import com.baidu.oped.apm.rpc.packet.ResponsePacket;
import com.baidu.oped.apm.rpc.packet.SendPacket;
import com.baidu.oped.apm.rpc.packet.ServerClosePacket;
import com.baidu.oped.apm.rpc.packet.stream.StreamClosePacket;
import com.baidu.oped.apm.rpc.packet.stream.StreamCreateFailPacket;
import com.baidu.oped.apm.rpc.packet.stream.StreamCreatePacket;
import com.baidu.oped.apm.rpc.packet.stream.StreamCreateSuccessPacket;
import com.baidu.oped.apm.rpc.packet.stream.StreamPingPacket;
import com.baidu.oped.apm.rpc.packet.stream.StreamPongPacket;
import com.baidu.oped.apm.rpc.packet.stream.StreamResponsePacket;
/**
* @author emeroad
* @author koo.taejin
*/
public class PacketDecoder extends FrameDecoder {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final WriteFailFutureListener pongWriteFutureListener = new WriteFailFutureListener(logger, "pong write fail.", "pong write success.");
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {
if (buffer.readableBytes() < 2) {
return null;
}
buffer.markReaderIndex();
final short packetType = buffer.readShort();
switch (packetType) {
case PacketType.APPLICATION_SEND:
return readSend(packetType, buffer);
case PacketType.APPLICATION_REQUEST:
return readRequest(packetType, buffer);
case PacketType.APPLICATION_RESPONSE:
return readResponse(packetType, buffer);
case PacketType.APPLICATION_STREAM_CREATE:
return readStreamCreate(packetType, buffer);
case PacketType.APPLICATION_STREAM_CLOSE:
return readStreamClose(packetType, buffer);
case PacketType.APPLICATION_STREAM_CREATE_SUCCESS:
return readStreamCreateSuccess(packetType, buffer);
case PacketType.APPLICATION_STREAM_CREATE_FAIL:
return readStreamCreateFail(packetType, buffer);
case PacketType.APPLICATION_STREAM_RESPONSE:
return readStreamData(packetType, buffer);
case PacketType.APPLICATION_STREAM_PING:
return readStreamPing(packetType, buffer);
case PacketType.APPLICATION_STREAM_PONG:
return readStreamPong(packetType, buffer);
case PacketType.CONTROL_CLIENT_CLOSE:
return readControlClientClose(packetType, buffer);
case PacketType.CONTROL_SERVER_CLOSE:
return readControlServerClose(packetType, buffer);
case PacketType.CONTROL_PING:
readPing(packetType, buffer);
sendPong(channel);
// just drop ping
return null;
case PacketType.CONTROL_PONG:
logger.debug("receive pong. {}", channel);
readPong(packetType, buffer);
// just also drop pong.
return null;
case PacketType.CONTROL_HANDSHAKE:
return readEnableWorker(packetType, buffer);
case PacketType.CONTROL_HANDSHAKE_RESPONSE:
return readEnableWorkerConfirm(packetType, buffer);
}
logger.error("invalid packetType received. packetType:{}, channel:{}", packetType, channel);
channel.close();
return null;
}
private void sendPong(Channel channel) {
// a "pong" responds to a "ping" automatically.
logger.debug("received ping. sending pong. {}", channel);
ChannelFuture write = channel.write(PongPacket.PONG_PACKET);
write.addListener(pongWriteFutureListener);
}
private Object readControlClientClose(short packetType, ChannelBuffer buffer) {
return ClientClosePacket.readBuffer(packetType, buffer);
}
private Object readControlServerClose(short packetType, ChannelBuffer buffer) {
return ServerClosePacket.readBuffer(packetType, buffer);
}
private Object readPong(short packetType, ChannelBuffer buffer) {
return PongPacket.readBuffer(packetType, buffer);
}
private Object readPing(short packetType, ChannelBuffer buffer) {
return PingPacket.readBuffer(packetType, buffer);
}
private Object readSend(short packetType, ChannelBuffer buffer) {
return SendPacket.readBuffer(packetType, buffer);
}
private Object readRequest(short packetType, ChannelBuffer buffer) {
return RequestPacket.readBuffer(packetType, buffer);
}
private Object readResponse(short packetType, ChannelBuffer buffer) {
return ResponsePacket.readBuffer(packetType, buffer);
}
private Object readStreamCreate(short packetType, ChannelBuffer buffer) {
return StreamCreatePacket.readBuffer(packetType, buffer);
}
private Object readStreamCreateSuccess(short packetType, ChannelBuffer buffer) {
return StreamCreateSuccessPacket.readBuffer(packetType, buffer);
}
private Object readStreamCreateFail(short packetType, ChannelBuffer buffer) {
return StreamCreateFailPacket.readBuffer(packetType, buffer);
}
private Object readStreamData(short packetType, ChannelBuffer buffer) {
return StreamResponsePacket.readBuffer(packetType, buffer);
}
private Object readStreamPong(short packetType, ChannelBuffer buffer) {
return StreamPongPacket.readBuffer(packetType, buffer);
}
private Object readStreamPing(short packetType, ChannelBuffer buffer) {
return StreamPingPacket.readBuffer(packetType, buffer);
}
private Object readStreamClose(short packetType, ChannelBuffer buffer) {
return StreamClosePacket.readBuffer(packetType, buffer);
}
private Object readEnableWorker(short packetType, ChannelBuffer buffer) {
return ControlHandshakePacket.readBuffer(packetType, buffer);
}
private Object readEnableWorkerConfirm(short packetType, ChannelBuffer buffer) {
return ControlHandshakeResponsePacket.readBuffer(packetType, buffer);
}
}
| apache-2.0 |
Landoop/landoop-avro-generator | src/main/java/com.landoop.avrogenerator/SimpleTextAvroProducer.java | 3272 | package com.landoop.avrogenerator;
import io.confluent.kafka.serializers.KafkaAvroSerializer;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericRecord;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;
import java.util.Properties;
import java.util.Random;
public class SimpleTextAvroProducer {
public static void main(String args[]) throws InterruptedException {
Random r = new Random();
long counter = 0;
String brokers = System.getenv("BROKERS");
String zookeepers = System.getenv("ZK");
String schemaregistry = System.getenv("SCHEMA_REGISTRY");
// Producer myProducer = getAvroProducer("192.168.99.100:9092", "http://192.168.99.100:8081");
// String zookeepers = "192.168.99.100:2181";
Producer myProducer = getStringAvroProducer(brokers, schemaregistry);
String topicName = "SalesStringExample";
Schema valueSchema = getSchema(VALUE_SCHEMA);
KafkaTools.createTopic(zookeepers, topicName, 3, 1);
while (true) {
Long randomInt = new Long(r.nextInt(10));
GenericRecord valueRecord = new GenericData.Record(valueSchema);
valueRecord.put("itemID", randomInt);
valueRecord.put("storeCode", "store-code-" + randomInt);
valueRecord.put("count", randomInt);
ProducerRecord newRecord = new ProducerRecord<String, GenericRecord>(topicName, "Key-" + randomInt, valueRecord);
Integer dice = r.nextInt(1 + (int) counter % 100);
if ((dice < 20) && (dice % 2 == 1)) {
// noop
} else {
myProducer.send(newRecord);
}
myProducer.flush();
Thread.sleep(randomInt);
counter++;
// Log out every 1K messages
if (counter % 1000 == 0) {
System.out.print(" . " + (counter / 1000) + "K");
}
}
}
private static final String VALUE_SCHEMA = "{`type`:`record`,`name`:`com.saleValue`," +
"`doc`:`Sale object stored as value`," +
"`fields`:[" +
"{`name`:`itemID`,`type`:`long`,`doc`:`unique item ID`}," +
"{`name`:`storeCode`,`type`:`string`,`doc`:`store code `}," +
"{`name`:`count`,`type`:`long`,`doc`:`number of products shipped to store`}" +
"]}";
private static Schema getSchema(String schemaString) {
Schema.Parser parser = new Schema.Parser();
return parser.parse(schemaString.replace('`', '"'));
}
private static Producer<String, Object> getStringAvroProducer(String brokers, String schemaregistry) {
System.out.println("Starting [AvroProducer] with brokers=[" + brokers + "] and schema-registry=[" + schemaregistry + "]");
Properties producerProps = new Properties();
producerProps.put("bootstrap.servers", brokers);
producerProps.put("acks", "all");
producerProps.put("key.serializer", StringSerializer.class.getName());
producerProps.put("value.serializer", KafkaAvroSerializer.class.getName());
producerProps.put("linger.ms", "10"); // ?
producerProps.put("schema.registry.url", schemaregistry);
return new KafkaProducer<>(producerProps);
}
}
| apache-2.0 |
RobAustin/byte-buddy | byte-buddy-dep/src/test/java/net/bytebuddy/instrumentation/type/AbstractPackageDescriptionTest.java | 3003 | package net.bytebuddy.instrumentation.type;
import net.bytebuddy.instrumentation.attribute.annotation.AnnotationList;
import net.bytebuddy.test.pkg.Sample;
import net.bytebuddy.test.pkg.child.Child;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
public abstract class AbstractPackageDescriptionTest {
protected abstract PackageDescription describe(Class<?> type);
@Test
public void testTrivialPackage() throws Exception {
assertThat(describe(Child.class).getName(), is(Child.class.getPackage().getName()));
assertThat(describe(Child.class).getDeclaredAnnotations(), is((AnnotationList) new AnnotationList.Empty()));
}
@Test
public void testNonTrivialPackage() throws Exception {
assertThat(describe(Sample.class).getName(), is(Sample.class.getPackage().getName()));
assertThat(describe(Sample.class).getDeclaredAnnotations(),
is((AnnotationList) new AnnotationList.ForLoadedAnnotation(Sample.class.getPackage().getDeclaredAnnotations())));
}
@Test
public void testHashCode() throws Exception {
assertThat(describe(Child.class).hashCode(), is(Child.class.getPackage().hashCode()));
assertThat(describe(Child.class).hashCode(), is(describe(Child.class).hashCode()));
assertThat(describe(Child.class).hashCode(), not(is(describe(Sample.class).hashCode())));
assertThat(describe(Sample.class).hashCode(), is(Sample.class.getPackage().hashCode()));
assertThat(describe(Sample.class).hashCode(), is(describe(Sample.class).hashCode()));
assertThat(describe(Sample.class).hashCode(), not(is(describe(Child.class).hashCode())));
}
@Test
public void testEquals() throws Exception {
assertThat(describe(Child.class).toString(), not(equalTo(null)));
assertThat(describe(Child.class).toString(), not(equalTo(new Object())));
assertThat(describe(Child.class).toString(), equalTo(describe(Child.class).toString()));
assertThat(describe(Child.class).toString(), not(equalTo(describe(Sample.class).toString())));
assertThat(describe(Sample.class).toString(), equalTo(describe(Sample.class).toString()));
assertThat(describe(Sample.class).toString(), not(equalTo(describe(Child.class).toString())));
}
@Test
public void testToString() throws Exception {
assertThat(describe(Child.class).toString(), is(Child.class.getPackage().toString()));
assertThat(describe(Child.class).toString(), is(describe(Child.class).toString()));
assertThat(describe(Child.class).toString(), not(is(describe(Sample.class).toString())));
assertThat(describe(Sample.class).toString(), is(Sample.class.getPackage().toString()));
assertThat(describe(Sample.class).toString(), is(describe(Sample.class).toString()));
assertThat(describe(Sample.class).toString(), not(is(describe(Child.class).toString())));
}
}
| apache-2.0 |
Medium/closure-templates | java/src/com/google/template/soy/shared/internal/BuiltinFunction.java | 2877 | /*
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.template.soy.shared.internal;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.template.soy.shared.restricted.SoyFunction;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Enum of built-in functions supported in Soy expressions.
*
* <p>Important: Do not use outside of Soy code (treat as superpackage-private).
*
*/
public enum BuiltinFunction implements SoyFunction {
IS_FIRST("isFirst"),
IS_LAST("isLast"),
INDEX("index"),
QUOTE_KEYS_IF_JS("quoteKeysIfJs"),
CHECK_NOT_NULL("checkNotNull"),
/**
* Function for substituting CSS class names according to a lookup map.
*
* <p>Takes 1 or 2 arguments: an optional prefix (if present, this is the first arg), followed by
* a string literal selector name.
*/
CSS("css"),
XID("xid"),
V1_EXPRESSION("v1Expression"),
REMAINDER("remainder"),
MSG_ID("msgId"),
IS_PRIMARY_MSG_IN_USE("$$isPrimaryMsgInUse"),
;
public static ImmutableSet<String> names() {
return NONPLUGIN_FUNCTIONS_BY_NAME.keySet();
}
/** Map of NonpluginFunctions by function name. */
private static final ImmutableMap<String, BuiltinFunction> NONPLUGIN_FUNCTIONS_BY_NAME;
static {
ImmutableMap.Builder<String, BuiltinFunction> mapBuilder = ImmutableMap.builder();
for (BuiltinFunction nonpluginFn : values()) {
mapBuilder.put(nonpluginFn.functionName, nonpluginFn);
}
NONPLUGIN_FUNCTIONS_BY_NAME = mapBuilder.build();
}
/**
* Returns the NonpluginFunction for the given function name, or null if not found.
*
* @param functionName The function name to retrieve.
*/
@Nullable
public static BuiltinFunction forFunctionName(String functionName) {
return NONPLUGIN_FUNCTIONS_BY_NAME.get(functionName);
}
/** The function name. */
private final String functionName;
BuiltinFunction(String name) {
this.functionName = name;
}
@Override
public String getName() {
return functionName;
}
@Override
public Set<Integer> getValidArgsSizes() {
switch (this) {
case CSS:
return ImmutableSet.of(1, 2);
case IS_PRIMARY_MSG_IN_USE:
return ImmutableSet.of(3);
default:
return ImmutableSet.of(1);
}
}
}
| apache-2.0 |
nguyenq/tess4j | src/test/java/net/sourceforge/tess4j/Tesseract1Test.java | 14040 | /**
* Copyright @ 2010 Quan Nguyen
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package net.sourceforge.tess4j;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import javax.imageio.ImageIO;
import net.sourceforge.tess4j.util.ImageHelper;
import net.sourceforge.tess4j.util.LoggHelper;
import net.sourceforge.tess4j.util.Utils;
import net.sourceforge.tess4j.ITesseract.RenderedFormat;
import net.sourceforge.tess4j.ITessAPI.TessPageIteratorLevel;
import com.recognition.software.jdeskew.ImageDeskew;
import java.awt.Graphics2D;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Tesseract1Test {
private static final Logger logger = LoggerFactory.getLogger(new LoggHelper().toString());
static final double MINIMUM_DESKEW_THRESHOLD = 0.05d;
ITesseract instance;
private final String datapath = "src/main/resources/tessdata";
private final String testResourcesDataPath = "src/test/resources/test-data";
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() {
instance = new Tesseract1();
instance.setDatapath(new File(datapath).getPath());
}
@After
public void tearDown() {
}
/**
* Test of doOCR method, of class Tesseract1.
*
* @throws Exception while processing image.
*/
@Test
public void testDoOCR_File() throws Exception {
logger.info("doOCR on a PNG image");
File imageFile = new File(this.testResourcesDataPath, "eurotext.png");
String expResult = "The (quick) [brown] {fox} jumps!\nOver the $43,456.78 <lazy> #90 dog";
String result = instance.doOCR(imageFile);
logger.info(result);
assertEquals(expResult, result.substring(0, expResult.length()));
}
/**
* Test of doOCR method, of class Tesseract.
*
* @throws java.lang.Exception
*/
@Test
@Ignore
public void testDoOCR_UNLV_Zone_File() throws Exception {
logger.info("doOCR on a PNG image with UNLV zone file .uzn");
//UNLV zone format: left top width height label
String filename = String.format("%s/%s", this.testResourcesDataPath, "eurotext_unlv.png");
File imageFile = new File(filename);
String expResult = "& duck/goose, as 12.5% of E-mail\n\n"
+ "from aspammer@website.com is spam.\n\n"
+ "The (quick) [brown] {fox} jumps!\n"
+ "Over the $43,456.78 <lazy> #90 dog";
String result = instance.doOCR(imageFile);
logger.info(result);
assertEquals(expResult, result.trim().replace('—', '-'));
}
/**
* Test of doOCR method, of class Tesseract.
*
* @throws java.lang.Exception
*/
@Test
public void testDoOCR_File_With_Configs() throws Exception {
logger.info("doOCR with configs");
File imageFile = new File(this.testResourcesDataPath, "eurotext.png");
String expResult = "[-0123456789.\n ]+";
List<String> configs = Arrays.asList("digits");
instance.setConfigs(configs);
String result = instance.doOCR(imageFile);
logger.info(result);
assertTrue(result.matches(expResult));
}
/**
* Test of doOCR method, of class Tesseract1.
*
* @throws Exception while processing image.
*/
@Test
public void testDoOCR_File_Rectangle() throws Exception {
logger.info("doOCR on a BMP image with bounding rectangle");
File imageFile = new File(this.testResourcesDataPath, "eurotext.bmp");
Rectangle rect = new Rectangle(0, 0, 1024, 800); // define an equal or smaller region of interest on the image
String expResult = "The (quick) [brown] {fox} jumps!\nOver the $43,456.78 <lazy> #90 dog";
String result = instance.doOCR(imageFile, rect);
logger.info(result);
assertEquals(expResult, result.substring(0, expResult.length()));
}
/**
* Test of doOCR method, of class Tesseract1.
*
* @throws Exception while processing image.
*/
@Test
public void testDoOCR_PDF() throws Exception {
logger.info("doOCR on a PDF document");
File inputFile = new File(this.testResourcesDataPath, "eurotext.pdf");
String expResult = "The (quick) [brown] {fox} jumps!\nOver the $43,456.78 <lazy> #90 dog";
String result = instance.doOCR(inputFile, null);
logger.info(result);
assertEquals(expResult, result.substring(0, expResult.length()));
}
/**
* Test of doOCR method, of class Tesseract1.
*
* @throws Exception while processing image.
*/
@Test
public void testDoOCR_BufferedImage() throws Exception {
logger.info("doOCR on a buffered image of a PNG");
File imageFile = new File(this.testResourcesDataPath, "eurotext.png");
BufferedImage bi = ImageIO.read(imageFile);
String expResult = "The (quick) [brown] {fox} jumps!\nOver the $43,456.78 <lazy> #90 dog";
Map<String, Integer> types = new HashMap<>();
types.put("TYPE_INT_RGB", BufferedImage.TYPE_INT_RGB);
types.put("TYPE_INT_ARGB", BufferedImage.TYPE_INT_ARGB);
// types.put("TYPE_INT_ARGB_PRE", BufferedImage.TYPE_INT_ARGB_PRE);
// types.put("TYPE_INT_BGR", BufferedImage.TYPE_INT_BGR);
// types.put("TYPE_3BYTE_BGR", BufferedImage.TYPE_3BYTE_BGR);
// types.put("TYPE_4BYTE_ABGR", BufferedImage.TYPE_4BYTE_ABGR);
// types.put("TYPE_4BYTE_ABGR_PRE", BufferedImage.TYPE_4BYTE_ABGR_PRE);
// types.put("TYPE_USHORT_565_RGB", BufferedImage.TYPE_USHORT_565_RGB);
// types.put("TYPE_USHORT_555_RGB", BufferedImage.TYPE_USHORT_555_RGB);
// types.put("TYPE_BYTE_GRAY", BufferedImage.TYPE_BYTE_GRAY);
// types.put("TYPE_USHORT_GRAY", BufferedImage.TYPE_USHORT_GRAY);
// types.put("TYPE_BYTE_BINARY", BufferedImage.TYPE_BYTE_BINARY);
// types.put("TYPE_BYTE_INDEXED", BufferedImage.TYPE_BYTE_INDEXED);
for (Map.Entry<String, Integer> entry : types.entrySet()) {
if (entry.getValue() == bi.getType()) {
String result = instance.doOCR(bi);
logger.info("BufferedImage type: " + entry.getKey() + " (Original)");
logger.info(result);
logger.info("");
assertEquals(expResult, result.substring(0, expResult.length()));
} else {
BufferedImage imageWithType = new BufferedImage(bi.getWidth(), bi.getHeight(), entry.getValue());
Graphics2D g = imageWithType.createGraphics();
g.drawImage(bi, 0, 0, null);
g.dispose();
String result = instance.doOCR(imageWithType);
logger.info("BufferedImage type: " + entry.getKey());
logger.info(result);
logger.info("");
assertEquals(expResult, result.substring(0, expResult.length()));
}
}
}
/**
* Test of deskew algorithm.
*
* @throws Exception while processing image.
*/
@Test
public void testDoOCR_SkewedImage() throws Exception {
logger.info("doOCR on a skewed PNG image");
File imageFile = new File(this.testResourcesDataPath, "eurotext_deskew.png");
BufferedImage bi = ImageIO.read(imageFile);
ImageDeskew id = new ImageDeskew(bi);
double imageSkewAngle = id.getSkewAngle(); // determine skew angle
if ((imageSkewAngle > MINIMUM_DESKEW_THRESHOLD || imageSkewAngle < -(MINIMUM_DESKEW_THRESHOLD))) {
bi = ImageHelper.rotateImage(bi, -imageSkewAngle); // deskew image
}
String expResult = "The (quick) [brown] {fox} jumps!\nOver the $43,456.78 <lazy> #90 dog";
String result = instance.doOCR(bi);
logger.info(result);
assertEquals(expResult, result.substring(0, expResult.length()));
}
/**
* Test of createDocuments method, of class Tesseract1.
*
* @throws java.lang.Exception
*/
@Test
public void testCreateDocuments() throws Exception {
logger.info("createDocuments for an image");
File imageFile1 = new File(this.testResourcesDataPath, "eurotext.pdf");
File imageFile2 = new File(this.testResourcesDataPath, "eurotext.png");
String outputbase1 = "target/test-classes/test-results/docrenderer1-1";
String outputbase2 = "target/test-classes/test-results/docrenderer1-2";
List<RenderedFormat> formats = new ArrayList<RenderedFormat>(Arrays.asList(RenderedFormat.HOCR, RenderedFormat.PDF, RenderedFormat.TEXT));
instance.createDocuments(new String[]{imageFile1.getPath(), imageFile2.getPath()}, new String[]{outputbase1, outputbase2}, formats);
assertTrue(new File(outputbase1 + ".pdf").exists());
}
/**
* Test of getWords method, of class Tesseract1.
*
* @throws java.lang.Exception
*/
@Test
public void testGetWords() throws Exception {
logger.info("getWords");
File imageFile = new File(this.testResourcesDataPath, "eurotext.tif");
String expResult = "The (quick) [brown] {fox} jumps!\nOver the $43,456.78 <lazy> #90 dog";
String[] expResults = expResult.split("\\s");
int pageIteratorLevel = TessPageIteratorLevel.RIL_WORD;
logger.info("PageIteratorLevel: " + Utils.getConstantName(pageIteratorLevel, TessPageIteratorLevel.class));
BufferedImage bi = ImageIO.read(imageFile);
List<Word> result = instance.getWords(bi, pageIteratorLevel);
// print the complete results
for (Word word : result) {
logger.info(word.toString());
}
List<String> text = new ArrayList<String>();
for (Word word : result.subList(0, expResults.length)) {
text.add(word.getText().trim());
}
assertArrayEquals(expResults, text.toArray());
}
/**
* Test of getSegmentedRegions method, of class Tesseract1.
*
* @throws java.lang.Exception
*/
@Test
public void testGetSegmentedRegions() throws Exception {
logger.info("getSegmentedRegions at given TessPageIteratorLevel");
File imageFile = new File(testResourcesDataPath, "eurotext.png");
BufferedImage bi = ImageIO.read(imageFile);
int level = TessPageIteratorLevel.RIL_SYMBOL;
logger.info("PageIteratorLevel: " + Utils.getConstantName(level, TessPageIteratorLevel.class));
List<Rectangle> result = instance.getSegmentedRegions(bi, level);
for (int i = 0; i < result.size(); i++) {
Rectangle rect = result.get(i);
logger.info(String.format("Box[%d]: x=%d, y=%d, w=%d, h=%d", i, rect.x, rect.y, rect.width, rect.height));
}
assertTrue(result.size() > 0);
}
/**
* Test of createDocumentsWithResults method, of class Tesseract1.
*
* @throws java.lang.Exception
*/
@Test
public void testCreateDocumentsWithResults() throws Exception {
logger.info("createDocumentsWithResults for multiple images at given TessPageIteratorLevel");
File imageFile1 = new File(this.testResourcesDataPath, "eurotext.pdf");
File imageFile2 = new File(this.testResourcesDataPath, "eurotext.png");
String outputbase1 = "target/test-classes/test-results/docrenderer1-3";
String outputbase2 = "target/test-classes/test-results/docrenderer1-4";
List<RenderedFormat> formats = new ArrayList<RenderedFormat>(Arrays.asList(RenderedFormat.HOCR, RenderedFormat.PDF, RenderedFormat.TEXT));
List<OCRResult> results = instance.createDocumentsWithResults(new String[]{imageFile1.getPath(), imageFile2.getPath()}, new String[]{outputbase1, outputbase2}, formats, TessPageIteratorLevel.RIL_WORD);
assertTrue(new File(outputbase1 + ".pdf").exists());
assertEquals(2, results.size());
// Not work on Linux because unable to load pdf.ttf
// assertTrue(results.get(0).getConfidence() > 0);
// assertEquals(66, results.get(0).getWords().size());
}
/**
* Test of createDocumentsWithResults method, of class Tesseract1.
*
* @throws java.lang.Exception
*/
@Test
public void testCreateDocumentsWithResults1() throws Exception {
logger.info("createDocumentsWithResults for a buffered image at given TessPageIteratorLevel");
File imageFile = new File(this.testResourcesDataPath, "eurotext.tif");
BufferedImage bi = ImageIO.read(imageFile);
String outputbase = "target/test-classes/test-results/docrenderer-5";
List<RenderedFormat> formats = new ArrayList<RenderedFormat>(Arrays.asList(RenderedFormat.HOCR, RenderedFormat.PDF, RenderedFormat.TEXT));
OCRResult result = instance.createDocumentsWithResults(bi, imageFile.getName(), outputbase, formats, TessPageIteratorLevel.RIL_WORD);
assertTrue(new File(outputbase + ".pdf").exists());
assertTrue(result.getConfidence() > 0);
assertEquals(66, result.getWords().size());
}
}
| apache-2.0 |
OlegNyr/GisGMP | src/main/java/ru/nyrk/gisgmp/database/entity/security/WpGroupPermisionEntityPK.java | 1364 | package ru.nyrk.gisgmp.database.entity.security;
import javax.persistence.Column;
import javax.persistence.Id;
import java.io.Serializable;
/**
* Created with IntelliJ IDEA.
* User: olegnyr
* Date: 18.12.13
* Time: 18:00
* To change this template use File | Settings | File Templates.
*/
public class WpGroupPermisionEntityPK implements Serializable {
private long groupId;
private long permissionId;
@Id
@Column(name = "group_id")
public long getGroupId() {
return groupId;
}
public void setGroupId(long groupId) {
this.groupId = groupId;
}
@Id@Column(name = "permission_id")
public long getPermissionId() {
return permissionId;
}
public void setPermissionId(long permissionId) {
this.permissionId = permissionId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
WpGroupPermisionEntityPK that = (WpGroupPermisionEntityPK) o;
if (groupId != that.groupId) return false;
if (permissionId != that.permissionId) return false;
return true;
}
@Override
public int hashCode() {
int result = (int) (groupId ^ (groupId >>> 32));
result = 31 * result + (int) (permissionId ^ (permissionId >>> 32));
return result;
}}
| apache-2.0 |
googleads/googleads-java-lib | modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202102/UrlErrorReason.java | 2091 | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.api.ads.admanager.jaxws.v202102;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for UrlError.Reason.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="UrlError.Reason">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="CANNOT_USE_RESERVED_URL"/>
* <enumeration value="CANNOT_USE_GOOGLE_URL"/>
* <enumeration value="INVALID_URL"/>
* <enumeration value="UNKNOWN"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "UrlError.Reason")
@XmlEnum
public enum UrlErrorReason {
/**
*
* The URL has been reserved, and not available for usage.
*
*
*/
CANNOT_USE_RESERVED_URL,
/**
*
* The URL belongs to Google, and not available for usage.
*
*
*/
CANNOT_USE_GOOGLE_URL,
/**
*
* The URL is invalid.
*
*
*/
INVALID_URL,
/**
*
* The value returned if the actual value is not exposed by the requested API version.
*
*
*/
UNKNOWN;
public String value() {
return name();
}
public static UrlErrorReason fromValue(String v) {
return valueOf(v);
}
}
| apache-2.0 |
WASdev/sample.netflixoss.wlp | ws-hystrix/src/main/java/net/wasdev/wlp/netflixoss/hystrix/WsHystrixConcurrencyStrategy.java | 3862 | /**
* (C) Copyright IBM Corporation 2014.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.wasdev.wlp.netflixoss.hystrix;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
import com.netflix.hystrix.strategy.properties.HystrixProperty;
public class WsHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy {
private static final String CLASSNAME = WsHystrixConcurrencyStrategy.class.getName();
private static final Logger LOGGER = Logger.getLogger(CLASSNAME);
private ThreadPoolExecutorFactory executorFactory;
private BlockingQueueFactory blockingQueueFactory;
private final ConcurrentMap<HystrixThreadPoolKey, ThreadPoolExecutor> poolMap = new ConcurrentHashMap<HystrixThreadPoolKey, ThreadPoolExecutor>();
void activate() {
LOGGER.entering(CLASSNAME, "activate");
LOGGER.exiting(CLASSNAME, "activate");
}
void deactivate() {
LOGGER.entering(CLASSNAME, "deactivate");
LOGGER.exiting(CLASSNAME, "deactivate");
}
void setThreadPoolExecutorFactory(ThreadPoolExecutorFactory threadPoolExecutorFactory) {
LOGGER.entering(CLASSNAME, "setThreadPoolExecutorFactory", threadPoolExecutorFactory);
executorFactory = threadPoolExecutorFactory;
LOGGER.exiting(CLASSNAME, "setThreadPoolExecutorFactory");
}
void unsetThreadPoolExecutorFactory(ThreadPoolExecutorFactory threadPoolExecutorFactory) {
LOGGER.entering(CLASSNAME, "unsetThreadPoolExecutorFactory");
LOGGER.exiting(CLASSNAME, "unsetThreadPoolExecutorFactory");
}
void setBlockingQueueFactory(BlockingQueueFactory blockingQueueFactory) {
LOGGER.entering(CLASSNAME, "setBlockingQueueFactory", blockingQueueFactory);
this.blockingQueueFactory = blockingQueueFactory;
LOGGER.exiting(CLASSNAME, "setBlockingQueueFactory");
}
void unsetBlockingQueueFactory(BlockingQueueFactory blockingQueueFactory) {
LOGGER.entering(CLASSNAME, "unsetBlockingQueueFactory");
LOGGER.exiting(CLASSNAME, "unsetBlockingQueueFactory");
}
@Override
public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey,
HystrixProperty<Integer> corePoolSize,
HystrixProperty<Integer> maximumPoolSize,
HystrixProperty<Integer> keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
ThreadPoolExecutor pool = poolMap.get(threadPoolKey);
if (pool == null) {
ThreadPoolExecutor newPool =
executorFactory.createThreadPoolExecutor(
corePoolSize.get(), maximumPoolSize.get(),
keepAliveTime.get(), unit, workQueue);
pool = poolMap.putIfAbsent(threadPoolKey, newPool);
pool = (pool == null) ? newPool : pool;
}
return pool;
}
@Override
public BlockingQueue<Runnable> getBlockingQueue(int maxQueueSize) {
return blockingQueueFactory.createBlockingQueue(maxQueueSize);
}
}
| apache-2.0 |
cdmckay/mediawikiprovider | src/org/cdmckay/android/provider/xml/OpenSearchHandler.java | 3225 | /*******************************************************************************
* Copyright 2010 Cameron McKay
*
* 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.cdmckay.android.provider.xml;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class OpenSearchHandler extends DefaultHandler {
private static final String EMPTY_STRING = "";
private boolean inItem = false;
private boolean inTitle = false;
private boolean inDescription = false;
private boolean inUrl = false;
private int id = 1;
private String title = EMPTY_STRING;
private StringBuilder description = new StringBuilder();
private String url = EMPTY_STRING;
public static class Result {
public final int id;
public final String title;
public final String description;
public final String url;
public Result(int id, String title, String description, String url) {
this.id = id;
this.title = title;
this.description = description;
this.url = url;
}
}
private List<Result> results = new ArrayList<Result>();
public List<Result> getResults() {
return results;
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
final String name = localName.trim().toLowerCase();
if (name.equals("item")) {
inItem = true;
} else if (name.equals("text")) {
inTitle = true;
} else if (name.equals("description")) {
inDescription = true;
} else if (name.equals("url")) {
inUrl = true;
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
final String name = localName.trim().toLowerCase();
if (name.equals("item")) {
results.add(new Result(id, title, description.toString(), url));
id++;
title = EMPTY_STRING;
description.delete(0, description.length());
url = EMPTY_STRING;
inItem = false;
} else if (name.equals("text")) {
inTitle = false;
} else if (name.equals("description")) {
inDescription = false;
} else if (name.equals("url")) {
inUrl = false;
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
final String str = new String(ch).substring(start, start + length);
if (inItem) {
if (inTitle) {
title = str;
} else if (inDescription) {
description.append(str);
} else if (inUrl) {
url = str;
}
}
}
}
| apache-2.0 |
MegafonWebLab/histone-java | src/test/java/ru/histone/acceptance/tests/general/ExpressionsTest.java | 1010 | /**
* Copyright 2013 MegaFon
*
* 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 ru.histone.acceptance.tests.general;
import org.junit.runner.RunWith;
import ru.histone.acceptance.support.AcceptanceTest;
import ru.histone.acceptance.support.AcceptanceTestsRunner;
@RunWith(AcceptanceTestsRunner.class)
public class ExpressionsTest extends AcceptanceTest {
@Override
public String getFileName() {
return "/general/expressions.json";
}
}
| apache-2.0 |
googleapis/java-dialogflow-cx | proto-google-cloud-dialogflow-cx-v3/src/main/java/com/google/cloud/dialogflow/cx/v3/EnvironmentOrBuilder.java | 7456 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/dialogflow/cx/v3/environment.proto
package com.google.cloud.dialogflow.cx.v3;
public interface EnvironmentOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.dialogflow.cx.v3.Environment)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* The name of the environment.
* Format: `projects/<Project ID>/locations/<Location ID>/agents/<Agent
* ID>/environments/<Environment ID>`.
* </pre>
*
* <code>string name = 1;</code>
*
* @return The name.
*/
java.lang.String getName();
/**
*
*
* <pre>
* The name of the environment.
* Format: `projects/<Project ID>/locations/<Location ID>/agents/<Agent
* ID>/environments/<Environment ID>`.
* </pre>
*
* <code>string name = 1;</code>
*
* @return The bytes for name.
*/
com.google.protobuf.ByteString getNameBytes();
/**
*
*
* <pre>
* Required. The human-readable name of the environment (unique in an agent). Limit of
* 64 characters.
* </pre>
*
* <code>string display_name = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The displayName.
*/
java.lang.String getDisplayName();
/**
*
*
* <pre>
* Required. The human-readable name of the environment (unique in an agent). Limit of
* 64 characters.
* </pre>
*
* <code>string display_name = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for displayName.
*/
com.google.protobuf.ByteString getDisplayNameBytes();
/**
*
*
* <pre>
* The human-readable description of the environment. The maximum length is
* 500 characters. If exceeded, the request is rejected.
* </pre>
*
* <code>string description = 3;</code>
*
* @return The description.
*/
java.lang.String getDescription();
/**
*
*
* <pre>
* The human-readable description of the environment. The maximum length is
* 500 characters. If exceeded, the request is rejected.
* </pre>
*
* <code>string description = 3;</code>
*
* @return The bytes for description.
*/
com.google.protobuf.ByteString getDescriptionBytes();
/**
*
*
* <pre>
* Required. A list of configurations for flow versions. You should include version
* configs for all flows that are reachable from [`Start
* Flow`][Agent.start_flow] in the agent. Otherwise, an error will be
* returned.
* </pre>
*
* <code>
* repeated .google.cloud.dialogflow.cx.v3.Environment.VersionConfig version_configs = 6 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
java.util.List<com.google.cloud.dialogflow.cx.v3.Environment.VersionConfig>
getVersionConfigsList();
/**
*
*
* <pre>
* Required. A list of configurations for flow versions. You should include version
* configs for all flows that are reachable from [`Start
* Flow`][Agent.start_flow] in the agent. Otherwise, an error will be
* returned.
* </pre>
*
* <code>
* repeated .google.cloud.dialogflow.cx.v3.Environment.VersionConfig version_configs = 6 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
com.google.cloud.dialogflow.cx.v3.Environment.VersionConfig getVersionConfigs(int index);
/**
*
*
* <pre>
* Required. A list of configurations for flow versions. You should include version
* configs for all flows that are reachable from [`Start
* Flow`][Agent.start_flow] in the agent. Otherwise, an error will be
* returned.
* </pre>
*
* <code>
* repeated .google.cloud.dialogflow.cx.v3.Environment.VersionConfig version_configs = 6 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
int getVersionConfigsCount();
/**
*
*
* <pre>
* Required. A list of configurations for flow versions. You should include version
* configs for all flows that are reachable from [`Start
* Flow`][Agent.start_flow] in the agent. Otherwise, an error will be
* returned.
* </pre>
*
* <code>
* repeated .google.cloud.dialogflow.cx.v3.Environment.VersionConfig version_configs = 6 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
java.util.List<? extends com.google.cloud.dialogflow.cx.v3.Environment.VersionConfigOrBuilder>
getVersionConfigsOrBuilderList();
/**
*
*
* <pre>
* Required. A list of configurations for flow versions. You should include version
* configs for all flows that are reachable from [`Start
* Flow`][Agent.start_flow] in the agent. Otherwise, an error will be
* returned.
* </pre>
*
* <code>
* repeated .google.cloud.dialogflow.cx.v3.Environment.VersionConfig version_configs = 6 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
com.google.cloud.dialogflow.cx.v3.Environment.VersionConfigOrBuilder getVersionConfigsOrBuilder(
int index);
/**
*
*
* <pre>
* Output only. Update time of this environment.
* </pre>
*
* <code>.google.protobuf.Timestamp update_time = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*
* @return Whether the updateTime field is set.
*/
boolean hasUpdateTime();
/**
*
*
* <pre>
* Output only. Update time of this environment.
* </pre>
*
* <code>.google.protobuf.Timestamp update_time = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*
* @return The updateTime.
*/
com.google.protobuf.Timestamp getUpdateTime();
/**
*
*
* <pre>
* Output only. Update time of this environment.
* </pre>
*
* <code>.google.protobuf.Timestamp update_time = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
com.google.protobuf.TimestampOrBuilder getUpdateTimeOrBuilder();
/**
*
*
* <pre>
* The test cases config for continuous tests of this environment.
* </pre>
*
* <code>.google.cloud.dialogflow.cx.v3.Environment.TestCasesConfig test_cases_config = 7;</code>
*
* @return Whether the testCasesConfig field is set.
*/
boolean hasTestCasesConfig();
/**
*
*
* <pre>
* The test cases config for continuous tests of this environment.
* </pre>
*
* <code>.google.cloud.dialogflow.cx.v3.Environment.TestCasesConfig test_cases_config = 7;</code>
*
* @return The testCasesConfig.
*/
com.google.cloud.dialogflow.cx.v3.Environment.TestCasesConfig getTestCasesConfig();
/**
*
*
* <pre>
* The test cases config for continuous tests of this environment.
* </pre>
*
* <code>.google.cloud.dialogflow.cx.v3.Environment.TestCasesConfig test_cases_config = 7;</code>
*/
com.google.cloud.dialogflow.cx.v3.Environment.TestCasesConfigOrBuilder
getTestCasesConfigOrBuilder();
}
| apache-2.0 |
BlesseNtumble/GalaxySpace | src/main/java/galaxyspace/core/hooklib/asm/TypeHelper.java | 3639 | package galaxyspace.core.hooklib.asm;
import java.util.HashMap;
import java.util.Map;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
/**
* Класс, позволяющий создавать типы из разных входных данных.
* Эти типы нужны для того, чтобы задавать параметры и возвращаемые значения методов.
*/
public class TypeHelper {
private static final Map<String, Type> primitiveTypes = new HashMap<String, Type>(9);
static {
primitiveTypes.put("void", Type.VOID_TYPE);
primitiveTypes.put("boolean", Type.BOOLEAN_TYPE);
primitiveTypes.put("byte", Type.BYTE_TYPE);
primitiveTypes.put("short", Type.SHORT_TYPE);
primitiveTypes.put("char", Type.CHAR_TYPE);
primitiveTypes.put("int", Type.INT_TYPE);
primitiveTypes.put("float", Type.FLOAT_TYPE);
primitiveTypes.put("long", Type.LONG_TYPE);
primitiveTypes.put("double", Type.DOUBLE_TYPE);
}
/**
* Создает тип по названию класса или примитива.
* Пример использования: getType("net.minecraft.world.World") - вернёт тип для World
*
* @param className необфусцированное название класса
* @return соответствующий тип
*/
public static Type getType(String className) {
return getArrayType(className, 0);
}
/**
* Создает тип для одномерного массива указанного класса или примитиа.
* Пример использования: getArrayType("net.minecraft.world.World") - вернёт тип для World[]
*
* @param className необфусцированное название класса
* @return соответствующий классу тип одномерного массива
*/
public static Type getArrayType(String className) {
return getArrayType(className, 1);
}
/**
* Создает тип для n-мерного массива указанного класса или примитива.
* Пример использования: getArrayType("net.minecraft.world.World", 2) - вернёт тип для World[][]
*
* @param className название класса
* @return соответствующий классу тип n-мерного массива
*/
public static Type getArrayType(String className, int arrayDimensions) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arrayDimensions; i++) {
sb.append("[");
}
Type primitive = primitiveTypes.get(className);
if (primitive == null) {
sb.append("L");
sb.append(className.replace(".", "/"));
sb.append(";");
} else {
sb.append(primitive.getDescriptor());
}
return Type.getType(sb.toString());
}
static Object getStackMapFrameEntry(Type type) {
if (type == Type.BOOLEAN_TYPE || type == Type.BYTE_TYPE || type == Type.SHORT_TYPE ||
type == Type.CHAR_TYPE || type == Type.INT_TYPE) {
return Opcodes.INTEGER;
}
if (type == Type.FLOAT_TYPE) {
return Opcodes.FLOAT;
}
if (type == Type.DOUBLE_TYPE) {
return Opcodes.DOUBLE;
}
if (type == Type.LONG_TYPE) {
return Opcodes.LONG;
}
return type.getInternalName();
}
}
| apache-2.0 |
aravindc/databenecommons | src/test/java/org/databene/commons/bean/PropertyAccessConverterTest.java | 1460 | /*
* Copyright (C) 2004-2015 Volker Bergmann (volker.bergmann@bergmann-it.de).
* 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.databene.commons.bean;
import org.junit.Test;
import static junit.framework.Assert.*;
import org.databene.commons.ConversionException;
import org.databene.commons.bean.PropertyAccessConverter;
/**
* Tests the PropertyAccessConverter.
* Created: 21.07.2007 16:35:28
* @author Volker Bergmann
*/
public class PropertyAccessConverterTest {
@Test
public void test() throws ConversionException {
Bean bean = new Bean(42, "foobar");
PropertyAccessConverter numberExtractor = new PropertyAccessConverter("number");
assertEquals(42, numberExtractor.convert(bean));
PropertyAccessConverter textExtractor = new PropertyAccessConverter("text");
assertEquals("foobar", textExtractor.convert(bean));
}
}
| apache-2.0 |
gawkermedia/googleads-java-lib | modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/v201601/o/TrafficEstimatorErrorReason.java | 5407 | /**
* TrafficEstimatorErrorReason.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.adwords.axis.v201601.o;
public class TrafficEstimatorErrorReason implements java.io.Serializable {
private java.lang.String _value_;
private static java.util.HashMap _table_ = new java.util.HashMap();
// Constructor
protected TrafficEstimatorErrorReason(java.lang.String value) {
_value_ = value;
_table_.put(_value_,this);
}
public static final java.lang.String _NO_CAMPAIGN_FOR_AD_GROUP_ESTIMATE_REQUEST = "NO_CAMPAIGN_FOR_AD_GROUP_ESTIMATE_REQUEST";
public static final java.lang.String _NO_AD_GROUP_FOR_KEYWORD_ESTIMATE_REQUEST = "NO_AD_GROUP_FOR_KEYWORD_ESTIMATE_REQUEST";
public static final java.lang.String _NO_MAX_CPC_FOR_KEYWORD_ESTIMATE_REQUEST = "NO_MAX_CPC_FOR_KEYWORD_ESTIMATE_REQUEST";
public static final java.lang.String _TOO_MANY_KEYWORD_ESTIMATE_REQUESTS = "TOO_MANY_KEYWORD_ESTIMATE_REQUESTS";
public static final java.lang.String _TOO_MANY_CAMPAIGN_ESTIMATE_REQUESTS = "TOO_MANY_CAMPAIGN_ESTIMATE_REQUESTS";
public static final java.lang.String _TOO_MANY_ADGROUP_ESTIMATE_REQUESTS = "TOO_MANY_ADGROUP_ESTIMATE_REQUESTS";
public static final java.lang.String _TOO_MANY_TARGETS = "TOO_MANY_TARGETS";
public static final java.lang.String _KEYWORD_TOO_LONG = "KEYWORD_TOO_LONG";
public static final java.lang.String _KEYWORD_CONTAINS_BROAD_MATCH_MODIFIERS = "KEYWORD_CONTAINS_BROAD_MATCH_MODIFIERS";
public static final java.lang.String _INVALID_INPUT = "INVALID_INPUT";
public static final java.lang.String _SERVICE_UNAVAILABLE = "SERVICE_UNAVAILABLE";
public static final TrafficEstimatorErrorReason NO_CAMPAIGN_FOR_AD_GROUP_ESTIMATE_REQUEST = new TrafficEstimatorErrorReason(_NO_CAMPAIGN_FOR_AD_GROUP_ESTIMATE_REQUEST);
public static final TrafficEstimatorErrorReason NO_AD_GROUP_FOR_KEYWORD_ESTIMATE_REQUEST = new TrafficEstimatorErrorReason(_NO_AD_GROUP_FOR_KEYWORD_ESTIMATE_REQUEST);
public static final TrafficEstimatorErrorReason NO_MAX_CPC_FOR_KEYWORD_ESTIMATE_REQUEST = new TrafficEstimatorErrorReason(_NO_MAX_CPC_FOR_KEYWORD_ESTIMATE_REQUEST);
public static final TrafficEstimatorErrorReason TOO_MANY_KEYWORD_ESTIMATE_REQUESTS = new TrafficEstimatorErrorReason(_TOO_MANY_KEYWORD_ESTIMATE_REQUESTS);
public static final TrafficEstimatorErrorReason TOO_MANY_CAMPAIGN_ESTIMATE_REQUESTS = new TrafficEstimatorErrorReason(_TOO_MANY_CAMPAIGN_ESTIMATE_REQUESTS);
public static final TrafficEstimatorErrorReason TOO_MANY_ADGROUP_ESTIMATE_REQUESTS = new TrafficEstimatorErrorReason(_TOO_MANY_ADGROUP_ESTIMATE_REQUESTS);
public static final TrafficEstimatorErrorReason TOO_MANY_TARGETS = new TrafficEstimatorErrorReason(_TOO_MANY_TARGETS);
public static final TrafficEstimatorErrorReason KEYWORD_TOO_LONG = new TrafficEstimatorErrorReason(_KEYWORD_TOO_LONG);
public static final TrafficEstimatorErrorReason KEYWORD_CONTAINS_BROAD_MATCH_MODIFIERS = new TrafficEstimatorErrorReason(_KEYWORD_CONTAINS_BROAD_MATCH_MODIFIERS);
public static final TrafficEstimatorErrorReason INVALID_INPUT = new TrafficEstimatorErrorReason(_INVALID_INPUT);
public static final TrafficEstimatorErrorReason SERVICE_UNAVAILABLE = new TrafficEstimatorErrorReason(_SERVICE_UNAVAILABLE);
public java.lang.String getValue() { return _value_;}
public static TrafficEstimatorErrorReason fromValue(java.lang.String value)
throws java.lang.IllegalArgumentException {
TrafficEstimatorErrorReason enumeration = (TrafficEstimatorErrorReason)
_table_.get(value);
if (enumeration==null) throw new java.lang.IllegalArgumentException();
return enumeration;
}
public static TrafficEstimatorErrorReason fromString(java.lang.String value)
throws java.lang.IllegalArgumentException {
return fromValue(value);
}
public boolean equals(java.lang.Object obj) {return (obj == this);}
public int hashCode() { return toString().hashCode();}
public java.lang.String toString() { return _value_;}
public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);}
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumSerializer(
_javaType, _xmlType);
}
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumDeserializer(
_javaType, _xmlType);
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(TrafficEstimatorErrorReason.class);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/o/v201601", "TrafficEstimatorError.Reason"));
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
}
| apache-2.0 |
utgenome/utgb | utgb-core/src/main/java/org/utgenome/gwt/utgb/client/track/lib/debug/URLQueryArgumentTrack.java | 2080 | /*--------------------------------------------------------------------------
* Copyright 2007 utgenome.org
*
* 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.
*--------------------------------------------------------------------------*/
//--------------------------------------
// GenomeBrowser Project
//
// URLQueryArgumentTrack.java
// Since: Jun 15, 2007
//
// $URL$
// $Author$
//--------------------------------------
package org.utgenome.gwt.utgb.client.track.lib.debug;
import java.util.HashMap;
import org.utgenome.gwt.utgb.client.track.Track;
import org.utgenome.gwt.utgb.client.track.TrackBase;
import org.utgenome.gwt.utgb.client.util.BrowserInfo;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
public class URLQueryArgumentTrack extends TrackBase {
private final HorizontalPanel _panel = new HorizontalPanel();
public static TrackFactory factory() {
return new TrackFactory() {
public Track newInstance() {
return new URLQueryArgumentTrack();
}
};
}
public URLQueryArgumentTrack() {
super("Query Argument");
_panel.setStyleName("selector");
}
public Widget getWidget() {
return _panel;
}
public void draw() {
_panel.clear();
HashMap<String, String> requestParam = BrowserInfo.getURLQueryRequestParameters();
for (String key : requestParam.keySet()) {
String value = (String) requestParam.get(key);
Label l = new Label(key + "=" + value);
l.setStyleName("selector-item");
_panel.add(l);
}
}
}
| apache-2.0 |
menski/camunda-bpm-platform | engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/caseDefinition/HalCaseDefinitionResolver.java | 1757 | /* 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.camunda.bpm.engine.rest.hal.caseDefinition;
import java.util.ArrayList;
import java.util.List;
import org.camunda.bpm.engine.ProcessEngine;
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.repository.CaseDefinition;
import org.camunda.bpm.engine.rest.hal.HalResource;
import org.camunda.bpm.engine.rest.hal.cache.HalIdResourceCacheLinkResolver;
/**
* @author Daniel Meyer
*
*/
public class HalCaseDefinitionResolver extends HalIdResourceCacheLinkResolver {
protected Class<?> getHalResourceClass() {
return HalCaseDefinition.class;
}
protected List<HalResource<?>> resolveNotCachedLinks(String[] linkedIds, ProcessEngine processEngine) {
RepositoryService repositoryService = processEngine.getRepositoryService();
List<CaseDefinition> caseDefinitions = repositoryService.createCaseDefinitionQuery()
.caseDefinitionIdIn(linkedIds)
.listPage(0, linkedIds.length);
List<HalResource<?>> resolved = new ArrayList<HalResource<?>>();
for (CaseDefinition caseDefinition : caseDefinitions) {
resolved.add(HalCaseDefinition.fromCaseDefinition(caseDefinition, processEngine));
}
return resolved;
}
}
| apache-2.0 |
gscdev/TestApp | app/src/androidTest/java/com/gsc/testapp/ExampleInstrumentedTest.java | 760 | package com.gsc.testapp;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.gsc.testapp", appContext.getPackageName());
}
}
| apache-2.0 |
SteveWinfield/IDK-Server-Java | src/main/java/org/stevewinfield/suja/idk/communication/player/writers/LevelRightsListWriter.java | 610 | /*
* IDK Game Server by Steve Winfield
* https://github.com/WinfieldSteve
*/
package org.stevewinfield.suja.idk.communication.player.writers;
import org.stevewinfield.suja.idk.communication.MessageWriter;
import org.stevewinfield.suja.idk.communication.OperationCodes;
public class LevelRightsListWriter extends MessageWriter {
public LevelRightsListWriter(final boolean hasVIP, final boolean hasClub, final boolean hasAdmin) {
super(OperationCodes.getOutgoingOpCode("LevelRightsWriter"));
super.push(hasVIP ? 2 : (hasClub ? 1 : 0));
super.push(hasAdmin ? 1000 : 0);
}
}
| apache-2.0 |
AlisonSouza/liquibase | liquibase-core/src/main/java/liquibase/datatype/core/ClobType.java | 2847 | package liquibase.datatype.core;
import liquibase.database.Database;
import liquibase.database.core.*;
import liquibase.datatype.DataTypeInfo;
import liquibase.datatype.DatabaseDataType;
import liquibase.datatype.LiquibaseDataType;
@DataTypeInfo(name="clob", aliases = {"text", "longtext", "java.sql.Types.CLOB"}, minParameters = 0, maxParameters = 0, priority = LiquibaseDataType.PRIORITY_DEFAULT)
public class ClobType extends LiquibaseDataType {
@Override
public String objectToSql(Object value, Database database) {
if (value == null || value.toString().equalsIgnoreCase("null")) {
return null;
}
String val = String.valueOf(value);
// postgres type character varying gets identified as a char type
// simple sanity check to avoid double quoting a value
if (val.startsWith("'")) {
return val;
} else {
return "'"+database.escapeStringForDatabase(val)+"'";
}
}
@Override
public DatabaseDataType toDatabaseDataType(Database database) {
if (database instanceof CacheDatabase) {
return new DatabaseDataType("LONGVARCHAR");
} else if (database instanceof FirebirdDatabase) {
return new DatabaseDataType("BLOB SUB_TYPE TEXT");
} else if (database instanceof MaxDBDatabase || database instanceof SybaseASADatabase) {
return new DatabaseDataType("LONG VARCHAR");
} else if (database instanceof MSSQLDatabase) {
return new DatabaseDataType("NVARCHAR", "MAX");
} else if (database instanceof MySQLDatabase) {
return new DatabaseDataType("LONGTEXT");
} else if (database instanceof PostgresDatabase || database instanceof SQLiteDatabase || database instanceof SybaseDatabase) {
return new DatabaseDataType("TEXT");
} else if (database instanceof OracleDatabase) {
return new DatabaseDataType("CLOB");
}
return super.toDatabaseDataType(database);
}
//sqlite
// } else if (columnTypeString.equals("TEXT") ||
// columnTypeString.toLowerCase(Locale.ENGLISH).contains("uuid") ||
// columnTypeString.toLowerCase(Locale.ENGLISH).contains("uniqueidentifier") ||
// columnTypeString.toLowerCase(Locale.ENGLISH).equals("uniqueidentifier") ||
// columnTypeString.toLowerCase(Locale.ENGLISH).equals("datetime") ||
// columnTypeString.toLowerCase(Locale.ENGLISH).contains("timestamp") ||
// columnTypeString.toLowerCase(Locale.ENGLISH).contains("char") ||
// columnTypeString.toLowerCase(Locale.ENGLISH).contains("clob") ||
// columnTypeString.toLowerCase(Locale.ENGLISH).contains("text")) {
// type = new CustomType("TEXT",0,0);
}
| apache-2.0 |
jasonwee/videoOnCloud | src/java/play/learn/java/design/execute_around/ExecuteAroundDemo.java | 357 | package play.learn.java.design.execute_around;
import java.io.IOException;
public class ExecuteAroundDemo {
public static void main(String[] args) throws IOException {
FileWriterAction writeHello = writer -> {
writer.write("Hello");
writer.append(" ");
writer.append("there!");
};
new SimpleFileWriter("testfile.txt", writeHello);
}
}
| apache-2.0 |
Nithanim/gw2api | src/main/java/me/nithanim/gw2api/v2/api/items/details/ConsumeableDetails.java | 658 | package me.nithanim.gw2api.v2.api.items.details;
import me.nithanim.gw2api.v2.api.items.Details;
@lombok.NoArgsConstructor
@lombok.AllArgsConstructor
@lombok.Getter
@lombok.EqualsAndHashCode
@lombok.ToString
public class ConsumeableDetails implements Details {
private ConsumeableType type;
private String description;
private int durationMs = -1;
private String unlockType;
private int colorId = -1;
private int recipeId = -1;
public static enum ConsumeableType {
APPEARANCE_CHANGE,
BOOZE,
CONTRACT_NPC,
FOOD,
GENERIC,
HALLOWEEN,
IMMEDIATE,
TRANSMUTATION,
UNLOCK,
UPGRADE_REMOVAL,
UTILITY;
}
}
| apache-2.0 |
ShamilovSV/DualSeekBar | lib/src/main/java/com/shamilov/dualseekbarlibrary/DualSeekBar.java | 29022 | package com.shamilov.dualseekbarlibrary;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.ColorInt;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import com.shamilov.dualseekbarlibrary.instrumentation.DrawingInstrumentation;
import com.shamilov.dualseekbarlibrary.instrumentation.MotionDirection;
import com.shamilov.dualseekbarlibrary.instrumentation.PoolKeyHolder;
import com.shamilov.dualseekbarlibrary.listener.DualProgressChangedListener;
import com.shamilov.dualseekbarlibrary.listener.ThumbProgressChangedListener;
import com.shamilov.dualseekbarlibrary.model.DraggingObjectHolder;
import com.shamilov.dualseekbarlibrary.model.Size;
public class DualSeekBar extends View {
private static final String TAG = "DualSeekBar";
private Bitmap leftThumbDrawable;
private Bitmap rightThumbDrawable;
private int minimumHeight;
private DrawingInstrumentation instrumentation = new DrawingInstrumentation();
private DraggingObjectHolder currentDraggingHolder;
private DraggingObjectHolder lastDraggingHolder;
private DualProgressChangedListener dualProgressChangedListener;
public DualSeekBar(Context context) {
super(context);
init(context, null, 0);
}
public DualSeekBar(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0);
}
public DualSeekBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr);
}
public void setProgressChangedListener(DualProgressChangedListener listener) {
this.dualProgressChangedListener = listener;
}
private void init(Context context, AttributeSet attributeSet, int defStyleAttr) {
parseAttributes(context, attributeSet, defStyleAttr);
final DraggingObjectHolder leftThumbHolder = instrumentation.getDraggingHolder(PoolKeyHolder.LEFT_THUMB_HOLDER);
leftThumbHolder.setDragListener(new ThumbProgressChangedListener() {
@Override
public void onThumbDraggedListener(DraggingObjectHolder holder, int pixels) {
if (dualProgressChangedListener != null) {
pixels = pixels - leftThumbDrawable.getWidth() / 2;
int viewStartXCoordinate = instrumentation.getPoint(PoolKeyHolder.VIEW_START_POINT).x;
int viewEndXCoordinate = instrumentation.getPoint(PoolKeyHolder.VIEW_END_POINT).x;
int viewWidth = viewEndXCoordinate - viewStartXCoordinate;
double percentage = instrumentation.getMeasurementCalculator()
.calculateDragPercentage(pixels, viewWidth, MotionDirection.LEFT_TO_RIGHT);
holder.setPercentage(percentage);
dualProgressChangedListener.onLeftThumbProgressChanged(percentage);
}
}
});
DraggingObjectHolder rightThumbHolder = instrumentation.getDraggingHolder(PoolKeyHolder.RIGHT_THUMB_HOLDER);
rightThumbHolder.setDragListener(new ThumbProgressChangedListener() {
@Override
public void onThumbDraggedListener(DraggingObjectHolder holder, int pixels) {
if (dualProgressChangedListener != null) {
pixels = pixels - leftThumbDrawable.getWidth() / 2;
int viewStartXCoordinate = instrumentation.getPoint(PoolKeyHolder.VIEW_START_POINT).x;
int viewEndXCoordinate = instrumentation.getPoint(PoolKeyHolder.VIEW_END_POINT).x;
int viewWidth = viewEndXCoordinate - viewStartXCoordinate;
double percentage = instrumentation.getMeasurementCalculator()
.calculateDragPercentage(pixels, viewWidth, MotionDirection.RIGHT_TO_LEFT);
holder.setPercentage(percentage);
dualProgressChangedListener.onRightThumbProgressChanged(percentage);
}
}
});
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int width = widthMode == MeasureSpec.EXACTLY ? widthSize : getSuggestedMinimumWidth();
int height = heightMode == MeasureSpec.EXACTLY ? heightSize : minimumHeight;
setMeasuredDimension(width, height);
}
@Override
protected void onDraw(Canvas canvas) {
Point leftThumbCenter = instrumentation.getPoint(PoolKeyHolder.LEFT_THUMB_CENTER);
Point rightThumbCenter = instrumentation.getPoint(PoolKeyHolder.RIGHT_THUMB_CENTER);
Point viewStartPoint = instrumentation.getPoint(PoolKeyHolder.VIEW_START_POINT);
Point viewEndPoint = instrumentation.getPoint(PoolKeyHolder.VIEW_END_POINT);
canvas.drawLine(leftThumbCenter.x, leftThumbCenter.y, rightThumbCenter.x, rightThumbCenter.y, instrumentation.getPaint(PoolKeyHolder.LINE_PAINT));
canvas.drawLine(viewStartPoint.x, viewStartPoint.y, leftThumbCenter.x, leftThumbCenter.y, instrumentation.getPaint(PoolKeyHolder.FILLED_LINE_PAINT));
canvas.drawLine(viewEndPoint.x, viewEndPoint.y, rightThumbCenter.x, rightThumbCenter.y, instrumentation.getPaint(PoolKeyHolder.FILLED_LINE_PAINT));
drawThumbs(canvas);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
setupStartupPoints();
}
@Override
public boolean onTouchEvent(final MotionEvent event) {
getParent().requestDisallowInterceptTouchEvent(true);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
boolean leftThumbTouched =
inBoundsOfPoint(
event,
instrumentation.getPoint(PoolKeyHolder.LEFT_THUMB_CENTER),
instrumentation.getSize(PoolKeyHolder.LEFT_THUMB_SIZE));
boolean rightThumbTouched =
inBoundsOfPoint(
event,
instrumentation.getPoint(PoolKeyHolder.RIGHT_THUMB_CENTER),
instrumentation.getSize(PoolKeyHolder.RIGHT_THUMB_SIZE));
if (leftThumbTouched && !rightThumbTouched) {
currentDraggingHolder = instrumentation.getDraggingHolder(PoolKeyHolder.LEFT_THUMB_HOLDER);
currentDraggingHolder.setDraggingNow(true);
lastDraggingHolder = currentDraggingHolder;
} else if (!leftThumbTouched && rightThumbTouched) {
currentDraggingHolder = instrumentation.getDraggingHolder(PoolKeyHolder.RIGHT_THUMB_HOLDER);
currentDraggingHolder.setDraggingNow(true);
lastDraggingHolder = currentDraggingHolder;
} else if (leftThumbTouched) {
currentDraggingHolder = instrumentation.findNearestObject(event.getX(), event.getY());
currentDraggingHolder.setDraggingNow(true);
} else {
currentDraggingHolder = instrumentation.findNearestObject(event.getX(), event.getY());
currentDraggingHolder.setDraggingNow(true);
ValueAnimator valueAnimator = ValueAnimator.ofInt(currentDraggingHolder.getObjectCenter().x, (int) event.getX());
valueAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
valueAnimator
.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
currentDraggingHolder.move((int) valueAnimator.getAnimatedValue(), (int) event.getY());
invalidate();
}
});
valueAnimator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animator) {
currentDraggingHolder.setDraggingNow(true);
}
@Override
public void onAnimationEnd(Animator animator) {
currentDraggingHolder.setDraggingNow(false);
}
@Override
public void onAnimationCancel(Animator animator) {
}
@Override
public void onAnimationRepeat(Animator animator) {
}
});
valueAnimator.start();
}
}
break;
case MotionEvent.ACTION_MOVE: {
@MotionDirection.Direction int direction =
currentDraggingHolder == instrumentation.getDraggingHolder(PoolKeyHolder.LEFT_THUMB_HOLDER)
? MotionDirection.LEFT_TO_RIGHT : MotionDirection.RIGHT_TO_LEFT;
if (currentDraggingHolder == null) currentDraggingHolder = lastDraggingHolder;
if (currentDraggingHolder.isDraggingNow()
&& !instrumentation.moveWillIntersect(currentDraggingHolder, event, direction)
&& currentDraggingHolder.move((int) event.getX(), (int) event.getY())) {
invalidate();
}
}
break;
case MotionEvent.ACTION_UP: {
if (currentDraggingHolder != null && currentDraggingHolder.isDraggingNow()) {
currentDraggingHolder.setDraggingNow(false);
}
}
break;
}
return true;
}
public void clear(boolean withAnimation) {
final Point viewStartPoint = instrumentation.getPoint(PoolKeyHolder.VIEW_START_POINT);
final Point viewEndPoint = instrumentation.getPoint(PoolKeyHolder.VIEW_END_POINT);
final DraggingObjectHolder leftThumb = instrumentation.getDraggingHolder(PoolKeyHolder.LEFT_THUMB_HOLDER);
final DraggingObjectHolder rightThumb = instrumentation.getDraggingHolder(PoolKeyHolder.RIGHT_THUMB_HOLDER);
if (!withAnimation) {
leftThumb.move(viewStartPoint.x, viewStartPoint.y);
rightThumb.move(viewEndPoint.x, viewEndPoint.y);
invalidate();
} else {
ValueAnimator leftThumbAnimator = ValueAnimator.ofInt(leftThumb.getObjectCenter().x, viewStartPoint.x);
leftThumbAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
leftThumb.move((int) animation.getAnimatedValue(), leftThumb.getObjectCenter().y);
invalidate();
}
});
ValueAnimator rightThumbAnimator = ValueAnimator.ofInt(rightThumb.getObjectCenter().x, viewEndPoint.x);
rightThumbAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
rightThumb.move((int) animation.getAnimatedValue(), rightThumb.getObjectCenter().y);
invalidate();
}
});
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
animatorSet.playTogether(leftThumbAnimator, rightThumbAnimator);
animatorSet.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
leftThumb.setDraggingNow(true);
rightThumb.setDraggingNow(true);
}
@Override
public void onAnimationEnd(Animator animation) {
leftThumb.setDraggingNow(false);
rightThumb.setDraggingNow(false);
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
animatorSet.start();
}
}
public void clear() {
clear(false);
}
public void setPercentage(final double leftThumbDistancePercentage, final double rightThumbDistancePercentage) {
post(new Runnable() {
@Override
public void run() {
final Point viewStartPoint = instrumentation.getPoint(PoolKeyHolder.VIEW_START_POINT);
final Point viewEndPoint = instrumentation.getPoint(PoolKeyHolder.VIEW_END_POINT);
int viewWidth = viewEndPoint.x - viewStartPoint.x;
final DraggingObjectHolder leftThumb = instrumentation.getDraggingHolder(PoolKeyHolder.LEFT_THUMB_HOLDER);
final DraggingObjectHolder rightThumb = instrumentation.getDraggingHolder(PoolKeyHolder.RIGHT_THUMB_HOLDER);
leftThumb.move(instrumentation.getMeasurementCalculator().convertWidth(leftThumbDistancePercentage, viewWidth, MotionDirection.LEFT_TO_RIGHT), leftThumb.getObjectCenter().y, false);
rightThumb.move(instrumentation.getMeasurementCalculator().convertWidth(rightThumbDistancePercentage, viewWidth, MotionDirection.RIGHT_TO_LEFT), rightThumb.getObjectCenter().y, false);
invalidate();
}
});
}
@Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
TempSavedState tempSavedState = new TempSavedState(superState);
Point leftThumbCenter = instrumentation.getPoint(PoolKeyHolder.LEFT_THUMB_CENTER);
tempSavedState.writePointToSave(PoolKeyHolder.LEFT_THUMB_CENTER, leftThumbCenter);
Point rightThumbCenter = instrumentation.getPoint(PoolKeyHolder.RIGHT_THUMB_CENTER);
tempSavedState.writePointToSave(PoolKeyHolder.RIGHT_THUMB_CENTER, rightThumbCenter);
double leftPercentage = instrumentation.getDraggingHolder(PoolKeyHolder.LEFT_THUMB_HOLDER).getPercentage();
if (Double.compare(leftPercentage, 0.0d) == 0) {
leftPercentage = instrumentation.getMeasurementCalculator().calculateDragPercentage(leftThumbCenter.x, getWidth(), MotionDirection.LEFT_TO_RIGHT);
}
tempSavedState.writePositionPercentage(PoolKeyHolder.LEFT_THUMB_CENTER, leftPercentage);
double rightPercentage = instrumentation.getDraggingHolder(PoolKeyHolder.RIGHT_THUMB_HOLDER).getPercentage();
if (Double.compare(rightPercentage, 0.0d) == 0) {
rightPercentage = instrumentation.getMeasurementCalculator().calculateDragPercentage(rightThumbCenter.x, getWidth(), MotionDirection.RIGHT_TO_LEFT);
}
tempSavedState.writePositionPercentage(PoolKeyHolder.RIGHT_THUMB_CENTER, rightPercentage);
tempSavedState.setLastDraggingHolder(currentDraggingHolder == instrumentation.getDraggingHolder(PoolKeyHolder.LEFT_THUMB_HOLDER)
? PoolKeyHolder.LEFT_THUMB_HOLDER
: PoolKeyHolder.RIGHT_THUMB_HOLDER);
return tempSavedState;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (!(state instanceof TempSavedState)) {
super.onRestoreInstanceState(state);
return;
}
TempSavedState savedState = (TempSavedState) state;
super.onRestoreInstanceState(savedState.getSuperState());
Point leftThumbSavedPoint = savedState.getSavedPoint(PoolKeyHolder.LEFT_THUMB_CENTER);
Point rightThumbSavedPoint = savedState.getSavedPoint(PoolKeyHolder.RIGHT_THUMB_CENTER);
Point leftThumb = instrumentation.getPoint(PoolKeyHolder.LEFT_THUMB_CENTER);
Point rightThumb = instrumentation.getPoint(PoolKeyHolder.RIGHT_THUMB_CENTER);
instrumentation.setThumbDraggedPercentage(PoolKeyHolder.LEFT_THUMB_DRAGGED_PERCENTAGE,
savedState.getPercentage(PoolKeyHolder.LEFT_THUMB_CENTER));
instrumentation.setThumbDraggedPercentage(PoolKeyHolder.RIGHT_THUMB_DRAGGED_PERCENTAGE,
savedState.getPercentage(PoolKeyHolder.RIGHT_THUMB_CENTER));
DrawingInstrumentation.copyPoint(leftThumbSavedPoint, leftThumb);
DrawingInstrumentation.copyPoint(rightThumbSavedPoint, rightThumb);
@PoolKeyHolder.DraggingHoldersKeys int lastDraggedHolderKey = savedState.getLastDraggingHolder();
lastDraggingHolder = instrumentation.getDraggingHolder(lastDraggedHolderKey);
}
private void parseAttributes(Context context, AttributeSet attributeSet, int defStyleAttr) {
TypedArray typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.DualSeekBar, defStyleAttr, 0);
int leftThumbDrawableRes = typedArray.getResourceId(R.styleable.DualSeekBar_left_thumb_icon, R.drawable.circle_filter);
int rightThumbDrawableRes = typedArray.getResourceId(R.styleable.DualSeekBar_right_thumb_icon, R.drawable.circle_filter);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(context.getResources(), leftThumbDrawableRes, options);
int leftThumbWidth = options.outWidth;
int leftThumbHeight = options.outHeight;
BitmapFactory.decodeResource(context.getResources(), rightThumbDrawableRes, options);
int rightThumbWidth = options.outWidth;
int rightThumbHeight = options.outHeight;
int thumbWidth = Math.max(leftThumbWidth, rightThumbWidth);
int thumbHeight = Math.max(leftThumbHeight, rightThumbHeight);
if (typedArray.hasValue(R.styleable.DualSeekBar_thumb_width)) {
thumbWidth = typedArray.getDimensionPixelSize(R.styleable.DualSeekBar_thumb_width, thumbWidth);
}
if (typedArray.hasValue(R.styleable.DualSeekBar_thumb_height)) {
thumbHeight = typedArray.getDimensionPixelSize(R.styleable.DualSeekBar_thumb_height, thumbHeight);
}
leftThumbDrawable = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(context.getResources(), leftThumbDrawableRes), thumbWidth, thumbHeight, true);
rightThumbDrawable = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(context.getResources(), rightThumbDrawableRes), thumbWidth, thumbHeight, true);
Size leftThumbSize = instrumentation.getSize(PoolKeyHolder.LEFT_THUMB_SIZE);
leftThumbSize.setWidth(leftThumbDrawable.getWidth());
leftThumbSize.setHeight(leftThumbDrawable.getHeight());
Size rightThumbSize = instrumentation.getSize(PoolKeyHolder.RIGHT_THUMB_SIZE);
rightThumbSize.setWidth(rightThumbDrawable.getWidth());
rightThumbSize.setHeight(rightThumbDrawable.getHeight());
minimumHeight = Math.max(leftThumbDrawable.getHeight(), rightThumbDrawable.getHeight());
int lineColor = typedArray.getColor(R.styleable.DualSeekBar_line_color, getPrimaryColor(context));
int filledLineColor = typedArray.getColor(R.styleable.DualSeekBar_filled_line_color, getAccentColor(context));
instrumentation.getPaint(PoolKeyHolder.LINE_PAINT).setColor(lineColor);
instrumentation.getPaint(PoolKeyHolder.LINE_PAINT).setStrokeWidth(10f);
instrumentation.getPaint(PoolKeyHolder.FILLED_LINE_PAINT).setStrokeWidth(6f);
instrumentation.getPaint(PoolKeyHolder.FILLED_LINE_PAINT).setColor(filledLineColor);
typedArray.recycle();
}
private
@ColorInt
int getAccentColor(Context context) {
TypedValue typedValue = new TypedValue();
TypedArray a = context.obtainStyledAttributes(typedValue.data, new int[]{R.attr.colorAccent});
int color = a.getColor(0, 0);
a.recycle();
return color;
}
private
@ColorInt
int getPrimaryColor(Context context) {
TypedValue typedValue = new TypedValue();
TypedArray a = context.obtainStyledAttributes(typedValue.data, new int[]{R.attr.colorPrimary});
int color = a.getColor(0, 0);
a.recycle();
return color;
}
private void drawThumbs(Canvas canvas) {
Point leftThumbCenter = instrumentation.getPoint(PoolKeyHolder.LEFT_THUMB_CENTER);
Point rightThumbCenter = instrumentation.getPoint(PoolKeyHolder.RIGHT_THUMB_CENTER);
drawBitmapAtCenter(canvas, leftThumbDrawable, leftThumbCenter);
drawBitmapAtCenter(canvas, rightThumbDrawable, rightThumbCenter);
}
private boolean inBoundsOfPoint(MotionEvent event, Point thumbCenter, Size size) {
float eventX = event.getX();
float eventY = event.getY();
int leftBound = thumbCenter.x - size.getWidth() / 2;
int rightBound = thumbCenter.x + size.getWidth() / 2;
int topBound = thumbCenter.y - size.getHeight() / 2;
int bottomBound = thumbCenter.y + size.getHeight() / 2;
return (eventX > leftBound && eventX < rightBound) && (eventY > topBound && eventY < bottomBound);
// int radius = Math.max(size.getWidth() / 2, size.getHeight() / 2);
// return Math.pow((eventX - thumbCenter.x), 2) + Math.pow((eventY - thumbCenter.y), 2) < Math.pow(radius, 2);
}
private void drawBitmapAtCenter(Canvas canvas, Bitmap bitmap, Point center) {
canvas.drawBitmap(bitmap, center.x - bitmap.getWidth() / 2, center.y - bitmap.getHeight() / 2, null);
}
private void setupStartupPoints() {
int viewStartX = 0 + leftThumbDrawable.getWidth() / 2;
int viewStartY = getHeight() / 2;
int viewEndX = getWidth() - leftThumbDrawable.getWidth() / 2;
int viewEndY = viewStartY;
Point viewStartPoint = instrumentation.getPoint(PoolKeyHolder.VIEW_START_POINT);
Point viewEndPoint = instrumentation.getPoint(PoolKeyHolder.VIEW_END_POINT);
viewStartPoint.x = viewStartX;
viewStartPoint.y = viewStartY;
viewEndPoint.x = viewEndX;
viewEndPoint.y = viewEndY;
Point leftThumbCenter = instrumentation.getPoint(PoolKeyHolder.LEFT_THUMB_CENTER);
double lastDraggedLeftPercentage = instrumentation.getThumbDraggedPercentage(PoolKeyHolder.LEFT_THUMB_DRAGGED_PERCENTAGE);
if (leftThumbCenter.x == -1) {
if (Double.compare(lastDraggedLeftPercentage, 0.0d) != 0) {
leftThumbCenter.x = instrumentation.getMeasurementCalculator().convertWidth(
lastDraggedLeftPercentage,
getWidth(),
MotionDirection.LEFT_TO_RIGHT);
} else {
leftThumbCenter.x = viewStartX;
leftThumbCenter.y = viewStartY;
}
}
Point rightThumbCenter = instrumentation.getPoint(PoolKeyHolder.RIGHT_THUMB_CENTER);
double lastDraggedRightPercentage = instrumentation.getThumbDraggedPercentage(PoolKeyHolder.RIGHT_THUMB_DRAGGED_PERCENTAGE);
if (rightThumbCenter.x == -1) {
if (Double.compare(lastDraggedRightPercentage, 0.0d) != 0) {
rightThumbCenter.x = instrumentation.getMeasurementCalculator().convertWidth(
lastDraggedRightPercentage,
getWidth(),
MotionDirection.RIGHT_TO_LEFT);
} else {
rightThumbCenter.x = viewEndX;
rightThumbCenter.y = viewEndY;
}
}
if (leftThumbCenter.x < viewStartX) leftThumbCenter.x = viewStartX;
if (rightThumbCenter.x > viewEndX) rightThumbCenter.x = viewEndX;
//Set critical points of dragging(for both thumbs)
DraggingObjectHolder leftThumbHolder = instrumentation.getDraggingHolder(PoolKeyHolder.LEFT_THUMB_HOLDER);
leftThumbHolder.setCriticalLeftPoint(viewStartX, viewStartY);
leftThumbHolder.setCriticalRightPoint(viewEndX, viewEndY);
DraggingObjectHolder rightThumbHolder = instrumentation.getDraggingHolder(PoolKeyHolder.RIGHT_THUMB_HOLDER);
rightThumbHolder.setCriticalLeftPoint(viewStartX, viewStartY);
rightThumbHolder.setCriticalRightPoint(viewEndX, viewEndY);
}
private static class TempSavedState extends View.BaseSavedState {
private Point leftThumbCoordinate;
private Point rightThumbCoordinate;
private double leftThumbDragPercentage;
private double rightThumbDragPercentage;
private
@PoolKeyHolder.DraggingHoldersKeys
int lastDraggingHolder;
public TempSavedState(Parcelable superState) {
super(superState);
}
private TempSavedState(Parcel in) {
super(in);
this.leftThumbCoordinate = new Point(in.readInt(), in.readInt());
this.rightThumbCoordinate = new Point(in.readInt(), in.readInt());
this.leftThumbDragPercentage = in.readInt();
this.rightThumbDragPercentage = in.readInt();
}
public int getLastDraggingHolder() {
return lastDraggingHolder;
}
public void setLastDraggingHolder(@PoolKeyHolder.DraggingHoldersKeys int lastDraggingHolder) {
this.lastDraggingHolder = lastDraggingHolder;
}
public Point getSavedPoint(@PoolKeyHolder.PointKeys int key) {
if (key == PoolKeyHolder.LEFT_THUMB_CENTER) {
return leftThumbCoordinate;
} else if (key == PoolKeyHolder.RIGHT_THUMB_CENTER) {
return rightThumbCoordinate;
} else {
throw new IllegalArgumentException("Unsupported key");
}
}
public double getPercentage(int key) {
if (key == PoolKeyHolder.LEFT_THUMB_CENTER) {
return leftThumbDragPercentage;
} else if (key == PoolKeyHolder.RIGHT_THUMB_CENTER) {
return rightThumbDragPercentage;
} else {
throw new IllegalArgumentException("Unsupported key");
}
}
public void writePointToSave(@PoolKeyHolder.PointKeys int key, Point value) {
if (key == PoolKeyHolder.LEFT_THUMB_CENTER) {
leftThumbCoordinate = value;
} else if (key == PoolKeyHolder.RIGHT_THUMB_CENTER) {
rightThumbCoordinate = value;
} else {
throw new IllegalArgumentException("Unsupported key");
}
}
public void writePositionPercentage(@PoolKeyHolder.PointKeys int key, double percentage) {
if (key == PoolKeyHolder.LEFT_THUMB_CENTER) {
leftThumbDragPercentage = percentage;
} else if (key == PoolKeyHolder.RIGHT_THUMB_CENTER) {
rightThumbDragPercentage = percentage;
} else {
throw new IllegalArgumentException("Unsupported key");
}
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(leftThumbCoordinate.x);
out.writeInt(leftThumbCoordinate.y);
out.writeInt(rightThumbCoordinate.x);
out.writeInt(rightThumbCoordinate.y);
out.writeDouble(leftThumbDragPercentage);
out.writeDouble(rightThumbDragPercentage);
}
public static final Parcelable.Creator<TempSavedState> CREATOR =
new Parcelable.Creator<TempSavedState>() {
public TempSavedState createFromParcel(Parcel in) {
return new TempSavedState(in);
}
public TempSavedState[] newArray(int size) {
return new TempSavedState[size];
}
};
}
}
| apache-2.0 |
iritgo/iritgo-aktera | aktera-aktario-aktario/src/main/java/de/iritgo/aktera/aktario/akteraconnector/DeleteAkteraObjectRequest.java | 2837 | /**
* This file is part of the Iritgo/Aktera Framework.
*
* Copyright (C) 2005-2011 Iritgo Technologies.
* Copyright (C) 2003-2005 BueroByte GbR.
*
* Iritgo 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 de.iritgo.aktera.aktario.akteraconnector;
import de.iritgo.aktario.core.Engine;
import de.iritgo.aktario.framework.action.ActionTools;
import de.iritgo.aktario.framework.base.DataObject;
import de.iritgo.aktario.framework.base.action.FrameworkInputStream;
import de.iritgo.aktario.framework.base.action.FrameworkOutputStream;
import de.iritgo.aktario.framework.base.action.FrameworkServerAction;
import java.io.IOException;
/**
*
*/
public class DeleteAkteraObjectRequest extends FrameworkServerAction
{
private String model;
private String keelObjectUniqueId;
private long dataObjectUniqueId;
private String onScreenUniqueId;
/**
* Standard constructor
*/
public DeleteAkteraObjectRequest()
{
}
/**
* Standard constructor
*/
public DeleteAkteraObjectRequest(String model, DataObject dataObject, String onScreenUniqueId)
{
this.model = model;
this.keelObjectUniqueId = dataObject.getStringAttribute("keelObjectId");
this.dataObjectUniqueId = dataObject.getUniqueId();
this.onScreenUniqueId = onScreenUniqueId;
}
/**
* Read the attributes from the given stream.
*/
public void readObject(FrameworkInputStream stream) throws IOException, ClassNotFoundException
{
model = stream.readUTF();
keelObjectUniqueId = stream.readUTF();
dataObjectUniqueId = stream.readLong();
onScreenUniqueId = stream.readUTF();
}
/**
* Write the attributes to the given stream.
*/
public void writeObject(FrameworkOutputStream stream) throws IOException
{
stream.writeUTF(model);
stream.writeUTF(keelObjectUniqueId);
stream.writeLong(dataObjectUniqueId);
stream.writeUTF(onScreenUniqueId);
}
/**
* Perform the action.
*/
public void perform()
{
ConnectorServerManager connectorServerManager = (ConnectorServerManager) Engine.instance().getManagerRegistry()
.getManager("ConnectorServerManager");
connectorServerManager.deleteKeelObject(model, keelObjectUniqueId, userUniqueId);
ActionTools.sendToClient(userUniqueId, new DeleteAkteraObjectResponse(model, keelObjectUniqueId,
dataObjectUniqueId, onScreenUniqueId));
}
}
| apache-2.0 |
SuperMap/STC2015_myTracks | src/com/supermap/mytracks/bean/RequestParam.java | 3823 | package com.supermap.mytracks.bean;
import java.util.List;
public class RequestParam {
private int pageSize = -1;
private String orderField = null;
private String orderType = null;
private int currentPage = -1;
private String tag = null;
private String joinTypes = null;
private String startTime = null;
private String endTime = null;
private String updateStart = null;
private String updateEnd = null;
private String visitStart = null;
private String visitEnd = null;
private String keyword = null;
private String userNames = null;
private String mapStatus = "PUBLISHED"; //"SAVED"
private boolean suggest = false;
private String sourceTypes;//根据地图来源类型过滤,包括:SUPERMAP_REST,MAPVIEWER,WMS,WMTS
private int epsgCode=-1;
private boolean unique = false;
public String getUserNames() {
return userNames;
}
public void setUserNames(String userNames) {
this.userNames = userNames;
}
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
public String getTag() {
return tag;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public String getUpdateStart() {
return updateStart;
}
public void setUpdateStart(String updateStart) {
this.updateStart = updateStart;
}
public String getUpdateEnd() {
return updateEnd;
}
public void setUpdateEnd(String updateEnd) {
this.updateEnd = updateEnd;
}
public String getVisitStart() {
return visitStart;
}
public void setVisitStart(String visitStart) {
this.visitStart = visitStart;
}
public String getVisitEnd() {
return visitEnd;
}
public void setVisitEnd(String visitEnd) {
this.visitEnd = visitEnd;
}
public int getPageSize() {
return pageSize;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getOrderField() {
return orderField;
}
public void setOrderField(String orderField) {
this.orderField = orderField;
}
public String getOrderType() {
return orderType;
}
public void setOrderType(String orderType) {
this.orderType = orderType;
}
public int getCurrentPage() {
return this.currentPage;
}
public void setCurrentPage(int page) {
this.currentPage = page;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public String getJoinTypes() {
return joinTypes;
}
public void setJoinTypes(String joinTypes) {
this.joinTypes = joinTypes;
}
public String getMapStatus() {
return mapStatus;
}
public void setMapStatus(String mapStatus) {
this.mapStatus = mapStatus;
}
public boolean isSuggest() {
return suggest;
}
public void setSuggest(boolean suggest) {
this.suggest = suggest;
}
public String getSourceTypes() {
return sourceTypes;
}
public void setSourceTypes(String sourceTypes) {
this.sourceTypes = sourceTypes;
}
public int getEpsgCode() {
return epsgCode;
}
public void setEpsgCode(int epsgCode) {
this.epsgCode = epsgCode;
}
public boolean isUnique() {
return unique;
}
public void setUnique(boolean unique) {
this.unique = unique;
}
}
| apache-2.0 |
BlesseNtumble/GalaxySpace | src/main/java/galaxyspace/core/events/GSEventHandler.java | 45434 | package galaxyspace.core.events;
import java.util.ArrayList;
import java.util.List;
import asmodeuscore.api.dimension.IAdvancedSpace;
import asmodeuscore.api.dimension.IProviderFreeze;
import asmodeuscore.api.item.IItemSpaceFood;
import asmodeuscore.core.event.PressureEvent;
import asmodeuscore.core.event.RadiationEvent;
import asmodeuscore.core.handler.LightningStormHandler;
import galaxyspace.GalaxySpace;
import galaxyspace.api.item.IJetpackArmor;
import galaxyspace.core.GSBlocks;
import galaxyspace.core.GSItems;
import galaxyspace.core.configs.GSConfigCore;
import galaxyspace.core.configs.GSConfigDimensions;
import galaxyspace.core.configs.GSConfigEnergy;
import galaxyspace.core.configs.GSConfigSchematics;
import galaxyspace.core.handler.capabilities.GSCapabilityProviderStats;
import galaxyspace.core.handler.capabilities.GSCapabilityProviderStatsClient;
import galaxyspace.core.handler.capabilities.GSCapabilityStatsHandler;
import galaxyspace.core.handler.capabilities.GSStatsCapability;
import galaxyspace.core.handler.capabilities.StatsCapability;
import galaxyspace.core.network.packet.GSPacketSimple;
import galaxyspace.core.network.packet.GSPacketSimple.GSEnumSimplePacket;
import galaxyspace.core.prefab.entities.EntityAstroWolf;
import galaxyspace.core.prefab.items.rockets.ItemTier4Rocket;
import galaxyspace.core.prefab.items.rockets.ItemTier5Rocket;
import galaxyspace.core.prefab.items.rockets.ItemTier6Rocket;
import galaxyspace.core.util.GSDamageSource;
import galaxyspace.core.util.GSUtils;
import galaxyspace.systems.ACentauriSystem.core.configs.ACConfigCore;
import galaxyspace.systems.ACentauriSystem.core.configs.ACConfigDimensions;
import galaxyspace.systems.BarnardsSystem.core.configs.BRConfigCore;
import galaxyspace.systems.BarnardsSystem.core.configs.BRConfigDimensions;
import galaxyspace.systems.SolarSystem.moons.titan.dimension.WorldProviderTitan;
import galaxyspace.systems.SolarSystem.planets.kuiperbelt.dimension.WorldProviderKuiperBelt;
import galaxyspace.systems.SolarSystem.planets.mars.dimension.WorldProviderMars_WE;
import galaxyspace.systems.SolarSystem.planets.overworld.items.ItemBasicGS;
import galaxyspace.systems.SolarSystem.planets.overworld.items.armor.ItemSpaceSuit;
import galaxyspace.systems.SolarSystem.planets.overworld.items.armor.ItemThermalPaddingBase;
import galaxyspace.systems.SolarSystem.planets.overworld.items.tools.ItemPlasmaSword;
import galaxyspace.systems.SolarSystem.planets.overworld.tile.TileEntityGravitationModule;
import galaxyspace.systems.SolarSystem.planets.overworld.tile.TileEntityPlanetShield;
import galaxyspace.systems.SolarSystem.planets.overworld.tile.TileEntityRadiationStabiliser;
import micdoodle8.mods.galacticraft.api.GalacticraftRegistry;
import micdoodle8.mods.galacticraft.api.event.ZeroGravityEvent;
import micdoodle8.mods.galacticraft.api.event.wgen.GCCoreEventPopulate;
import micdoodle8.mods.galacticraft.api.inventory.AccessInventoryGC;
import micdoodle8.mods.galacticraft.api.inventory.IInventoryGC;
import micdoodle8.mods.galacticraft.api.item.EnumExtendedInventorySlot;
import micdoodle8.mods.galacticraft.api.prefab.entity.EntityTieredRocket;
import micdoodle8.mods.galacticraft.api.vector.BlockVec3Dim;
import micdoodle8.mods.galacticraft.api.vector.Vector3;
import micdoodle8.mods.galacticraft.api.world.IGalacticraftWorldProvider;
import micdoodle8.mods.galacticraft.api.world.ITeleportType;
import micdoodle8.mods.galacticraft.core.GCBlocks;
import micdoodle8.mods.galacticraft.core.GCItems;
import micdoodle8.mods.galacticraft.core.entities.EntityLanderBase;
import micdoodle8.mods.galacticraft.core.entities.EntityMeteor;
import micdoodle8.mods.galacticraft.core.entities.player.GCPlayerHandler;
import micdoodle8.mods.galacticraft.core.entities.player.GCPlayerHandler.EnumModelPacketType;
import micdoodle8.mods.galacticraft.core.entities.player.GCPlayerHandler.ThermalArmorEvent;
import micdoodle8.mods.galacticraft.core.entities.player.GCPlayerStats;
import micdoodle8.mods.galacticraft.core.items.ItemTier1Rocket;
import micdoodle8.mods.galacticraft.core.util.CompatibilityManager;
import micdoodle8.mods.galacticraft.core.util.ConfigManagerCore;
import micdoodle8.mods.galacticraft.core.util.EnumColor;
import micdoodle8.mods.galacticraft.core.util.FluidUtil;
import micdoodle8.mods.galacticraft.core.util.GCCoreUtil;
import micdoodle8.mods.galacticraft.core.util.OxygenUtil;
import micdoodle8.mods.galacticraft.core.util.WorldUtil;
import micdoodle8.mods.galacticraft.core.world.gen.WorldGenMinableMeta;
import micdoodle8.mods.galacticraft.core.wrappers.IFluidHandlerWrapper;
import micdoodle8.mods.galacticraft.planets.asteroids.items.ItemTier3Rocket;
import micdoodle8.mods.galacticraft.planets.mars.blocks.MarsBlocks;
import micdoodle8.mods.galacticraft.planets.mars.dimension.WorldProviderMars;
import micdoodle8.mods.galacticraft.planets.mars.items.ItemTier2Rocket;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.passive.EntityWolf;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.init.MobEffects;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemFood;
import net.minecraft.item.ItemSeeds;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.play.server.SPacketRespawn;
import net.minecraft.potion.PotionEffect;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.world.DimensionType;
import net.minecraft.world.GameType;
import net.minecraft.world.World;
import net.minecraft.world.WorldProvider;
import net.minecraft.world.WorldServer;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.gen.feature.WorldGenerator;
import net.minecraftforge.common.config.Config.Type;
import net.minecraftforge.common.config.ConfigManager;
import net.minecraftforge.event.AttachCapabilitiesEvent;
import net.minecraftforge.event.entity.living.LivingDamageEvent;
import net.minecraftforge.event.entity.living.LivingEvent.LivingUpdateEvent;
import net.minecraftforge.event.entity.living.LivingFallEvent;
import net.minecraftforge.event.entity.player.AttackEntityEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.event.world.BlockEvent;
import net.minecraftforge.fluids.capability.IFluidHandler;
import net.minecraftforge.fml.client.event.ConfigChangedEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import net.minecraftforge.oredict.OreDictionary;
public class GSEventHandler {
private static List<BlockToChange> block_to_change = new ArrayList<BlockToChange>();
private static List<ItemsToChange> items_to_change = new ArrayList<ItemsToChange>();
static {
OreDictionary.getOres("treeLeaves").forEach((ItemStack stack) -> {
items_to_change.add(new ItemsToChange(stack, Blocks.AIR.getDefaultState()).setTempCheck(true).setOxygenCheck(true));
});
OreDictionary.getOres("treeSapling").forEach((ItemStack stack) -> {
//block_to_change.add(new BlockToChange(Block.getBlockFromItem(stack.getItem()).getDefaultState(), Blocks.AIR.getDefaultState(), Blocks.AIR.getDefaultState(), 0.0F, true));
items_to_change.add(new ItemsToChange(stack, Blocks.DEADBUSH.getDefaultState()).setTempCheck(true).setOxygenCheck(true));
});
items_to_change.add(new ItemsToChange(new ItemStack(Blocks.FURNACE), Blocks.AIR.getDefaultState()).setOxygenCheck(true));
items_to_change.add(new ItemsToChange(new ItemStack(Items.WATER_BUCKET), Blocks.AIR.getDefaultState()).setTempCheck(true).setOxygenCheck(false));
block_to_change.add(new BlockToChange(Blocks.WATER.getDefaultState(), Blocks.AIR.getDefaultState(), Blocks.ICE.getDefaultState(), 0.0F, true).setParticle("waterbubbles").setOxygenCheck(false));
block_to_change.add(new BlockToChange(Blocks.LEAVES.getStateFromMeta(0), Blocks.AIR.getDefaultState(), Blocks.AIR.getDefaultState(), 0.5F, true).setParticle("waterbubbles"));
}
@SubscribeEvent
public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event) {
if (event.getModID().equals(GalaxySpace.MODID)) {
ConfigManager.sync(GalaxySpace.MODID, Type.INSTANCE);
GSConfigCore.config.save();
GSConfigDimensions.config.save();
GSConfigSchematics.config.save();
GSConfigEnergy.config.save();
ACConfigCore.config.save();
ACConfigDimensions.config.save();
BRConfigCore.config.save();
BRConfigDimensions.config.save();
GSConfigCore.syncConfig(true);
GSConfigDimensions.syncConfig(true);
GSConfigSchematics.syncConfig(true);
GSConfigEnergy.syncConfig(true);
ACConfigCore.syncConfig(true);
ACConfigDimensions.syncConfig(true);
BRConfigCore.syncConfig(true);
BRConfigDimensions.syncConfig(true);
GalaxySpace.debug = GSConfigCore.enableDebug;
GalaxySpace.instance.debug("reload");
}
}
@SubscribeEvent
public void onAttachCapability(AttachCapabilitiesEvent<Entity> event)
{
if (event.getObject() instanceof EntityPlayerMP)
{
event.addCapability(GSCapabilityStatsHandler.GS_PLAYER_PROPERTIES, new GSCapabilityProviderStats((EntityPlayerMP) event.getObject()));
}
else if (event.getObject() instanceof EntityPlayer && ((EntityPlayer)event.getObject()).world.isRemote)
{
this.onAttachCapabilityClient(event);
}
}
@SideOnly(Side.CLIENT)
private void onAttachCapabilityClient(AttachCapabilitiesEvent<Entity> event)
{
if (event.getObject() instanceof EntityPlayerSP)
{
event.addCapability(GSCapabilityStatsHandler.GS_PLAYER_PROPERTIES_CLIENT, new GSCapabilityProviderStatsClient((EntityPlayerSP) event.getObject()));
}
}
@SubscribeEvent
public void onPlayerCloned(PlayerEvent.Clone event)
{
StatsCapability oldStats = GSStatsCapability.get(event.getOriginal());
StatsCapability newStats = GSStatsCapability.get(event.getEntityPlayer());
newStats.copyFrom(oldStats, !event.isWasDeath()|| event.getOriginal().world.getGameRules().getBoolean("keepInventory"));
}
/*
@SubscribeEvent
public void onPlayerJoinWorld(EntityJoinWorldEvent event)
{
if (event.getEntity() instanceof EntityPlayerMP)
{
GalaxySpace.packetPipeline.sendTo(new GSPacketSimple(GSEnumSimplePacket.C_UPDATE_WORLD, GCCoreUtil.getDimensionID(event.getEntity().getEntityWorld())), (EntityPlayerMP)event.getEntity());
}
}
*/
@SubscribeEvent
public void onPlayerLogin(PlayerLoggedInEvent event)
{
if (event.player instanceof EntityPlayerMP)
{
//GalaxySpace.packetPipeline.sendTo(new GSPacketSimple(GSEnumSimplePacket.C_UPDATE_WORLD, GCCoreUtil.getDimensionID(event.player.world)), (EntityPlayerMP)event.player);
StatsCapability stats = GSStatsCapability.get(event.player);
Integer[] ids = new Integer[256];
for(int i = 0; i < stats.getKnowledgeResearches().length; i++) {
ids[i] = stats.getKnowledgeResearches()[i];
}
GalaxySpace.packetPipeline.sendTo(new GSPacketSimple(GSEnumSimplePacket.C_UPDATE_RESEARCHES, GCCoreUtil.getDimensionID(event.player.world), new Object[] {ids}), (EntityPlayerMP)event.player);
}
}
@SubscribeEvent
public void onFall(LivingFallEvent e) {
if (e.getEntityLiving() instanceof EntityPlayer) {
ItemStack chest = ((EntityPlayer) e.getEntityLiving()).getItemStackFromSlot(EntityEquipmentSlot.CHEST);
e.setCanceled(chest != null && chest.getItem() instanceof IJetpackArmor && ((IJetpackArmor) chest.getItem()).canFly(chest, (EntityPlayer) e.getEntityLiving()) && ((IJetpackArmor) chest.getItem()).isActivated(chest));
}
}
@SubscribeEvent
public void onAttack(AttackEntityEvent e)
{
}
@SubscribeEvent
public void onDamage(LivingDamageEvent e) {
if(e.getSource().getTrueSource() instanceof EntityPlayerMP)
{
EntityPlayerMP player = (EntityPlayerMP) e.getSource().getTrueSource();
ItemStack stack = player.getHeldItemMainhand();
if(stack.getItem() instanceof ItemPlasmaSword && stack.getTagCompound().getFloat(ItemPlasmaSword.heat) >= 10.0F) {
player.sendMessage(new TextComponentString(EnumColor.DARK_RED + GCCoreUtil.translate("gui.message.overheat")));
e.setCanceled(true);
}
}
if(e.getEntityLiving() instanceof EntityPlayerMP)
{
EntityPlayerMP player = (EntityPlayerMP) e.getEntityLiving();
World world = player.getEntityWorld();
if(!world.isRemote)
{
float protect = 0.0F;
for(ItemStack s : player.inventory.armorInventory)
{
if(s.getItem() instanceof ItemSpaceSuit && s.hasTagCompound())
{
if(((ItemSpaceSuit)s.getItem()).getElectricityStored(s) > 5 && s.getTagCompound().hasKey("protection"))
protect += 0.1F;
}
}
e.setAmount(e.getAmount() - e.getAmount() * protect);
}
}
}
@SubscribeEvent
public void onSetBlock(SetBlockEvent e) {
if(e.world != null && !e.world.isRemote && e.world.provider instanceof IGalacticraftWorldProvider && e.pos != null && e.block != null)
{
float thermal = ((IGalacticraftWorldProvider)e.world.provider).getThermalLevelModifier();
AxisAlignedBB bb = new AxisAlignedBB(e.pos.getX()-1,e.pos.getY()-1,e.pos.getZ()-1, e.pos.getX()+1,e.pos.getY()+2,e.pos.getZ()+1);
for(BlockToChange block : block_to_change)
{
if(block.only_gs_dim && !(e.world.provider instanceof IProviderFreeze))
continue;
if(e.world.provider instanceof IProviderFreeze && !((IProviderFreeze)e.world.provider).isFreeze()) continue;
if(block.need_check_temp) {
if((e.block == block.state || e.block.getMaterial() == block.state.getMaterial()) && !OxygenUtil.isAABBInBreathableAirBlock(e.world, bb, true))
{
if(thermal <= -1.0F)
{
e.world.setBlockState(e.pos, block.cold_replaced);
e.setCanceled(true);
}
else if(thermal >= 1.5F) {
e.world.setBlockState(e.pos, block.hot_replaced);
block.spawnParticleHotTemp(e.world, e.pos);
e.setCanceled(true);
}
}
}
else
{
e.world.setBlockState(e.pos, block.cold_replaced);
block.spawnParticleHotTemp(e.world, e.pos);
e.setCanceled(true);
}
}
}
}
@SubscribeEvent
public void onInteract(PlayerInteractEvent.RightClickBlock event)
{
//Skip events triggered from Thaumcraft Golems and other non-players
if (event.getEntityPlayer() == null || event.getEntityPlayer().inventory == null || event.getPos() == null || (event.getPos().getX() == 0 && event.getPos().getY() == 0 && event.getPos().getZ() == 0))
{
return;
}
final World world = event.getEntityPlayer().world;
if (world == null) {
return;
}
final IBlockState state = world.getBlockState(event.getPos());
final Block block = state.getBlock();
ItemStack stack = event.getItemStack();
EntityPlayer player = event.getEntityPlayer();
if(world.isRemote)
{
}
if(!world.isRemote && !block.hasTileEntity(state))
{
if(CompatibilityManager.isIc2Loaded())
{
//IC2 WIND TURBINE
if(world.provider instanceof IGalacticraftWorldProvider && ((IGalacticraftWorldProvider)world.provider).hasNoAtmosphere() && ((IGalacticraftWorldProvider)world.provider).getWindLevel() <= 0.0F) {
if(stack.getItem() == Item.getByNameOrId("ic2:te") && (stack.getItemDamage() == 11 || stack.getItemDamage() == 21)) {
player.sendMessage(new TextComponentString(EnumColor.DARK_RED + GCCoreUtil.translate("gui.status.nowind.name") + "! " + GCCoreUtil.translate("gui.message.cant_place")));
event.setCanceled(true);
}
}
}
//ICE BUCKET
if(block == Blocks.ICE && stack.getItem() == Items.BUCKET)
{
stack.shrink(1);
player.inventory.addItemStackToInventory(new ItemStack(GSItems.BASIC, 1, 17));
world.setBlockToAir(event.getPos());
}
if(world.provider instanceof IGalacticraftWorldProvider && GSConfigCore.enableOxygenForPlantsAndFoods)
{
AxisAlignedBB bb = new AxisAlignedBB(event.getPos().up());
float thermal = ((IGalacticraftWorldProvider)world.provider).getThermalLevelModifier();
for(ItemsToChange ore : items_to_change)
{
if(stack.getItem().equals(ore.itemstack.getItem()) && !((IGalacticraftWorldProvider)world.provider).hasBreathableAtmosphere())
{
if(FluidUtil.isFilledContainer(stack) && world.getTileEntity(event.getPos()) != null)
if(world.getTileEntity(event.getPos()) instanceof IFluidHandlerWrapper || world.getTileEntity(event.getPos()) instanceof IFluidHandler)
return;
if(ore.need_check_oxygen)
{
if(!OxygenUtil.isAABBInBreathableAirBlock(world, bb, ore.need_check_temp && (thermal > 1.0F || thermal < -1.0F)))
{
player.sendMessage(new TextComponentString(EnumColor.DARK_RED + GCCoreUtil.translate("gui.message.needoxygen")));
event.setCanceled(true);
}
}
if(ore.need_check_temp)
{
if(!GSUtils.getThermalControl(world, event.getPos().up()) && (thermal > 1.0F || thermal < -1.0F))
{
player.sendMessage(new TextComponentString(EnumColor.DARK_RED + GCCoreUtil.translate("gui.message.needthermal")));
event.setCanceled(true);
}
}
if(ore.replaced != Blocks.AIR.getDefaultState())
if(world.getBlockState(event.getPos()).getBlock().isReplaceable(world, event.getPos()))
world.setBlockState(event.getPos(), ore.replaced);
else
world.setBlockState(event.getPos().up(), ore.replaced);
break;
}
}
if(stack.getItem() instanceof ItemSeeds && world.getBlockState(event.getPos()).getBlock() == Blocks.FARMLAND)
{
if(!OxygenUtil.isAABBInBreathableAirBlock(world, bb, true))
{
player.sendMessage(new TextComponentString(EnumColor.DARK_RED + GCCoreUtil.translate("gui.message.needoxygenthermal")));
event.setCanceled(true);
}
}
}
}
}
@SubscribeEvent
public void onEntityInteract(PlayerInteractEvent.EntityInteract event)
{
EntityPlayer player = event.getEntityPlayer();
if(!event.getWorld().isRemote) {
ItemStack stack = event.getItemStack();
//if(stack.isItemEqual(ItemBasicGS.BasicItems.ANIMAL_CELL.getItemStack()))
//{
//stack.setTagCompound(new NBTTagCompound());
//}
if(event.getTarget() instanceof EntityWolf && !(event.getTarget() instanceof EntityAstroWolf))
{
EntityWolf wolf = (EntityWolf) event.getTarget();
if(wolf.isTamed() && event.getItemStack().getItem() == GCItems.oxMask)
{
EntityAstroWolf astrowolf = new EntityAstroWolf(wolf.getEntityWorld());
astrowolf.setOwnerId(wolf.getOwnerId());
astrowolf.setTamed(wolf.isTamed());
astrowolf.setAngry(wolf.isAngry());
astrowolf.setHealth(wolf.getHealth());
astrowolf.getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH).setBaseValue(30.0D);
astrowolf.setSitting(wolf.isSitting());
astrowolf.setPositionAndRotation(wolf.posX, wolf.posY, wolf.posZ, wolf.rotationYaw, wolf.rotationPitch);
event.getTarget().setDead();
event.getWorld().spawnEntity(astrowolf);
}
}
}
}
@SubscribeEvent
public void onInteract(PlayerInteractEvent event)
{
World world = event.getWorld();
if (world == null) {
return;
}
EntityPlayer player = event.getEntityPlayer();
ItemStack i = event.getItemStack();
if(!world.isRemote && GalaxySpace.debug)
GalaxySpace.instance.debug(Item.REGISTRY.getNameForObject(i.getItem()) + " | " + i.getUnlocalizedName() + " | " + Biome.getBiome(Biome.getIdForBiome(world.getBiomeForCoordsBody(event.getPos()))));
if(!world.isRemote && GSConfigCore.enableOxygenForPlantsAndFoods && !player.capabilities.isCreativeMode)
{
if(world.provider instanceof IGalacticraftWorldProvider && !((IGalacticraftWorldProvider)world.provider).hasBreathableAtmosphere())
{
if(!OxygenUtil.isAABBInBreathableAirBlock(player, false) && checkFood(i))
{
player.sendMessage(new TextComponentString(EnumColor.DARK_RED + GCCoreUtil.translate("gui.message.needoxygen.food")));
event.setCancellationResult(EnumActionResult.FAIL);
event.setCanceled(true);
}
}
}
}
private boolean checkFood(ItemStack s)
{
return !s.isEmpty() && s.getItem() instanceof ItemFood && !(s.getItem() instanceof micdoodle8.mods.galacticraft.core.items.ItemFood) && !(s.getItem() instanceof IItemSpaceFood);
}
private void survivalMode(EntityPlayerMP player, int dimensionID) {
final GCPlayerStats stats = GCPlayerStats.get(player);
WorldServer worldOld = (WorldServer) player.world;
try {
worldOld.getPlayerChunkMap().removePlayer(player);
} catch (Exception e) {
}
worldOld.playerEntities.remove(player);
worldOld.updateAllPlayersSleepingFlag();
worldOld.loadedEntityList.remove(player);
worldOld.onEntityRemoved(player);
worldOld.getEntityTracker().untrack(player);
if (player.addedToChunk && worldOld.getChunkProvider().chunkExists(player.chunkCoordX, player.chunkCoordZ))
{
Chunk chunkOld = worldOld.getChunkFromChunkCoords(player.chunkCoordX, player.chunkCoordZ);
chunkOld.removeEntity(player);
chunkOld.setModified(true);
}
WorldServer worldNew = getStartWorld(worldOld, dimensionID);
int dimID = GCCoreUtil.getDimensionID(worldNew);
player.dimension = dimID;
player.connection.sendPacket(new SPacketRespawn(dimID, player.world.getDifficulty(), player.world.getWorldInfo().getTerrainType(), player.interactionManager.getGameType()));
worldNew.spawnEntity(player);
player.setWorld(worldNew);
player.mcServer.getPlayerList().preparePlayer(player, (WorldServer) worldOld);
player.interactionManager.setWorld((WorldServer) player.world);
final ITeleportType type = GalacticraftRegistry.getTeleportTypeForDimension(player.world.provider.getClass());
Vector3 spawnPos = type.getPlayerSpawnLocation((WorldServer) player.world, player);
ChunkPos pair = player.world.getChunkFromChunkCoords(spawnPos.intX() >> 4, spawnPos.intZ() >> 4).getPos();
((WorldServer) player.world).getChunkProvider().loadChunk(pair.x, pair.z);
player.setLocationAndAngles(spawnPos.x, spawnPos.y, spawnPos.z, player.rotationYaw, player.rotationPitch);
type.onSpaceDimensionChanged(player.world, player, false);
player.setSpawnChunk(new BlockPos(spawnPos.intX(), spawnPos.intY(), spawnPos.intZ()), true, GCCoreUtil.getDimensionID(player.world));
}
private WorldServer getStartWorld(WorldServer unchanged, int dimID)
{
if (ConfigManagerCore.challengeSpawnHandling)
{
WorldProvider wp = WorldUtil.getProviderForDimensionServer(dimID);
WorldServer worldNew = (wp == null) ? null : (WorldServer) wp.world;
if (worldNew != null)
{
return worldNew;
}
}
return unchanged;
}
@SubscribeEvent
public void onPortalCreated(BlockEvent.PortalSpawnEvent e)
{
World world = e.getWorld();
if(world != null) {
if(world.provider instanceof IGalacticraftWorldProvider) {
e.setCanceled(!((IGalacticraftWorldProvider)world.provider).netherPortalsOperational());
}
}
}
@SubscribeEvent
public void onEntityUpdate(LivingUpdateEvent event)
{
EntityLivingBase living = event.getEntityLiving();
World world = living.world;
if (living instanceof EntityPlayer) {
EntityPlayer player = (EntityPlayer) living;
ItemStack chest = ((EntityPlayer) living).getItemStackFromSlot(EntityEquipmentSlot.CHEST);
if (chest != null && chest.getItem() instanceof IJetpackArmor && !((EntityPlayer) living).onGround) {
if(((IJetpackArmor) chest.getItem()).canFly(chest, (EntityPlayer) living) && ((IJetpackArmor) chest.getItem()).isActivated(chest) && ((EntityPlayer) living).posY < 256)
{
((EntityPlayer) living).fallDistance = 0.0F;
((EntityPlayer) living).distanceWalkedModified = 0.6F;
GalaxySpace.proxy.resetPlayerInAirTime(((EntityPlayer) living));
((IJetpackArmor) chest.getItem()).decrementFuel(chest);
}
}
if(!player.capabilities.isCreativeMode) {
ItemStack held = player.getHeldItemMainhand();
if(held.getItem() instanceof ItemTier1Rocket
|| held.getItem() instanceof ItemTier2Rocket
|| held.getItem() instanceof ItemTier3Rocket
|| held.getItem() instanceof ItemTier4Rocket
|| held.getItem() instanceof ItemTier5Rocket
|| held.getItem() instanceof ItemTier6Rocket)
{
player.addPotionEffect(new PotionEffect(MobEffects.SLOWNESS, 10, 4));
}
}
}
if (living instanceof EntityPlayerMP)
{
EntityPlayerMP player = (EntityPlayerMP)living;
final GCPlayerStats stats = GCPlayerStats.get(player);
final StatsCapability gsstats = GSStatsCapability.get(player);
LightningStormHandler.spawnLightning(player);
if(BRConfigCore.enableBarnardsSystems && BRConfigDimensions.enableBarnardaC && BRConfigCore.survivalModeOnBarnarda && !gsstats.isBarnardaSurvivalMode()) {
//survivalMode(player, BRConfigDimensions.dimensionIDBarnardaC);
WorldUtil.transferEntityToDimension(player, BRConfigDimensions.dimensionIDBarnardaC, player.getServerWorld());
gsstats.setBarnardaSurvivalMode();
if (player.capabilities.isCreativeMode)
player.setGameType(GameType.SURVIVAL);
player.sendMessage(new TextComponentString(
EnumColor.BRIGHT_GREEN + "[BETA] Welcome in survival mode on Barnarda C."));
}
//this.updateSchematics(player, stats);
//this.throwMeteors(player);
//if(gs_stats.getKnowledgeResearch()[0] > 0)
//{
//GalaxySpace.debug(gs_stats.getKnowledgeResearch()[0] + "");
//}
if(world.rand.nextInt(50) <= 10 && !this.getProtectArmor(player) && world.provider instanceof WorldProviderTitan && world.isRaining() && world.canBlockSeeSky(player.getPosition()))
{
player.attackEntityFrom(GSDamageSource.acid, 1.5F);
}
if(player.world.provider instanceof WorldProviderKuiperBelt && player.posY <= -20)
{
player.connection.setPlayerLocation(player.posX, 188, player.posZ, player.rotationYaw, player.rotationPitch);
}
if(!player.capabilities.isCreativeMode && player.getHealth() <= 5.0F)
{
for(ItemStack stack : player.inventory.mainInventory)
{
if(stack.getItem() == GSItems.BASIC && stack.getItemDamage() == 18)
{
if(stack.hasTagCompound() && stack.getTagCompound().getBoolean("turnonoff"))
{
int[] pos = stack.getTagCompound().getIntArray("position");
if(pos != null && pos.length >= 3 && player.world.provider.getDimension() == pos[3]) {
player.sendMessage(new TextComponentString(EnumColor.AQUA + GCCoreUtil.translateWithFormat("gui.message.emergency_teleport") + " x:" + pos[0] + " y:" + pos[1] + " z:" + pos[2]));
player.connection.setPlayerLocation(pos[0], pos[1], pos[2], player.rotationYaw, player.rotationPitch);
stack.shrink(1);
}
}
break;
}
}
}
//
if (stats.getShieldControllerInSlot().isItemEqual(new ItemStack(GSItems.BASIC, 1, 16)))
{
ItemStack shield = stats.getShieldControllerInSlot();
if (shield.hasTagCompound())
{
int shieldtime = shield.getTagCompound().getInteger("shieldtime");
if(!player.capabilities.isCreativeMode && player.world.provider instanceof IGalacticraftWorldProvider && ((IGalacticraftWorldProvider)player.world.provider).getCelestialBody().atmosphere.isCorrosive())
{
if (shieldtime >= 1)
{
if(player.ticksExisted % 20 == 0)
{
shieldtime -= 1;
shield.getTagCompound().setInteger("shieldtime", shieldtime);
}
}
else
{
shield.shrink(1);
player.sendMessage(new TextComponentString(EnumColor.DARK_RED + GCCoreUtil.translateWithFormat("gui.message.now_noshield")));
}
}
}
else
{
shield.setTagCompound(new NBTTagCompound());
shield.getTagCompound().setInteger("shieldtime", ItemBasicGS.SHIELD_TIME);
}
int gearID = GalacticraftRegistry.findMatchingGearID(stats.getShieldControllerInSlot(), EnumExtendedInventorySlot.SHIELD_CONTROLLER);
if (gearID >= 0)
{
GCPlayerHandler.sendGearUpdatePacket(player, EnumModelPacketType.ADD, EnumExtendedInventorySlot.SHIELD_CONTROLLER, gearID);
}
}
//stats.setLastShieldControllerInSlot(stats.getShieldControllerInSlot());
ItemStack stack = player.inventory.armorInventory.get(3);
IInventoryGC inv = AccessInventoryGC.getGCInventoryForPlayer(player);
if(!stack.isEmpty())
{
if(stack.getItem() instanceof ItemSpaceSuit && player.isInWater() && stack.hasTagCompound() && stack.getTagCompound().hasKey("water_breathing"))
{
int count = 300;
int air = player.getAir();
for(int i = 2; i <= 3; i++)
{
if(!inv.getStackInSlot(i).isEmpty() && inv.getStackInSlot(i).getItemDamage() != inv.getStackInSlot(i).getMaxDamage())
{
if(air < count)
{
player.setAir(count);
if(inv.getStackInSlot(i).getItem() != GCItems.oxygenCanisterInfinite)
inv.getStackInSlot(i).setItemDamage(inv.getStackInSlot(i).getItemDamage() + 1);
}
break;
}
}
}
}
if(OxygenUtil.isAABBInBreathableAirBlock(player) || player.world.provider.getDimensionType() == DimensionType.OVERWORLD)
{
for(int i = 2; i <= 3; i++)
if(!inv.getStackInSlot(i).isEmpty() && (inv.getStackInSlot(i).getItem() == GSItems.OXYGENTANK_TIER_EPP || inv.getStackInSlot(i).hasTagCompound() && inv.getStackInSlot(i).getTagCompound().hasKey("epp")))
{
ItemStack tank = inv.getStackInSlot(i);
if(tank.getItemDamage() != 0)
{
if(player.ticksExisted % 10 == 0)
{
tank.setItemDamage(tank.getItemDamage() - 2);
}
}
}
}
}
}
@SubscribeEvent
public void onThermalArmorEvent(ThermalArmorEvent event) {
if (event.armorStack == ItemStack.EMPTY) {
event.setArmorAddResult(ThermalArmorEvent.ArmorAddResult.REMOVE);
return;
}
if (event.armorStack.getItem() instanceof ItemThermalPaddingBase && event.armorStack.getItemDamage() == event.armorIndex) {
event.setArmorAddResult(ThermalArmorEvent.ArmorAddResult.ADD);
return;
}
event.setArmorAddResult(ThermalArmorEvent.ArmorAddResult.NOTHING);
}
@SubscribeEvent
public void onPlanetDecorated(GCCoreEventPopulate.Post event)
{
if(GSConfigCore.enableMarsNewOres && (event.world.provider instanceof WorldProviderMars || event.world.provider instanceof WorldProviderMars_WE))
{
genOre(event.world, event.pos, new WorldGenMinableMeta(GSBlocks.MARS_ORES, 4, 0, true, MarsBlocks.marsBlock, 9), 6, 4, 18); //diamond
genOre(event.world, event.pos, new WorldGenMinableMeta(GSBlocks.MARS_ORES, 6, 1, true, MarsBlocks.marsBlock, 9), 10, 6, 30); //gold
genOre(event.world, event.pos, new WorldGenMinableMeta(GSBlocks.MARS_ORES, 16, 2, true, MarsBlocks.marsBlock, 9), 15, 6, 70); //coal
genOre(event.world, event.pos, new WorldGenMinableMeta(GSBlocks.MARS_ORES, 10, 3, true, MarsBlocks.marsBlock, 9), 10, 6, 20); //redstone
genOre(event.world, event.pos, new WorldGenMinableMeta(GSBlocks.MARS_ORES, 8, 4, true, MarsBlocks.marsBlock, 9), 4, 6, 20); //silicon
genOre(event.world, event.pos, new WorldGenMinableMeta(GSBlocks.MARS_ORES, 6, 5, true, MarsBlocks.marsBlock, 9), 16, 6, 45); //aluminum
}
}
void genOre(World world, BlockPos pos, WorldGenerator wg, int amountPerChunk, int minY, int maxY)
{
BlockPos pos1 = pos.add(world.rand.nextInt(16), world.rand.nextInt(maxY - minY) + minY, world.rand.nextInt(16));
for(int i = 0; i < amountPerChunk; i++)
wg.generate(world, world.rand, pos1);
}
@SubscribeEvent
public void onZeroGravity(ZeroGravityEvent.InFreefall event)
{
EntityLivingBase entity = event.getEntityLiving();
if(inGravityZone(entity.getEntityWorld(), entity, false))
event.setCanceled(true);
}
@SubscribeEvent
public void onRadiation(RadiationEvent event)
{
EntityLivingBase living = (EntityLivingBase) event.getEntity();
if(living instanceof EntityPlayerMP)
{
EntityPlayerMP player = (EntityPlayerMP) living;
boolean checkAirLock = false;
for(int y = 0; y < 255; y++) {
if(player.world.getBlockState(player.getPosition().up(y)).getBlock() == GCBlocks.airLockSeal) {
checkAirLock = true;
break;
}
}
if(!player.capabilities.isCreativeMode)
event.setCanceled(checkAirLock || !GSConfigCore.enableRadiationSystem || this.getProtectArmor(player) || player.getRidingEntity() instanceof EntityLanderBase || player.getRidingEntity() instanceof EntityTieredRocket || this.inRadiationBubble(player.getEntityWorld(), player.posX, player.posY, player.posZ));
}
}
@SubscribeEvent
public void onPressure(PressureEvent event)
{
EntityLivingBase living = (EntityLivingBase) event.getEntity();
if(living instanceof EntityPlayerMP)
{
EntityPlayerMP player = (EntityPlayerMP) living;
World world = player.getEntityWorld();
float level = event.getPressureLevel();
if(!player.capabilities.isCreativeMode)
event.setCanceled(!GSConfigCore.enablePressureSystem || this.getProtectArmor(player) || this.inGravityZone(world, player, true) || player.getRidingEntity() instanceof EntityLanderBase || player.getRidingEntity() instanceof EntityTieredRocket);
}
}
public static boolean getProtectArmor(EntityPlayerMP player)
{
boolean[] check = new boolean[4];
//boolean flag = false;
for(String string : GSConfigCore.radiation_armor)
{
String[] meta = string.split(":");
Item item = ForgeRegistries.ITEMS.getValue(new ResourceLocation(string));
if(meta.length > 2)
{
for(int i = 0; i <= 3; i++)
{
ItemStack itemstack = new ItemStack(item, 1, Integer.parseInt(meta[2]));
check[i] = !player.inventory.armorInventory.get(i).isEmpty() && player.inventory.armorInventory.get(i) == itemstack;
if(check[i]) break;
}
}
else
for(int i = 0; i <= 3; i++)
{
check[i] = !player.inventory.armorInventory.get(i).isEmpty() && player.inventory.armorInventory.get(i).getItem() == item;
if(check[i]) break;
}
if(check[0] && check[1] && check[2] && check[3]) break;
}
return check[0] && check[1] && check[2] && check[3];
}
public static boolean inGravityZone(World world, EntityLivingBase player, boolean checkStabilisationModule)
{
for (final BlockVec3Dim blockVec : TileEntityGravitationModule.loadedTiles)
{
if (blockVec != null && blockVec.dim == world.provider.getDimension())
{
TileEntity tile = world.getTileEntity(blockVec.toBlockPos());
if (tile instanceof TileEntityGravitationModule)
{
TileEntityGravitationModule gravity = (TileEntityGravitationModule)tile;
if(!gravity.disabled && gravity.hasEnoughEnergyToRun && gravity.inGravityZone(world, player)) {
if(!checkStabilisationModule) return true;
if(checkStabilisationModule)
{
for(int i = 0; i < 4; i++)
if(gravity.getStackInSlot(i + 1).isItemEqual(new ItemStack(GSItems.UPGRADES, 1, 1)))
return true;
return false;
}
}
}
}
}
return false;
}
public static boolean inRadiationBubble(World world, double avgX, double avgY, double avgZ)
{
for (final BlockVec3Dim blockVec : TileEntityRadiationStabiliser.loadedTiles)
{
if (blockVec != null && blockVec.dim == world.provider.getDimension())
{
TileEntity tile = world.getTileEntity(blockVec.toBlockPos());
if (tile instanceof TileEntityRadiationStabiliser)
{
if (((TileEntityRadiationStabiliser) tile).inBubble(avgX, avgY, avgZ)) return true;
}
}
}
return false;
}
public static boolean inShieldBubble(World world, double avgX, double avgY, double avgZ)
{
for (final BlockVec3Dim blockVec : TileEntityPlanetShield.loadedTiles)
{
if (blockVec != null && blockVec.dim == world.provider.getDimension())
{
TileEntity tile = world.getTileEntity(blockVec.toBlockPos());
if (tile instanceof TileEntityPlanetShield)
{
if (((TileEntityPlanetShield) tile).inBubble(avgX, avgY, avgZ)) return true;
}
}
}
return false;
}
public static boolean consumeItemStack(IInventory inventory, ItemStack stack) {
//GalaxySpace.debug(getAmount(inventory, stack) + "");
if(getAmount(inventory, stack) >= stack.getCount()) {
for (int i = 0; i < inventory.getSizeInventory(); i++) {
if(isItemStackEqual(inventory.getStackInSlot(i), stack)){
int amount = Math.min(stack.getCount(), inventory.getStackInSlot(i).getCount());
if(amount > 0) {
inventory.getStackInSlot(i).shrink(amount);
if(inventory.getStackInSlot(i).getCount() <= 0) {
inventory.setInventorySlotContents(i, ItemStack.EMPTY);
}
stack.shrink(amount);
}
if(stack.getCount() <= 0) {
return true;
}
}
}
}
return false;
}
public static int getAmount(IInventory inventory, ItemStack stack) {
int amount = 0;
for (int i = 0; i < inventory.getSizeInventory(); i++) {
if(isItemStackEqual(inventory.getStackInSlot(i), stack)) {
amount += inventory.getStackInSlot(i).getCount();
}
}
return amount;
}
public static boolean isItemStackEqual(ItemStack stack1, ItemStack stack2) {
return (!stack1.isEmpty() && stack1.getItem() == stack2.getItem() && (stack1.getItemDamage() == stack2.getItemDamage() || stack2.getItemDamage() == OreDictionary.WILDCARD_VALUE));
}
protected void updateSchematics(EntityPlayerMP player, GCPlayerStats playerStats)
{
/* SchematicRegistry.addUnlockedPage(player, SchematicRegistry.getMatchingRecipeForID(GSConfigSchematics.idSchematicCone));
SchematicRegistry.addUnlockedPage(player, SchematicRegistry.getMatchingRecipeForID(GSConfigSchematics.idSchematicBody));
SchematicRegistry.addUnlockedPage(player, SchematicRegistry.getMatchingRecipeForID(GSConfigSchematics.idSchematicEngine));
SchematicRegistry.addUnlockedPage(player, SchematicRegistry.getMatchingRecipeForID(GSConfigSchematics.idSchematicBooster));
SchematicRegistry.addUnlockedPage(player, SchematicRegistry.getMatchingRecipeForID(GSConfigSchematics.idSchematicFins));
*/
/*Collections.sort(playerStats.unlockedSchematics);
if (player.playerNetServerHandler != null && (playerStats.unlockedSchematics.size() != playerStats.lastUnlockedSchematics.size() || (player.ticksExisted - 1) % 100 == 0))
{
Integer[] iArray = new Integer[playerStats.unlockedSchematics.size()];
for (int i = 0; i < iArray.length; i++)
{
ISchematicPage page = playerStats.unlockedSchematics.get(i);
iArray[i] = page == null ? -2 : page.getPageID();
}
List<Object> objList = new ArrayList<Object>();
objList.add(iArray);
GalacticraftCore.packetPipeline.sendTo(new PacketSimple(EnumSimplePacket.C_UPDATE_SCHEMATIC_LIST, objList), player);
}*/
}
public static void enableFlight(EntityPlayer player, boolean state) {
ItemStack chest = player.getItemStackFromSlot(EntityEquipmentSlot.CHEST);
if (chest != null && chest.getItem() instanceof IJetpackArmor) {
((IJetpackArmor) chest.getItem()).switchState(chest, state);
/*if (((IJetpack) chest.getItem()).isActivated(chest)) {
player.worldObj.playSoundAtEntity(player, "jetpack:launch", 1, 1);
JetCore.network.sendToAllAround(new SoundMessage(Item.getIdFromItem(chest.getItem()), player.getCommandSenderName()), new TargetPoint(player.dimension, player.posX, player.posY, player.posZ, 64));
}*/
}
}
protected void throwMeteors(EntityPlayerMP player)
{
World world = player.world;
if (world.provider instanceof IAdvancedSpace && !world.isRemote)
{
if (((IGalacticraftWorldProvider) world.provider).getMeteorFrequency() > 0 && ConfigManagerCore.meteorSpawnMod > 0.0)
{
// final int f = (int) (((IGalacticraftWorldProvider) world.provider).getMeteorFrequency() * 1000D * (1.0 / ConfigManagerCore.meteorSpawnMod));
final int f = 1;
if (world.rand.nextInt(f) == 0) /*&& world.getWorldTime() > 6000L && world.getWorldTime() < 9000L)*/
{
final EntityPlayer closestPlayer = world.getClosestPlayerToEntity(player, 100);
if (closestPlayer == null || closestPlayer.getEntityId() <= player.getEntityId())
{
int x, y, z;
double motX, motZ;
x = world.rand.nextInt(1) - 4;
y = world.rand.nextInt(20) + 200;
z = world.rand.nextInt(1) - 4;
motX = world.rand.nextDouble() * 1;
motZ = world.rand.nextDouble() * 1;
final EntityMeteor meteor = new EntityMeteor(world, player.posX + x, player.posY + y, player.posZ + z, motX - 0.5D, 0, motZ - 0.5D, 1);
if (!world.isRemote)
{
world.spawnEntity(meteor);
}
}
}
}
}
}
private static class BlockToChange
{
private IBlockState state, hot_replaced, cold_replaced;
private float temp;
private boolean need_check_temp, need_check_oxygen, only_gs_dim = false;
private String particle_name = "";
BlockToChange(IBlockState state, IBlockState hot_replaced, IBlockState cold_replaced, float temp, boolean need_check_temp)
{
this.state = state;
this.hot_replaced = hot_replaced;
this.cold_replaced = cold_replaced;
this.temp = temp;
this.need_check_temp = need_check_temp;
}
public BlockToChange setParticle(String s)
{
this.particle_name = s;
return this;
}
public BlockToChange setOnlyGSDim()
{
this.only_gs_dim = true;
return this;
}
public BlockToChange setOxygenCheck(boolean check)
{
this.need_check_oxygen = check;
return this;
}
void spawnParticleHotTemp(World world, BlockPos pos)
{
if(!particle_name.isEmpty())
for(int i = 0; i < 5; i++)
GalaxySpace.proxy.spawnParticle(particle_name, new Vector3(pos.getX() + world.rand.nextDouble(), pos.getY() + 1.0D + world.rand.nextDouble(), pos.getZ() + world.rand.nextDouble()), new Vector3(0.0D, 0.001D, 0.0D), new Object [] { 10, 5, false, new Vector3(1.0F, 1.0F, 1.0F), 1.0D } );
}
}
private static class ItemsToChange
{
private ItemStack itemstack = ItemStack.EMPTY;
private IBlockState replaced;
private boolean need_check_temp, need_check_oxygen, only_gs_dim = false;
ItemsToChange(ItemStack stack, IBlockState placed)
{
this.itemstack = stack;
this.replaced = placed;
}
public ItemsToChange setOnlyGSDim()
{
this.only_gs_dim = true;
return this;
}
public ItemsToChange setOxygenCheck(boolean check)
{
this.need_check_oxygen = check;
return this;
}
public ItemsToChange setTempCheck(boolean check)
{
this.need_check_temp = check;
return this;
}
}
}
| apache-2.0 |
ctripcorp/dal | dal-dao-gen/src/main/java/com/ctrip/platform/dal/daogen/generator/csharp/CSharpDalGenerator.java | 6523 | package com.ctrip.platform.dal.daogen.generator.csharp;
import com.ctrip.platform.dal.daogen.CodeGenContext;
import com.ctrip.platform.dal.daogen.DalGenerator;
import com.ctrip.platform.dal.daogen.entity.Progress;
import com.ctrip.platform.dal.daogen.entity.Project;
import com.ctrip.platform.dal.daogen.generator.processor.csharp.*;
import com.ctrip.platform.dal.daogen.host.DalConfigHost;
import com.ctrip.platform.dal.daogen.log.LoggerManager;
import com.ctrip.platform.dal.daogen.utils.BeanGetter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CSharpDalGenerator implements DalGenerator {
@Override
public CodeGenContext createContext(int projectId, boolean regenerate, Progress progress, boolean newPojo,
boolean ignoreApproveStatus) throws Exception {
CSharpCodeGenContext ctx = null;
try {
Map<String, Boolean> hints = new HashMap<>();
hints.put("newPojo", newPojo);
ctx = new CSharpCodeGenContext(projectId, regenerate, progress, hints);
ctx.setNewPojo(newPojo);
Project project = BeanGetter.getDaoOfProject().getProjectByID(ctx.getProjectId());
DalConfigHost dalConfigHost = null;
if (project.getDal_config_name() != null && !project.getDal_config_name().isEmpty()) {
dalConfigHost = new DalConfigHost(project.getDal_config_name());
} else if (project.getNamespace() != null && !project.getNamespace().isEmpty()) {
dalConfigHost = new DalConfigHost(project.getNamespace());
} else {
dalConfigHost = new DalConfigHost("");
}
ctx.setDalConfigHost(dalConfigHost);
ctx.setNamespace(project.getNamespace());
} catch (Exception e) {
LoggerManager.getInstance().error(e);
throw e;
}
return ctx;
}
@Override
public void prepareDirectory(CodeGenContext context) throws Exception {
try {
CSharpCodeGenContext ctx = (CSharpCodeGenContext) context;
LoggerManager.getInstance()
.info(String.format("Begin to prepare csharp directory for project %s", ctx.getProjectId()));
new CSharpDirectoryPreparerProcessor().process(ctx);
LoggerManager.getInstance()
.info(String.format("Prepare csharp directory for project %s completed.", ctx.getProjectId()));
} catch (Exception e) {
LoggerManager.getInstance().error(e);
throw e;
}
}
@Override
public void prepareData(CodeGenContext context) throws Exception {
List<String> exceptions = new ArrayList<>();
CSharpCodeGenContext ctx = (CSharpCodeGenContext) context;
try {
LoggerManager.getInstance()
.info(String.format("Begin to prepare csharp table data for project %s", ctx.getProjectId()));
new CSharpDataPreparerOfTableViewSpProcessor().process(ctx);
LoggerManager.getInstance()
.info(String.format("Prepare csharp table data for project %s completed.", ctx.getProjectId()));
} catch (Exception e) {
LoggerManager.getInstance().error(e);
exceptions.add(e.getMessage());
}
try {
LoggerManager.getInstance()
.info(String.format("Begin to prepare csharp sqlbuilder data for project %s", ctx.getProjectId()));
new CSharpDataPreparerOfSqlBuilderProcessor().process(ctx);
LoggerManager.getInstance().info(
String.format("Prepare csharp sqlbuilder data for project %s completed.", ctx.getProjectId()));
} catch (Throwable e) {
LoggerManager.getInstance().error(e);
exceptions.add(e.getMessage());
}
try {
LoggerManager.getInstance()
.info(String.format("Begin to prepare csharp freesql data for project %s", ctx.getProjectId()));
new CSharpDataPreparerOfFreeSqlProcessor().process(ctx);
LoggerManager.getInstance()
.info(String.format("Prepare csharp freesql data for project %s completed.", ctx.getProjectId()));
} catch (Throwable e) {
LoggerManager.getInstance().error(e);
exceptions.add(e.getMessage());
}
if (exceptions.size() > 0) {
StringBuilder sb = new StringBuilder();
for (String exception : exceptions) {
sb.append(exception);
}
throw new RuntimeException(sb.toString());
}
}
@Override
public void generateCode(CodeGenContext context) throws Exception {
CSharpCodeGenContext ctx = (CSharpCodeGenContext) context;
try {
LoggerManager.getInstance()
.info(String.format("Begin to generate csharp table code for project %s", ctx.getProjectId()));
new CSharpCodeGeneratorOfTableProcessor().process(ctx);
LoggerManager.getInstance()
.info(String.format("Generate csharp table code for project %s completed.", ctx.getProjectId()));
LoggerManager.getInstance()
.info(String.format("Begin to generate csharp sp code for project %s", ctx.getProjectId()));
new CSharpCodeGeneratorOfSpProcessor().process(ctx);
LoggerManager.getInstance()
.info(String.format("Generate csharp sp code for project %s completed.", ctx.getProjectId()));
LoggerManager.getInstance()
.info(String.format("Begin to generate csharp freesql code for project %s", ctx.getProjectId()));
new CSharpCodeGeneratorOfFreeSqlProcessor().process(ctx);
LoggerManager.getInstance()
.info(String.format("Generate csharp freesql code for project %s completed.", ctx.getProjectId()));
LoggerManager.getInstance()
.info(String.format("Begin to generate csharp other code for project %s", ctx.getProjectId()));
new CSharpCodeGeneratorOfOthersProcessor().process(ctx);
LoggerManager.getInstance()
.info(String.format("Generate csharp other code for project %s completed.", ctx.getProjectId()));
} catch (Exception e) {
LoggerManager.getInstance().error(e);
throw e;
}
}
}
| apache-2.0 |
weijiancai/metaui | metaui-fxbase/src/main/java/com/metaui/fxbase/view/MUForm.java | 4453 | package com.metaui.fxbase.view;
import com.metaui.core.view.IView;
import com.metaui.core.view.config.FormConfig;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ToolBar;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import java.util.ArrayList;
import java.util.List;
/**
* MetaUI 表单
*
* @author wei_jc
* @since 1.0.0
*/
public class MUForm extends BorderPane implements IView {
private FormConfig config;
private GridPane gridPane = new GridPane();
private ToolBar toolBar = new ToolBar();
public MUForm(FormConfig config) {
this.config = config;
init();
}
public FormConfig getConfig() {
return config;
}
@Override
public void init() {
layoutUI();
}
@Override
public void layoutUI() {
/*if (config.getActions().size() > 0) {
this.setTop(toolBar);
}*/
this.setCenter(gridPane);
this.setStyle("-fx-padding: 10");
createToolBar();
createCenter();
}
private void createToolBar() {
/*for (ActionModel action : config.getActions()) {
Button button = new Button();
button.textProperty().bindBidirectional(action.displayNameProperty());
button.idProperty().bindBidirectional(action.idProperty());
button.setOnAction(new MuEventHandler<ActionEvent>() {
@Override
public void doHandler(ActionEvent event) throws Exception {
action.getCallback().call(null);
}
});
toolBar.getItems().add(button);
}*/
}
private Node createCenter() {
// gridPane.setGridLinesVisible(true);
gridPane.setHgap(config.getHgap());
gridPane.setVgap(config.getVgap());
gridPane.setAlignment(Pos.TOP_LEFT);
gridPane.setPadding(new Insets(5, 0, 0, 0));
Region labelGap;
/*BaseFormField formField;
Region fieldGap;
int idxRow = 0;
int idxCol = 0;
for (FormFieldModel field : config.getFormFields()) {
*//*if (onlyShowHidden) { // 只显示隐藏的
if (field.isDisplay()) {
continue;
}
} else if (!field.isDisplay()) { // 不显示
continue;
}*//*
formField = BaseFormField.getInstance(field);
queryList.add(formField);
// 查询表单
if (FormType.QUERY == config.getFormType()) {
// TextArea不显示
if ((formField instanceof MUTextArea || field.getMaxLength() > 200)) {
continue;
}
// 查询表单,查询条件,至显示3行
if (idxRow > 3) {
break;
}
}
// 单行
if (field.isSingleLine()) {
idxRow++;
gridPane.add(formField.getLabelNode(), 0, idxRow);
labelGap = new Region();
labelGap.setPrefWidth(config.getLabelGap());
gridPane.add(labelGap, 1, idxRow);
gridPane.add(formField, 2, idxRow, config.getColCount() * 4 - 2, 1);
GridPane.setHgrow(formField, Priority.ALWAYS);
idxCol = 0;
idxRow++;
continue;
}
gridPane.add(formField.getLabelNode(), idxCol++, idxRow);
labelGap = new Region();
labelGap.setPrefWidth(config.getLabelGap());
gridPane.add(labelGap, idxCol++, idxRow);
gridPane.add(formField, idxCol++, idxRow);
if (config.getColCount() == 1) { // 单列
idxCol = 0;
idxRow++;
} else { // 多列
if (idxCol == config.getColCount() * 4 - 1) {
idxCol = 0;
idxRow++;
} else {
fieldGap = new Region();
fieldGap.setPrefWidth(config.getFieldGap());
gridPane.add(fieldGap, idxCol++, idxRow);
}
}
}*/
return gridPane;
}
}
| apache-2.0 |
hotpads/datarouter | datarouter-bytes/src/main/java/io/datarouter/bytes/codec/intcodec/UInt31Codec.java | 1376 | /*
* Copyright © 2009 HotPads (admin@hotpads.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.datarouter.bytes.codec.intcodec;
@Deprecated//use ComparableIntCodec or RawIntCodec
public class UInt31Codec{
public static final UInt31Codec INSTANCE = new UInt31Codec();
private static final RawIntCodec RAW_CODEC = RawIntCodec.INSTANCE;
private static final int LENGTH = RAW_CODEC.length();
public int length(){
return LENGTH;
}
public byte[] encode(int value){
var bytes = new byte[LENGTH];
encode(value, bytes, 0);
return bytes;
}
public int encode(int value, byte[] bytes, int offset){
//TODO reject negatives
return RAW_CODEC.encode(value, bytes, offset);
}
public int decode(byte[] bytes){
return decode(bytes, 0);
}
public int decode(byte[] bytes, int offset){
return RAW_CODEC.decode(bytes, offset);
}
}
| apache-2.0 |
b2ihealthcare/snow-owl | core/com.b2international.snowowl.core/src/com/b2international/snowowl/core/events/util/RequestHeaders.java | 1167 | /*
* Copyright 2019 B2i Healthcare Pte Ltd, http://b2i.sg
*
* 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.b2international.snowowl.core.events.util;
import java.util.Collections;
import java.util.Map;
import com.google.common.collect.ImmutableMap;
/**
* @since 7.2
*/
public final class RequestHeaders {
private final Map<String, String> headers;
public RequestHeaders(Map<String, String> headers) {
this.headers = headers == null ? Collections.emptyMap() : ImmutableMap.copyOf(headers);
}
public String header(String name) {
return headers.get(name);
}
public Map<String, String> headers() {
return headers;
}
}
| apache-2.0 |
osmdroid/osmdroid | osmdroid-android/src/main/java/org/osmdroid/tileprovider/tilesource/OnlineTileSourceBase.java | 3579 | package org.osmdroid.tileprovider.tilesource;
import java.util.concurrent.Semaphore;
public abstract class OnlineTileSourceBase extends BitmapTileSourceBase {
private final String[] mBaseUrls;
/**
* @since 6.1.0
*/
private final Semaphore mSemaphore;
/**
* @since 6.1.0
*/
private final TileSourcePolicy mTileSourcePolicy;
public OnlineTileSourceBase(final String aName,
final int aZoomMinLevel, final int aZoomMaxLevel, final int aTileSizePixels,
final String aImageFilenameEnding, final String[] aBaseUrl) {
this(aName, aZoomMinLevel, aZoomMaxLevel, aTileSizePixels,
aImageFilenameEnding, aBaseUrl, null);
}
public OnlineTileSourceBase(final String aName,
final int aZoomMinLevel, final int aZoomMaxLevel, final int aTileSizePixels,
final String aImageFilenameEnding, final String[] aBaseUrl, String copyyright) {
this(aName, aZoomMinLevel, aZoomMaxLevel, aTileSizePixels,
aImageFilenameEnding, aBaseUrl, copyyright, new TileSourcePolicy());
}
/**
* @param pName a human-friendly name for this tile source
* @param pZoomMinLevel the minimum zoom level this tile source can provide
* @param pZoomMaxLevel the maximum zoom level this tile source can provide
* @param pTileSizePixels the tile size in pixels this tile source provides
* @param pImageFilenameEnding the file name extension used when constructing the filename
* @param pBaseUrl the base url(s) of the tile server used when constructing the url to download the tiles
* @param pCopyright the source copyright
* @param pTileSourcePolicy tile source policy
* @since 6.1.0
*/
public OnlineTileSourceBase(final String pName,
final int pZoomMinLevel, final int pZoomMaxLevel, final int pTileSizePixels,
final String pImageFilenameEnding, final String[] pBaseUrl, final String pCopyright,
final TileSourcePolicy pTileSourcePolicy) {
super(pName, pZoomMinLevel, pZoomMaxLevel, pTileSizePixels,
pImageFilenameEnding, pCopyright);
mBaseUrls = pBaseUrl;
mTileSourcePolicy = pTileSourcePolicy;
if (mTileSourcePolicy.getMaxConcurrent() > 0) {
mSemaphore = new Semaphore(mTileSourcePolicy.getMaxConcurrent(), true);
} else {
mSemaphore = null;
}
}
public abstract String getTileURLString(final long pMapTileIndex);
/**
* Get the base url, which will be a random one if there are more than one.
* <br>
* Updated around 6.1.1, if base url list is null or empty, empty string is returned
*/
public String getBaseUrl() {
if (mBaseUrls != null && mBaseUrls.length > 0)
return mBaseUrls[random.nextInt(mBaseUrls.length)];
return "";
}
/**
* @since 6.1.0
*/
public void acquire() throws InterruptedException {
if (mSemaphore == null) {
return;
}
mSemaphore.acquire();
}
/**
* @since 6.1.0
*/
public void release() {
if (mSemaphore == null) {
return;
}
mSemaphore.release();
}
/**
* @since 6.1.0
*/
public TileSourcePolicy getTileSourcePolicy() {
return mTileSourcePolicy;
}
}
| apache-2.0 |
iFarSeer/TodoFluxArchitecture | app/src/main/java/com/farseer/todo/flux/action/base/ActionType.java | 792 | /*
*
* Copyright 2016 zhaosc
*
* 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.farseer.todo.flux.action.base;
/**
* 抽象的Action类型
*
* @author zhaosc
* @version 1.0.0
* @since 2016-04-19
*/
public interface ActionType {
} | apache-2.0 |
Wolfgang-Schuetzelhofer/jcypher | src/main/java/iot/jcypher/domainquery/QueryLoader.java | 5647 | /************************************************************************
* Copyright (c) 2016 IoT-Solutions e.U.
*
* 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 iot.jcypher.domainquery;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import iot.jcypher.database.IDBAccess;
import iot.jcypher.domain.IDomainAccess;
import iot.jcypher.domain.IGenericDomainAccess;
import iot.jcypher.domain.internal.IIntDomainAccess;
import iot.jcypher.domainquery.api.APIAccess;
import iot.jcypher.domainquery.api.DomainObjectMatch;
import iot.jcypher.domainquery.internal.JSONConverter;
import iot.jcypher.domainquery.internal.QueryExecutor;
import iot.jcypher.domainquery.internal.RecordedQuery;
import iot.jcypher.domainquery.internal.RecordedQueryPlayer;
import iot.jcypher.domainquery.internal.ReplayedQueryContext;
import iot.jcypher.graph.GrNode;
import iot.jcypher.query.JcQuery;
import iot.jcypher.query.JcQueryResult;
import iot.jcypher.query.api.IClause;
import iot.jcypher.query.factories.clause.MATCH;
import iot.jcypher.query.factories.clause.RETURN;
import iot.jcypher.query.values.JcNode;
import iot.jcypher.util.Util;
public class QueryLoader<T> {
private Object domainAccess; // can be IDomainAccess or IGenericDomainAccess
private String queryName;
private ReplayedQueryContext replayedQueryContext;
QueryLoader( String qName, Object domAccess) {
this.queryName = qName;
this.domainAccess = domAccess;
}
@SuppressWarnings("unchecked")
public T load() {
QueryMemento qm = loadMemento();
if (qm != null) {
RecordedQuery rq = new JSONConverter().fromJSON(qm.getQueryJSON());
RecordedQueryPlayer qp = new RecordedQueryPlayer(true); // create new
T q;
if (isGeneric())
q = (T) qp.replayGenericQuery(rq, (IGenericDomainAccess) this.domainAccess);
else
q = (T) qp.replayQuery(rq, (IDomainAccess) this.domainAccess);
this.replayedQueryContext = ((AbstractDomainQuery) q).getReplayedQueryContext();
QueryExecutor qe = InternalAccess.getQueryExecutor((AbstractDomainQuery) q);
qe.queryCreationCompleted(true); // delete the replayedQueryContext
return q;
}
return null;
}
/**
* The memento contains a JSON representation of the query as well as a Java-DSL like string representation.
* @return
*/
public QueryMemento loadMemento() {
IDBAccess dbAccess = ((IIntDomainAccess)this.domainAccess).getInternalDomainAccess().getDBAccess();
String qLabel = ((IIntDomainAccess)this.domainAccess).getInternalDomainAccess().getDomainLabel()
.concat(QueryPersistor.Q_LABEL_POSTFIX);
JcNode n = new JcNode("n");
IClause[] clauses = new IClause[] {
MATCH.node(n).label(qLabel).property(QueryPersistor.PROP_NAME).value(queryName),
RETURN.value(n)
};
JcQuery q = new JcQuery();
q.setClauses(clauses);
JcQueryResult result = dbAccess.execute(q);
if (result.hasErrors()) {
StringBuilder sb = new StringBuilder();
Util.appendErrorList(Util.collectErrors(result), sb);
throw new RuntimeException(sb.toString());
}
List<GrNode> lgn = result.resultOf(n);
if (lgn.size() > 0) {
GrNode gn = lgn.get(0);
String qJava = gn.getProperty(QueryPersistor.PROP_Q_JAVA).getValue().toString();
String qJSON = gn.getProperty(QueryPersistor.PROP_Q_JSON).getValue().toString();
QueryMemento qm = new QueryMemento(qJava, qJSON);
return qm;
}
return null;
}
public List<String> getAugmentedDOMNames() {
List<String> dNames;
if (this.replayedQueryContext.getRecordedQuery().getAugmentations() != null) {
dNames = new ArrayList<String>(
this.replayedQueryContext.getRecordedQuery().getAugmentations().values());
Collections.sort(dNames);
} else
dNames = Collections.emptyList();
return dNames;
}
public List<String> getInternalDOMNames() {
List<String> dNames = new ArrayList<String>(
replayedQueryContext.getId2DomainObjectMatch().keySet());
Collections.sort(dNames);
return dNames;
}
public DomainObjectMatch<?> getDomainObjectMatch(String name) {
DomainObjectMatch<?> ret = null;
if (this.replayedQueryContext.getRecordedQuery().getAugmentations() != null) {
Iterator<Entry<String, String>> it =
this.replayedQueryContext.getRecordedQuery().getAugmentations().entrySet().iterator();
while(it.hasNext()) {
Entry<String, String> entry = it.next();
if (entry.getValue().equals(name)) {
ret = this.replayedQueryContext.getById(entry.getKey());
break;
}
}
}
if (ret == null) {
ret = this.replayedQueryContext.getById(name);
}
return ret;
}
@SuppressWarnings("unchecked")
public <E> DomainObjectMatch<E> getDomainObjectMatch(String name, Class<E> type) {
DomainObjectMatch<?> dom = this.getDomainObjectMatch(name);
Class<?> typ = APIAccess.getDomainObjectType(dom);
if (!type.isAssignableFrom(typ))
throw new ClassCastException();
return (DomainObjectMatch<E>) dom;
}
private boolean isGeneric() {
return this.domainAccess instanceof IGenericDomainAccess;
}
}
| apache-2.0 |
tiankun/YmPaoPao | app/src/main/java/com/yeming/paopao/aty/UserPaopaoListActivity.java | 9877 | package com.yeming.paopao.aty;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.nhaarman.listviewanimations.swinginadapters.AnimationAdapter;
import com.nhaarman.listviewanimations.swinginadapters.prepared.ScaleInAnimationAdapter;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.yeming.paopao.R;
import com.yeming.paopao.adapter.FansListAdapter;
import com.yeming.paopao.adapter.PaopaoFtmListAdapter;
import com.yeming.paopao.app.YmApplication;
import com.yeming.paopao.bean.Paopao;
import com.yeming.paopao.bean.User;
import com.yeming.paopao.commons.Constant;
import com.yeming.paopao.commons.DataInfoCache;
import com.yeming.paopao.utils.LogUtil;
import com.yeming.paopao.views.MySwipeRefreshLayout;
import com.yeming.paopao.views.ToastView;
import com.yeming.paopao.views.third.DialogView;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobDate;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.listener.FindListener;
/**
* author YeMing(yeming_1001@163.com)
* Date: 2015-01-28 21:27
* version: V1.0
* Description: 用户泡泡列表
*/
public class UserPaopaoListActivity extends Activity{
private String TAG = "PaoPaoFragment" ;
private Context context ;
private MySwipeRefreshLayout swipeRefreshLayout ;
private ListView listView ;
private PaopaoFtmListAdapter adapter ;
private ImageLoader imageLoader = ImageLoader.getInstance(); // 图片加载器
private List<Paopao> mList ;
private int pageNum = 0 ; // 当前页
public enum RefreshType{ // 加载数据操作类型 刷新 加载更多
REFRESH,LOAD_MORE
}
private RefreshType mRefreshType = RefreshType.LOAD_MORE;
private boolean noMore = false ; // 判断是否还有数据,为true时不执行上拉加载更多
private static final int REQUEST_EDIT_MAOPAO = 1 ; // 跳转编辑泡泡页面请求码
private Dialog loadDialog;
private User user ;
private boolean isCache = true ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.paopao_fmt_layout);
YmApplication.getInstance().addActivity(this);
context = this ;
setActionBar();
loadDialog = DialogView.loadDialog(context, R.string.loading) ;
setActionBar();
Intent intent = getIntent() ;
user = (User) intent.getSerializableExtra("user");
mList = new ArrayList<Paopao>() ;
initView();
loadDialog.show();
getUserPaopaoList() ;
initListener();
adapter = new PaopaoFtmListAdapter(context,mList,imageLoader) ;
AnimationAdapter animAdapter = new ScaleInAnimationAdapter(adapter);
animAdapter.setAbsListView(listView);
animAdapter.setInitialDelayMillis(300);
listView.setAdapter(animAdapter);
}
/**
*
*/
private void initView(){
swipeRefreshLayout = (MySwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
swipeRefreshLayout.setColorSchemeResources(R.color.green, R.color.green, R.color.green, R.color.green);
listView = (ListView) findViewById(R.id.listView);
}
private void initListener(){
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
pageNum = 0 ;
mRefreshType = RefreshType.REFRESH;
swipeRefreshLayout.setRefreshing(true);
getUserPaopaoList();
}
});
swipeRefreshLayout.setOnLoadListener(new MySwipeRefreshLayout.OnLoadListener() {
@Override
public void onLoadMore() {
LogUtil.d("FansListActivity", "---------onLoadMore---------");
ToastView.showToast(context, "正在加载。。。", Toast.LENGTH_SHORT);
mRefreshType = RefreshType.LOAD_MORE;
swipeRefreshLayout.setLoading(true);
getUserPaopaoList() ;
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent() ;
Paopao paopao = mList.get(i) ;
intent.putExtra("paopao_detail",paopao) ;
intent.setClass(context, PaopaoDetailActivity.class) ;
startActivity(intent);
}
});
}
/**
* 获取用户泡泡列表
*/
private void getUserPaopaoList(){
BmobQuery<Paopao> query = new BmobQuery<Paopao>() ;
query.order("-createdAt") ;
query.setLimit(Constant.PAGE_SIZE);
BmobDate date = new BmobDate(new Date(System.currentTimeMillis()));
query.addWhereLessThan("createdAt", date);
query.setSkip(Constant.PAGE_SIZE*(pageNum++));
query.include("user");
query.addWhereRelatedTo("paopao", new BmobPointer(user));
query.findObjects(context,new FindListener<Paopao>() {
@Override
public void onSuccess(List<Paopao> paopaos) {
if(loadDialog.isShowing()){
LogUtil.d(TAG, "-----getUserPaopaoList loadDialog dismiss 2-----");
loadDialog.dismiss();
}
LogUtil.d(TAG,"---getUserPaopaoList Success----"+paopaos.size());
if(paopaos.size()!=0&&paopaos.get(paopaos.size()-1)!=null){
if(mRefreshType==RefreshType.REFRESH){ //刷新
mList.clear();
swipeRefreshLayout.setRefreshing(false);// 设置状态
// 每次刷新都缓存第一页数据
// DataInfoCache.saveListPaopaos(context, (ArrayList<Paopao>) paopaos);
}else if(mRefreshType==RefreshType.LOAD_MORE){ // 加载更多
swipeRefreshLayout.setLoading(false);// 设置状态
}
if(paopaos.size()<Constant.PAGE_SIZE){
ToastView.showToast(context,"~已加载完所有数据~",Toast.LENGTH_SHORT);
}
mList.addAll(paopaos) ;
adapter.setList(mList);
adapter.notifyDataSetChanged();
/* if(pageNum == 1){ // 加载完第一页数据后则缓存,不管是刷新还是加载操作
DataInfoCache.saveListPaopaos(context, (ArrayList<Paopao>) mList);
}*/
}else{
LogUtil.d(TAG,"---getUserPaopaoList Success----暂无更多数据");
ToastView.showToast(context,"~暂无更多数据~",Toast.LENGTH_SHORT);
pageNum--;
// 设置状态
if(mRefreshType==RefreshType.REFRESH){
swipeRefreshLayout.setRefreshing(false);
}else if(mRefreshType==RefreshType.LOAD_MORE){
swipeRefreshLayout.setLoading(false);
}
}
}
@Override
public void onError(int i, String s) {
if(loadDialog.isShowing()){
loadDialog.dismiss();
}
LogUtil.d(TAG,"-----getUserPaopaoList Error--code="+i+"____"+s);
if(pageNum > 0){
pageNum--;
}
if(mRefreshType==RefreshType.REFRESH){
LogUtil.d(TAG,"-----getUserPaopaoList Error--RefreshType.REFRESH");
swipeRefreshLayout.setRefreshing(false);
}else if(mRefreshType==RefreshType.LOAD_MORE){
LogUtil.d(TAG, "-----getUserPaopaoList Error--RefreshType.LOAD_MORE");
swipeRefreshLayout.setLoading(false);
}
}
});
}
/**
* actionbar style
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private void setActionBar(){
//this.getActionBar().setTitle("PaoPao");
getActionBar().setBackgroundDrawable(
this.getBaseContext().getResources()
.getDrawable(R.drawable.actionbar_bg));
//getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setDisplayShowHomeEnabled(false);
//getActionBar().setTitle(user.getNickname());
int titleId = Resources.getSystem().getIdentifier("action_bar_title",
"id", "android");
TextView textView = (TextView) findViewById(titleId);
textView.setTypeface(YmApplication.chineseTypeface);
textView.setTextColor(0xFFdfdfdf);
textView.setTextSize(20);
textView.setGravity(Gravity.CENTER);
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
int id = item.getItemId() ;
switch (id){
case android.R.id.home:
onBackPressed();
break ;
}
return super.onMenuItemSelected(featureId, item);
}
}
| apache-2.0 |
pupudu/analytics-dashboard | components/analytics-dashboard/org.wso2.carbon.analytics.dashboard.stub/target/generated-code/src/org/wso2/carbon/analytics/dashboard/admin/GetDashboardsResponse.java | 27439 |
/**
* GetDashboardsResponse.java
*
* This file was auto-generated from WSDL
* by the Apache Axis2 version: 1.6.1-wso2v10 Built on : Apr 16, 2014 (01:16:09 UTC)
*/
package org.wso2.carbon.analytics.dashboard.admin;
/**
* GetDashboardsResponse bean class
*/
@SuppressWarnings({"unchecked","unused"})
public class GetDashboardsResponse
implements org.apache.axis2.databinding.ADBBean{
public static final javax.xml.namespace.QName MY_QNAME = new javax.xml.namespace.QName(
"http://admin.dashboard.analytics.carbon.wso2.org",
"getDashboardsResponse",
"ns3");
/**
* field for _return
* This was an Array!
*/
protected org.wso2.carbon.analytics.dashboard.admin.data.xsd.Dashboard[] local_return ;
/* This tracker boolean wil be used to detect whether the user called the set method
* for this attribute. It will be used to determine whether to include this field
* in the serialized XML
*/
protected boolean local_returnTracker = false ;
public boolean is_returnSpecified(){
return local_returnTracker;
}
/**
* Auto generated getter method
* @return org.wso2.carbon.analytics.dashboard.admin.data.xsd.Dashboard[]
*/
public org.wso2.carbon.analytics.dashboard.admin.data.xsd.Dashboard[] get_return(){
return local_return;
}
/**
* validate the array for _return
*/
protected void validate_return(org.wso2.carbon.analytics.dashboard.admin.data.xsd.Dashboard[] param){
}
/**
* Auto generated setter method
* @param param _return
*/
public void set_return(org.wso2.carbon.analytics.dashboard.admin.data.xsd.Dashboard[] param){
validate_return(param);
local_returnTracker = true;
this.local_return=param;
}
/**
* Auto generated add method for the array for convenience
* @param param org.wso2.carbon.analytics.dashboard.admin.data.xsd.Dashboard
*/
public void add_return(org.wso2.carbon.analytics.dashboard.admin.data.xsd.Dashboard param){
if (local_return == null){
local_return = new org.wso2.carbon.analytics.dashboard.admin.data.xsd.Dashboard[]{};
}
//update the setting tracker
local_returnTracker = true;
java.util.List list =
org.apache.axis2.databinding.utils.ConverterUtil.toList(local_return);
list.add(param);
this.local_return =
(org.wso2.carbon.analytics.dashboard.admin.data.xsd.Dashboard[])list.toArray(
new org.wso2.carbon.analytics.dashboard.admin.data.xsd.Dashboard[list.size()]);
}
/**
*
* @param parentQName
* @param factory
* @return org.apache.axiom.om.OMElement
*/
public org.apache.axiom.om.OMElement getOMElement (
final javax.xml.namespace.QName parentQName,
final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException{
org.apache.axiom.om.OMDataSource dataSource =
new org.apache.axis2.databinding.ADBDataSource(this,MY_QNAME);
return factory.createOMElement(dataSource,MY_QNAME);
}
public void serialize(final javax.xml.namespace.QName parentQName,
javax.xml.stream.XMLStreamWriter xmlWriter)
throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{
serialize(parentQName,xmlWriter,false);
}
public void serialize(final javax.xml.namespace.QName parentQName,
javax.xml.stream.XMLStreamWriter xmlWriter,
boolean serializeType)
throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{
java.lang.String prefix = null;
java.lang.String namespace = null;
prefix = parentQName.getPrefix();
namespace = parentQName.getNamespaceURI();
writeStartElement(prefix, namespace, parentQName.getLocalPart(), xmlWriter);
if (serializeType){
java.lang.String namespacePrefix = registerPrefix(xmlWriter,"http://admin.dashboard.analytics.carbon.wso2.org");
if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)){
writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type",
namespacePrefix+":getDashboardsResponse",
xmlWriter);
} else {
writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type",
"getDashboardsResponse",
xmlWriter);
}
}
if (local_returnTracker){
if (local_return!=null){
for (int i = 0;i < local_return.length;i++){
if (local_return[i] != null){
local_return[i].serialize(new javax.xml.namespace.QName("http://admin.dashboard.analytics.carbon.wso2.org","return"),
xmlWriter);
} else {
writeStartElement(null, "http://admin.dashboard.analytics.carbon.wso2.org", "return", xmlWriter);
// write the nil attribute
writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","nil","1",xmlWriter);
xmlWriter.writeEndElement();
}
}
} else {
writeStartElement(null, "http://admin.dashboard.analytics.carbon.wso2.org", "return", xmlWriter);
// write the nil attribute
writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","nil","1",xmlWriter);
xmlWriter.writeEndElement();
}
}
xmlWriter.writeEndElement();
}
private static java.lang.String generatePrefix(java.lang.String namespace) {
if(namespace.equals("http://admin.dashboard.analytics.carbon.wso2.org")){
return "ns3";
}
return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
/**
* Utility method to write an element start tag.
*/
private void writeStartElement(java.lang.String prefix, java.lang.String namespace, java.lang.String localPart,
javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String writerPrefix = xmlWriter.getPrefix(namespace);
if (writerPrefix != null) {
xmlWriter.writeStartElement(namespace, localPart);
} else {
if (namespace.length() == 0) {
prefix = "";
} else if (prefix == null) {
prefix = generatePrefix(namespace);
}
xmlWriter.writeStartElement(prefix, localPart, namespace);
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
}
/**
* Util method to write an attribute with the ns prefix
*/
private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName,
java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{
if (xmlWriter.getPrefix(namespace) == null) {
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
xmlWriter.writeAttribute(namespace,attName,attValue);
}
/**
* Util method to write an attribute without the ns prefix
*/
private void writeAttribute(java.lang.String namespace,java.lang.String attName,
java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{
if (namespace.equals("")) {
xmlWriter.writeAttribute(attName,attValue);
} else {
registerPrefix(xmlWriter, namespace);
xmlWriter.writeAttribute(namespace,attName,attValue);
}
}
/**
* Util method to write an attribute without the ns prefix
*/
private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName,
javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String attributeNamespace = qname.getNamespaceURI();
java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace);
if (attributePrefix == null) {
attributePrefix = registerPrefix(xmlWriter, attributeNamespace);
}
java.lang.String attributeValue;
if (attributePrefix.trim().length() > 0) {
attributeValue = attributePrefix + ":" + qname.getLocalPart();
} else {
attributeValue = qname.getLocalPart();
}
if (namespace.equals("")) {
xmlWriter.writeAttribute(attName, attributeValue);
} else {
registerPrefix(xmlWriter, namespace);
xmlWriter.writeAttribute(namespace, attName, attributeValue);
}
}
/**
* method to handle Qnames
*/
private void writeQName(javax.xml.namespace.QName qname,
javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String namespaceURI = qname.getNamespaceURI();
if (namespaceURI != null) {
java.lang.String prefix = xmlWriter.getPrefix(namespaceURI);
if (prefix == null) {
prefix = generatePrefix(namespaceURI);
xmlWriter.writeNamespace(prefix, namespaceURI);
xmlWriter.setPrefix(prefix,namespaceURI);
}
if (prefix.trim().length() > 0){
xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
} else {
// i.e this is the default namespace
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
} else {
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
}
private void writeQNames(javax.xml.namespace.QName[] qnames,
javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
if (qnames != null) {
// we have to store this data until last moment since it is not possible to write any
// namespace data after writing the charactor data
java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer();
java.lang.String namespaceURI = null;
java.lang.String prefix = null;
for (int i = 0; i < qnames.length; i++) {
if (i > 0) {
stringToWrite.append(" ");
}
namespaceURI = qnames[i].getNamespaceURI();
if (namespaceURI != null) {
prefix = xmlWriter.getPrefix(namespaceURI);
if ((prefix == null) || (prefix.length() == 0)) {
prefix = generatePrefix(namespaceURI);
xmlWriter.writeNamespace(prefix, namespaceURI);
xmlWriter.setPrefix(prefix,namespaceURI);
}
if (prefix.trim().length() > 0){
stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
} else {
stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
}
} else {
stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
}
}
xmlWriter.writeCharacters(stringToWrite.toString());
}
}
/**
* Register a namespace prefix
*/
private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException {
java.lang.String prefix = xmlWriter.getPrefix(namespace);
if (prefix == null) {
prefix = generatePrefix(namespace);
while (xmlWriter.getNamespaceContext().getNamespaceURI(prefix) != null) {
prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
return prefix;
}
/**
* databinding method to get an XML representation of this object
*
*/
public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName)
throws org.apache.axis2.databinding.ADBException{
java.util.ArrayList elementList = new java.util.ArrayList();
java.util.ArrayList attribList = new java.util.ArrayList();
if (local_returnTracker){
if (local_return!=null) {
for (int i = 0;i < local_return.length;i++){
if (local_return[i] != null){
elementList.add(new javax.xml.namespace.QName("http://admin.dashboard.analytics.carbon.wso2.org",
"return"));
elementList.add(local_return[i]);
} else {
elementList.add(new javax.xml.namespace.QName("http://admin.dashboard.analytics.carbon.wso2.org",
"return"));
elementList.add(null);
}
}
} else {
elementList.add(new javax.xml.namespace.QName("http://admin.dashboard.analytics.carbon.wso2.org",
"return"));
elementList.add(local_return);
}
}
return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(), attribList.toArray());
}
/**
* Factory class that keeps the parse method
*/
public static class Factory{
/**
* static method to create the object
* Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable
* If this object is not an element, it is a complex type and the reader is at the event just after the outer start element
* Postcondition: If this object is an element, the reader is positioned at its end element
* If this object is a complex type, the reader is positioned at the end element of its outer element
*/
public static GetDashboardsResponse parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{
GetDashboardsResponse object =
new GetDashboardsResponse();
int event;
java.lang.String nillableValue = null;
java.lang.String prefix ="";
java.lang.String namespaceuri ="";
try {
while (!reader.isStartElement() && !reader.isEndElement())
reader.next();
if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","type")!=null){
java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance",
"type");
if (fullTypeName!=null){
java.lang.String nsPrefix = null;
if (fullTypeName.indexOf(":") > -1){
nsPrefix = fullTypeName.substring(0,fullTypeName.indexOf(":"));
}
nsPrefix = nsPrefix==null?"":nsPrefix;
java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":")+1);
if (!"getDashboardsResponse".equals(type)){
//find namespace for the prefix
java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix);
return (GetDashboardsResponse)org.wso2.carbon.analytics.dashboard.admin.data.xsd.ExtensionMapper.getTypeObject(
nsUri,type,reader);
}
}
}
// Note all attributes that were handled. Used to differ normal attributes
// from anyAttributes.
java.util.Vector handledAttributes = new java.util.Vector();
reader.next();
java.util.ArrayList list1 = new java.util.ArrayList();
while (!reader.isStartElement() && !reader.isEndElement()) reader.next();
if (reader.isStartElement() && new javax.xml.namespace.QName("http://admin.dashboard.analytics.carbon.wso2.org","return").equals(reader.getName())){
// Process the array and step past its final element's end.
nillableValue = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","nil");
if ("true".equals(nillableValue) || "1".equals(nillableValue)){
list1.add(null);
reader.next();
} else {
list1.add(org.wso2.carbon.analytics.dashboard.admin.data.xsd.Dashboard.Factory.parse(reader));
}
//loop until we find a start element that is not part of this array
boolean loopDone1 = false;
while(!loopDone1){
// We should be at the end element, but make sure
while (!reader.isEndElement())
reader.next();
// Step out of this element
reader.next();
// Step to next element event.
while (!reader.isStartElement() && !reader.isEndElement())
reader.next();
if (reader.isEndElement()){
//two continuous end elements means we are exiting the xml structure
loopDone1 = true;
} else {
if (new javax.xml.namespace.QName("http://admin.dashboard.analytics.carbon.wso2.org","return").equals(reader.getName())){
nillableValue = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","nil");
if ("true".equals(nillableValue) || "1".equals(nillableValue)){
list1.add(null);
reader.next();
} else {
list1.add(org.wso2.carbon.analytics.dashboard.admin.data.xsd.Dashboard.Factory.parse(reader));
}
}else{
loopDone1 = true;
}
}
}
// call the converter utility to convert and set the array
object.set_return((org.wso2.carbon.analytics.dashboard.admin.data.xsd.Dashboard[])
org.apache.axis2.databinding.utils.ConverterUtil.convertToArray(
org.wso2.carbon.analytics.dashboard.admin.data.xsd.Dashboard.class,
list1));
} // End of if for expected property start element
else {
}
while (!reader.isStartElement() && !reader.isEndElement())
reader.next();
if (reader.isStartElement())
// A start element we are not expecting indicates a trailing invalid property
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName());
} catch (javax.xml.stream.XMLStreamException e) {
throw new java.lang.Exception(e);
}
return object;
}
}//end of factory class
}
| apache-2.0 |
effektif/effektif | effektif-workflow-api/src/main/java/com/effektif/workflow/api/workflow/diagram/Node.java | 3815 | /*
* Copyright 2015 Effektif GmbH.
*
* 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.effektif.workflow.api.workflow.diagram;
import java.util.ArrayList;
import java.util.List;
/**
* An element - such as a shape - on a BPMN diagram.
*/
public class Node {
public String id;
public Bounds bounds;
public List<Node> children = null;
public String elementId;
/** Optional attribute that is only used for Pools and Lanes. */
public Boolean horizontal;
/** Optional attribute that is only used for collapsed sub-processes. */
public Boolean expanded;
public Node bounds(Bounds bounds) {
this.bounds = bounds;
return this;
}
public Node children(List<Node> children) {
if (children != null) {
this.children = new ArrayList<>(children);
} else {
this.children = null;
}
return this;
}
public Node elementId(String elementId) {
this.elementId = elementId;
return this;
}
public Node horizontal(boolean horizontal) {
this.horizontal = horizontal;
return this;
}
public Node expanded(Boolean expanded) {
this.expanded = expanded;
return this;
}
public Node id(String id) {
this.id = id;
return this;
}
public Node addNode(Node node) {
if (node != null) {
if (children == null) {
children = new ArrayList<>();
}
children.add(node);
}
return this;
}
public Node getChild(String id) {
if (id != null && children != null) {
for (Node node : children) {
if (id.equals(node.elementId)) {
return node;
}
}
}
return null;
}
public boolean hasChildren() {
return children != null && !children.isEmpty();
}
/**
* A Node is considered valid if its Bounds are valid
* and all the contained children are valid.
*/
public boolean isValid() {
if (bounds == null || !bounds.isValid()) {
return false;
}
if (children != null) {
for (Node node : children) {
if (!node.isValid()) {
return false;
}
}
}
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((elementId == null) ? 0 : elementId.hashCode());
result = prime * result + ((bounds == null) ? 0 : bounds.hashCode());
result = prime * result + ((children == null) ? 0 : children.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Node other = (Node) obj;
if (elementId == null) {
if (other.elementId != null)
return false;
} else if (!elementId.equals(other.elementId))
return false;
if (bounds == null) {
if (other.bounds != null)
return false;
} else if (!bounds.equals(other.bounds))
return false;
if (children == null) {
if (other.children != null)
return false;
} else if (!children.equals(other.children))
return false;
return true;
}
}
| apache-2.0 |
PerfCake/PerfClipse | org.perfclipse.wizards/src/org/perfclipse/wizards/DestinationAddWizard.java | 2174 | /*
* Perfclispe
*
*
* Copyright (c) 2013 Jakub Knetl
*
* 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.perfclipse.wizards;
import org.eclipse.swt.widgets.TableItem;
import org.perfcake.model.ObjectFactory;
import org.perfcake.model.Scenario.Reporting.Reporter.Destination;
import org.perfclipse.core.model.PeriodModel;
import org.perfclipse.core.model.PropertyModel;
import org.perfclipse.wizards.pages.DestinationPage;
/**
* @author Jakub Knetl
*
*/
public class DestinationAddWizard extends AbstractPerfCakeAddWizard {
private DestinationPage destinationPage;
private Destination destination;
/**
*
*/
public DestinationAddWizard() {
super();
setWindowTitle("Add destination");
}
@Override
public boolean performFinish() {
destination = new ObjectFactory().createScenarioReportingReporterDestination();
destination.setClazz(destinationPage.getDestinationType());
destination.setEnabled(destinationPage.getEnabled());
for (TableItem i : destinationPage.getPeriodViewer().getTable().getItems()){
if (i.getData() instanceof PeriodModel){
PeriodModel p = (PeriodModel) i.getData();
destination.getPeriod().add(p.getPeriod());
}
}
for (TableItem i : destinationPage.getPropertyViewer().getTable().getItems()){
if (i.getData() instanceof PropertyModel){
PropertyModel p = (PropertyModel) i.getData();
destination.getProperty().add(p.getProperty());
}
}
return true;
}
@Override
public void addPages() {
destinationPage = new DestinationPage();
addPage(destinationPage);
super.addPages();
}
public Destination getDestination() {
return destination;
}
}
| apache-2.0 |
cnlinjie/infrastructure | util/src/main/java/com/github/cnlinjie/infrastructure/util/SystemInfoUtils.java | 2427 | package com.github.cnlinjie.infrastructure.util;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.List;
/**
* 系统工具
*
* @author linjie
* @version 0.0.1
* @date 16-5-4
*/
public final class SystemInfoUtils {
private static final Logger logger = LoggerFactory.getLogger(SystemInfoUtils.class);
public enum OSType {
Windows, Linux, Unknown
}
public final static OSType getOSType() {
String name = System.getProperty("os.name");
System.out.println(name.toLowerCase().startsWith("linux"));
if (name.toLowerCase().startsWith("windows")) {
return OSType.Windows;
} else if (name.toLowerCase().startsWith("linux")) {
return OSType.Linux;
}
logger.info("System.getProperty(\"os.name\")" + System.getProperty("os.name"));
return OSType.Unknown;
}
/**
* 获取应用程序地址
*
* @return 返回应用程序地址
*/
public static String getApplicationPath() {
String appDir = System.getProperty("user.dir");// 应用程序目录
return appDir;
}
/**
* 获取本机的MAC地址
*
* @return 返回本机的MAC地址
*/
public static List<String> getMacAddress() {
List<String> macs = Lists.newArrayList();
try {
Enumeration<NetworkInterface> netWorks = NetworkInterface.getNetworkInterfaces();
while (netWorks.hasMoreElements()) {
NetworkInterface netWork = netWorks.nextElement();
byte[] mac = netWork.getHardwareAddress();
if (mac == null)
continue;
StringBuilder builder = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
builder.append(String.format("%02X%s", mac[i],(i < mac.length - 1) ? "-" : ""));
}
macs.add(builder.toString());
}
} catch (Exception e) {
logger.error("getMacAddress Error:",e);
}
return macs;
}
public static void main(String[] args) {
System.out.println(SystemInfoUtils.getOSType());
List<String> macAddress = SystemInfoUtils.getMacAddress();
System.out.println(macAddress.size());
}
}
| apache-2.0 |
qiumingkui/sample | sample-common/src/main/java/com/qiumingkui/sample/imedia/common/ext/util/AssertionUtil.java | 2712 | package com.qiumingkui.sample.imedia.common.ext.util;
public class AssertionUtil {
public static void assertArgumentEquals(Object anObject1, Object anObject2, String aMessage) {
if (!anObject1.equals(anObject2)) {
throw new IllegalArgumentException(aMessage);
}
}
public static void assertArgumentFalse(boolean aBoolean, String aMessage) {
if (aBoolean) {
throw new IllegalArgumentException(aMessage);
}
}
public static void assertArgumentLength(String aString, int aMaximum, String aMessage) {
int length = aString.trim().length();
if (length > aMaximum) {
throw new IllegalArgumentException(aMessage);
}
}
public static void assertArgumentLength(String aString, int aMinimum, int aMaximum, String aMessage) {
int length = aString.trim().length();
if (length < aMinimum || length > aMaximum) {
throw new IllegalArgumentException(aMessage);
}
}
public static void assertArgumentNotEmpty(String aString, String aMessage) {
if (aString == null || aString.trim().isEmpty()) {
throw new IllegalArgumentException(aMessage);
}
}
public static void assertArgumentNotEquals(Object anObject1, Object anObject2, String aMessage) {
if (anObject1.equals(anObject2)) {
throw new IllegalArgumentException(aMessage);
}
}
public static void assertArgumentNotNull(Object anObject, String aMessage) {
if (anObject == null) {
throw new IllegalArgumentException(aMessage);
}
}
public static void assertArgumentRange(double aValue, double aMinimum, double aMaximum, String aMessage) {
if (aValue < aMinimum || aValue > aMaximum) {
throw new IllegalArgumentException(aMessage);
}
}
public static void assertArgumentRange(float aValue, float aMinimum, float aMaximum, String aMessage) {
if (aValue < aMinimum || aValue > aMaximum) {
throw new IllegalArgumentException(aMessage);
}
}
public static void assertArgumentRange(int aValue, int aMinimum, int aMaximum, String aMessage) {
if (aValue < aMinimum || aValue > aMaximum) {
throw new IllegalArgumentException(aMessage);
}
}
public static void assertArgumentRange(long aValue, long aMinimum, long aMaximum, String aMessage) {
if (aValue < aMinimum || aValue > aMaximum) {
throw new IllegalArgumentException(aMessage);
}
}
public static void assertArgumentTrue(boolean aBoolean, String aMessage) {
if (!aBoolean) {
throw new IllegalArgumentException(aMessage);
}
}
public static void assertStateFalse(boolean aBoolean, String aMessage) {
if (aBoolean) {
throw new IllegalStateException(aMessage);
}
}
public static void assertStateTrue(boolean aBoolean, String aMessage) {
if (!aBoolean) {
throw new IllegalStateException(aMessage);
}
}
}
| apache-2.0 |
willmorejg/net.ljcomputing.sql | src/main/java/net/ljcomputing/sql/collection/SqlFragmentIterator.java | 1668 | /**
Copyright 2016, James G. Willmore
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package net.ljcomputing.sql.collection;
import java.util.Iterator;
import java.util.Spliterator;
import java.util.function.Consumer;
/**
* Interface shared by all collections of SQL fragments.
*
* @author James G. Willmore
*
*/
public interface SqlFragmentIterator<T> extends Iterator<T>, Iterable<T> {
/**
* Reverse the order of the iterator.
*/
void reverse();
/**
* @see java.util.Iterator#hasNext()
*/
@Override
boolean hasNext();
/**
* @see java.util.Iterator#next()
*/
@Override
T next();
/**
* Remove the given element from the array of elements
* within the implementing class.
*
* @param obj the obj
* @return true, if successful
*/
boolean remove(T obj);
/**
* @see java.lang.Iterable#iterator()
*/
@Override
Iterator<T> iterator();
/**
* @see java.lang.Iterable#forEach(java.util.function.Consumer)
*/
@Override
void forEach(Consumer<? super T> action);
/**
* @see java.lang.Iterable#spliterator()
*/
@Override
Spliterator<T> spliterator();
}
| apache-2.0 |
spring-projects/spring-framework | spring-context/src/test/java/org/springframework/context/support/AutowiredService.java | 1123 | /*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.support;
import org.springframework.context.MessageSource;
/**
* @author Juergen Hoeller
*/
public class AutowiredService {
private MessageSource messageSource;
public void setMessageSource(MessageSource messageSource) {
if (this.messageSource != null) {
throw new IllegalArgumentException("MessageSource should not be set twice");
}
this.messageSource = messageSource;
}
public MessageSource getMessageSource() {
return messageSource;
}
}
| apache-2.0 |
equella/Equella | Platform/Plugins/com.tle.web.sections/src/com/tle/web/sections/SectionTree.java | 10048 | /*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* The Apereo Foundation 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.tle.web.sections;
import com.tle.web.sections.events.SectionEvent;
import com.tle.web.sections.registry.TreeRegistry;
import java.util.EventListener;
import java.util.List;
import java.util.Map;
/**
* The <code>SectionTree</code> is an object which stores a tree of {@link Section}s.
*
* <p>Normally a <code>SectionTree</code> will be mapped to a URL (e.g. <code>/access/search.do
* </code>) and registered with the {@link TreeRegistry}, but in the case of {@link SectionFilter}s
* they generally create anonymous <code>SectionTree</code>s.
*
* <p>Generally a Section will only deal with the <code>SectionTree</code> directly during the tree
* registration process. Normally that will consist of registering any child/inner <code>Section
* </code>s and registering any application {@link SectionEvent}s and/or {@link EventListener}s
*
* @author jmaginnis
*/
public interface SectionTree {
/**
* Check for the existance of a particular Section id.
*
* @param id The id to look for
* @return True if it exists
*/
boolean containsId(String id);
/**
* A place holder id is a more descriptive id for a section. <br>
* Generally it's used as an id for an extension point where other sections can be inserted.
*
* @param placeHolderId
* @return The Section id of that placeHolderId
*/
String getPlaceHolder(String placeHolderId);
/**
* Get the parent id of the section with the given id.
*
* @param sectionId The id of the section to find the parent of
* @return The parent id
*/
String getParentId(String sectionId);
/**
* Get the Section for the given id.
*
* @param sectionId The id of the Section
* @return The Section
*/
Section getSectionForId(String sectionId);
/**
* Get a list of child id's for the given parent id. Does not include inner children. Note that
* this is used within the Sections framework for renderFirstResult and renderChildren
*
* @param sectionId
* @return A list of child Section id's
*/
List<SectionId> getChildIds(String sectionId);
/**
* Get a list of all child id's (including inner children) for the given parent id.
*
* @param sectionId
* @return A list of child Section id's
*/
List<SectionId> getAllChildIds(String sectionId);
/**
* Register an inner Section. <br>
* An inner Section is a section which will not be returned by the <code>getChildIds()</code> call
* (which is used within the Sections framework for renderFirstResult and renderChildren).<br>
* Generally a section should be registered as an inner section if the parent has a hard
* dependency on it, e.g. components from the <code>com.tle.web.sections.standard</code> package.
*
* @param section The Section to register
* @param parentId The id of the parent section
* @return The id of the registered section
*/
String registerInnerSection(Object section, String parentId);
/**
* Register one of more sections into the given parent id. <br>
* Same as calling <code>registerSections(section, parent, null, true)</code>
*
* @param section Can be either a Section, or a {@link SectionNode}, or a List of either.
* @param parent The id of the parent Section
* @return If only one Section is registered, the id of that Section.
* @see SectionNode
* @see #registerSections(Object, String, String, boolean)
*/
String registerSections(Object section, String parent);
/**
* Register one of more sections into the given parent id, inserted after or before the given id.
* <br>
*
* @param section Can be either a Section, or a {@link SectionNode}, or a List of either.
* @param parent The id of the parent Section
* @param insertId The id of a sibling Section from which to insert after or before. If <code>null
* </code> is passed in, always add the Section's to the end of the parent.
* @param after True if Section's are to be inserted after the inserId, else insert before.
* @return If only one Section is registered, the id of that Section.
* @see SectionNode
*/
String registerSections(Object section, String parent, String insertId, boolean after);
/**
* Set an attribute on this SectionTree.
*
* @param key Key to set
* @param value Value to set
*/
void setAttribute(Object key, Object value);
/**
* Returns whether or not this SectionTree has an attribute with the given key.
*
* @param key The Key to check
* @return True if the attribute exists
*/
boolean containsKey(Object key);
/**
* Get an attribute on this SectionTree
*
* @param <T> The type of the attribute
* @param key The key for the attribute
* @return The attribute for the given key
*/
<T> T getAttribute(Object key);
/**
* Finds the section 'closest' to reference. By closest I mean: 1. Search children first. 2. Check
* parent and it's children (excluding reference of course) next 3. Check the parent's parent and
* it's children etc. Until we find a match.
*
* @param key
* @param reference
* @return
*/
<T extends SectionId, S extends T> S lookupSection(Class<T> key, SectionId reference);
/**
* Finds all sections indexed with key
*
* @param key
* @return
*/
<T extends SectionId, S extends T> List<S> lookupSections(Class<T> key);
/**
* Set private SectionTree related data for a particular Section.
*
* @param <T> The type of the data
* @param id The id of the Section
* @param data The data to set
*/
<T> void setData(String id, T data);
/**
* Get private data previously set with <code>setData()</code>
*
* @param <T> The type of the data
* @param id The id of the Section
* @return The data for the Section
* @see #setData(String, Object)
*/
<T> T getData(String id);
/**
* Set the layout information for a particular section. The format of this data can be anything,
* and it usually up to the parent as to what makes sense here.
*
* @param <T> The type of the layout data
* @param id The id of the Section
* @return The layout data object or null if non set
*/
<T> T getLayout(String id);
/**
* @param id
* @param data
*/
void setLayout(String id, Object data);
/**
* Get the root id of this SectionTree. <br>
* All Section's registered within this SectionTree are prepended with this id.<br>
* A {@link SectionInfo} can only contain SectionTree's with different root id's.
*
* @return The root id
*/
String getRootId();
/**
* Get all application events associated with this SectionTree.
*
* @return All application {@link SectionEvent}s
*/
List<SectionEvent<? extends EventListener>> getApplicationEvents();
/**
* Add an application {@link SectionEvent}. <br>
* Any events registered with the SectionTree will be queued in the {@link SectionInfo} by the
* {@link SectionsController}.
*
* @param event The SectionEvent to be added.
*/
void addApplicationEvent(SectionEvent<? extends EventListener> event);
/**
* Get any <code>EventListener</code>s registered to the given target.
*
* @param <T> The type of the EventListener subclass
* @param target The target event listener list. Use <code>null</code> for the broadcast event
* listener list.
* @param clazz The EventListener subclass
* @return A list of event listeners, which can either by a <code>String</code> which is the id of
* a Section which implements the EventListener subclass, or an object that implements the
* EventListener subclass.
*/
<T extends EventListener> List<Object> getListeners(String target, Class<? extends T> clazz);
/**
* Register an <code>EventListener</code> in the given target list.
*
* @param <T> The type of the EventListener subclass
* @param target The target event listener list. Use <code>null</code> for the broadcast event
* listener list.
* @param clazz The EventListener subclass
* @param eventListener Can either by a <code>String</code> which is the id of a Section which
* implements the EventListener subclass, or an object that implements the EventListener
* subclass.
*/
<T extends EventListener> void addListener(String target, Class<T> clazz, Object eventListener);
/**
* Used for pruning a section tree dynamically. E.g. a portlet has been removed from the tree.
*
* @param target
*/
void removeListeners(String target);
List<RegistrationHandler> getExtraRegistrationHandlers();
void addRegistrationHandler(RegistrationHandler handler);
void addDelayedRegistration(DelayedRegistration delayed);
void runDelayedRegistration();
void finished();
boolean isFinished();
void setRuntimeAttribute(Object key, Object value);
Map<Object, Object> getRuntimeAttributes();
<T> List<T> addToListAttribute(Object key, T value);
interface DelayedRegistration {
void register(SectionTree tree);
}
String getSubId(String parentId, String childId);
String registerSubInnerSection(Section section, String parentId);
String registerSubInnerSection(Section section, String parentId, String preferredId);
}
| apache-2.0 |
icunning/fcvtc | src/LTK/LTKJava/src/main/java/org/llrp/ltk/util/LLRPConverter.java | 11567 | /*
* Copyright 2007 ETH Zurich
*
* 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.llrp.ltk.util;
import jargs.gnu.CmdLineParser;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.jdom.JDOMException;
import org.llrp.ltk.exceptions.InvalidLLRPMessageException;
import org.llrp.ltk.types.LLRPMessage;
/**
* LLRPConverter is a (command line) tool to convert
* LLRP binary messages to LTK-XML messages and vice versa.<p>
*
* Usage: java -jar LTKJava<Version>.jar
* [{-v,--verbose}]
* [{-b,--binary}] input message(s) is in LLRP binary format<p>
* [{-x,--xml}] input message(s) is in LTK XML format<p>
* [{-d,--dir} directory path] directory with messages<p>
* [{-f,--file} file path] single message to be converted<p>
* [{-t,--targetDir} targetDirectory path] target directory for converted messages<p>
* Example binary->xml file conversion to console: java -jar LTKJava<Version>.jar -b ADD_ROSPEC.bin<p>
* Example xml->binary file conversion to console: java -jar LTKJava<Version>.jar -x ADD_ROSPEC.xml<p>
* Example xml->binary file conversion of all files in a dir:
* java -jar LTKJava<Version>.jar -x -d messages/xml -t messages/bin");<p>
}
*
*
*/
public class LLRPConverter {
LLRPMessage message;
static final Logger LOGGER = Logger.getLogger("LLRPConverter.class");
public LLRPConverter(){
super();
}
private void convertFilesInDirectory(String dir, String target, Boolean xml) {
File testDir = new File(dir);
int i;
String filename;
String targetFile;
String targetDir;
String[] filenames;
FileWriter out;
String output;
FilenameFilter filter;
LLRPMessage message;
// converted files are written to the destination directory if
// no other directory is specified
if (target == null) {
targetDir = dir;
}
else {
targetDir = target;
}
// find all binary or all xml files in the directory
if (xml == Boolean.FALSE) {
filter = new BinaryFilter();
}
else {
filter = new XMLFilter();
}
for (filenames = testDir.list(filter), i = 0;
filenames != null && i < filenames.length; i++) {
// for each file found, convert it, and write the result to the appropriate file
filename = filenames[i];
int dotPos = filename.lastIndexOf(".");
try {
if (xml == Boolean.TRUE) {
message = (LLRPMessage) Util.loadXMLLLRPMessage(new File(dir + "/" + filename));
filename = filename.substring(0, dotPos) + ".bin" ;
FileOutputStream ous = new FileOutputStream(new File(targetDir + "/" + filename));
ous.write(message.encodeBinary());
ous.flush();
ous.close();
System.out.println("Successfully converted to " + filename);
}
else {
message = (LLRPMessage) Util.loadBinaryLLRPMessage(new File(dir + "/" + filename));
filename = filename.substring(0, dotPos) + ".xml" ;
out = new FileWriter(new File(targetDir + "/" + filename));
out.write(message.toXMLString());
out.close();
System.out.println("Successfully converted to " + filename);
}
}
catch (InvalidLLRPMessageException e) {
System.err.println("LLRP Message is not valid " + filename);
System.err.println(e.getMessage());
}
catch (FileNotFoundException e) {
System.err.println("File not found " + filename);
}
catch (IOException e) {
System.err.println("File IO problem " + filename);
}
catch (JDOMException e) {
System.err.println("Could not create XML document to instantiate LLRP Message " + filename);
e.printStackTrace();
}
}
}
private void convert(Boolean xml, Boolean binary, String file, String dir, String targetDir) {
LLRPMessage message;
try {
if (binary != null) {
if (file != null) {
message = Util.loadBinaryLLRPMessage(new File(file));
System.out.println(message.toXMLString());
}
else if (dir != null) {
convertFilesInDirectory(dir, targetDir, Boolean.FALSE);
}
else {
System.err.println("This should never happen!");
}
}
else if (xml != null) {
if (file != null) {
message = Util.loadXMLLLRPMessage(new File(file));
System.out.println(message.toHexString());
}
else if (dir != null) {
convertFilesInDirectory(dir, targetDir, Boolean.TRUE);
}
else {
System.err.println("This should never happen!");
}
}
}
catch (InvalidLLRPMessageException e) {
System.err.println("LLRP Message is not valid " + file);
System.err.println(e.getMessage());
}
catch (FileNotFoundException e) {
System.err.println("File not found");
printUsage();
System.exit(2);
}
catch (IOException e) {
System.err.println("File not found");
printUsage();
System.exit(2);
}
catch (JDOMException e) {
System.err.println("Invalid XML document to instantiate LLRP Message" + file);
System.exit(2);
}
}
private static void printUsage() {
System.err.println(
"Usage: java -jar LTKJava<Version>.jar [{-v,--verbose}]\n" +
" [{-b,--binary}] input message(s) is in LLRP binary format\n" +
" [{-x,--xml}] input message(s) is in LTK XML format\n" +
" [{-d,--dir} directory path] directory with messages\n" +
" [{-f,--file} file path] single message to be converted\n" +
" [{-t,--targetDir} targetDirectory path] target directory for converted messages\n\n" +
"Example binary->xml file conversion to console:\n java -jar LTKJava<Version>.jar -b -f ADD_ROSPEC.bin\n" +
"Example xml->binary file conversion to console:\n java -jar LTKJava<Version>.jar -x -f ADD_ROSPEC.xml\n" +
"Example xml->binary file conversion of all files in a dir:\n" +
" java -jar LTKJava<Version>.jar -x -d messages/xml -t messages/bin\n");
}
public static void main( String[] args ) {
// First, you must create a CmdLineParser, and add to it the
// appropriate Options.
BasicConfigurator.configure();
Logger rootLogger = LogManager.getRootLogger();
rootLogger.setLevel(Level.WARN);
CmdLineParser parser = new CmdLineParser();
CmdLineParser.Option verbose = parser.addBooleanOption('v', "verbose");
CmdLineParser.Option binary = parser.addBooleanOption('b',"binary");
CmdLineParser.Option xml = parser.addBooleanOption('x',"xml");
CmdLineParser.Option dir = parser.addStringOption('d',"dir");
CmdLineParser.Option file = parser.addStringOption('f',"file");
CmdLineParser.Option targetDir = parser.addStringOption('t',"targetDir");
// Next, you must parse the user-provided command line arguments, and
// catch any errors therein.
// Options may appear on the command line in any order, and may even
// appear after some or all of the non-option arguments.
try {
parser.parse(args);
}
catch ( CmdLineParser.OptionException e ) {
System.err.println(e.getMessage());
printUsage();
System.exit(2);
}
// For options that may be specified only zero or one time, the value
// of that option is extracted. If the options
// were not specified, the corresponding values will be null.
Boolean verboseValue = (Boolean)parser.getOptionValue(verbose, Boolean.FALSE);
Boolean xmlValue = (Boolean)parser.getOptionValue(xml);
Boolean binaryValue = (Boolean)parser.getOptionValue(binary);
String dirValue = (String)parser.getOptionValue(dir);
String fileValue = (String)parser.getOptionValue(file);
String targetDirValue = (String)parser.getOptionValue(targetDir);
if ((xmlValue == null) && (binaryValue == null) && (fileValue == null) && (dirValue == null)){
printUsage();
System.exit(2);
}
if ((xmlValue == null) && (binaryValue == null)){
System.err.println("Specify the type of input message format (either binary or xml)");
printUsage();
System.exit(2);
}
if ((xmlValue != null) && (binaryValue != null)){
System.err.println("Specify the type of input message format (either binary or xml)");
printUsage();
System.exit(2);
}
if ((fileValue == null) && (dirValue == null)){
System.err.println("Specify a file or directory for conversion");
printUsage();
System.exit(2);
}
if ((fileValue != null) && (dirValue != null)){
System.err.println("Specify either a file or a directory for conversion");
printUsage();
System.exit(2);
}
if ((targetDirValue != null) && (!(new File(targetDirValue)).isDirectory())){
System.err.println("Target Directory does not exist: " + targetDirValue);
printUsage();
System.exit(2);
}
if ((dirValue != null) && (!(new File(dirValue)).isDirectory())){
System.err.println("Directory does not exist: " + dirValue);
printUsage();
System.exit(2);
}
if ((fileValue != null) && (!(new File(fileValue)).isFile())){
System.err.println("File does not exist: " + fileValue);
printUsage();
System.exit(2);
}
LLRPConverter converter = new LLRPConverter();
converter.convert(xmlValue, binaryValue, fileValue, dirValue, targetDirValue);
}
class BinaryFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.endsWith(".bin"));
}
}
class XMLFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.endsWith(".xml"));
}
}
}
| apache-2.0 |
Novemser/LearnJava | src/main/java/File/Java7FileIO.java | 2990 | package File;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Random;
import java.util.Scanner;
/**
* Project: LearnJava
* Package: File
* Author: Novemser
* 2017/9/5
*/
public class Java7FileIO {
private String path;
public Java7FileIO(String path) {
this.path = path;
}
public static void main(String[] args) throws IOException {
Java7FileIO fileIO = new Java7FileIO("F:\\IAMLARGE.txt");
// fileIO.writeFileTest();
// fileIO.readFileTest();
// fileIO.readFileByBuffer();
// fileIO.readFileNIO();
fileIO.readFileCommonIO();
}
public void writeFileTest() throws IOException {
File fileToWrite = new File(path);
Path filePath = fileToWrite.toPath();
BufferedWriter writer =
Files.newBufferedWriter(filePath, Charset.defaultCharset(), StandardOpenOption.APPEND);
Random random = new Random();
for (int i = 0; i < Integer.MAX_VALUE; i++) {
String content = String.valueOf(random.nextInt());
writer.write(content);
writer.newLine();
}
writer.flush();
writer.close();
}
private Long count = 0L;
public void readFileTest() throws IOException {
try (Scanner scanner = new Scanner(Paths.get(path))) {
while (scanner.hasNext()) {
count++;
if (count % 10000000 == 0) {
System.out.println(count);
}
}
}
}
public void readFileByBuffer() throws IOException {
BufferedReader reader =
Files.newBufferedReader(Paths.get(path));
String line = null;
while ((line = reader.readLine()) != null) {
count++;
if (count % 10000000 == 0) {
System.out.println(count);
}
}
}
/**
* TODO:Pending to validate this method
*
* @throws IOException
*/
public void readFileNIO() throws IOException {
try (SeekableByteChannel ch = Files.newByteChannel(Paths.get(path))) {
ByteBuffer bb = ByteBuffer.allocateDirect(10000000);
for (; ; ) {
StringBuilder line = new StringBuilder();
int n = ch.read(bb);
line.append((char) n);
// add chars to line
// ...
if (line.length() >= 10000000) {
System.out.println("Yeah");
break;
}
}
}
}
public void readFileCommonIO() throws IOException {
Files.readAllLines(Paths.get(path));
}
}
| apache-2.0 |
commsen/EM | em.common/src/main/java/com/commsen/em/storage/ContractStorage.java | 355 | package com.commsen.em.storage;
import java.io.File;
import java.io.IOException;
import java.util.Set;
import org.osgi.resource.Requirement;
public interface ContractStorage {
boolean saveContractor (File contractor, String coordinates) throws IOException;
Set<String> getContractors (Requirement requirement);
Set<String> getAllContracts ();
}
| apache-2.0 |
inbloom/secure-data-service | tools/csv2xml/src/org/slc/sli/sample/entities/Recognition.java | 4428 | /*
* Copyright 2012-2013 inBloom, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.04.20 at 03:09:04 PM EDT
//
package org.slc.sli.sample.entities;
import java.util.Calendar;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* Recognition given to the student for accomplishments in a co-curricular, or extra-curricular activity.
*
* <p>Java class for Recognition complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Recognition">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="RecognitionType" type="{http://ed-fi.org/0100}RecognitionType"/>
* <element name="RecognitionDescription" type="{http://ed-fi.org/0100}RecognitionDescription" minOccurs="0"/>
* <element name="RecognitionAwardDate" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Recognition", propOrder = {
"recognitionType",
"recognitionDescription",
"recognitionAwardDate"
})
public class Recognition {
@XmlElement(name = "RecognitionType", required = true)
protected RecognitionType recognitionType;
@XmlElement(name = "RecognitionDescription")
protected String recognitionDescription;
@XmlElement(name = "RecognitionAwardDate", type = String.class)
@XmlJavaTypeAdapter(Adapter2 .class)
@XmlSchemaType(name = "date")
protected Calendar recognitionAwardDate;
/**
* Gets the value of the recognitionType property.
*
* @return
* possible object is
* {@link RecognitionType }
*
*/
public RecognitionType getRecognitionType() {
return recognitionType;
}
/**
* Sets the value of the recognitionType property.
*
* @param value
* allowed object is
* {@link RecognitionType }
*
*/
public void setRecognitionType(RecognitionType value) {
this.recognitionType = value;
}
/**
* Gets the value of the recognitionDescription property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRecognitionDescription() {
return recognitionDescription;
}
/**
* Sets the value of the recognitionDescription property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRecognitionDescription(String value) {
this.recognitionDescription = value;
}
/**
* Gets the value of the recognitionAwardDate property.
*
* @return
* possible object is
* {@link String }
*
*/
public Calendar getRecognitionAwardDate() {
return recognitionAwardDate;
}
/**
* Sets the value of the recognitionAwardDate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRecognitionAwardDate(Calendar value) {
this.recognitionAwardDate = value;
}
}
| apache-2.0 |
yschimke/rsocket-java | rsocket-core/src/test/java/io/rsocket/test/util/TestDuplexConnection.java | 3796 | /*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.rsocket.test.util;
import io.reactivex.subscribers.TestSubscriber;
import io.rsocket.DuplexConnection;
import io.rsocket.Frame;
import java.util.Collection;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingQueue;
import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.DirectProcessor;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.publisher.MonoProcessor;
/**
* An implementation of {@link DuplexConnection} that provides functionality to modify the behavior
* dynamically.
*/
public class TestDuplexConnection implements DuplexConnection {
private static final Logger logger = LoggerFactory.getLogger(TestDuplexConnection.class);
private final LinkedBlockingQueue<Frame> sent;
private final DirectProcessor<Frame> sentPublisher;
private final DirectProcessor<Frame> received;
private final MonoProcessor<Void> close;
private final ConcurrentLinkedQueue<TestSubscriber<Frame>> sendSubscribers;
private volatile double availability = 1;
private volatile int initialSendRequestN = Integer.MAX_VALUE;
public TestDuplexConnection() {
sent = new LinkedBlockingQueue<>();
received = DirectProcessor.create();
sentPublisher = DirectProcessor.create();
sendSubscribers = new ConcurrentLinkedQueue<>();
close = MonoProcessor.create();
}
@Override
public Mono<Void> send(Publisher<Frame> frames) {
if (availability <= 0) {
return Mono.error(
new IllegalStateException("RSocket not available. Availability: " + availability));
}
TestSubscriber<Frame> subscriber = TestSubscriber.create(initialSendRequestN);
Flux.from(frames)
.doOnNext(
frame -> {
sent.offer(frame);
sentPublisher.onNext(frame);
})
.doOnError(
throwable -> {
logger.error("Error in send stream on test connection.", throwable);
})
.subscribe(subscriber);
sendSubscribers.add(subscriber);
return Mono.empty();
}
@Override
public Flux<Frame> receive() {
return received;
}
@Override
public double availability() {
return availability;
}
@Override
public Mono<Void> close() {
return close;
}
@Override
public Mono<Void> onClose() {
return close();
}
public Frame awaitSend() throws InterruptedException {
return sent.take();
}
public void setAvailability(double availability) {
this.availability = availability;
}
public Collection<Frame> getSent() {
return sent;
}
public Publisher<Frame> getSentAsPublisher() {
return sentPublisher;
}
public void addToReceivedBuffer(Frame... received) {
for (Frame frame : received) {
this.received.onNext(frame);
}
}
public void clearSendReceiveBuffers() {
sent.clear();
sendSubscribers.clear();
}
public void setInitialSendRequestN(int initialSendRequestN) {
this.initialSendRequestN = initialSendRequestN;
}
public Collection<TestSubscriber<Frame>> getSendSubscribers() {
return sendSubscribers;
}
}
| apache-2.0 |
ravi115/RestaurantApp | RestaurantApp/src/com/mobile/restaurant/business/ApplicationBusiness.java | 1443 | /*
* (c) copyright 2017.
*/
package com.mobile.restaurant.business;
import org.apache.log4j.Logger;
import com.mobile.restaurant.database.DBClientImpl;
import com.mobile.restaurant.exception.ApplicationException;
import com.mobile.restaurant.query.QueryReader;
import com.mobile.restaurant.response.ApplicationResponse;
/**
* This class is the central unit of this application. It is responsible to
* initialize Response of this application with desired result.
*
* @author ravi ranjan kumar
* @since 2017-08-28
*
*/
public class ApplicationBusiness {
// Logger variable
private final Logger LOG = Logger.getLogger(getClass());
/**
* Method to initialize the Application Response with desired result.
*
* @param cuisineType
* requested parameter.
* @return result in the form of application response.
* @throws ApplicationException
* throws any checked or unchecked exception while processing of
* application.
*/
public ApplicationResponse getResult(final String cuisineType) throws ApplicationException {
LOG.info("Inside business Logic.");
final String query = new QueryReader(cuisineType).readQuery();
LOG.info("Generated Query is :" + query);
final ApplicationResponse appResponse = new ApplicationResponse();
if (null != query && !query.isEmpty()) {
appResponse.restaurants = new DBClientImpl().getQueryResult(query);
}
return appResponse;
}
}
| apache-2.0 |
ehrmann/classifier4j | src/main/java/com/davidehrmann/classifier4J/util/MapEntryFlattener.java | 182 | package com.davidehrmann.classifier4j.util;
public interface MapEntryFlattener<K, LeftV, RightV, ResultV> {
public ResultV flatten(K key, LeftV leftValue, RightV rightValue);
} | apache-2.0 |
DALDEI/byte-buddy | byte-buddy-dep/src/test/java/net/bytebuddy/implementation/EqualsMethodOtherTest.java | 26179 | package net.bytebuddy.implementation;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.field.FieldDescription;
import net.bytebuddy.description.modifier.Ownership;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import org.junit.Test;
import java.lang.annotation.RetentionPolicy;
import java.util.Comparator;
import static net.bytebuddy.matcher.ElementMatchers.any;
import static net.bytebuddy.matcher.ElementMatchers.*;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.*;
public class EqualsMethodOtherTest {
private static final String FOO = "foo", BAR = "bar";
@Test(expected = NullPointerException.class)
public void testNullableField() throws Exception {
Class<?> type = new ByteBuddy()
.subclass(Object.class)
.defineField(FOO, Object.class, Visibility.PUBLIC)
.method(isEquals())
.intercept(EqualsMethod.isolated().withNonNullableFields(named(FOO)))
.make()
.load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
type.getDeclaredConstructor().newInstance().equals(type.getDeclaredConstructor().newInstance());
}
@Test
public void testEqualToSelf() throws Exception {
DynamicType.Loaded<?> loaded = new ByteBuddy()
.subclass(Object.class)
.defineField(FOO, Object.class, Visibility.PUBLIC)
.method(isEquals())
.intercept(EqualsMethod.isolated().withNonNullableFields(named(FOO)))
.make()
.load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER);
assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1));
assertThat(loaded.getLoaded().getDeclaredFields().length, is(1));
Object instance = loaded.getLoaded().getDeclaredConstructor().newInstance();
assertThat(instance, is(instance));
}
@Test
public void testEqualToSelfIdentity() throws Exception {
DynamicType.Loaded<?> loaded = new ByteBuddy()
.subclass(Object.class)
.defineField(FOO, Object.class, Visibility.PUBLIC)
.method(isEquals())
.intercept(EqualsMethod.isolated())
.make()
.load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER);
assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1));
assertThat(loaded.getLoaded().getDeclaredFields().length, is(1));
Object instance = loaded.getLoaded().getDeclaredConstructor().newInstance();
loaded.getLoaded().getDeclaredField(FOO).set(instance, new NonEqualsBase());
assertThat(instance, is(instance));
}
@Test
public void testIgnoredField() throws Exception {
DynamicType.Loaded<?> loaded = new ByteBuddy()
.subclass(Object.class)
.defineField(FOO, Object.class, Visibility.PUBLIC)
.method(isEquals())
.intercept(EqualsMethod.isolated().withIgnoredFields(named(FOO)))
.make()
.load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER);
assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1));
assertThat(loaded.getLoaded().getDeclaredFields().length, is(1));
Object left = loaded.getLoaded().getDeclaredConstructor().newInstance(), right = loaded.getLoaded().getDeclaredConstructor().newInstance();
left.getClass().getDeclaredField(FOO).set(left, FOO);
left.getClass().getDeclaredField(FOO).set(left, BAR);
assertThat(left, is(right));
}
@Test
public void testSuperMethod() throws Exception {
DynamicType.Loaded<?> loaded = new ByteBuddy()
.subclass(EqualsBase.class)
.defineField(FOO, Object.class, Visibility.PUBLIC)
.method(isEquals())
.intercept(EqualsMethod.requiringSuperClassEquality())
.make()
.load(EqualsBase.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1));
assertThat(loaded.getLoaded().getDeclaredFields().length, is(1));
Object left = loaded.getLoaded().getDeclaredConstructor().newInstance(), right = loaded.getLoaded().getDeclaredConstructor().newInstance();
left.getClass().getDeclaredField(FOO).set(left, FOO);
right.getClass().getDeclaredField(FOO).set(right, FOO);
assertThat(left, is(right));
}
@Test
public void testSuperClass() throws Exception {
DynamicType.Loaded<?> superClass = new ByteBuddy()
.subclass(EqualsBase.class)
.defineField(FOO, Object.class, Visibility.PUBLIC)
.method(isEquals())
.intercept(EqualsMethod.isolated())
.make()
.load(EqualsBase.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
DynamicType.Loaded<?> subClass = new ByteBuddy()
.subclass(superClass.getLoaded())
.make()
.load(superClass.getLoaded().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
Object left = subClass.getLoaded().getDeclaredConstructor().newInstance(), right = subClass.getLoaded().getDeclaredConstructor().newInstance();
superClass.getLoaded().getDeclaredField(FOO).set(left, FOO);
superClass.getLoaded().getDeclaredField(FOO).set(right, FOO);
assertThat(left, is(right));
}
@Test
public void testSuperMethodNoMatch() throws Exception {
DynamicType.Loaded<?> loaded = new ByteBuddy()
.subclass(NonEqualsBase.class)
.defineField(FOO, Object.class, Visibility.PUBLIC)
.method(isEquals())
.intercept(EqualsMethod.requiringSuperClassEquality())
.make()
.load(NonEqualsBase.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1));
assertThat(loaded.getLoaded().getDeclaredFields().length, is(1));
Object left = loaded.getLoaded().getDeclaredConstructor().newInstance(), right = loaded.getLoaded().getDeclaredConstructor().newInstance();
left.getClass().getDeclaredField(FOO).set(left, FOO);
right.getClass().getDeclaredField(FOO).set(right, FOO);
assertThat(left, not(right));
}
@Test
public void testInstanceOf() throws Exception {
DynamicType.Loaded<?> superClass = new ByteBuddy()
.subclass(Object.class)
.method(isEquals())
.intercept(EqualsMethod.isolated().withSubclassEquality())
.make()
.load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER);
DynamicType.Loaded<?> subClass = new ByteBuddy()
.subclass(superClass.getLoaded())
.make()
.load(superClass.getLoaded().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
assertThat(superClass.getLoaded().getDeclaredConstructor().newInstance(), is(subClass.getLoaded().getDeclaredConstructor().newInstance()));
assertThat(subClass.getLoaded().getDeclaredConstructor().newInstance(), is(superClass.getLoaded().getDeclaredConstructor().newInstance()));
}
@Test
public void testTypeOrderForPrimitiveTypedFields() throws Exception {
DynamicType.Loaded<?> loaded = new ByteBuddy()
.subclass(Object.class)
.defineField(FOO, Object.class, Visibility.PUBLIC)
.defineField(BAR, int.class, Visibility.PUBLIC)
.method(isEquals())
.intercept(EqualsMethod.isolated().withNonNullableFields(any()).withPrimitiveTypedFieldsFirst())
.make()
.load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER);
assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1));
assertThat(loaded.getLoaded().getDeclaredFields().length, is(2));
Object left = loaded.getLoaded().getDeclaredConstructor().newInstance(), right = loaded.getLoaded().getDeclaredConstructor().newInstance();
left.getClass().getDeclaredField(BAR).setInt(left, 42);
right.getClass().getDeclaredField(BAR).setInt(right, 84);
assertThat(left, not(right));
}
@Test
public void testTypeOrderForEnumerationTypedFields() throws Exception {
DynamicType.Loaded<?> loaded = new ByteBuddy()
.subclass(Object.class)
.defineField(FOO, Object.class, Visibility.PUBLIC)
.defineField(BAR, RetentionPolicy.class, Visibility.PUBLIC)
.method(isEquals())
.intercept(EqualsMethod.isolated().withNonNullableFields(any()).withEnumerationTypedFieldsFirst())
.make()
.load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER);
assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1));
assertThat(loaded.getLoaded().getDeclaredFields().length, is(2));
Object left = loaded.getLoaded().getDeclaredConstructor().newInstance(), right = loaded.getLoaded().getDeclaredConstructor().newInstance();
left.getClass().getDeclaredField(BAR).set(left, RetentionPolicy.RUNTIME);
right.getClass().getDeclaredField(BAR).set(right, RetentionPolicy.CLASS);
assertThat(left, not(right));
}
@Test
public void testTypeOrderForStringTypedFields() throws Exception {
DynamicType.Loaded<?> loaded = new ByteBuddy()
.subclass(Object.class)
.defineField(FOO, Object.class, Visibility.PUBLIC)
.defineField(BAR, String.class, Visibility.PUBLIC)
.method(isEquals())
.intercept(EqualsMethod.isolated().withNonNullableFields(any()).withStringTypedFieldsFirst())
.make()
.load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER);
assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1));
assertThat(loaded.getLoaded().getDeclaredFields().length, is(2));
Object left = loaded.getLoaded().getDeclaredConstructor().newInstance(), right = loaded.getLoaded().getDeclaredConstructor().newInstance();
left.getClass().getDeclaredField(BAR).set(left, FOO);
right.getClass().getDeclaredField(BAR).set(right, BAR);
assertThat(left, not(right));
}
@Test
public void testTypeOrderForPrimitiveWrapperTypes() throws Exception {
DynamicType.Loaded<?> loaded = new ByteBuddy()
.subclass(Object.class)
.defineField(FOO, Object.class, Visibility.PUBLIC)
.defineField(BAR, Integer.class, Visibility.PUBLIC)
.method(isEquals())
.intercept(EqualsMethod.isolated().withNonNullableFields(any()).withPrimitiveWrapperTypedFieldsFirst())
.make()
.load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER);
assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1));
assertThat(loaded.getLoaded().getDeclaredFields().length, is(2));
Object left = loaded.getLoaded().getDeclaredConstructor().newInstance(), right = loaded.getLoaded().getDeclaredConstructor().newInstance();
left.getClass().getDeclaredField(BAR).set(left, 42);
right.getClass().getDeclaredField(BAR).set(right, 84);
assertThat(left, not(right));
}
@Test
public void testNaturalOrderComparator() {
Comparator<FieldDescription.InDefinedShape> comparator = EqualsMethod.NaturalOrderComparator.INSTANCE;
FieldDescription.InDefinedShape left = mock(FieldDescription.InDefinedShape.class), right = mock(FieldDescription.InDefinedShape.class);
assertThat(comparator.compare(left, right), is(0));
}
@Test
public void testPrimitiveTypeComparatorLeftPrimitive() {
Comparator<FieldDescription.InDefinedShape> comparator = EqualsMethod.TypePropertyComparator.FOR_PRIMITIVE_TYPES;
FieldDescription.InDefinedShape left = mock(FieldDescription.InDefinedShape.class), right = mock(FieldDescription.InDefinedShape.class);
TypeDescription.Generic leftType = mock(TypeDescription.Generic.class), rightType = mock(TypeDescription.Generic.class);
when(left.getType()).thenReturn(leftType);
when(right.getType()).thenReturn(rightType);
when(leftType.isPrimitive()).thenReturn(true);
assertThat(comparator.compare(left, right), is(-1));
}
@Test
public void testPrimitiveTypeComparatorRightPrimitive() {
Comparator<FieldDescription.InDefinedShape> comparator = EqualsMethod.TypePropertyComparator.FOR_PRIMITIVE_TYPES;
FieldDescription.InDefinedShape left = mock(FieldDescription.InDefinedShape.class), right = mock(FieldDescription.InDefinedShape.class);
TypeDescription.Generic leftType = mock(TypeDescription.Generic.class), rightType = mock(TypeDescription.Generic.class);
when(left.getType()).thenReturn(leftType);
when(right.getType()).thenReturn(rightType);
when(rightType.isPrimitive()).thenReturn(true);
assertThat(comparator.compare(left, right), is(1));
}
@Test
public void testPrimitiveTypeComparatorBothPrimitive() {
Comparator<FieldDescription.InDefinedShape> comparator = EqualsMethod.TypePropertyComparator.FOR_PRIMITIVE_TYPES;
FieldDescription.InDefinedShape left = mock(FieldDescription.InDefinedShape.class), right = mock(FieldDescription.InDefinedShape.class);
TypeDescription.Generic leftType = mock(TypeDescription.Generic.class), rightType = mock(TypeDescription.Generic.class);
when(left.getType()).thenReturn(leftType);
when(right.getType()).thenReturn(rightType);
when(leftType.isPrimitive()).thenReturn(true);
when(rightType.isPrimitive()).thenReturn(true);
assertThat(comparator.compare(left, right), is(0));
}
@Test
public void testEnumerationTypeComparatorLeftEnumeration() {
Comparator<FieldDescription.InDefinedShape> comparator = EqualsMethod.TypePropertyComparator.FOR_ENUMERATION_TYPES;
FieldDescription.InDefinedShape left = mock(FieldDescription.InDefinedShape.class), right = mock(FieldDescription.InDefinedShape.class);
TypeDescription.Generic leftType = mock(TypeDescription.Generic.class), rightType = mock(TypeDescription.Generic.class);
when(left.getType()).thenReturn(leftType);
when(right.getType()).thenReturn(rightType);
when(leftType.isEnum()).thenReturn(true);
assertThat(comparator.compare(left, right), is(-1));
}
@Test
public void testEnumerationTypeComparatorRightEnumeration() {
Comparator<FieldDescription.InDefinedShape> comparator = EqualsMethod.TypePropertyComparator.FOR_ENUMERATION_TYPES;
FieldDescription.InDefinedShape left = mock(FieldDescription.InDefinedShape.class), right = mock(FieldDescription.InDefinedShape.class);
TypeDescription.Generic leftType = mock(TypeDescription.Generic.class), rightType = mock(TypeDescription.Generic.class);
when(left.getType()).thenReturn(leftType);
when(right.getType()).thenReturn(rightType);
when(rightType.isEnum()).thenReturn(true);
assertThat(comparator.compare(left, right), is(1));
}
@Test
public void testStringTypeComparatorBothEnumeration() {
Comparator<FieldDescription.InDefinedShape> comparator = EqualsMethod.TypePropertyComparator.FOR_ENUMERATION_TYPES;
FieldDescription.InDefinedShape left = mock(FieldDescription.InDefinedShape.class), right = mock(FieldDescription.InDefinedShape.class);
TypeDescription.Generic leftType = mock(TypeDescription.Generic.class), rightType = mock(TypeDescription.Generic.class);
when(left.getType()).thenReturn(leftType);
when(right.getType()).thenReturn(rightType);
when(leftType.isEnum()).thenReturn(true);
when(rightType.isEnum()).thenReturn(true);
assertThat(comparator.compare(left, right), is(0));
}
@Test
public void testStringTypeComparatorLeftString() {
Comparator<FieldDescription.InDefinedShape> comparator = EqualsMethod.TypePropertyComparator.FOR_STRING_TYPES;
FieldDescription.InDefinedShape left = mock(FieldDescription.InDefinedShape.class), right = mock(FieldDescription.InDefinedShape.class);
TypeDescription.Generic leftType = mock(TypeDescription.Generic.class), rightType = mock(TypeDescription.Generic.class);
when(left.getType()).thenReturn(leftType);
when(right.getType()).thenReturn(rightType);
when(leftType.represents(String.class)).thenReturn(true);
assertThat(comparator.compare(left, right), is(-1));
}
@Test
public void testStringTypeComparatorRightString() {
Comparator<FieldDescription.InDefinedShape> comparator = EqualsMethod.TypePropertyComparator.FOR_STRING_TYPES;
FieldDescription.InDefinedShape left = mock(FieldDescription.InDefinedShape.class), right = mock(FieldDescription.InDefinedShape.class);
TypeDescription.Generic leftType = mock(TypeDescription.Generic.class), rightType = mock(TypeDescription.Generic.class);
when(left.getType()).thenReturn(leftType);
when(right.getType()).thenReturn(rightType);
when(rightType.represents(String.class)).thenReturn(true);
assertThat(comparator.compare(left, right), is(1));
}
@Test
public void testStringTypeComparatorBothString() {
Comparator<FieldDescription.InDefinedShape> comparator = EqualsMethod.TypePropertyComparator.FOR_STRING_TYPES;
FieldDescription.InDefinedShape left = mock(FieldDescription.InDefinedShape.class), right = mock(FieldDescription.InDefinedShape.class);
TypeDescription.Generic leftType = mock(TypeDescription.Generic.class), rightType = mock(TypeDescription.Generic.class);
when(left.getType()).thenReturn(leftType);
when(right.getType()).thenReturn(rightType);
when(leftType.represents(String.class)).thenReturn(true);
when(rightType.represents(String.class)).thenReturn(true);
assertThat(comparator.compare(left, right), is(0));
}
@Test
public void testPrimitiveWrapperTypeComparatorLeftPrimitiveWrapper() {
Comparator<FieldDescription.InDefinedShape> comparator = EqualsMethod.TypePropertyComparator.FOR_PRIMITIVE_WRAPPER_TYPES;
FieldDescription.InDefinedShape left = mock(FieldDescription.InDefinedShape.class), right = mock(FieldDescription.InDefinedShape.class);
TypeDescription.Generic leftType = mock(TypeDescription.Generic.class), rightType = mock(TypeDescription.Generic.class);
when(left.getType()).thenReturn(leftType);
when(right.getType()).thenReturn(rightType);
TypeDescription leftErasure = mock(TypeDescription.class), rightErasure = mock(TypeDescription.class);
when(leftType.asErasure()).thenReturn(leftErasure);
when(rightType.asErasure()).thenReturn(rightErasure);
when(leftErasure.isPrimitiveWrapper()).thenReturn(true);
assertThat(comparator.compare(left, right), is(-1));
}
@Test
public void testPrimitiveWrapperTypeComparatorRightPrimitiveWrapper() {
Comparator<FieldDescription.InDefinedShape> comparator = EqualsMethod.TypePropertyComparator.FOR_PRIMITIVE_WRAPPER_TYPES;
FieldDescription.InDefinedShape left = mock(FieldDescription.InDefinedShape.class), right = mock(FieldDescription.InDefinedShape.class);
TypeDescription.Generic leftType = mock(TypeDescription.Generic.class), rightType = mock(TypeDescription.Generic.class);
when(left.getType()).thenReturn(leftType);
when(right.getType()).thenReturn(rightType);
TypeDescription leftErasure = mock(TypeDescription.class), rightErasure = mock(TypeDescription.class);
when(leftType.asErasure()).thenReturn(leftErasure);
when(rightType.asErasure()).thenReturn(rightErasure);
when(rightErasure.isPrimitiveWrapper()).thenReturn(true);
assertThat(comparator.compare(left, right), is(1));
}
@Test
public void testPrimitiveWrapperTypeComparatorBothPrimitiveWrapper() {
Comparator<FieldDescription.InDefinedShape> comparator = EqualsMethod.TypePropertyComparator.FOR_PRIMITIVE_WRAPPER_TYPES;
FieldDescription.InDefinedShape left = mock(FieldDescription.InDefinedShape.class), right = mock(FieldDescription.InDefinedShape.class);
TypeDescription.Generic leftType = mock(TypeDescription.Generic.class), rightType = mock(TypeDescription.Generic.class);
when(left.getType()).thenReturn(leftType);
when(right.getType()).thenReturn(rightType);
TypeDescription leftErasure = mock(TypeDescription.class), rightErasure = mock(TypeDescription.class);
when(leftType.asErasure()).thenReturn(leftErasure);
when(rightType.asErasure()).thenReturn(rightErasure);
when(leftErasure.isPrimitiveWrapper()).thenReturn(true);
when(rightErasure.isPrimitiveWrapper()).thenReturn(true);
assertThat(comparator.compare(left, right), is(0));
}
@Test
@SuppressWarnings("unchecked")
public void testCompoundComparatorNoComparator() {
Comparator<FieldDescription.InDefinedShape> comparator = new EqualsMethod.CompoundComparator();
FieldDescription.InDefinedShape left = mock(FieldDescription.InDefinedShape.class), right = mock(FieldDescription.InDefinedShape.class);
assertThat(comparator.compare(left, right), is(0));
}
@Test
@SuppressWarnings("unchecked")
public void testCompoundComparatorSingleComparator() {
FieldDescription.InDefinedShape left = mock(FieldDescription.InDefinedShape.class), right = mock(FieldDescription.InDefinedShape.class);
Comparator<FieldDescription.InDefinedShape> delegate = mock(Comparator.class);
when(delegate.compare(left, right)).thenReturn(42);
Comparator<FieldDescription.InDefinedShape> comparator = new EqualsMethod.CompoundComparator(delegate);
assertThat(comparator.compare(left, right), is(42));
}
@Test
@SuppressWarnings("unchecked")
public void testCompoundComparatorDoubleComparator() {
FieldDescription.InDefinedShape left = mock(FieldDescription.InDefinedShape.class), right = mock(FieldDescription.InDefinedShape.class);
Comparator<FieldDescription.InDefinedShape> delegate = mock(Comparator.class), first = mock(Comparator.class);
when(delegate.compare(left, right)).thenReturn(42);
when(first.compare(left, right)).thenReturn(0);
Comparator<FieldDescription.InDefinedShape> comparator = new EqualsMethod.CompoundComparator(first, delegate);
assertThat(comparator.compare(left, right), is(42));
verify(first).compare(left, right);
}
@Test(expected = IllegalStateException.class)
public void testInterface() throws Exception {
new ByteBuddy()
.makeInterface()
.method(isEquals())
.intercept(EqualsMethod.isolated())
.make();
}
@Test(expected = IllegalStateException.class)
public void testIncompatibleReturn() throws Exception {
new ByteBuddy()
.subclass(Object.class)
.defineMethod(FOO, Object.class)
.withParameters(Object.class)
.intercept(EqualsMethod.isolated())
.make();
}
@Test(expected = IllegalStateException.class)
public void testIncompatibleArgumentLength() throws Exception {
new ByteBuddy()
.subclass(Object.class)
.defineMethod(FOO, boolean.class)
.withParameters(Object.class, Object.class)
.intercept(EqualsMethod.isolated())
.make();
}
@Test(expected = IllegalStateException.class)
public void testIncompatibleArgumentType() throws Exception {
new ByteBuddy()
.subclass(Object.class)
.defineMethod(FOO, boolean.class)
.withParameters(int.class)
.intercept(EqualsMethod.isolated())
.make();
}
@Test(expected = IllegalStateException.class)
public void testStaticMethod() throws Exception {
new ByteBuddy()
.subclass(Object.class)
.defineMethod(FOO, boolean.class, Ownership.STATIC)
.withParameters(Object.class)
.intercept(EqualsMethod.isolated())
.make();
}
public static class EqualsBase {
@Override
public boolean equals(Object other) {
return true;
}
}
public static class NonEqualsBase {
@Override
public boolean equals(Object other) {
return false;
}
}
}
| apache-2.0 |
virtuozo/spa-framework | commons/src/main/java/virtuozo/infra/CNPJValidator.java | 1506 | package virtuozo.infra;
public class CNPJValidator extends Validator<CNPJValidator, String> {
private static final CNPJValidator instance = new CNPJValidator();
private CNPJValidator() {
super();
}
public static CNPJValidator get() {
return instance;
}
public boolean delegateValidation(String cnpj) {
cnpj = CNPJFormat.get().unformat(cnpj);
if (cnpj == null) {
return false;
}
int soma = 0;
String cnpj_calc = cnpj.substring(0, 12);
char[] chr_cnpj = cnpj.toCharArray();
// Primeira parte
for (int i = 0; i < 4; i++) {
if (chr_cnpj[i] - 48 >= 0 && chr_cnpj[i] - 48 <= 9) {
soma += (chr_cnpj[i] - 48) * (6 - (i + 1));
}
}
for (int i = 0; i < 8; i++) {
if (chr_cnpj[i + 4] - 48 >= 0 && chr_cnpj[i + 4] - 48 <= 9) {
soma += (chr_cnpj[i + 4] - 48) * (10 - (i + 1));
}
}
int dig = 11 - (soma % 11);
cnpj_calc += (dig == 10 || dig == 11) ? "0" : Integer.toString(dig);
// Segunda parte
soma = 0;
for (int i = 0; i < 5; i++) {
if (chr_cnpj[i] - 48 >= 0 && chr_cnpj[i] - 48 <= 9) {
soma += (chr_cnpj[i] - 48) * (7 - (i + 1));
}
}
for (int i = 0; i < 8; i++) {
if (chr_cnpj[i + 5] - 48 >= 0 && chr_cnpj[i + 5] - 48 <= 9) {
soma += (chr_cnpj[i + 5] - 48) * (10 - (i + 1));
}
}
dig = 11 - (soma % 11);
cnpj_calc += (dig == 10 || dig == 11) ? "0" : Integer.toString(dig);
return cnpj.equals(cnpj_calc);
}
} | apache-2.0 |
ogema/tutorial | src/simulations/simple-devices/src/main/java/org/smartrplace/sim/simple/devices/switchbox/SwitchboxPattern.java | 2975 | package org.smartrplace.sim.simple.devices.switchbox;
import org.ogema.core.model.Resource;
import org.ogema.core.model.simple.BooleanResource;
import org.ogema.core.model.units.ElectricCurrentResource;
import org.ogema.core.model.units.EnergyResource;
import org.ogema.core.model.units.FrequencyResource;
import org.ogema.core.model.units.PowerResource;
import org.ogema.core.model.units.VoltageResource;
import org.ogema.core.resourcemanager.pattern.ResourcePattern;
import org.ogema.model.actors.OnOffSwitch;
import org.ogema.model.connections.ElectricityConnection;
import org.ogema.model.devices.sensoractordevices.SingleSwitchBox;
import org.ogema.model.sensors.ElectricCurrentSensor;
import org.ogema.model.sensors.ElectricFrequencySensor;
import org.ogema.model.sensors.ElectricPowerSensor;
import org.ogema.model.sensors.ElectricVoltageSensor;
import org.ogema.model.sensors.EnergyAccumulatedSensor;
/**
* Resource pattern for a switchbox, such as the one provided by the Homematic driver
*/
public class SwitchboxPattern extends ResourcePattern<SingleSwitchBox> {
public final OnOffSwitch onOffSwitch = model.onOffSwitch();
@Existence(required=CreateMode.OPTIONAL)
public final BooleanResource stateControl = onOffSwitch.stateControl();
@Existence(required=CreateMode.OPTIONAL)
public final BooleanResource stateFeedback = onOffSwitch.stateFeedback();
public final BooleanResource controllable = onOffSwitch.controllable();
public final ElectricityConnection connection = model.electricityConnection();
public final ElectricPowerSensor powerSensor = connection.powerSensor();
@Existence(required=CreateMode.OPTIONAL)
public final PowerResource power = powerSensor.reading();
public final ElectricCurrentSensor currentSensor = connection.currentSensor();
@Existence(required=CreateMode.OPTIONAL)
public final ElectricCurrentResource current = currentSensor.reading();
public final ElectricVoltageSensor voltageSensor = connection.voltageSensor();
@Existence(required=CreateMode.OPTIONAL)
public final VoltageResource voltage = voltageSensor.reading();
public final ElectricFrequencySensor frequencySensor = connection.frequencySensor();
@Existence(required=CreateMode.OPTIONAL)
public final FrequencyResource frequency = frequencySensor.reading();
public final EnergyAccumulatedSensor energySensor = connection.energySensor();
@Existence(required=CreateMode.OPTIONAL)
public final EnergyResource energy = energySensor.reading();
/**
* Constructor for the access pattern. This constructor is invoked by the framework.
*/
public SwitchboxPattern(Resource device) {
super(device);
}
@Override
public boolean equals(Object obj) {
if (obj == null || !obj.getClass().equals(getClass()))
return false;
SwitchboxPattern other = (SwitchboxPattern) obj;
return this.model.equalsLocation(other.model);
}
@Override
public int hashCode() {
return model.getLocation().hashCode();
}
}
| apache-2.0 |
ukwa/w3act | app/com/thesecretserver/service/Folder.java | 2919 |
package com.thesecretserver.service;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for Folder complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Folder">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Id" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="Name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="TypeId" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="ParentFolderId" type="{http://www.w3.org/2001/XMLSchema}int"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Folder", propOrder = {
"id",
"name",
"typeId",
"parentFolderId"
})
@XmlSeeAlso({
FolderExtended.class
})
public class Folder {
@XmlElement(name = "Id")
protected int id;
@XmlElement(name = "Name")
protected String name;
@XmlElement(name = "TypeId")
protected int typeId;
@XmlElement(name = "ParentFolderId")
protected int parentFolderId;
/**
* Gets the value of the id property.
*
*/
public int getId() {
return id;
}
/**
* Sets the value of the id property.
*
*/
public void setId(int value) {
this.id = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the typeId property.
*
*/
public int getTypeId() {
return typeId;
}
/**
* Sets the value of the typeId property.
*
*/
public void setTypeId(int value) {
this.typeId = value;
}
/**
* Gets the value of the parentFolderId property.
*
*/
public int getParentFolderId() {
return parentFolderId;
}
/**
* Sets the value of the parentFolderId property.
*
*/
public void setParentFolderId(int value) {
this.parentFolderId = value;
}
}
| apache-2.0 |
gtkrug/bae-shib3 | src/main/java/net/gfipm/shibboleth/dataconnector/BAEAttributeNameMap.java | 889 |
/* ========================================================================
* Copyright (c) 2013 GTRI
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================================
*/
package net.gfipm.shibboleth.dataconnector;
public class BAEAttributeNameMap {
public String QueryName;
public String ReturnName;
}
| apache-2.0 |
aalsul1/p1compiler | src/edu/towson/cis/cosc455/aalsul1/project1/implementation/CompilerException.java | 792 | package edu.towson.cis.cosc455.aalsul1.project1.implementation;
/**
* Parsing exception. For simplicity, this is used for both lexical errors as
* well as parsing errors. A more complete design would include a hierarchy of
* specific error types.
*
* Developed by Adam Conover (2012) and modified by Josh Dehlinger (2013), used with permission.
*
*/
public class CompilerException extends Exception {
/**
* Instantiates a new CompilerException.
*
* @param errorMessage the error message to be printed
*/
public CompilerException(String errorMessage) {
super(errorMessage);
}
/**
* Gets the error message.
*
* @return the error message
*/
public String getErrorMessage() {
return super.getMessage();
}
}
| apache-2.0 |
masaki-yamakawa/geode | geode-membership/src/main/java/org/apache/geode/distributed/internal/membership/gms/MemberIdentifierImpl.java | 32247 | /*
* 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.distributed.internal.membership.gms;
import static org.apache.geode.distributed.internal.membership.gms.GMSMemberData.COORD_ENABLED_BIT;
import static org.apache.geode.distributed.internal.membership.gms.GMSMemberData.NPD_ENABLED_BIT;
import static org.apache.geode.distributed.internal.membership.gms.GMSMemberData.PARTIAL_ID_BIT;
import static org.apache.geode.distributed.internal.membership.gms.GMSMemberData.VERSION_BIT;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.EOFException;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.net.InetAddress;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import org.apache.commons.validator.routines.InetAddressValidator;
import org.jgroups.util.UUID;
import org.apache.geode.annotations.Immutable;
import org.apache.geode.annotations.VisibleForTesting;
import org.apache.geode.distributed.internal.membership.api.MemberData;
import org.apache.geode.distributed.internal.membership.api.MemberDataBuilder;
import org.apache.geode.distributed.internal.membership.api.MemberIdentifier;
import org.apache.geode.internal.serialization.DataSerializableFixedID;
import org.apache.geode.internal.serialization.DeserializationContext;
import org.apache.geode.internal.serialization.KnownVersion;
import org.apache.geode.internal.serialization.SerializationContext;
import org.apache.geode.internal.serialization.StaticSerialization;
import org.apache.geode.internal.serialization.Version;
import org.apache.geode.internal.serialization.Versioning;
import org.apache.geode.internal.serialization.VersioningIO;
/**
* An implementation of {@link MemberIdentifier}
*/
public class MemberIdentifierImpl implements MemberIdentifier, DataSerializableFixedID {
/** The versions in which this message was modified */
@Immutable
private static final KnownVersion[] dsfidVersions = new KnownVersion[] {
KnownVersion.GFE_71, KnownVersion.GFE_90};
private MemberData memberData; // the underlying member object
public MemberIdentifierImpl() {}
public MemberIdentifierImpl(
MemberData memberData) {
this.memberData = memberData;
}
public int getVmPid() {
return memberData.getProcessId();
}
public void setDurableTimeout(int newValue) {
memberData.setDurableTimeout(newValue);
}
public void setDurableId(String id) {
memberData.setDurableId(id);
}
/**
* Replace the current member data with the given member data. This can be used to fill out an
* InternalDistributedMember that was created from a partial data created by
* readEssentialData.
*
* @param m the replacement member data
*/
public void setMemberData(MemberData m) {
this.memberData = m;
}
/**
* Return the underlying host address
*
* @return the underlying host address
*/
public InetAddress getInetAddress() {
return memberData.getInetAddress();
}
/**
* Return the underlying port (membership port)
*
* @return the underlying membership port
*/
public int getMembershipPort() {
return memberData.getMembershipPort();
}
@Override
public short getVersionOrdinal() {
return memberData.getVersionOrdinal();
}
/**
* Returns the port on which the direct channel runs
*/
public int getDirectChannelPort() {
assert !this.isPartial();
return memberData.getDirectChannelPort();
}
/**
* [GemStone] Returns the kind of VM that hosts the distribution manager with this address.
*
* @see MemberIdentifier#NORMAL_DM_TYPE
*/
public int getVmKind() {
return memberData.getVmKind();
}
@Override
public int getMemberWeight() {
return memberData.getMemberWeight();
}
/**
* Returns the membership view ID that this member was born in. For backward compatibility reasons
* this is limited to 16 bits.
*/
public int getVmViewId() {
return memberData.getVmViewId();
}
@Override
public boolean preferredForCoordinator() {
return memberData.isPreferredForCoordinator();
}
@Override
public List<String> getGroups() {
String[] groups = memberData.getGroups();
return groups == null ? Collections.emptyList()
: Collections.unmodifiableList(Arrays.asList(groups));
}
@Override
public void setVmViewId(int p) {
memberData.setVmViewId(p);
cachedToString = null;
}
@Override
public void setPreferredForCoordinator(boolean preferred) {
memberData.setPreferredForCoordinator(preferred);
cachedToString = null;
}
@Override
public void setDirectChannelPort(int dcPort) {
memberData.setDirectChannelPort(dcPort);
cachedToString = null;
}
@Override
public void setVmKind(int dmType) {
memberData.setVmKind(dmType);
cachedToString = null;
}
public void setGroups(String[] newGroups) {
this.memberData.setGroups(newGroups);
cachedToString = null;
}
/**
* Returns the name of this member's distributed system connection or null if no name was
* specified.
*/
public String getName() {
String result = memberData.getName();
if (result == null) {
result = "";
}
return result;
}
@Override
public void setName(String name) {
memberData.setName(name);
}
@Override
public String getUniqueTag() {
return memberData.getUniqueTag();
}
@Override
public String getDurableId() {
return memberData.getDurableId();
}
@Override
public int getDurableTimeout() {
return memberData.getDurableTimeout();
}
@Override
public void setHostName(String hostName) {
memberData.setHostName(hostName);
}
@Override
public void setProcessId(int id) {
memberData.setProcessId(id);
}
@Override
public boolean hasUUID() {
return memberData.hasUUID();
}
public int compare(MemberIdentifier other) {
return this.compareTo(other, false, true);
}
@Override
public int compareTo(MemberIdentifier other, boolean compareMemberData,
boolean compareViewIds) {
int myPort = getMembershipPort();
int otherPort = other.getMembershipPort();
if (myPort < otherPort) {
return -1;
}
if (myPort > otherPort) {
return 1;
}
InetAddress myAddr = getInetAddress();
InetAddress otherAddr = other.getInetAddress();
// Discard null cases
if (myAddr == null && otherAddr == null) {
return 0;
} else if (myAddr == null) {
return -1;
} else if (otherAddr == null) {
return 1;
}
byte[] myBytes = myAddr.getAddress();
byte[] otherBytes = otherAddr.getAddress();
if (myBytes != otherBytes) {
for (int i = 0; i < myBytes.length; i++) {
if (i >= otherBytes.length) {
return -1; // same as far as they go, but shorter...
}
if (myBytes[i] < otherBytes[i]) {
return -1;
}
if (myBytes[i] > otherBytes[i]) {
return 1;
}
}
if (myBytes.length > otherBytes.length) {
return 1; // same as far as they go, but longer...
}
}
String myName = getName();
String otherName = other.getName();
if (!(other.isPartial() || this.isPartial())) {
if (myName == null && otherName == null) {
// do nothing
} else if (myName == null) {
return -1;
} else if (otherName == null) {
return 1;
} else {
int i = myName.compareTo(otherName);
if (i != 0) {
return i;
}
}
}
if (this.getUniqueTag() == null && other.getUniqueTag() == null) {
if (compareViewIds) {
// not loners, so look at P2P view ID
int thisViewId = getVmViewId();
int otherViewId = other.getVmViewId();
if (thisViewId >= 0 && otherViewId >= 0) {
if (thisViewId < otherViewId) {
return -1;
} else if (thisViewId > otherViewId) {
return 1;
} // else they're the same, so continue
}
}
} else if (this.getUniqueTag() == null) {
return -1;
} else if (other.getUniqueTag() == null) {
return 1;
} else {
int i = this.getUniqueTag().compareTo(other.getUniqueTag());
if (i != 0) {
return i;
}
}
if (compareMemberData && this.memberData != null && other.getMemberData() != null) {
return this.memberData.compareAdditionalData(other.getMemberData());
} else {
return 0;
}
}
/**
* An InternalDistributedMember created for a test or via readEssentialData will be a Partial ID,
* possibly not having ancillary info like "name".
*
* @return true if this is a partial ID
*/
public boolean isPartial() {
return memberData.isPartial();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
// GemStone fix for 29125
if (!(obj instanceof MemberIdentifierImpl)) {
return false;
}
MemberIdentifierImpl other = (MemberIdentifierImpl) obj;
int myPort = getMembershipPort();
int otherPort = other.getMembershipPort();
if (myPort != otherPort) {
return false;
}
InetAddress myAddr = getInetAddress();
InetAddress otherAddr = other.getInetAddress();
if (myAddr == null && otherAddr == null) {
return true;
} else if (!Objects.equals(myAddr, otherAddr)) {
return false;
}
if (!isPartial() && !other.isPartial()) {
if (!Objects.equals(getName(), other.getName())) {
return false;
}
}
if (this.getUniqueTag() == null && other.getUniqueTag() == null) {
// not loners, so look at P2P view ID
int thisViewId = getVmViewId();
int otherViewId = other.getVmViewId();
if (thisViewId >= 0 && otherViewId >= 0) {
if (thisViewId != otherViewId) {
return false;
} // else they're the same, so continue
}
} else if (!Objects.equals(this.getUniqueTag(), other.getUniqueTag())) {
return false;
}
if (this.memberData != null && other.memberData != null) {
if (0 != this.memberData.compareAdditionalData(other.memberData)) {
return false;
}
}
// purposely avoid checking roles
// @todo Add durableClientAttributes to equals
return true;
}
@Override
public int hashCode() {
int result = 0;
result = result + memberData.getInetAddress().hashCode();
result = result + getMembershipPort();
return result;
}
private String shortName(String hostname) {
if (hostname == null) {
return "<null inet_addr hostname>";
}
int index = hostname.indexOf('.');
if (index > 0 && !Character.isDigit(hostname.charAt(0))) {
return hostname.substring(0, index);
} else {
return hostname;
}
}
/** the cached string description of this object */
private transient String cachedToString;
@Override
public String toString() {
String result = cachedToString;
if (result == null) {
final StringBuilder sb = new StringBuilder();
addFixedToString(sb, false);
// add version if not current
short version = memberData.getVersionOrdinal();
if (version != KnownVersion.CURRENT.ordinal()) {
sb.append("(version:").append(Versioning.getVersion(version)).append(')');
}
// leave out Roles on purpose
result = sb.toString();
cachedToString = result;
}
return result;
}
public void addFixedToString(StringBuilder sb, boolean useIpAddress) {
// Note: This method is used to generate the HARegion name. If it is changed, memory and GII
// issues will occur in the case of clients with subscriptions during rolling upgrade.
String host;
InetAddress inetAddress = getInetAddress();
if ((inetAddress != null) && (inetAddress.isMulticastAddress() || useIpAddress)) {
host = inetAddress.getHostAddress();
} else {
String hostName = memberData.getHostName();
InetAddressValidator inetAddressValidator = InetAddressValidator.getInstance();
boolean isIpAddress = inetAddressValidator.isValid(hostName);
host = isIpAddress ? hostName : shortName(hostName);
}
sb.append(host);
String myName = getName();
int vmPid = memberData.getProcessId();
int vmKind = memberData.getVmKind();
if (vmPid > 0 || vmKind != MemberIdentifier.NORMAL_DM_TYPE || !"".equals(myName)) {
sb.append("(");
if (!"".equals(myName)) {
sb.append(myName);
if (vmPid > 0) {
sb.append(':');
}
}
if (vmPid > 0) {
sb.append(vmPid);
}
String vmStr = "";
switch (vmKind) {
case MemberIdentifier.NORMAL_DM_TYPE:
// vmStr = ":local"; // let this be silent
break;
case MemberIdentifier.LOCATOR_DM_TYPE:
vmStr = ":locator";
break;
case MemberIdentifier.ADMIN_ONLY_DM_TYPE:
vmStr = ":admin";
break;
case MemberIdentifier.LONER_DM_TYPE:
vmStr = ":loner";
break;
default:
vmStr = ":<unknown:" + vmKind + ">";
break;
}
sb.append(vmStr);
sb.append(")");
}
if (vmKind != MemberIdentifier.LONER_DM_TYPE
&& memberData.isPreferredForCoordinator()) {
sb.append("<ec>");
}
int vmViewId = getVmViewId();
if (vmViewId >= 0) {
sb.append("<v" + vmViewId + ">");
}
sb.append(":");
sb.append(getMembershipPort());
if (vmKind == MemberIdentifier.LONER_DM_TYPE) {
// add some more info that was added in 4.2.1 for loner bridge clients
// impact on non-bridge loners is ok
if (this.getUniqueTag() != null && this.getUniqueTag().length() != 0) {
sb.append(":").append(this.getUniqueTag());
}
String name = getName();
if (name.length() != 0) {
sb.append(":").append(name);
}
}
}
private short readVersion(int flags, DataInput in) throws IOException {
if ((flags & VERSION_BIT) != 0) {
short version = VersioningIO.readOrdinal(in);
return version;
} else {
// prior to 7.1 member IDs did not serialize their version information
KnownVersion v = StaticSerialization.getVersionForDataStreamOrNull(in);
if (v != null) {
return v.ordinal();
}
return KnownVersion.CURRENT_ORDINAL;
}
}
/**
* For Externalizable
*
* @see Externalizable
*/
public void writeExternal(ObjectOutput out) throws IOException {
assert memberData.getVmKind() > 0;
// do it the way we like
byte[] address = getInetAddress().getAddress();
out.writeInt(address.length); // IPv6 compatible
out.write(address);
out.writeInt(getMembershipPort());
StaticSerialization.writeString(memberData.getHostName(), out);
int flags = 0;
if (memberData.isNetworkPartitionDetectionEnabled()) {
flags |= NPD_ENABLED_BIT;
}
if (memberData.isPreferredForCoordinator()) {
flags |= COORD_ENABLED_BIT;
}
if (this.isPartial()) {
flags |= PARTIAL_ID_BIT;
}
// always write product version but enable reading from older versions
// that do not have it
flags |= VERSION_BIT;
out.writeByte((byte) (flags & 0xff));
out.writeInt(memberData.getDirectChannelPort());
out.writeInt(memberData.getProcessId());
out.writeInt(memberData.getVmKind());
out.writeInt(memberData.getVmViewId());
StaticSerialization.writeStringArray(memberData.getGroups(), out);
StaticSerialization.writeString(memberData.getName(), out);
StaticSerialization.writeString(memberData.getUniqueTag(), out);
String durableId = memberData.getDurableId();
StaticSerialization.writeString(durableId == null ? "" : durableId, out);
StaticSerialization.writeInteger(
Integer.valueOf(durableId == null ? 300 : memberData.getDurableTimeout()),
out);
VersioningIO.writeOrdinal(out, memberData.getVersionOrdinal(), true);
memberData.writeAdditionalData(out);
}
/**
* For Externalizable
*
* @see Externalizable
*/
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
int len = in.readInt(); // IPv6 compatible
byte addr[] = new byte[len];
in.readFully(addr);
InetAddress inetAddr = InetAddress.getByAddress(addr);
int port = in.readInt();
String hostName = StaticSerialization.readString(in);
int flags = in.readUnsignedByte();
boolean sbEnabled = (flags & NPD_ENABLED_BIT) != 0;
boolean elCoord = (flags & COORD_ENABLED_BIT) != 0;
boolean isPartial = (flags & PARTIAL_ID_BIT) != 0;
int dcPort = in.readInt();
int vmPid = in.readInt();
int vmKind = in.readInt();
int vmViewId = in.readInt();
String[] groups = StaticSerialization.readStringArray(in);
String name = StaticSerialization.readString(in);
String uniqueTag = StaticSerialization.readString(in);
String durableId = StaticSerialization.readString(in);
int durableTimeout = in.readInt();
short version = readVersion(flags, in);
memberData = MemberDataBuilder.newBuilder(inetAddr, hostName)
.setMembershipPort(port)
.setDirectChannelPort(dcPort)
.setName(name)
.setNetworkPartitionDetectionEnabled(sbEnabled)
.setPreferredForCoordinator(elCoord)
.setVersionOrdinal(version)
.setVmPid(vmPid)
.setVmKind(vmKind)
.setVmViewId(vmViewId)
.setGroups(groups)
.setDurableId(durableId)
.setDurableTimeout(durableTimeout)
.setIsPartial(isPartial)
.setUniqueTag(uniqueTag)
.build();
if (version >= KnownVersion.GFE_90.ordinal()) {
try {
memberData.readAdditionalData(in);
} catch (java.io.EOFException e) {
// old version
}
}
assert memberData.getVmKind() > 0;
}
@Override
public int getDSFID() {
return MEMBER_IDENTIFIER;
}
@Override
public void toData(DataOutput out,
SerializationContext context) throws IOException {
toDataPre_GFE_9_0_0_0(out, context);
if (memberData.getVersionOrdinal() >= KnownVersion.GFE_90.ordinal()) {
memberData.writeAdditionalData(out);
}
}
public void toDataPre_GFE_9_0_0_0(DataOutput out, SerializationContext context)
throws IOException {
// Assert.assertTrue(vmKind > 0);
// NOTE: If you change the serialized format of this class
// then bump Connection.HANDSHAKE_VERSION since an
// instance of this class is sent during Connection handshake.
StaticSerialization.writeInetAddress(getInetAddress(), out);
out.writeInt(getMembershipPort());
StaticSerialization.writeString(memberData.getHostName(), out);
int flags = 0;
if (memberData.isNetworkPartitionDetectionEnabled()) {
flags |= NPD_ENABLED_BIT;
}
if (memberData.isPreferredForCoordinator()) {
flags |= COORD_ENABLED_BIT;
}
if (this.isPartial()) {
flags |= PARTIAL_ID_BIT;
}
// always write product version but enable reading from older versions
// that do not have it
flags |= VERSION_BIT;
out.writeByte((byte) (flags & 0xff));
out.writeInt(memberData.getDirectChannelPort());
out.writeInt(memberData.getProcessId());
int vmKind = memberData.getVmKind();
out.writeByte(vmKind);
StaticSerialization.writeStringArray(memberData.getGroups(), out);
StaticSerialization.writeString(memberData.getName(), out);
if (vmKind == MemberIdentifier.LONER_DM_TYPE) {
StaticSerialization.writeString(memberData.getUniqueTag(), out);
} else { // added in 6.5 for unique identifiers in P2P
StaticSerialization.writeString(String.valueOf(memberData.getVmViewId()), out);
}
String durableId = memberData.getDurableId();
StaticSerialization.writeString(durableId == null ? "" : durableId, out);
StaticSerialization.writeInteger(
Integer.valueOf(durableId == null ? 300 : memberData.getDurableTimeout()),
out);
short version = memberData.getVersionOrdinal();
VersioningIO.writeOrdinal(out, version, true);
}
public void toDataPre_GFE_7_1_0_0(DataOutput out, SerializationContext context)
throws IOException {
assert memberData.getVmKind() > 0;
// disabled to allow post-connect setting of the port for loner systems
// Assert.assertTrue(getPort() > 0);
// if (this.getPort() == 0) {
// InternalDistributedSystem.getLogger().warning(String.format("%s",
// "Serializing ID with zero port", new Exception("Stack trace")));
// }
// NOTE: If you change the serialized format of this class
// then bump Connection.HANDSHAKE_VERSION since an
// instance of this class is sent during Connection handshake.
StaticSerialization.writeInetAddress(getInetAddress(), out);
out.writeInt(getMembershipPort());
StaticSerialization.writeString(memberData.getHostName(), out);
int flags = 0;
if (memberData.isNetworkPartitionDetectionEnabled()) {
flags |= NPD_ENABLED_BIT;
}
if (memberData.isPreferredForCoordinator()) {
flags |= COORD_ENABLED_BIT;
}
if (this.isPartial()) {
flags |= PARTIAL_ID_BIT;
}
out.writeByte((byte) (flags & 0xff));
out.writeInt(memberData.getDirectChannelPort());
out.writeInt(memberData.getProcessId());
out.writeByte(memberData.getVmKind());
StaticSerialization.writeStringArray(memberData.getGroups(), out);
StaticSerialization.writeString(memberData.getName(), out);
int vmKind = memberData.getVmKind();
if (vmKind == MemberIdentifier.LONER_DM_TYPE) {
StaticSerialization.writeString(memberData.getUniqueTag(), out);
} else { // added in 6.5 for unique identifiers in P2P
StaticSerialization.writeString(String.valueOf(memberData.getVmViewId()), out);
}
String durableId = memberData.getDurableId();
StaticSerialization.writeString(durableId == null ? "" : durableId, out);
StaticSerialization.writeInteger(
Integer.valueOf(durableId == null ? 300 : memberData.getDurableTimeout()),
out);
}
@Override
public void fromData(DataInput in,
DeserializationContext context) throws IOException, ClassNotFoundException {
fromDataPre_GFE_9_0_0_0(in, context);
// just in case this is just a non-versioned read
// from a file we ought to check the version
if (memberData.getVersionOrdinal() >= KnownVersion.GFE_90.ordinal()) {
try {
memberData.readAdditionalData(in);
} catch (EOFException e) {
// nope - it's from a pre-GEODE client or WAN site
}
}
}
public void fromDataPre_GFE_9_0_0_0(DataInput in, DeserializationContext context)
throws IOException, ClassNotFoundException {
InetAddress inetAddr = StaticSerialization.readInetAddress(in);
int port = in.readInt();
String hostName = StaticSerialization.readString(in);
int flags = in.readUnsignedByte();
boolean sbEnabled = (flags & NPD_ENABLED_BIT) != 0;
boolean elCoord = (flags & COORD_ENABLED_BIT) != 0;
boolean isPartial = (flags & PARTIAL_ID_BIT) != 0;
int dcPort = in.readInt();
int vmPid = in.readInt();
int vmKind = in.readUnsignedByte();
String[] groups = StaticSerialization.readStringArray(in);
int vmViewId = -1;
String name = StaticSerialization.readString(in);
String uniqueTag = null;
if (vmKind == MemberIdentifier.LONER_DM_TYPE) {
uniqueTag = StaticSerialization.readString(in);
} else {
String str = StaticSerialization.readString(in);
if (str != null) { // backward compatibility from earlier than 6.5
vmViewId = Integer.parseInt(str);
}
}
String durableId = StaticSerialization.readString(in);
int durableTimeout = in.readInt();
short version = readVersion(flags, in);
memberData = MemberDataBuilder.newBuilder(inetAddr, hostName)
.setMembershipPort(port)
.setDirectChannelPort(dcPort)
.setName(name)
.setNetworkPartitionDetectionEnabled(sbEnabled)
.setPreferredForCoordinator(elCoord)
.setVersionOrdinal(version)
.setVmPid(vmPid)
.setVmKind(vmKind)
.setVmViewId(vmViewId)
.setGroups(groups)
.setDurableId(durableId)
.setDurableTimeout(durableTimeout)
.setIsPartial(isPartial)
.setUniqueTag(uniqueTag)
.build();
assert memberData.getVmKind() > 0;
// Assert.assertTrue(getPort() > 0);
}
public void fromDataPre_GFE_7_1_0_0(DataInput in, DeserializationContext context)
throws IOException, ClassNotFoundException {
InetAddress inetAddr = StaticSerialization.readInetAddress(in);
int port = in.readInt();
String hostName = StaticSerialization.readString(in);
int flags = in.readUnsignedByte();
boolean sbEnabled = (flags & NPD_ENABLED_BIT) != 0;
boolean elCoord = (flags & COORD_ENABLED_BIT) != 0;
boolean isPartial = (flags & PARTIAL_ID_BIT) != 0;
int dcPort = in.readInt();
int vmPid = in.readInt();
int vmKind = in.readUnsignedByte();
String[] groups = StaticSerialization.readStringArray(in);
int vmViewId = -1;
String name = StaticSerialization.readString(in);
String uniqueTag = null;
if (vmKind == MemberIdentifier.LONER_DM_TYPE) {
uniqueTag = StaticSerialization.readString(in);
} else {
String str = StaticSerialization.readString(in);
if (str != null) { // backward compatibility from earlier than 6.5
vmViewId = Integer.parseInt(str);
}
}
String durableId = StaticSerialization.readString(in);
int durableTimeout = in.readInt();
short version = readVersion(flags, in);
memberData = MemberDataBuilder.newBuilder(inetAddr, hostName)
.setMembershipPort(port)
.setDirectChannelPort(dcPort)
.setName(name)
.setNetworkPartitionDetectionEnabled(sbEnabled)
.setPreferredForCoordinator(elCoord)
.setVersionOrdinal(version)
.setVmPid(vmPid)
.setVmKind(vmKind)
.setVmViewId(vmViewId)
.setGroups(groups)
.setDurableId(durableId)
.setDurableTimeout(durableTimeout)
.setIsPartial(isPartial)
.setUniqueTag(uniqueTag)
.build();
assert memberData.getVmKind() > 0;
}
public void _readEssentialData(DataInput in, Function<InetAddress, String> hostnameResolver)
throws IOException, ClassNotFoundException {
InetAddress inetAddr = StaticSerialization.readInetAddress(in);
int port = in.readInt();
String hostName = hostnameResolver.apply(inetAddr);
int flags = in.readUnsignedByte();
boolean sbEnabled = (flags & NPD_ENABLED_BIT) != 0;
boolean elCoord = (flags & COORD_ENABLED_BIT) != 0;
int vmKind = in.readUnsignedByte();
int vmViewId = -1;
String uniqueTag = null;
if (vmKind == MemberIdentifier.LONER_DM_TYPE) {
uniqueTag = StaticSerialization.readString(in);
} else {
String str = StaticSerialization.readString(in);
if (str != null) { // backward compatibility from earlier than 6.5
vmViewId = Integer.parseInt(str);
}
}
String name = StaticSerialization.readString(in);
memberData = MemberDataBuilder.newBuilder(inetAddr, hostName)
.setMembershipPort(port)
.setName(name)
.setNetworkPartitionDetectionEnabled(sbEnabled)
.setPreferredForCoordinator(elCoord)
.setVersionOrdinal(StaticSerialization.getVersionForDataStream(in).ordinal())
.setVmKind(vmKind)
.setVmViewId(vmViewId)
.setIsPartial(true)
.setUniqueTag(uniqueTag)
.build();
if (StaticSerialization.getVersionForDataStream(in) == KnownVersion.GFE_90) {
memberData.readAdditionalData(in);
}
}
public void writeEssentialData(DataOutput out) throws IOException {
assert memberData.getVmKind() > 0;
StaticSerialization.writeInetAddress(getInetAddress(), out);
out.writeInt(getMembershipPort());
int flags = 0;
if (memberData.isNetworkPartitionDetectionEnabled()) {
flags |= NPD_ENABLED_BIT;
}
if (memberData.isPreferredForCoordinator()) {
flags |= COORD_ENABLED_BIT;
}
flags |= PARTIAL_ID_BIT;
out.writeByte((byte) (flags & 0xff));
// out.writeInt(dcPort);
byte vmKind = memberData.getVmKind();
out.writeByte(vmKind);
if (vmKind == MemberIdentifier.LONER_DM_TYPE) {
StaticSerialization.writeString(memberData.getUniqueTag(), out);
} else { // added in 6.5 for unique identifiers in P2P
StaticSerialization.writeString(String.valueOf(memberData.getVmViewId()), out);
}
// write name last to fix bug 45160
StaticSerialization.writeString(memberData.getName(), out);
KnownVersion outputVersion = StaticSerialization.getVersionForDataStream(out);
if (outputVersion.isOlderThan(KnownVersion.GEODE_1_1_0)
&& outputVersion.isNotOlderThan(KnownVersion.GFE_90)) {
memberData.writeAdditionalData(out);
}
}
/**
* Set the membership port. This is done in loner systems using client/server connection
* information to help form a unique ID
*/
public void setPort(int p) {
assert memberData.getVmKind() == MemberIdentifier.LONER_DM_TYPE;
this.memberData.setPort(p);
cachedToString = null;
}
@Override
public MemberData getMemberData() {
return memberData;
}
@Override
public String getHostName() {
return memberData.getHostName();
}
public String getHost() {
return this.memberData.getInetAddress().getCanonicalHostName();
}
public int getProcessId() {
return memberData.getProcessId();
}
public String getId() {
return toString();
}
public String getUniqueId() {
StringBuilder sb = new StringBuilder();
addFixedToString(sb, false);
// add version if not current
short version = memberData.getVersionOrdinal();
if (version != KnownVersion.CURRENT.ordinal()) {
sb.append("(version:").append(Versioning.getVersion(version)).append(')');
}
return sb.toString();
}
public void setVersionForTest(Version v) {
memberData.setVersion(v);
cachedToString = null;
}
@Override
public Version getVersion() {
return memberData.getVersion();
}
@Override
public KnownVersion[] getSerializationVersions() {
return dsfidVersions;
}
@VisibleForTesting
public void setUniqueTag(String tag) {
memberData.setUniqueTag(tag);
}
@Override
public void setIsPartial(boolean value) {
memberData.setIsPartial(value);
}
@Override
public long getUuidLeastSignificantBits() {
return memberData.getUuidLeastSignificantBits();
}
@Override
public long getUuidMostSignificantBits() {
return memberData.getUuidMostSignificantBits();
}
@Override
public boolean isNetworkPartitionDetectionEnabled() {
return memberData.isNetworkPartitionDetectionEnabled();
}
@Override
public void setUUID(UUID uuid) {
memberData.setUUID(uuid);
}
@Override
public void setMemberWeight(byte b) {
memberData.setMemberWeight(b);
}
@Override
public void setUdpPort(int port) {
memberData.setUdpPort(port);
}
@Override
public UUID getUUID() {
return memberData.getUUID();
}
}
| apache-2.0 |
dkhwangbo/druid | server/src/test/java/org/apache/druid/segment/realtime/appenderator/AppenderatorPlumberTest.java | 4761 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.druid.segment.realtime.appenderator;
import org.apache.druid.data.input.InputRow;
import org.apache.druid.segment.indexing.RealtimeTuningConfig;
import org.apache.druid.segment.realtime.SegmentPublisher;
import org.apache.druid.segment.realtime.plumber.IntervalStartVersioningPolicy;
import org.apache.druid.segment.realtime.plumber.NoopRejectionPolicyFactory;
import org.apache.druid.segment.realtime.plumber.SegmentHandoffNotifier;
import org.apache.druid.segment.realtime.plumber.SegmentHandoffNotifierFactory;
import org.apache.druid.server.coordination.DataSegmentAnnouncer;
import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Test;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class AppenderatorPlumberTest
{
private final AppenderatorPlumber plumber;
private final AppenderatorTester appenderatorTester;
public AppenderatorPlumberTest() throws Exception
{
this.appenderatorTester = new AppenderatorTester(10);
DataSegmentAnnouncer segmentAnnouncer = EasyMock
.createMock(DataSegmentAnnouncer.class);
segmentAnnouncer.announceSegment(EasyMock.anyObject());
EasyMock.expectLastCall().anyTimes();
SegmentPublisher segmentPublisher = EasyMock
.createNiceMock(SegmentPublisher.class);
SegmentHandoffNotifierFactory handoffNotifierFactory = EasyMock
.createNiceMock(SegmentHandoffNotifierFactory.class);
SegmentHandoffNotifier handoffNotifier = EasyMock
.createNiceMock(SegmentHandoffNotifier.class);
EasyMock
.expect(
handoffNotifierFactory.createSegmentHandoffNotifier(EasyMock
.anyString())).andReturn(handoffNotifier).anyTimes();
EasyMock
.expect(
handoffNotifier.registerSegmentHandoffCallback(
EasyMock.anyObject(),
EasyMock.anyObject(),
EasyMock.anyObject())).andReturn(true).anyTimes();
RealtimeTuningConfig tuningConfig = new RealtimeTuningConfig(
1,
null,
null,
null,
null,
new IntervalStartVersioningPolicy(),
new NoopRejectionPolicyFactory(),
null,
null,
null,
true,
0,
0,
false,
null,
null,
null,
null
);
this.plumber = new AppenderatorPlumber(appenderatorTester.getSchema(),
tuningConfig, appenderatorTester.getMetrics(),
segmentAnnouncer, segmentPublisher, handoffNotifier,
appenderatorTester.getAppenderator());
}
@Test
public void testSimpleIngestion() throws Exception
{
final ConcurrentMap<String, String> commitMetadata = new ConcurrentHashMap<>();
Appenderator appenderator = appenderatorTester.getAppenderator();
// startJob
Assert.assertEquals(null, plumber.startJob());
// getDataSource
Assert.assertEquals(AppenderatorTester.DATASOURCE,
appenderator.getDataSource());
InputRow[] rows = new InputRow[] {AppenderatorTest.IR("2000", "foo", 1),
AppenderatorTest.IR("2000", "bar", 2), AppenderatorTest.IR("2000", "qux", 4)};
// add
commitMetadata.put("x", "1");
Assert.assertEquals(
1,
plumber.add(rows[0], null).getRowCount());
commitMetadata.put("x", "2");
Assert.assertEquals(
2,
plumber.add(rows[1], null).getRowCount());
commitMetadata.put("x", "3");
Assert.assertEquals(
3,
plumber.add(rows[2], null).getRowCount());
Assert.assertEquals(1, plumber.getSegmentsView().size());
SegmentIdentifier si = plumber.getSegmentsView().values().toArray(new SegmentIdentifier[0])[0];
Assert.assertEquals(3,
appenderator.getRowCount(si));
appenderator.clear();
Assert.assertTrue(appenderator.getSegments().isEmpty());
plumber.dropSegment(si);
plumber.finishJob();
}
}
| apache-2.0 |
SixCan/Android5.x | SupportDemo/app/src/main/java/cn/six/sup/design_lib/coordinate/DemoView.java | 1748 | package cn.six.sup.design_lib.coordinate;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.design.widget.CoordinatorLayout;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
public class DemoView extends View {
private int centerX, centerY;
private Paint paint;
public DemoView(Context context) {
super(context);
init();
}
public DemoView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.RED);
paint.setTextSize(40);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
centerX = w / 2;
centerY = h / 2;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawText("Dependency", 50, 130, paint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getRawX();
int y = (int) event.getRawY();
// 加上action_move, 是因为不加的话, action_down时会有一种抖动的感觉
if(event.getAction() == MotionEvent.ACTION_MOVE) {
CoordinatorLayout.MarginLayoutParams layoutParams = (CoordinatorLayout.MarginLayoutParams) getLayoutParams();
layoutParams.leftMargin = x - centerX;
layoutParams.topMargin = y - centerY;
setLayoutParams(layoutParams);
}
return true;
}
}
| apache-2.0 |
AEGONTH/kpi-report-app | src/main/java/com/adms/batch/kpireport/util/NewTimeFormatHelper.java | 1878 | package com.adms.batch.kpireport.util;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class NewTimeFormatHelper {
private static NewTimeFormatHelper instance;
private String campaignCodeWithNewFormat = "";
private Boolean flag;
public static NewTimeFormatHelper getInstance() {
if(instance == null) {
instance = new NewTimeFormatHelper();
}
return instance;
}
public void setCampaignCodeWithNewFormat(String campaignCodeWithNewFormat) {
this.campaignCodeWithNewFormat = campaignCodeWithNewFormat;
}
public BigDecimal getTimeBase100(String campaignCode, BigDecimal time) throws Exception {
BigDecimal result = new BigDecimal(0);
if(StringUtils.isBlank(campaignCode) && flag == null) {
throw new Exception("CampaignCode or Flag is required!!");
}
if(time == null || time.equals(new BigDecimal(0))) return result;
if((!StringUtils.isBlank(campaignCode) && campaignCodeWithNewFormat.contains(campaignCode))
|| (flag != null && flag == true)) {
result = new BigDecimal(time.intValue()).add(new BigDecimal(time.doubleValue() % 1d / 60d * 100d));
} else {
result = new BigDecimal(time.doubleValue());
}
return result;
}
public void setThisFileIsNewTimeFormat(boolean flag) {
this.flag = flag;
}
public void validateTimeFormatByTableHeader(String dir) {
Workbook wb = null;
InputStream is = null;
try {
is = new FileInputStream(dir);
wb = WorkbookFactory.create(is);
} catch(Exception e) {
e.printStackTrace();
} finally {
try { is.close();} catch(Exception e) {}
try { wb.close();} catch(Exception e) {}
}
}
}
| apache-2.0 |
soda211/CoolWeather | app/src/main/java/soda/coolweather/model/Province.java | 656 | package soda.coolweather.model;
/**
* Created by soda on 2016/11/28.
*/
public class Province {
private int id;
private String provinceName;
private String provinceCode;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProvinceCode() {
return provinceCode;
}
public void setProvinceCode(String provinceCode) {
this.provinceCode = provinceCode;
}
public String getProvinceName() {
return provinceName;
}
public void setProvinceName(String provinceName) {
this.provinceName = provinceName;
}
}
| apache-2.0 |
cping/LGame | Java/Loon-Neo/src/loon/opengl/BlendMethod.java | 2080 | /**
* Copyright 2008 - 2020 The Loon Game Engine 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.
*
* @project loon
* @author cping
* @email:javachenpeng@yahoo.com
* @version 0.5
*/
package loon.opengl;
public class BlendMethod {
public static final int MODE_NORMAL = 1;
public static final int MODE_ALPHA_MAP = 2;
public static final int MODE_ALPHA_BLEND = 3;
public static final int MODE_COLOR_MULTIPLY = 4;
public static final int MODE_ADD = 5;
public static final int MODE_SCREEN = 6;
public static final int MODE_ALPHA = 7;
public static final int MODE_SPEED = 8;
public static final int MODE_ALPHA_ONE = 9;
public static final int MODE_NONE = 10;
public static final int MODE_MASK = 11;
public static final int MODE_LIGHT = 12;
public static final int MODE_ALPHA_ADD = 13;
public static final int MODE_MULTIPLY = 14;
protected int _GL_BLEND;
public BlendMethod(int b) {
this._GL_BLEND = b;
}
public BlendMethod() {
this(BlendMethod.MODE_NORMAL);
}
public void blendNormal() {
_GL_BLEND = BlendMethod.MODE_NORMAL;
}
public void blendSpeed() {
_GL_BLEND = BlendMethod.MODE_SPEED;
}
public void blendAdd() {
_GL_BLEND = BlendMethod.MODE_ALPHA_ADD;
}
public void blendMultiply() {
_GL_BLEND = BlendMethod.MODE_MULTIPLY;
}
public void blendLight() {
_GL_BLEND = BlendMethod.MODE_LIGHT;
}
public void blendMask() {
_GL_BLEND = BlendMethod.MODE_MASK;
}
public int getBlend() {
return _GL_BLEND;
}
public BlendMethod setBlend(int b) {
this._GL_BLEND = b;
return this;
}
}
| apache-2.0 |
NationalSecurityAgency/ghidra | Ghidra/Features/ByteViewer/src/main/java/ghidra/app/plugin/core/byteviewer/ByteViewerOptionsDialog.java | 9328 | /* ###
* IP: GHIDRA
*
* 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 ghidra.app.plugin.core.byteviewer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigInteger;
import java.util.*;
import java.util.List;
import java.util.Map.Entry;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import docking.DialogComponentProvider;
import docking.widgets.checkbox.GCheckBox;
import docking.widgets.label.GLabel;
import ghidra.app.plugin.core.format.ByteBlockSelection;
import ghidra.app.plugin.core.format.DataFormatModel;
import ghidra.app.util.AddressInput;
import ghidra.app.util.bean.FixedBitSizeValueField;
import ghidra.program.model.address.Address;
import ghidra.program.model.listing.Program;
import ghidra.util.HelpLocation;
import ghidra.util.layout.PairLayout;
import ghidra.util.layout.VerticalLayout;
public class ByteViewerOptionsDialog extends DialogComponentProvider
implements ChangeListener, ActionListener {
private AddressInput addressInputField;
private FixedBitSizeValueField bytesPerLineField;
private FixedBitSizeValueField groupSizeField;
private ByteViewerComponentProvider provider;
private Map<String, JCheckBox> checkboxMap = new HashMap<>();
public ByteViewerOptionsDialog(ByteViewerComponentProvider provider) {
super("Byte Viewer Options");
this.provider = provider;
addWorkPanel(buildPanel());
addOKButton();
addCancelButton();
setResizable(false);
setHelpLocation(new HelpLocation("ByteViewerPlugin", "Byte_Viewer_Options"));
setRememberLocation(false);
setRememberSize(false);
}
private JComponent buildPanel() {
JPanel mainPanel = new JPanel(new VerticalLayout(10));
mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
mainPanel.add(buildSettingsPanel());
mainPanel.add(buildViewOptionsPanel());
setOkEnabled(hasValidFieldValues());
return mainPanel;
}
private Component buildSettingsPanel() {
JPanel panel = new JPanel(new PairLayout(5, 5));
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
panel.add(new GLabel("Alignment Address:"));
if (provider instanceof ProgramByteViewerComponentProvider) {
Program program = ((ProgramByteViewerComponentProvider) provider).getProgram();
if (program != null) {
addressInputField = new AddressInput();
addressInputField.setAddressFactory(program.getAddressFactory());
addressInputField.showAddressSpaceCombo(false);
addressInputField.setAddress(getAlignmentAddress());
panel.add(addressInputField);
addressInputField.addChangeListener(this);
}
}
panel.add(new GLabel("Bytes Per Line:"));
bytesPerLineField = new FixedBitSizeValueField(8, false, true);
bytesPerLineField.setFormat(10, false);
bytesPerLineField.setMinMax(BigInteger.valueOf(1), BigInteger.valueOf(256));
bytesPerLineField.setValue(BigInteger.valueOf(provider.getBytesPerLine()));
panel.add(bytesPerLineField);
bytesPerLineField.addChangeListener(this);
panel.add(new GLabel("Group size (Hex View Only):"));
groupSizeField = new FixedBitSizeValueField(8, false, true);
groupSizeField.setFormat(10, false);
groupSizeField.setMinMax(BigInteger.valueOf(1), BigInteger.valueOf(256));
groupSizeField.setValue(BigInteger.valueOf(provider.getGroupSize()));
panel.add(groupSizeField);
groupSizeField.addChangeListener(this);
return panel;
}
private Component buildViewOptionsPanel() {
JPanel panel = new JPanel(new GridLayout(0, 2, 40, 0));
Border outer = BorderFactory.createTitledBorder("Views");
Border inner = BorderFactory.createEmptyBorder(5, 15, 5, 15);
panel.setBorder(BorderFactory.createCompoundBorder(outer, inner));
Set<String> currentViews = provider.getCurrentViews();
List<String> dataModelNames = provider.getDataFormatNames();
for (String formatName : dataModelNames) {
GCheckBox checkBox = new GCheckBox(formatName);
checkBox.addActionListener(this);
checkboxMap.put(formatName, checkBox);
if (currentViews.contains(formatName)) {
checkBox.setSelected(true);
}
panel.add(checkBox);
}
return panel;
}
private Address getAlignmentAddress() {
int bytesPerLine = provider.getBytesPerLine();
int offset = provider.getOffset();
Address minAddr =
((ProgramByteViewerComponentProvider) provider).getProgram().getMinAddress();
long addressOffset = minAddr.getOffset() + offset;
int alignment = (int) (addressOffset % bytesPerLine);
return (alignment == 0) ? minAddr : minAddr.add(bytesPerLine - alignment);
}
@Override
protected void okCallback() {
Address alignmentAddress = addressInputField.getAddress();
int bytesPerLine = bytesPerLineField.getValue().intValue();
int groupSize = groupSizeField.getValue().intValue();
int addrOffset = (int) (alignmentAddress.getOffset() % bytesPerLine);
// since we want the alignment address to begin a column, need to subtract addrOffset from bytesPerLine
int offset = addrOffset == 0 ? 0 : bytesPerLine - addrOffset;
ByteBlockSelection blockSelection = provider.getBlockSelection();
// Setting these properties individually is problematic since it can temporarily put
// the system into a bad state. As a hack, set the bytes per line to 256 since that
// can support all allowed group sizes. Then set the group first since there
// will be a divide by zero exception if the group size is ever bigger than the bytes
// per line. Also, remove any deleted views before changing settings because the new settings
// may not be compatible with a deleted view. Finally, after all setting have been updated,
// add in the newly added views. This has to happen last because the new views may not be
// compatible with the old settings.
removeDeletedViews();
provider.setBytesPerLine(256);
provider.setGroupSize(groupSize);
provider.setBytesPerLine(bytesPerLine);
provider.setBlockOffset(offset);
addNewViews();
close();
}
private void removeDeletedViews() {
Set<String> currentViews = provider.getCurrentViews();
for (String viewName : currentViews) {
JCheckBox checkBox = checkboxMap.get(viewName);
if (!checkBox.isSelected()) {
provider.removeView(viewName, true);
}
}
}
private void addNewViews() {
Set<String> currentViews = provider.getCurrentViews();
// now add any views that have been selected
for (String viewName : checkboxMap.keySet()) {
JCheckBox checkBox = checkboxMap.get(viewName);
if (!currentViews.contains(viewName) && checkBox.isSelected()) {
provider.addView(viewName);
}
}
}
@Override
public void actionPerformed(ActionEvent e) {
update();
}
@Override
public void stateChanged(ChangeEvent e) {
update();
}
private void update() {
setOkEnabled(hasValidFieldValues());
}
private boolean hasValidFieldValues() {
if (addressInputField.getValue().length() == 0) {
setStatusText("Enter an alignment address");
return false;
}
Address alignmentAddress = addressInputField.getAddress();
if (alignmentAddress == null) {
setStatusText("Invalid alignment address:" + addressInputField.getValue());
return false;
}
BigInteger bytesPerLine = bytesPerLineField.getValue();
if (bytesPerLine == null) {
setStatusText("Enter a value for Bytes Per Line");
return false;
}
BigInteger groupSize = groupSizeField.getValue();
if (groupSize == null) {
setStatusText("Enter a group size");
return false;
}
if (bytesPerLine.intValue() % groupSize.intValue() != 0) {
setStatusText("The bytes per line must be a multiple of the group size.");
return false;
}
if (checkForUnsupportedModels(bytesPerLine.intValue())) {
setStatusText("Not all selected views support the current bytes per line value.");
return false;
}
if (!atLeastOneViewOn()) {
setStatusText("You must have at least one view selected");
return false;
}
setStatusText("");
return true;
}
private boolean atLeastOneViewOn() {
Set<Entry<String, JCheckBox>> entrySet = checkboxMap.entrySet();
for (Entry<String, JCheckBox> entry : entrySet) {
JCheckBox checkBox = entry.getValue();
if (checkBox.isSelected()) {
return true;
}
}
return false;
}
private boolean checkForUnsupportedModels(int bytesPerLine) {
boolean isBad = false;
Set<Entry<String, JCheckBox>> entrySet = checkboxMap.entrySet();
for (Entry<String, JCheckBox> entry : entrySet) {
JCheckBox checkBox = entry.getValue();
DataFormatModel model = provider.getDataFormatModel(entry.getKey());
if (model.validateBytesPerLine(bytesPerLine)) {
checkBox.setForeground(Color.BLACK);
}
else {
checkBox.setForeground(Color.RED);
isBad |= checkBox.isSelected();
}
}
return isBad;
}
}
| apache-2.0 |
White0ut/PantryTracker | app/src/main/java/com/whiteout/pantrytracker/data/web/interfaces/YummlyRecipeRetriever.java | 3206 | package com.whiteout.pantrytracker.data.web.interfaces;
import android.util.Log;
import com.whiteout.pantrytracker.data.model.Recipe;
import com.whiteout.pantrytracker.data.model.RecipeSearch;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
/**
* Author: Kendrick Cline
* Date: 12/3/2014
* Email: kdecline@gmail.com
*/
public class YummlyRecipeRetriever {
private static final String ENDPOINT = "http://api.yummly.com/v1/api/recipe/";
private static final String ENDPOINT_TAG = "?_app_id=9cc50088&_app_key=347d218bb9d46fe84a9c904a4874d364";
private static final String TAG = "Kenny";
public byte[] getUrlBytes(String urlSpec) throws IOException {
URL url = new URL(urlSpec);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
try {
ByteArrayOutputStream out =new ByteArrayOutputStream();
InputStream in = connection.getInputStream();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return null;
}
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
}
out.close();
return out.toByteArray();
} finally {
connection.disconnect();
}
}
String getUrl(String urlSpec) throws IOException {
return new String(getUrlBytes(urlSpec));
}
public Recipe fetchRecipes(String recipeId) {
Recipe recipe = null;
try {
String url = ENDPOINT + recipeId + ENDPOINT_TAG;
String jsonString = getUrl(url);
recipe = parseJSON(jsonString);
} catch (IOException ioe) {
Log.e(TAG, "Failed to fetch items", ioe);
} catch (JSONException e) {
Log.e(TAG, "Failed to fetch items", e);
}
return recipe;
}
Recipe parseJSON(String jsonString) throws JSONException {
Recipe recipe = new Recipe();
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray images = jsonObject.getJSONArray("images");
JSONObject imagesY = images.getJSONObject(0);
JSONObject attribution = jsonObject.getJSONObject("attribution");
String lines = "";
JSONArray ingredLines = jsonObject.getJSONArray("ingredientLines");
for (int i=0; i < ingredLines.length(); i++) {
lines += ingredLines.getString(i) + "\n";
}
recipe.setdirections(lines);
recipe.setName(jsonObject.getString("name"));
recipe.setYield(jsonObject.getString("yield"));
recipe.setYummlyId(jsonObject.getString("id"));
recipe.setFoodDownload(imagesY.getString("hostedLargeUrl"));
recipe.setYummlyLogo(attribution.getString("logo"));
recipe.setCookTime(jsonObject.getString("totalTime"));
return recipe;
}
}
| apache-2.0 |
bricket/bricket | bricket-core/src/main/java/org/bricket/plugin/authentication/web/SignUpTile.java | 1625 | /**
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.bricket.plugin.authentication.web;
import org.apache.wicket.Component;
import org.apache.wicket.model.IModel;
import brix.jcr.wrapper.BrixNode;
import brix.plugin.site.page.tile.Tile;
import brix.plugin.site.page.tile.admin.TileEditorPanel;
/**
* @author Ingo Renner
* @author Henning Teek
*/
public class SignUpTile implements Tile {
@Override
public String getDisplayName() {
return SignUpPanel.class.getSimpleName();
}
@Override
public String getTypeName() {
return "bricket.web.Signup";
}
@Override
public TileEditorPanel newEditor(String id, IModel<BrixNode> tileContainerNode) {
return new SignUpTileEditor(id, getDisplayName(), tileContainerNode);
}
@Override
public Component newViewer(String id, IModel<BrixNode> tileNode) {
return new SignUpPanel(id, tileNode).setOutputMarkupId(true);
}
@Override
public boolean requiresSSL(IModel<BrixNode> tileNode) {
return false;
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-gamelift/src/main/java/com/amazonaws/services/gamelift/model/VpcPeeringAuthorization.java | 16879 | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.gamelift.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Represents an authorization for a VPC peering connection between the VPC for an Amazon GameLift fleet and another VPC
* on an account you have access to. This authorization must exist and be valid for the peering connection to be
* established. Authorizations are valid for 24 hours after they are issued.
* </p>
* <ul>
* <li>
* <p>
* <a>CreateVpcPeeringAuthorization</a>
* </p>
* </li>
* <li>
* <p>
* <a>DescribeVpcPeeringAuthorizations</a>
* </p>
* </li>
* <li>
* <p>
* <a>DeleteVpcPeeringAuthorization</a>
* </p>
* </li>
* <li>
* <p>
* <a>CreateVpcPeeringConnection</a>
* </p>
* </li>
* <li>
* <p>
* <a>DescribeVpcPeeringConnections</a>
* </p>
* </li>
* <li>
* <p>
* <a>DeleteVpcPeeringConnection</a>
* </p>
* </li>
* </ul>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/gamelift-2015-10-01/VpcPeeringAuthorization" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class VpcPeeringAuthorization implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* Unique identifier for the AWS account that you use to manage your Amazon GameLift fleet. You can find your
* Account ID in the AWS Management Console under account settings.
* </p>
*/
private String gameLiftAwsAccountId;
/** <p/> */
private String peerVpcAwsAccountId;
/**
* <p>
* Unique identifier for a VPC with resources to be accessed by your Amazon GameLift fleet. The VPC must be in the
* same region where your fleet is deployed. Look up a VPC ID using the <a
* href="https://console.aws.amazon.com/vpc/">VPC Dashboard</a> in the AWS Management Console. Learn more about VPC
* peering in <a href="https://docs.aws.amazon.com/gamelift/latest/developerguide/vpc-peering.html">VPC Peering with
* Amazon GameLift Fleets</a>.
* </p>
*/
private String peerVpcId;
/**
* <p>
* Time stamp indicating when this authorization was issued. Format is a number expressed in Unix time as
* milliseconds (for example "1469498468.057").
* </p>
*/
private java.util.Date creationTime;
/**
* <p>
* Time stamp indicating when this authorization expires (24 hours after issuance). Format is a number expressed in
* Unix time as milliseconds (for example "1469498468.057").
* </p>
*/
private java.util.Date expirationTime;
/**
* <p>
* Unique identifier for the AWS account that you use to manage your Amazon GameLift fleet. You can find your
* Account ID in the AWS Management Console under account settings.
* </p>
*
* @param gameLiftAwsAccountId
* Unique identifier for the AWS account that you use to manage your Amazon GameLift fleet. You can find your
* Account ID in the AWS Management Console under account settings.
*/
public void setGameLiftAwsAccountId(String gameLiftAwsAccountId) {
this.gameLiftAwsAccountId = gameLiftAwsAccountId;
}
/**
* <p>
* Unique identifier for the AWS account that you use to manage your Amazon GameLift fleet. You can find your
* Account ID in the AWS Management Console under account settings.
* </p>
*
* @return Unique identifier for the AWS account that you use to manage your Amazon GameLift fleet. You can find
* your Account ID in the AWS Management Console under account settings.
*/
public String getGameLiftAwsAccountId() {
return this.gameLiftAwsAccountId;
}
/**
* <p>
* Unique identifier for the AWS account that you use to manage your Amazon GameLift fleet. You can find your
* Account ID in the AWS Management Console under account settings.
* </p>
*
* @param gameLiftAwsAccountId
* Unique identifier for the AWS account that you use to manage your Amazon GameLift fleet. You can find your
* Account ID in the AWS Management Console under account settings.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public VpcPeeringAuthorization withGameLiftAwsAccountId(String gameLiftAwsAccountId) {
setGameLiftAwsAccountId(gameLiftAwsAccountId);
return this;
}
/**
* <p/>
*
* @param peerVpcAwsAccountId
*/
public void setPeerVpcAwsAccountId(String peerVpcAwsAccountId) {
this.peerVpcAwsAccountId = peerVpcAwsAccountId;
}
/**
* <p/>
*
* @return
*/
public String getPeerVpcAwsAccountId() {
return this.peerVpcAwsAccountId;
}
/**
* <p/>
*
* @param peerVpcAwsAccountId
* @return Returns a reference to this object so that method calls can be chained together.
*/
public VpcPeeringAuthorization withPeerVpcAwsAccountId(String peerVpcAwsAccountId) {
setPeerVpcAwsAccountId(peerVpcAwsAccountId);
return this;
}
/**
* <p>
* Unique identifier for a VPC with resources to be accessed by your Amazon GameLift fleet. The VPC must be in the
* same region where your fleet is deployed. Look up a VPC ID using the <a
* href="https://console.aws.amazon.com/vpc/">VPC Dashboard</a> in the AWS Management Console. Learn more about VPC
* peering in <a href="https://docs.aws.amazon.com/gamelift/latest/developerguide/vpc-peering.html">VPC Peering with
* Amazon GameLift Fleets</a>.
* </p>
*
* @param peerVpcId
* Unique identifier for a VPC with resources to be accessed by your Amazon GameLift fleet. The VPC must be
* in the same region where your fleet is deployed. Look up a VPC ID using the <a
* href="https://console.aws.amazon.com/vpc/">VPC Dashboard</a> in the AWS Management Console. Learn more
* about VPC peering in <a
* href="https://docs.aws.amazon.com/gamelift/latest/developerguide/vpc-peering.html">VPC Peering with Amazon
* GameLift Fleets</a>.
*/
public void setPeerVpcId(String peerVpcId) {
this.peerVpcId = peerVpcId;
}
/**
* <p>
* Unique identifier for a VPC with resources to be accessed by your Amazon GameLift fleet. The VPC must be in the
* same region where your fleet is deployed. Look up a VPC ID using the <a
* href="https://console.aws.amazon.com/vpc/">VPC Dashboard</a> in the AWS Management Console. Learn more about VPC
* peering in <a href="https://docs.aws.amazon.com/gamelift/latest/developerguide/vpc-peering.html">VPC Peering with
* Amazon GameLift Fleets</a>.
* </p>
*
* @return Unique identifier for a VPC with resources to be accessed by your Amazon GameLift fleet. The VPC must be
* in the same region where your fleet is deployed. Look up a VPC ID using the <a
* href="https://console.aws.amazon.com/vpc/">VPC Dashboard</a> in the AWS Management Console. Learn more
* about VPC peering in <a
* href="https://docs.aws.amazon.com/gamelift/latest/developerguide/vpc-peering.html">VPC Peering with
* Amazon GameLift Fleets</a>.
*/
public String getPeerVpcId() {
return this.peerVpcId;
}
/**
* <p>
* Unique identifier for a VPC with resources to be accessed by your Amazon GameLift fleet. The VPC must be in the
* same region where your fleet is deployed. Look up a VPC ID using the <a
* href="https://console.aws.amazon.com/vpc/">VPC Dashboard</a> in the AWS Management Console. Learn more about VPC
* peering in <a href="https://docs.aws.amazon.com/gamelift/latest/developerguide/vpc-peering.html">VPC Peering with
* Amazon GameLift Fleets</a>.
* </p>
*
* @param peerVpcId
* Unique identifier for a VPC with resources to be accessed by your Amazon GameLift fleet. The VPC must be
* in the same region where your fleet is deployed. Look up a VPC ID using the <a
* href="https://console.aws.amazon.com/vpc/">VPC Dashboard</a> in the AWS Management Console. Learn more
* about VPC peering in <a
* href="https://docs.aws.amazon.com/gamelift/latest/developerguide/vpc-peering.html">VPC Peering with Amazon
* GameLift Fleets</a>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public VpcPeeringAuthorization withPeerVpcId(String peerVpcId) {
setPeerVpcId(peerVpcId);
return this;
}
/**
* <p>
* Time stamp indicating when this authorization was issued. Format is a number expressed in Unix time as
* milliseconds (for example "1469498468.057").
* </p>
*
* @param creationTime
* Time stamp indicating when this authorization was issued. Format is a number expressed in Unix time as
* milliseconds (for example "1469498468.057").
*/
public void setCreationTime(java.util.Date creationTime) {
this.creationTime = creationTime;
}
/**
* <p>
* Time stamp indicating when this authorization was issued. Format is a number expressed in Unix time as
* milliseconds (for example "1469498468.057").
* </p>
*
* @return Time stamp indicating when this authorization was issued. Format is a number expressed in Unix time as
* milliseconds (for example "1469498468.057").
*/
public java.util.Date getCreationTime() {
return this.creationTime;
}
/**
* <p>
* Time stamp indicating when this authorization was issued. Format is a number expressed in Unix time as
* milliseconds (for example "1469498468.057").
* </p>
*
* @param creationTime
* Time stamp indicating when this authorization was issued. Format is a number expressed in Unix time as
* milliseconds (for example "1469498468.057").
* @return Returns a reference to this object so that method calls can be chained together.
*/
public VpcPeeringAuthorization withCreationTime(java.util.Date creationTime) {
setCreationTime(creationTime);
return this;
}
/**
* <p>
* Time stamp indicating when this authorization expires (24 hours after issuance). Format is a number expressed in
* Unix time as milliseconds (for example "1469498468.057").
* </p>
*
* @param expirationTime
* Time stamp indicating when this authorization expires (24 hours after issuance). Format is a number
* expressed in Unix time as milliseconds (for example "1469498468.057").
*/
public void setExpirationTime(java.util.Date expirationTime) {
this.expirationTime = expirationTime;
}
/**
* <p>
* Time stamp indicating when this authorization expires (24 hours after issuance). Format is a number expressed in
* Unix time as milliseconds (for example "1469498468.057").
* </p>
*
* @return Time stamp indicating when this authorization expires (24 hours after issuance). Format is a number
* expressed in Unix time as milliseconds (for example "1469498468.057").
*/
public java.util.Date getExpirationTime() {
return this.expirationTime;
}
/**
* <p>
* Time stamp indicating when this authorization expires (24 hours after issuance). Format is a number expressed in
* Unix time as milliseconds (for example "1469498468.057").
* </p>
*
* @param expirationTime
* Time stamp indicating when this authorization expires (24 hours after issuance). Format is a number
* expressed in Unix time as milliseconds (for example "1469498468.057").
* @return Returns a reference to this object so that method calls can be chained together.
*/
public VpcPeeringAuthorization withExpirationTime(java.util.Date expirationTime) {
setExpirationTime(expirationTime);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getGameLiftAwsAccountId() != null)
sb.append("GameLiftAwsAccountId: ").append(getGameLiftAwsAccountId()).append(",");
if (getPeerVpcAwsAccountId() != null)
sb.append("PeerVpcAwsAccountId: ").append(getPeerVpcAwsAccountId()).append(",");
if (getPeerVpcId() != null)
sb.append("PeerVpcId: ").append(getPeerVpcId()).append(",");
if (getCreationTime() != null)
sb.append("CreationTime: ").append(getCreationTime()).append(",");
if (getExpirationTime() != null)
sb.append("ExpirationTime: ").append(getExpirationTime());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof VpcPeeringAuthorization == false)
return false;
VpcPeeringAuthorization other = (VpcPeeringAuthorization) obj;
if (other.getGameLiftAwsAccountId() == null ^ this.getGameLiftAwsAccountId() == null)
return false;
if (other.getGameLiftAwsAccountId() != null && other.getGameLiftAwsAccountId().equals(this.getGameLiftAwsAccountId()) == false)
return false;
if (other.getPeerVpcAwsAccountId() == null ^ this.getPeerVpcAwsAccountId() == null)
return false;
if (other.getPeerVpcAwsAccountId() != null && other.getPeerVpcAwsAccountId().equals(this.getPeerVpcAwsAccountId()) == false)
return false;
if (other.getPeerVpcId() == null ^ this.getPeerVpcId() == null)
return false;
if (other.getPeerVpcId() != null && other.getPeerVpcId().equals(this.getPeerVpcId()) == false)
return false;
if (other.getCreationTime() == null ^ this.getCreationTime() == null)
return false;
if (other.getCreationTime() != null && other.getCreationTime().equals(this.getCreationTime()) == false)
return false;
if (other.getExpirationTime() == null ^ this.getExpirationTime() == null)
return false;
if (other.getExpirationTime() != null && other.getExpirationTime().equals(this.getExpirationTime()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getGameLiftAwsAccountId() == null) ? 0 : getGameLiftAwsAccountId().hashCode());
hashCode = prime * hashCode + ((getPeerVpcAwsAccountId() == null) ? 0 : getPeerVpcAwsAccountId().hashCode());
hashCode = prime * hashCode + ((getPeerVpcId() == null) ? 0 : getPeerVpcId().hashCode());
hashCode = prime * hashCode + ((getCreationTime() == null) ? 0 : getCreationTime().hashCode());
hashCode = prime * hashCode + ((getExpirationTime() == null) ? 0 : getExpirationTime().hashCode());
return hashCode;
}
@Override
public VpcPeeringAuthorization clone() {
try {
return (VpcPeeringAuthorization) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.gamelift.model.transform.VpcPeeringAuthorizationMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| apache-2.0 |
dagnir/aws-sdk-java | aws-java-sdk-elasticache/src/main/java/com/amazonaws/services/elasticache/model/transform/DeleteCacheSubnetGroupRequestMarshaller.java | 2089 | /*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.elasticache.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.elasticache.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;
/**
* DeleteCacheSubnetGroupRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeleteCacheSubnetGroupRequestMarshaller implements Marshaller<Request<DeleteCacheSubnetGroupRequest>, DeleteCacheSubnetGroupRequest> {
public Request<DeleteCacheSubnetGroupRequest> marshall(DeleteCacheSubnetGroupRequest deleteCacheSubnetGroupRequest) {
if (deleteCacheSubnetGroupRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
Request<DeleteCacheSubnetGroupRequest> request = new DefaultRequest<DeleteCacheSubnetGroupRequest>(deleteCacheSubnetGroupRequest, "AmazonElastiCache");
request.addParameter("Action", "DeleteCacheSubnetGroup");
request.addParameter("Version", "2015-02-02");
request.setHttpMethod(HttpMethodName.POST);
if (deleteCacheSubnetGroupRequest.getCacheSubnetGroupName() != null) {
request.addParameter("CacheSubnetGroupName", StringUtils.fromString(deleteCacheSubnetGroupRequest.getCacheSubnetGroupName()));
}
return request;
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-rekognition/src/main/java/com/amazonaws/services/rekognition/model/transform/ImageQualityJsonUnmarshaller.java | 2947 | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.rekognition.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.rekognition.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* ImageQuality JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ImageQualityJsonUnmarshaller implements Unmarshaller<ImageQuality, JsonUnmarshallerContext> {
public ImageQuality unmarshall(JsonUnmarshallerContext context) throws Exception {
ImageQuality imageQuality = new ImageQuality();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("Brightness", targetDepth)) {
context.nextToken();
imageQuality.setBrightness(context.getUnmarshaller(Float.class).unmarshall(context));
}
if (context.testExpression("Sharpness", targetDepth)) {
context.nextToken();
imageQuality.setSharpness(context.getUnmarshaller(Float.class).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return imageQuality;
}
private static ImageQualityJsonUnmarshaller instance;
public static ImageQualityJsonUnmarshaller getInstance() {
if (instance == null)
instance = new ImageQualityJsonUnmarshaller();
return instance;
}
}
| apache-2.0 |
xperimental/garanbot | src/net/sourcewalker/garanbot/data/GaranbotDBHelper.java | 1664 | //
// Copyright 2011 Thomas Gumprecht, Robert Jacob, Thomas Pieronczyk
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package net.sourcewalker.garanbot.data;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class GaranbotDBHelper extends SQLiteOpenHelper {
private static final String TAG = "GaranbotDBHelper";
private static final String DATABASE_NAME = "garanbot.db";
private static final int DATABASE_VERSION = 9;
private Context context;
public GaranbotDBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(GaranbotDBMetaData.SCHEMA);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database, which will destroy all old data.");
db.execSQL("DROP TABLE IF EXISTS " + GaranbotDBMetaData.TABLE_NAME);
ImageCache.clearCache(context);
onCreate(db);
}
}
| apache-2.0 |
lmjacksoniii/hazelcast | hazelcast-client/src/test/java/com/hazelcast/client/cache/jsr/CacheLoaderClientServerTest.java | 1295 | /*
* Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.client.cache.jsr;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
@RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class CacheLoaderClientServerTest
extends org.jsr107.tck.integration.CacheLoaderClientServerTest {
@BeforeClass
public static void setupInstance() {
JsrClientTestUtil.setup();
}
@AfterClass
public static void cleanup(){
JsrClientTestUtil.cleanup();
}
}
| apache-2.0 |
immutables/immutables | criteria/geode/src/org/immutables/criteria/geode/GeodeWatchEvent.java | 1678 | /*
* Copyright 2019 Immutables Authors and Contributors
*
* 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.immutables.criteria.geode;
import org.apache.geode.cache.query.CqEvent;
import org.immutables.criteria.backend.WatchEvent;
import java.util.Objects;
import java.util.Optional;
/**
* Geode change event
* @param <T> event type
*/
class GeodeWatchEvent<T> implements WatchEvent<T> {
private final Object key;
private final T newValue;
private final Operation operation;
GeodeWatchEvent(CqEvent cqEvent) {
this.key = Objects.requireNonNull(cqEvent.getKey(), "event.key");
@SuppressWarnings("unchecked")
final T newValue = (T) cqEvent.getNewValue();
this.newValue = newValue;
this.operation = toOperation(cqEvent);
}
@Override
public Object key() {
return key;
}
@Override
public Optional<T> newValue() {
return Optional.ofNullable(newValue);
}
@Override
public Operation operation() {
return this.operation;
}
private static WatchEvent.Operation toOperation(CqEvent event) {
// TODO add proper mapping between Geode and Criteria operations
return Operation.UPDATE;
}
}
| apache-2.0 |
KDanila/KDanila | chapter_002/src/main/java/ru/job4j/profession/Time.java | 158 | package ru.job4j.profession;
/**
* Time class.
*
* @author Kuzmin Danila (mailto:bus1d0@mail.ru)
* @version $Id$
* @since 0.1
*/
public class Time {
}
| apache-2.0 |
piotr-j/VisEditor | editor/src/main/java/com/kotcrab/vis/editor/ui/dialog/NewProjectDialogLibGDX.java | 5704 | /*
* Copyright 2014-2016 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kotcrab.vis.editor.ui.dialog;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.kotcrab.vis.editor.module.editor.FileChooserModule;
import com.kotcrab.vis.editor.module.editor.ProjectIOModule;
import com.kotcrab.vis.editor.module.project.ProjectLibGDX;
import com.kotcrab.vis.ui.util.TableUtils;
import com.kotcrab.vis.ui.util.dialog.Dialogs;
import com.kotcrab.vis.ui.util.form.FormInputValidator;
import com.kotcrab.vis.ui.util.form.FormValidator;
import com.kotcrab.vis.ui.widget.VisLabel;
import com.kotcrab.vis.ui.widget.VisTable;
import com.kotcrab.vis.ui.widget.VisTextButton;
import com.kotcrab.vis.ui.widget.VisValidatableTextField;
import com.kotcrab.vis.ui.widget.file.SingleFileChooserListener;
import java.io.File;
/**
* LibGDX project subdialog for {@link NewProjectDialog}
* @author Kotcrab
*/
public class NewProjectDialogLibGDX extends VisTable {
private VisValidatableTextField projectRoot;
private VisValidatableTextField sourceLoc;
private VisValidatableTextField assetsLoc;
private VisTextButton chooseRootButton;
private VisLabel errorLabel;
private VisTextButton cancelButton;
private VisTextButton createButton;
private NewProjectDialog dialog;
private FileChooserModule fileChooserModule;
private ProjectIOModule projectIO;
public NewProjectDialogLibGDX (NewProjectDialog dialog, FileChooserModule fileChooserModule, ProjectIOModule projectIO) {
this.dialog = dialog;
this.fileChooserModule = fileChooserModule;
this.projectIO = projectIO;
createUI();
createListeners();
createValidators();
}
private void createUI () {
projectRoot = new VisValidatableTextField("");
chooseRootButton = new VisTextButton("Choose...");
sourceLoc = new VisValidatableTextField("/core/src");
assetsLoc = new VisValidatableTextField("/android/assets");
errorLabel = new VisLabel();
errorLabel.setColor(Color.RED);
TableUtils.setSpacingDefaults(this);
columnDefaults(0).left();
columnDefaults(1).width(300);
row().padTop(4);
add(new VisLabel("Project root"));
add(projectRoot);
add(chooseRootButton);
row();
add(new VisLabel("Source folder"));
add(sourceLoc).fill();
row();
add(new VisLabel("Assets folder"));
add(assetsLoc).fill();
row();
add(new VisLabel("Assets folder is cleared on each export!")).colspan(3).row();
VisTable buttonTable = new VisTable(true);
buttonTable.defaults().minWidth(70);
cancelButton = new VisTextButton("Cancel");
createButton = new VisTextButton("Create");
createButton.setDisabled(true);
buttonTable.add(errorLabel).fill().expand();
buttonTable.add(cancelButton);
buttonTable.add(createButton);
add(buttonTable).colspan(3).fillX().expandX();
}
private void createListeners () {
chooseRootButton.addListener(new ChangeListener() {
@Override
public void changed (ChangeEvent event, Actor actor) {
fileChooserModule.pickFileOrDirectory(new SingleFileChooserListener() {
@Override
public void selected (FileHandle file) {
String path = file.file().getAbsolutePath();
if (path.endsWith(File.separator) == false) path += File.separator;
projectRoot.setText(path);
}
});
}
});
cancelButton.addListener(new ChangeListener() {
@Override
public void changed (ChangeEvent event, Actor actor) {
dialog.fadeOut();
}
});
createButton.addListener(new ChangeListener() {
@Override
public void changed (ChangeEvent event, Actor actor) {
createProject();
}
});
}
private void createValidators () {
FormValidator validator = new FormValidator(createButton, errorLabel);
validator.notEmpty(projectRoot, "Project root path cannot be empty!");
validator.notEmpty(sourceLoc, "Source location cannot be empty!");
validator.notEmpty(assetsLoc, "Assets location cannot be empty!");
validator.fileExists(projectRoot, "Project folder does not exist!");
validator.fileExists(sourceLoc, projectRoot, "Source folder does not exist!", false);
validator.fileExists(assetsLoc, projectRoot, "Assets folder does not exist!", false);
validator.custom(sourceLoc, new FormInputValidator("Source folder can't be the same as project root") {
@Override
protected boolean validate (String input) {
return !new File(projectRoot.getText()).equals(new File(projectRoot.getText() + input));
}
});
validator.custom(assetsLoc, new FormInputValidator("Assets folder can't be the same as project root") {
@Override
protected boolean validate (String input) {
return !new File(projectRoot.getText()).equals(new File(projectRoot.getText() + input));
}
});
}
private void createProject () {
ProjectLibGDX project = new ProjectLibGDX(projectRoot.getText(), sourceLoc.getText(), assetsLoc.getText());
String error = project.verifyIfCorrect();
if (error == null) {
projectIO.createLibGDXProject(project);
dialog.fadeOut();
} else {
Dialogs.showErrorDialog(getStage(), error);
}
}
}
| apache-2.0 |
hxh129/AndroidProject | PeopleDriver/src/com/example/driverapp/entity/City.java | 818 | package com.example.driverapp.entity;
/**
*
* @author 地级市
*
*/
public class City {
/** 地级市ID */
private int id;
/** 省 */
private int province;
/** 地级市名称 */
private String cityname;
public City() {
// TODO Auto-generated constructor stub
}
public City(int id, int province, String cityname) {
super();
this.id = id;
this.province = province;
this.cityname = cityname;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getProvince() {
return province;
}
public void setProvince(int province) {
this.province = province;
}
public String getCityname() {
return cityname;
}
public void setCityname(String cityname) {
this.cityname = cityname;
}
}
| apache-2.0 |
Movilizer/movilizer-spring-connector | src/test/java/com/movilizer/connector/newTests/mappers/DataContainerMapperTest.java | 7325 | package com.movilizer.connector.newTests.mappers;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.movilitas.movilizer.v15.MovilizerGenericDataContainer;
import com.movilitas.movilizer.v15.MovilizerGenericDataContainerEntry;
import com.movilitas.movilizer.v15.MovilizerGenericUploadDataContainer;
import com.movilitas.movilizer.v15.MovilizerUploadDataContainer;
import com.movilizer.connector.mapper.direct.GenericDataContainerMapperImpl;
import com.movilizer.connector.model.mapper.GenericDataContainerMapper;
import com.movilizer.connector.newTests.mappers.models.MapperTestObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
public class DataContainerMapperTest {
private GenericDataContainerMapperImpl dcMapper;
@Before
public void before() {
dcMapper = new GenericDataContainerMapperImpl();
}
@After
public void after() {
}
@Test
public void convertObjectToMap() {
ObjectMapper objectMapper = new ObjectMapper();
@SuppressWarnings("unchecked")
Map<String, Object> objectAsMap = objectMapper.convertValue(MapperTestObject.createTestObject(), Map.class);
assertThat(objectAsMap, hasEntry("booleanField", (Object) true));
assertThat(objectAsMap, hasEntry("dateField", "2015-01-01"));
assertThat((Map<String, Object>) objectAsMap.get("objectField"), hasEntry("stringField", (Object) "test"));
}
@Test
public void convertMapToObject() {
Map<String, Object> objectAsMap = new HashMap<>();
objectAsMap.put("booleanField", "true");
objectAsMap.put("stringField", "test");
Map<String, Object> subObjectAsMap = new HashMap<>();
subObjectAsMap.put("stringField", "test");
objectAsMap.put("objectField", subObjectAsMap);
List<Map<String, Object>> objectFieldList = new ArrayList<>();
Map<String, Object> subObjectAsMapForList = new HashMap<>();
subObjectAsMapForList.put("stringField", "test");
objectFieldList.add(subObjectAsMapForList);
objectAsMap.put("objectFieldList", objectFieldList);
ObjectMapper objectMapper = new ObjectMapper();
MapperTestObject tMapperTestObject = objectMapper.convertValue(objectAsMap, MapperTestObject.class);
assertThat(tMapperTestObject.isBooleanField(), is(equalTo(true)));
assertThat(tMapperTestObject.getStringField(), is(equalTo("test")));
assertThat(tMapperTestObject.getObjectField().getStringField(), is(equalTo("test")));
assertThat(tMapperTestObject.getObjectFieldList().get(0).getStringField(), is(equalTo("test")));
}
@Test
public void convertObjectToDC() throws ClassNotFoundException {
MovilizerGenericDataContainer dataContainer = dcMapper.toDataContainer(MapperTestObject.createTestObject());
assertThat(getEntry(dataContainer.getEntry(), "stringField").getValstr(), is("test"));
assertThat(getEntry(dataContainer.getEntry(), "intField").getValstr(), is("100"));
assertThat(getEntry(dataContainer.getEntry(), "booleanField").getValstr(), is("true"));
assertThat(getEntry(dataContainer.getEntry(), "dateField").getValstr(), is("2015-01-01"));
MovilizerGenericDataContainerEntry objectField = getEntry(dataContainer.getEntry(), "objectField");
assertThat(getEntry(objectField.getEntry(), "stringField").getValstr(), is("test"));
MovilizerGenericDataContainerEntry objectFieldList = getEntry(dataContainer.getEntry(), "objectFieldList");
MovilizerGenericDataContainerEntry objectFieldListFirstEntry = objectFieldList.getEntry().get(0);
assertThat(getEntry(objectFieldListFirstEntry.getEntry(), "stringField").getValstr(), is("test"));
}
@Test
public void convertDCtoObject() throws ClassNotFoundException {
MovilizerUploadDataContainer container = new MovilizerUploadDataContainer();
MovilizerGenericUploadDataContainer genericContainer = new MovilizerGenericUploadDataContainer();
container.setContainer(genericContainer);
genericContainer.setKey("containerKey");
MovilizerGenericDataContainer objectContainer = new MovilizerGenericDataContainer();
objectContainer.getEntry().add(createDataEntry(GenericDataContainerMapperImpl.JAVA_CLASS_ENTRY, "com.movilizer.connector.v15.newTests.mappers.models.MapperTestObject"));
objectContainer.getEntry().add(createDataEntry("intField", "1"));
objectContainer.getEntry().add(createDataEntry("booleanField", "true"));
objectContainer.getEntry().add(createDataEntry("dateField", "2015-08-30"));
objectContainer.getEntry().add(createDataEntry("stringField", "test"));
objectContainer.getEntry().add(createListEntry());
objectContainer.getEntry().add(createObjectEntry());
genericContainer.setData(objectContainer);
assertThat(dcMapper.isType(container.getContainer().getData(), MapperTestObject.class), is(equalTo(true)));
assertThat(dcMapper.getType(container.getContainer().getData()).equals(MapperTestObject.class), is(equalTo(true)));
MapperTestObject tMapperTestObject = dcMapper.fromDataContainer(container.getContainer().getData(), MapperTestObject.class);
assertThat(tMapperTestObject.isBooleanField(), is(equalTo(true)));
assertThat(tMapperTestObject.getStringField(), is(equalTo("test")));
assertThat(tMapperTestObject.getObjectField().getStringField(), is(equalTo("test")));
assertThat(tMapperTestObject.getObjectFieldList().get(0).getStringField(), is(equalTo("test")));
}
private MovilizerGenericDataContainerEntry createDataEntry(String key, String value) {
MovilizerGenericDataContainerEntry entry = new MovilizerGenericDataContainerEntry();
entry.setName(key);
entry.setValstr(value);
return entry;
}
private MovilizerGenericDataContainerEntry createListEntry() {
MovilizerGenericDataContainerEntry entry = new MovilizerGenericDataContainerEntry();
entry.setName("objectFieldList");
entry.getEntry().add(createObjectListEntry(0));
return entry;
}
private MovilizerGenericDataContainerEntry createObjectEntry() {
MovilizerGenericDataContainerEntry entry = new MovilizerGenericDataContainerEntry();
entry.setName("objectField");
entry.getEntry().add(createDataEntry("stringField", "test"));
return entry;
}
private MovilizerGenericDataContainerEntry createObjectListEntry(int key) {
MovilizerGenericDataContainerEntry entry = new MovilizerGenericDataContainerEntry();
entry.setName(Integer.toString(key));
entry.getEntry().add(createDataEntry("stringField", "test"));
return entry;
}
private MovilizerGenericDataContainerEntry getEntry(List<MovilizerGenericDataContainerEntry> updates, String key) {
for (MovilizerGenericDataContainerEntry entry : updates) {
if (entry.getName().equals(key)) {
return entry;
}
}
return null;
}
}
| apache-2.0 |
ostap0207/remotify.me | remotify.android/Remotify/src/main/java/com/google/zxing/client/android/share/BookmarkAdapter.java | 2631 | /*
* Copyright (C) 2011 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.client.android.share;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.progost.remotify.R;
/**
* A custom adapter designed to fetch bookmarks from a cursor. Before Honeycomb we used
* SimpleCursorAdapter, but it assumes the existence of an _id column, and the bookmark schema was
* rewritten for HC without one. This caused the app to crash, hence this new class, which is
* forwards and backwards compatible.
*
* @author dswitkin@google.com (Daniel Switkin)
*/
final class BookmarkAdapter extends BaseAdapter {
private final Context context;
private final Cursor cursor;
BookmarkAdapter(Context context, Cursor cursor) {
this.context = context;
this.cursor = cursor;
}
@Override
public int getCount() {
return cursor.getCount();
}
@Override
public Object getItem(int index) {
// Not used, so no point in retrieving it.
return null;
}
@Override
public long getItemId(int index) {
return index;
}
@Override
public View getView(int index, View view, ViewGroup viewGroup) {
LinearLayout layout;
if (view instanceof LinearLayout) {
layout = (LinearLayout) view;
} else {
LayoutInflater factory = LayoutInflater.from(context);
layout = (LinearLayout) factory.inflate(R.layout.bookmark_picker_list_item, viewGroup, false);
}
if (!cursor.isClosed()) {
cursor.moveToPosition(index);
String title = cursor.getString(BookmarkPickerActivity.TITLE_COLUMN);
((TextView) layout.findViewById(R.id.bookmark_title)).setText(title);
String url = cursor.getString(BookmarkPickerActivity.URL_COLUMN);
((TextView) layout.findViewById(R.id.bookmark_url)).setText(url);
} // Otherwise... just don't update as the object is shutting down
return layout;
}
}
| apache-2.0 |
shamanDevel/ProceduralTerrain | src/net/sourceforge/arbaro/gui/TreePreview.java | 13701 | //#**************************************************************************
//#
//# Copyright (C) 2003-2006 Wolfram Diestel
//#
//# This program is free software; you can redistribute it and/or modify
//# it under the terms of the GNU General Public License as published by
//# the Free Software Foundation; either version 2 of the License, or
//# (at your option) any later version.
//#
//# This program is distributed in the hope that it will be useful,
//# but WITHOUT ANY WARRANTY; without even the implied warranty of
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//# GNU General Public License for more details.
//#
//# You should have received a copy of the GNU General Public License
//# along with this program; if not, write to the Free Software
//# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//#
//# Send comments and bug fixes to diestel@steloj.de
//#
//#**************************************************************************/
package net.sourceforge.arbaro.gui;
import javax.swing.JComponent;
import javax.swing.BorderFactory;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.util.Enumeration;
import java.awt.geom.AffineTransform;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Point2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Color;
import net.sourceforge.arbaro.tree.*;
import net.sourceforge.arbaro.transformation.*;
import net.sourceforge.arbaro.mesh.*;
import net.sourceforge.arbaro.params.Params;
import net.sourceforge.arbaro.export.Console;
/**
* An image showing parts of the edited tree
*/
public class TreePreview extends JComponent {
private static final long serialVersionUID = 1L;
PreviewTree previewTree;
int perspective;
Config config;
boolean draft=false;
public final static int PERSPECTIVE_FRONT=0;
public final static int PERSPECTIVE_TOP=90;
static final Color thisLevelColor = new Color(0.3f,0.2f,0.2f);
static final Color otherLevelColor = new Color(0.6f,0.6f,0.6f);
static final Color leafColor = new Color(0.1f,0.6f,0.1f);
static final Color bgClr = new Color(250,250,245);
AffineTransform transform;
Transformation rotation; // viewing perspective
Vector origin = new Vector(0,0,0);
public TreePreview(PreviewTree prvTree, int perspect, Config config) {
super();
this.config = config;
setMinimumSize(new Dimension(100,100));
setBorder(BorderFactory.createEmptyBorder(2,2,2,2));
setOpaque(true);
setBackground(Color.WHITE);
previewTree = prvTree;
perspective = perspect;
initRotation();
previewTree.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
repaint();
}
});
}
public void paint(Graphics g) {
if (previewTree.getMesh() == null) {
try {
previewTree.remake(false);
} catch (Exception e) {
Console.printException(e);
}
// return;
}
Graphics2D g2 = (Graphics2D)g;
// turn antialiasing on or off
RenderingHints rh;
if (config.getProperty("preview.antialias","on").equals("on")) {
rh = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
} else {
rh = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_OFF);
}
g2.addRenderingHints(rh);
try {
g.clearRect(0,0,getWidth(),getHeight());
g.setColor(bgClr);
if (perspective==PERSPECTIVE_FRONT)
g.fillRect(0,0,getWidth()-1,getHeight());
else
g.fillRect(0,0,getWidth(),getHeight()-1);
//g.drawRect(10,10,getWidth()-20,getHeight()-20);
initTransform(/*g*/);
if (draft) previewTree.traverseTree(new StemDrawer(g)); //drawStems(g);
else {
drawMesh(g);
//drawLeaves(g);
Params params = previewTree.getParams();
previewTree.traverseTree(new LeafDrawer(g,params,previewTree));
}
// DEBUG
// Enumeration e = previewTree.allStems(previewTree.getShowLevel()-1);
// Stem stem = (Stem)e.nextElement();
// Vector diag = stem.getMaxPoint().sub(stem.getMinPoint());
// Vector orig = stem.getTransformation().getT();
// setOrigin(new Vector(orig.getX(),orig.getY(),0));
// Vector max = stem.getMaxPoint();
// Vector min = stem.getMinPoint();
//
// // get greatest distance from orig
// double x1 = Math.abs(min.getX())-Math.abs(orig.getX());
// double x2 = Math.abs(max.getX())-Math.abs(orig.getX());
// double x = Math.max(Math.abs(x1),Math.abs(x2));
// double y1 = Math.abs(min.getY())-Math.abs(orig.getY());
// double y2 = Math.abs(max.getY())-Math.abs(orig.getY());
// double y = Math.max(Math.abs(y1),Math.abs(y2));
//
// Vector av = max.sub(orig).add(min.sub(orig));
// //av=av.mul(0.5);
//
//// double dw = Math.sqrt(x*x+y*y)*2;
// double dw = Math.sqrt(av.getX()*av.getX()+av.getY()*av.getY())*2;
// double minw = -dw/2;
//
// double dh = diag.getZ();
// double minh = min.getZ();
//
// g.setColor(Color.RED);
// drawLine(g,orig,min);
// drawLine(g,orig,max);
//
// g.setColor(Color.GREEN);
// drawLine(g,orig,orig.add(new Vector(dw/2,dw/2,0)));
//
// g.setColor(Color.BLUE);
// drawLine(g,orig,av.add(orig));
//// drawLine(g,orig,new Vector(dw/4,dw/4,orig.getZ()));
//
//// g.setColor(Color.BLUE);
//// drawLine(g,stem.getTransformation().getT(),stem.getMaxPoint().sub(stem.getMinPoint()));
} catch (Exception e) {
Console.errorOutput(e.toString());
// do nothing, don't draw
}
}
public void setDraft(boolean d) {
draft=d;
}
protected void initRotation() {
rotation = new Transformation();
if (perspective == PERSPECTIVE_TOP)
rotation = rotation.rotx(90);
}
public void setRotation(double zangle) {
initRotation();
rotation = rotation.rotz(zangle);
repaint();
}
public void setOrigin(Vector orig) {
origin=orig;
}
private void initTransform(/*Graphics g*/) throws Exception {
// Perform transformation
transform = new AffineTransform();
double dw=1;
double minw=0;
double dh=0;
double minh=0;
double scale;
double x;
double y;
//double abs;
final int margin=5;
int showLevel = previewTree.getShowLevel();
class FindAStem extends DefaultTreeTraversal {
Stem found = null;
int level;
public FindAStem(int level) {
this.level=level;
}
public Stem getFound() { return found; }
public boolean enterStem(Stem stem) {
if (found == null && stem.getLevel() < level)
return true; // look further
else if (found != null || stem.getLevel() > level)
return false; // found a stem or too deep
else if (stem.getLevel() == level)
found = stem;
return true;
}
public boolean leaveTree(Tree tree) {
return (found != null);
}
}
if (showLevel < 1) {
setOrigin(new Vector());
//////////// FRONT view
if (perspective==PERSPECTIVE_FRONT) {
// get width and height of the tree
dw = previewTree.getWidth()*2;
dh = previewTree.getHeight();
minh = 0;
minw = -dw/2;
///////////////// TOP view
} else {
// get width of the tree
dw = previewTree.getWidth()*2;
minw = -dw/2;
}
} else {
// find stem which to show
/* Enumeration e = previewTree.allStems(showLevel-1);
if (! e.hasMoreElements()) throw new Exception("Stem not found");
Stem stem = (Stem)e.nextElement();
*/
Stem aStem = null;
FindAStem stemFinder = new FindAStem(showLevel-1);
if (previewTree.traverseTree(stemFinder)) {
aStem = stemFinder.getFound();
}
if (aStem != null) {
Vector diag = aStem.getMaxPoint().sub(aStem.getMinPoint());
Vector orig = aStem.getTransformation().getT();
setOrigin(new Vector(orig.getX(),orig.getY(),0));
Vector max = aStem.getMaxPoint();
Vector min = aStem.getMinPoint();
// get greatest distance from orig
x = Math.max(Math.abs(min.getX()-orig.getX()),
Math.abs(max.getX()-orig.getX()));
y = Math.max(Math.abs(min.getY()-orig.getY()),
Math.abs(max.getY()-orig.getY()));
dw = Math.sqrt(x*x+y*y)*2;
minw = -dw/2;
dh = diag.getZ();
minh = min.getZ();
}
//DEBUG
// System.err.println("O: "+ orig +" min: "+min+" max: "+max);
// System.err.println("maxX: "+x+" maxY: "+y);
// System.err.println("dg: "+diag+" dw: "+dw+" minw: "+minw+" dh: "+dh+" minh: "+minh);
}
//////////// FRONT view
if (perspective==PERSPECTIVE_FRONT) {
// how much to scale for fitting into view?
scale = Math.min((getHeight()-2*margin)/dh,(getWidth()-2*margin)/dw);
/*if (previewTree.params.debug)
System.err.println("scale: "+scale);
*/
// shift to mid point of the view
transform.translate(getWidth()/2,getHeight()/2);
// scale to image height
transform.scale(scale,-scale);
// shift mid of the tree to the origin of the image
transform.translate(-minw-dw/2,-minh-dh/2);
///////////////// TOP view
} else {
// how much to scale for fitting into view?
scale = Math.min((getHeight()-2*margin)/dw,(getWidth()-2*margin)/dw);
// shift to mid point of the view
transform.translate(getWidth()/2,getHeight()/2);
// scale to image height
transform.scale(scale,-scale);
// shift mid of the stem to the origin of the image
transform.translate(-minw-dw/2,-minw-dw/2);
}
// DEBUG
Point p = new Point();
transform.transform(new Point2D.Double(0.0,0.0),p);
/* if (previewTree.params.debug) {
System.err.println("width: "+minw+"+"+dw);
System.err.println("height: "+minh+"+"+dh);
System.err.println("Origin at: "+p);
System.err.println("view: "+getWidth()+"x"+getHeight());
}
*/
}
private void drawMesh(Graphics g) {
try {
for (Enumeration parts=previewTree.getMesh().elements(); parts.hasMoreElements();)
{
MeshPart m = (MeshPart)parts.nextElement();
if (m.getLevel()==previewTree.getShowLevel()) {
g.setColor(thisLevelColor);
} else {
g.setColor(otherLevelColor);
}
drawMeshPart(g,m);
}
} catch (Exception e) {
//System.err.println("nummer "+i);
e.printStackTrace();
}
}
private void drawMeshPart(Graphics g, MeshPart m) {
if (m.size()>0) {
MeshSection s = (MeshSection)m.elementAt(1);
// c=0;
while (s.next != null) {
// g.setColor(clr[c]);
if (s.size()>=s.next.size()) {
for (int i=0; i<s.size(); i++) {
drawLine(g,s.here(i),s.up(i));
drawLine(g,s.here(i),s.right(i));
}
s=s.next;
// c=1-c;
} else {
s=s.next;
// c=1-c;
for (int i=0; i<s.size(); i++) {
drawLine(g,s.here(i),s.down(i));
drawLine(g,s.here(i),s.right(i));
}
}
}
}
}
private class LeafDrawer implements TreeTraversal {
LeafMesh m;
Graphics g;
// PreviewTree pTree;
public LeafDrawer(Graphics g, Params params, PreviewTree pTree) {
this.g = g;
this.m = pTree.getLeafMesh();
g.setColor(leafColor);
}
public boolean enterTree(Tree tree) {
// m = ((PreviewTree)tree).getLeafMesh(); //meshGenerator.createLeafMesh(tree,true /* useQuads */);
return true;
}
public boolean leaveTree(Tree tree) {
return true;
}
public boolean enterStem(Stem stem) {
return true;
}
public boolean leaveStem(Stem stem) {
return true;
}
public boolean visitLeaf(Leaf leaf) {
if (m.isFlat()) {
Vector p = leaf.getTransformation().apply(m.shapeVertexAt(m.getShapeVertexCount()-1).point);
for (int i=0; i<m.getShapeVertexCount(); i++) {
Vector q = leaf.getTransformation().apply(m.shapeVertexAt(i).point);
drawLine(g,p,q);
p=q;
}
} else {
for (int i=0; i<m.getShapeFaceCount(); i++) {
Face f = m.shapeFaceAt(i);
Vector p = leaf.getTransformation().apply(m.shapeVertexAt((int)f.points[0]).point);
Vector q = leaf.getTransformation().apply(m.shapeVertexAt((int)f.points[1]).point);
Vector r = leaf.getTransformation().apply(m.shapeVertexAt((int)f.points[2]).point);
drawLine(g,p,q);
drawLine(g,p,r);
drawLine(g,r,q);
}
}
return true;
}
}
void drawLine(Graphics g,Vector p, Vector q) {
// FIXME: maybe eliminate class instantiations
// from this method for performance reasons:
// use static point arrays for transformations
Vector u = rotation.apply(p.sub(origin));
Vector v = rotation.apply(q.sub(origin));
Point2D.Double from = new Point2D.Double(u.getX(),u.getZ());
Point2D.Double to = new Point2D.Double(v.getX(),v.getZ());
Point ifrom = new Point();
Point ito = new Point();
transform.transform(from,ifrom);
transform.transform(to,ito);
g.drawLine(ifrom.x,ifrom.y,ito.x,ito.y);
}
private class StemDrawer implements TreeTraversal {
Stem stem;
Graphics g;
public StemDrawer(Graphics g) {
this.g = g;
g.setColor(otherLevelColor);
}
public boolean enterTree(Tree tree) {
return true;
}
public boolean leaveTree(Tree tree) {
return true;
}
public boolean enterStem(Stem stem) {
Enumeration sections = stem.sections();
if (sections.hasMoreElements()) {
StemSection from; StemSection to;
from = (StemSection)sections.nextElement();
while (sections.hasMoreElements()) {
to = (StemSection)sections.nextElement();
// FIXME: maybe draw rectangles instead of thin lines
//drawStripe(g,seg.posFrom(),seg.rad1,seg.postTo(),seg.rad2());
drawLine(g,from.getPosition(),to.getPosition());
from = to;
}
}
return true;
}
public boolean leaveStem(Stem stem) {
return true;
}
public boolean visitLeaf(Leaf l) {
return true;
}
}
}
| apache-2.0 |
dhmay/msInspect | src/org/fhcrc/cpl/viewer/quant/commandline/PeptideRatioVariationCLM.java | 9173 | /*
* Copyright (c) 2003-2012 Fred Hutchinson Cancer Research Center
*
* 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.fhcrc.cpl.viewer.quant.commandline;
import org.fhcrc.cpl.viewer.commandline.modules.BaseViewerCommandLineModuleImpl;
import org.fhcrc.cpl.toolbox.commandline.arguments.ArgumentValidationException;
import org.fhcrc.cpl.toolbox.commandline.arguments.CommandLineArgumentDefinition;
import org.fhcrc.cpl.toolbox.commandline.arguments.FileToWriteArgumentDefinition;
import org.fhcrc.cpl.toolbox.commandline.arguments.DecimalArgumentDefinition;
import org.fhcrc.cpl.toolbox.proteomics.feature.FeatureSet;
import org.fhcrc.cpl.toolbox.proteomics.feature.Feature;
import org.fhcrc.cpl.toolbox.proteomics.feature.extraInfo.IsotopicLabelExtraInfoDef;
import org.fhcrc.cpl.toolbox.proteomics.feature.extraInfo.MS2ExtraInfoDef;
import org.apache.log4j.Logger;
import org.fhcrc.cpl.toolbox.statistics.BasicStatistics;
import org.fhcrc.cpl.toolbox.commandline.CommandLineModuleExecutionException;
import org.fhcrc.cpl.toolbox.commandline.CommandLineModule;
import org.fhcrc.cpl.toolbox.gui.chart.PanelWithHistogram;
import org.fhcrc.cpl.toolbox.gui.chart.PanelWithBoxAndWhiskerChart;
import java.io.File;
import java.io.PrintWriter;
import java.util.*;
import java.util.List;
/**
* test
*/
public class PeptideRatioVariationCLM extends BaseViewerCommandLineModuleImpl
implements CommandLineModule
{
protected static Logger _log = Logger.getLogger(PeptideRatioVariationCLM.class);
protected File[] featureFiles;
protected File outFile;
protected float minPeptideProphet = .9f;
public PeptideRatioVariationCLM()
{
init();
}
protected void init()
{
mCommandName = "peptideratiovariation";
mHelpMessage ="peptideratiovariation";
mShortDescription = "peptideratiovariation";
CommandLineArgumentDefinition[] argDefs =
{
createUnnamedSeriesFileArgumentDefinition(true, "input files"),
new FileToWriteArgumentDefinition("out", true, "output file"),
new DecimalArgumentDefinition("minpprophet", false, "min peptideprophet", minPeptideProphet)
};
addArgumentDefinitions(argDefs);
}
public void assignArgumentValues()
throws ArgumentValidationException
{
featureFiles = this.getUnnamedSeriesFileArgumentValues();
outFile = this.getFileArgumentValue("out");
minPeptideProphet = getFloatArgumentValue("minpprophet");
}
/**
* do the actual work
*/
public void execute() throws CommandLineModuleExecutionException
{
Map<String, List<List<Double>>> peptidePerFileLogRatiosMap = new HashMap<String, List<List<Double>>>();
try
{
for (File featureFile : featureFiles)
{
FeatureSet featureSet = new FeatureSet(featureFile);
Map<String, List<Double>> peptideLogRatiosMapThisFile = new HashMap<String, List<Double>>();
for (Feature feature : featureSet.getFeatures())
{
if (MS2ExtraInfoDef.hasPeptideProphet(feature) &&
MS2ExtraInfoDef.getPeptideProphet(feature) >= minPeptideProphet &&
IsotopicLabelExtraInfoDef.hasRatio(feature))
{
String peptide = MS2ExtraInfoDef.getFirstPeptide(feature);
List<Double> thisPeptideLogRatios = peptideLogRatiosMapThisFile.get(peptide);
if (thisPeptideLogRatios == null)
{
thisPeptideLogRatios = new ArrayList<Double>();
peptideLogRatiosMapThisFile.put(peptide, thisPeptideLogRatios);
}
thisPeptideLogRatios.add( Math.log(IsotopicLabelExtraInfoDef.getRatio(feature)));
}
}
for (String peptide : peptideLogRatiosMapThisFile.keySet())
{
List<List<Double>> peptideRatioLists = peptidePerFileLogRatiosMap.get(peptide);
if (peptideRatioLists == null)
{
peptideRatioLists = new ArrayList<List<Double>>();
peptidePerFileLogRatiosMap.put(peptide, peptideRatioLists);
}
peptideRatioLists.add(peptideLogRatiosMapThisFile.get(peptide));
}
}
Map<String, List<Double>> peptideMeanLogRatios = new HashMap<String, List<Double>>();
Map<String, Integer> peptideIdCountMap = new HashMap<String, Integer>();
for (String peptide : peptidePerFileLogRatiosMap.keySet())
{
List<Double> thisPeptideLogRatios = new ArrayList<Double>();
int idCount = 0;
for (List<Double> perFileLogRatios : peptidePerFileLogRatiosMap.get(peptide))
{
thisPeptideLogRatios.add(BasicStatistics.mean(perFileLogRatios));
idCount += perFileLogRatios.size();
}
peptideMeanLogRatios.put(peptide, thisPeptideLogRatios);
peptideIdCountMap.put(peptide, idCount);
}
Map<Integer, List<Float>> perFractionCountStandardDevs = new HashMap<Integer, List<Float>>();
List<Float> allPeptideStandardDevs = new ArrayList<Float>();
Map<String, Float> peptideStdDevMap = new HashMap<String, Float>();
Map<String, Float> peptideUberMeanMap = new HashMap<String, Float>();
for (String peptide : peptideMeanLogRatios.keySet())
{
List<Double> logRatioMeans = peptideMeanLogRatios.get(peptide);
int fractionCount = logRatioMeans.size();
double stdDevLogRatios = BasicStatistics.standardDeviation(logRatioMeans);
allPeptideStandardDevs.add((float) stdDevLogRatios);
peptideStdDevMap.put(peptide, (float) stdDevLogRatios);
List<Float> thisNumFractionsDevList = perFractionCountStandardDevs.get(fractionCount);
if (thisNumFractionsDevList == null)
{
thisNumFractionsDevList = new ArrayList<Float>();
perFractionCountStandardDevs.put(fractionCount,thisNumFractionsDevList );
}
thisNumFractionsDevList.add((float) stdDevLogRatios);
peptideUberMeanMap.put(peptide, (float)BasicStatistics.mean(logRatioMeans));
}
PanelWithHistogram pwh = new PanelWithHistogram(allPeptideStandardDevs, "Fraction Std Devs", 200);
pwh.displayInTab();
PanelWithBoxAndWhiskerChart boxWhiskers = new PanelWithBoxAndWhiskerChart("Std Devs Per Frac Count");
for (int i=0; i<featureFiles.length; i++)
{
List<Float> thisNumFractionsStdDevs = perFractionCountStandardDevs.get(i);
if (thisNumFractionsStdDevs != null)
{
double[] asDouble = new double[thisNumFractionsStdDevs.size()];
for (int j=0; j<thisNumFractionsStdDevs.size(); j++)
asDouble[j] = thisNumFractionsStdDevs.get(j);
boxWhiskers.addData(asDouble, "" + (i));
}
boxWhiskers.displayInTab();
}
for (int i=0; i<featureFiles.length; i++)
{
List<Float> thisNumFractionsStdDevs = perFractionCountStandardDevs.get(i);
if (thisNumFractionsStdDevs != null)
{
PanelWithHistogram pwhi = new PanelWithHistogram(thisNumFractionsStdDevs,
"Std Devs " + i + " fracs", 200);
pwhi.displayInTab();
}
}
PrintWriter pw = new PrintWriter(outFile);
pw.println("peptide\tmean_frac_log_ratio\tstddev_frac_log_ratio\tnum_fractions\tnum_times_idd");
for (String peptide : peptidePerFileLogRatiosMap.keySet())
{
pw.println(peptide + "\t" + peptideUberMeanMap.get(peptide) + "\t" +
peptideStdDevMap.get(peptide) + "\t" + peptideIdCountMap.get(peptide));
pw.flush();
}
pw.close();
}
catch (Exception e)
{
throw new CommandLineModuleExecutionException(e);
}
}
}
| apache-2.0 |
drmaas/resilience4j | resilience4j-spring-boot/src/main/java/io/github/resilience4j/bulkhead/autoconfigure/ThreadPoolBulkheadMetricsAutoConfiguration.java | 2901 | /*
* Copyright 2019 Ingyu Hwang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.resilience4j.bulkhead.autoconfigure;
import com.codahale.metrics.MetricRegistry;
import io.github.resilience4j.bulkhead.ThreadPoolBulkhead;
import io.github.resilience4j.bulkhead.ThreadPoolBulkheadRegistry;
import io.github.resilience4j.metrics.ThreadPoolBulkheadMetrics;
import io.github.resilience4j.metrics.publisher.ThreadPoolBulkheadMetricsPublisher;
import org.springframework.boot.actuate.autoconfigure.MetricRepositoryAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.MetricsDropwizardAutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConditionalOnClass({MetricRegistry.class, ThreadPoolBulkhead.class,
ThreadPoolBulkheadMetricsPublisher.class})
@AutoConfigureAfter(MetricsDropwizardAutoConfiguration.class)
@AutoConfigureBefore(MetricRepositoryAutoConfiguration.class)
@ConditionalOnProperty(value = "resilience4j.thread-pool-bulkhead.metrics.enabled", matchIfMissing = true)
public class ThreadPoolBulkheadMetricsAutoConfiguration {
@Bean
@ConditionalOnProperty(value = "resilience4j.thread-pool-bulkhead.metrics.legacy.enabled", havingValue = "true")
@ConditionalOnMissingBean
public ThreadPoolBulkheadMetrics registerThreadPoolBulkheadMetrics(
ThreadPoolBulkheadRegistry threadPoolBulkheadRegistry, MetricRegistry metricRegistry) {
return ThreadPoolBulkheadMetrics
.ofBulkheadRegistry(threadPoolBulkheadRegistry, metricRegistry);
}
@Bean
@ConditionalOnProperty(value = "resilience4j.thread-pool-bulkhead.metrics.legacy.enabled", havingValue = "false", matchIfMissing = true)
@ConditionalOnMissingBean
public ThreadPoolBulkheadMetricsPublisher threadPoolBulkheadDropwizardMetricsPublisher(
MetricRegistry metricRegistry) {
return new ThreadPoolBulkheadMetricsPublisher(metricRegistry);
}
}
| apache-2.0 |
objectos/jabuticava | cnab/src/main/java/br/com/objectos/jabuticava/cnab/remessa/Carteira.java | 1560 | /*
* Copyright 2012 Objectos, Fábrica de Software LTDA.
*
* 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 br.com.objectos.jabuticava.cnab.remessa;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
/**
* @author marcio.endo@objectos.com.br (Marcio Endo)
*/
public enum Carteira {
COBRANCA_SIMPLES_COM_REGISTRO("CSR", "Cobrança simples (com registro)");
private static final Map<String, Carteira> codigoMap = new HashMap<>();
static {
EnumSet<Carteira> values = EnumSet.allOf(Carteira.class);
for (Carteira value : values) {
String codigo = value.getCodigo();
codigoMap.put(codigo, value);
}
}
private final String codigo;
private final String descricao;
private Carteira(String codigo, String descricao) {
this.codigo = codigo;
this.descricao = descricao;
}
public static Carteira load(String codigo) {
return codigoMap.get(codigo);
}
public String getCodigo() {
return codigo;
}
public String getDescricao() {
return descricao;
}
} | apache-2.0 |
jaikiran/ant-ivy | src/java/org/apache/ivy/core/event/retrieve/RetrieveArtifactEvent.java | 1992 | /*
* 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.ivy.core.event.retrieve;
import java.io.File;
import org.apache.ivy.core.event.IvyEvent;
import org.apache.ivy.core.module.descriptor.Artifact;
import org.apache.ivy.core.report.ArtifactDownloadReport;
public class RetrieveArtifactEvent extends IvyEvent {
private ArtifactDownloadReport report;
private File destFile;
public RetrieveArtifactEvent(String name, ArtifactDownloadReport report, File destFile) {
super(name);
addArtifactAttributes(report.getArtifact());
this.report = report;
this.destFile = destFile;
addAttribute("from", report.getLocalFile().getAbsolutePath());
addAttribute("to", destFile.getAbsolutePath());
addAttribute("size", String.valueOf(destFile.length()));
}
protected void addArtifactAttributes(Artifact artifact) {
addMridAttributes(artifact.getModuleRevisionId());
addAttributes(artifact.getAttributes());
addAttribute("metadata", String.valueOf(artifact.isMetadata()));
}
public File getDestFile() {
return destFile;
}
public ArtifactDownloadReport getReport() {
return report;
}
}
| apache-2.0 |
rodbate/bouncycastle-examples | src/main/java/bcfipsin100/pbeks/Key.java | 1715 | package bcfipsin100.pbeks;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import bcfipsin100.base.Rsa;
import bcfipsin100.base.Setup;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.pkcs.PKCSException;
public class Key
{
public static byte[] encodePublic(PublicKey publicKey)
{
return publicKey.getEncoded();
}
public static PublicKey producePublicKey(byte[] encoding)
throws GeneralSecurityException
{
KeyFactory keyFact = KeyFactory.getInstance("RSA", "BCFIPS");
return keyFact.generatePublic(new X509EncodedKeySpec(encoding));
}
public static byte[] encodePrivate(PrivateKey privateKey)
{
return privateKey.getEncoded();
}
public static PrivateKey producePrivateKey(byte[] encoding)
throws GeneralSecurityException
{
KeyFactory keyFact = KeyFactory.getInstance("RSA", "BCFIPS");
return keyFact.generatePrivate(new PKCS8EncodedKeySpec(encoding));
}
public static void main(String[] args)
throws GeneralSecurityException, IOException, OperatorCreationException, PKCSException
{
Setup.installProvider();
KeyPair keyPair = Rsa.generateKeyPair();
System.err.println(keyPair.getPublic().equals(producePublicKey(encodePublic(keyPair.getPublic()))));
System.err.println(keyPair.getPrivate().equals(producePrivateKey(encodePrivate(keyPair.getPrivate()))));
}
}
| apache-2.0 |
tsuyoikaze/WhiteRabbit-new-GUI | src/TargetTableRectangle.java | 8240 | import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.ohdsi.rabbitInAHat.dataModel.Field;
import org.ohdsi.rabbitInAHat.dataModel.Table;
import org.ohdsi.whiteRabbit.ObjectExchange;
import javafx.event.EventHandler;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
public class TargetTableRectangle extends StackPane implements Expandable {
public static final Color TABLE_STROKE_COLOR = Color.web("rgb(164,164,248)");
public static final Color TABLE_FILL_COLOR = Color.web("rgb(183,183,247)");
public static final Color FIELD_STROKE_COLOR = Color.web("rgb(211,211,252)");
public static final Color FIELD_FILL_COLOR = Color.web("rgb(229,229,252)");
public static final Color FIELD_STROKE_HIGHLIGHT_COLOR = Color.web("rgb(140,140,246)");
public static final Color FIELD_FILL_HIGHLIGHT_COLOR = Color.web("rgb(160,160,244)");
public static final double FIELD_INTERVAL = 5;
public static final double FIELD_HEIGHT = 20;
public static final double FIELD_WIDTH = 140;
public static final double FIELD_X = 350;
private double x=370, y, width=200, height=30;
protected boolean isExpanded = false;
Table table;
public Rectangle rect;
public Text text;
public LinkedList<FieldRectangle> fieldRectList;
public static Pane displayPane;
public static LinkedList<TargetTableRectangle> targetTableRects;
public static FieldRectangle selectingField;
public static TargetTableRectangle expandingTable;
public static LinkedList<Arrow> arrowList = new LinkedList<>();
protected class FieldRectangle extends StackPane {
private double fx=FIELD_X, fy, fwidth=FIELD_WIDTH, fheight=FIELD_HEIGHT;
Field field;
public Rectangle frect;
public Text ftext;
private void setFieldMisc() {
this.frect = new Rectangle(this.fx, this.fy, this.fwidth, this.fheight);
this.frect.setFill(FIELD_FILL_COLOR);
this.frect.setStroke(FIELD_STROKE_COLOR);
this.frect.setStrokeWidth(1);
this.frect.setArcWidth(3);
this.frect.setArcHeight(3);
this.ftext = new Text(fx, fy, field.getName());
this.ftext.wrappingWidthProperty().bind(this.widthProperty());
this.ftext.prefHeight(this.fheight);
this.ftext.setTextAlignment(TextAlignment.CENTER);
this.getChildren().addAll(this.frect, this.ftext);
}
public FieldRectangle(double fy, Field fd) {
super();
this.setLayoutX(fx);
this.setLayoutY(fy);
this.setWidth(200);
this.field = fd;
this.fy = fy;
setFieldMisc();
FieldRectangle self = this;
this.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent arg0) {
if (selectingField != null) {
selectingField.frect.setFill(FIELD_FILL_COLOR);
selectingField.frect.setStroke(FIELD_STROKE_COLOR);
}
frect.setFill(FIELD_FILL_HIGHLIGHT_COLOR);
frect.setStroke(FIELD_STROKE_HIGHLIGHT_COLOR);
selectingField = self;
if (TargetTableRectangle.selectingField != null && SourceTableRectangle.selectingField != null) {
if (ObjectExchange.etl.getTableToTableMapping().getSourceToTargetMap(SourceTableRectangle.selectingField.field.getTable(), TargetTableRectangle.selectingField.field.getTable()) == null) {
ObjectExchange.etl.getTableToTableMapping().addSourceToTargetMap(SourceTableRectangle.selectingField.field.getTable(), TargetTableRectangle.selectingField.field.getTable());
}
ObjectExchange.etl.getFieldToFieldMapping(SourceTableRectangle.selectingField.field.getTable(), TargetTableRectangle.selectingField.field.getTable()).addSourceToTargetMap(SourceTableRectangle.selectingField.field, TargetTableRectangle.selectingField.field);
TargetTableRectangle.selectingField.field.setDisplayName(TargetTableRectangle.selectingField.field.getName() + " <" + SourceTableRectangle.selectingField.field.getTable().getName() + "." + SourceTableRectangle.selectingField.field.getName() + ">");
if (Arrow.displayPane == null) {
Arrow.displayPane = displayPane;
}
arrowList.add(new Arrow(SourceTableRectangle.selectingField.getBoundsInParent().getMaxX(), (SourceTableRectangle.selectingField.getBoundsInParent().getMinY() + 0.5 * SourceTableRectangle.selectingField.getHeight()), TargetTableRectangle.selectingField.getBoundsInParent().getMinX(), (TargetTableRectangle.selectingField.getBoundsInParent().getMinY() + 0.5 * TargetTableRectangle.selectingField.getHeight()), SourceTableRectangle.selectingField.field, TargetTableRectangle.selectingField.field));
SourceTableRectangle.expandingTable.resetFieldSelection();
TargetTableRectangle.expandingTable.resetFieldSelection();
}
}
});
}
}
private void setMisc() {
rect = new Rectangle(this.x, this.y, this.width, this.height);
rect.setFill(TABLE_FILL_COLOR);
rect.setStroke(TABLE_STROKE_COLOR);
rect.setStrokeWidth(1.5);
rect.setArcWidth(5);
rect.setArcHeight(5);
text = new Text(x, y, table.getName());
text.wrappingWidthProperty().bind(this.widthProperty());
text.prefHeight(height);
text.setTextAlignment(TextAlignment.CENTER);
this.getChildren().addAll(rect, text);
}
public TargetTableRectangle(double y, Table tb) {
super();
this.setLayoutX(x);
this.setLayoutY(y);
this.setWidth(200);
table = tb;
this.y = y;
setMisc();
fieldRectList = new LinkedList<>();
this.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent arg0) {
toggle(targetTableRects);
}
});
}
public void resetFieldSelection () {
if (selectingField != null) {
selectingField.frect.setFill(FIELD_FILL_COLOR);
selectingField.frect.setStroke(FIELD_STROKE_COLOR);
selectingField = null;
}
}
public String toString() {
return table.getName();
}
@Override
public void expand(List<? extends Expandable> list) {
int numFields = table.getFields().size();
double deltaY = numFields * (FIELD_INTERVAL + FIELD_HEIGHT);
displayPane.setPrefHeight(displayPane.getPrefHeight() + deltaY);
Iterator<? extends Expandable> iter = list.iterator();
while (iter.hasNext()) {
TargetTableRectangle item = (TargetTableRectangle) iter.next();
if (item.equals(this)) {
break;
}
else {
if (item.isExpanded) {
item.collapse(list);
}
}
}
expand();
while (iter.hasNext()) {
TargetTableRectangle item = (TargetTableRectangle) iter.next();
item.shift(deltaY);
if (item.isExpanded) {
item.collapse();
}
}
}
@Override
public void collapse(List<? extends Expandable> list) {
double deltaY = 0 - fieldRectList.size() * (FIELD_HEIGHT + FIELD_INTERVAL);
displayPane.setPrefHeight(displayPane.getPrefHeight() + deltaY);
expandingTable = null;
collapse();
Iterator<? extends Expandable> iter = list.iterator();
while (iter.hasNext()) {
if (iter.next().equals(this)) {
break;
}
}
while (iter.hasNext()) {
iter.next().shift(deltaY);
}
}
@Override
public void toggle(List<? extends Expandable> list) {
if (isExpanded) {
collapse(list);
}
else {
expand(list);
}
Arrow.redraw();
}
@Override
public void expand() {
expandingTable = this;
double currY = y + height;
for (Field fd : table.getFields()) {
currY += FIELD_INTERVAL;
FieldRectangle newNode = new FieldRectangle(currY, fd);
fieldRectList.add(newNode);
displayPane.getChildren().add(newNode);
currY += FIELD_HEIGHT;
}
isExpanded = true;
}
@Override
public void collapse() {
for (FieldRectangle item : this.fieldRectList) {
displayPane.getChildren().remove(item);
}
fieldRectList.clear();
selectingField = null;
isExpanded = false;
}
@Override
public void shift(double y) {
this.y += y;
this.setLayoutY(this.getLayoutY() + y);
rect.setY(rect.getY() + y);
text.setY(text.getY() + y);
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-transfer/src/main/java/com/amazonaws/services/transfer/model/transform/WorkflowDetailMarshaller.java | 2276 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.transfer.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.transfer.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* WorkflowDetailMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class WorkflowDetailMarshaller {
private static final MarshallingInfo<String> WORKFLOWID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("WorkflowId").build();
private static final MarshallingInfo<String> EXECUTIONROLE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ExecutionRole").build();
private static final WorkflowDetailMarshaller instance = new WorkflowDetailMarshaller();
public static WorkflowDetailMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(WorkflowDetail workflowDetail, ProtocolMarshaller protocolMarshaller) {
if (workflowDetail == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(workflowDetail.getWorkflowId(), WORKFLOWID_BINDING);
protocolMarshaller.marshall(workflowDetail.getExecutionRole(), EXECUTIONROLE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
zoozooll/MyExercise | VV/asmackbeem/org/jivesoftware/smack/packet/StreamError.java | 4989 | /**
* $Revision: 2408 $
* $Date: 2004-11-02 20:53:30 -0300 (Tue, 02 Nov 2004) $
*
* Copyright 2003-2005 Jive Software.
*
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smack.packet;
/**
* Represents a stream error packet. Stream errors are unrecoverable errors where the server will
* close the unrelying TCP connection after the stream error was sent to the client. These is the
* list of stream errors as defined in the XMPP spec:
* <p>
* <table border=1>
* <tr>
* <td><b>Code</b></td>
* <td><b>Description</b></td>
* </tr>
* <tr>
* <td>bad-format</td>
* <td>the entity has sent XML that cannot be processed</td>
* </tr>
* <tr>
* <td>unsupported-encoding</td>
* <td>the entity has sent a namespace prefix that is unsupported</td>
* </tr>
* <tr>
* <td>bad-namespace-prefix</td>
* <td>Remote Server Timeout</td>
* </tr>
* <tr>
* <td>conflict</td>
* <td>the server is closing the active stream for this entity because a new stream has been
* initiated that conflicts with the existing stream.</td>
* </tr>
* <tr>
* <td>connection-timeout</td>
* <td>the entity has not generated any traffic over the stream for some period of time.</td>
* </tr>
* <tr>
* <td>host-gone</td>
* <td>the value of the 'to' attribute provided by the initiating entity in the stream header
* corresponds to a hostname that is no longer hosted by the server.</td>
* </tr>
* <tr>
* <td>host-unknown</td>
* <td>the value of the 'to' attribute provided by the initiating entity in the stream header does
* not correspond to a hostname that is hosted by the server.</td>
* </tr>
* <tr>
* <td>improper-addressing</td>
* <td>a stanza sent between two servers lacks a 'to' or 'from' attribute</td>
* </tr>
* <tr>
* <td>internal-server-error</td>
* <td>the server has experienced a misconfiguration.</td>
* </tr>
* <tr>
* <td>invalid-from</td>
* <td>the JID or hostname provided in a 'from' address does not match an authorized JID.</td>
* </tr>
* <tr>
* <td>invalid-id</td>
* <td>the stream ID or dialback ID is invalid or does not match an ID previously provided.</td>
* </tr>
* <tr>
* <td>invalid-namespace</td>
* <td>the streams namespace name is invalid.</td>
* </tr>
* <tr>
* <td>invalid-xml</td>
* <td>the entity has sent invalid XML over the stream.</td>
* </tr>
* <tr>
* <td>not-authorized</td>
* <td>the entity has attempted to send data before the stream has been authenticated</td>
* </tr>
* <tr>
* <td>policy-violation</td>
* <td>the entity has violated some local service policy.</td>
* </tr>
* <tr>
* <td>remote-connection-failed</td>
* <td>Rthe server is unable to properly connect to a remote entity.</td>
* </tr>
* <tr>
* <td>resource-constraint</td>
* <td>Rthe server lacks the system resources necessary to service the stream.</td>
* </tr>
* <tr>
* <td>restricted-xml</td>
* <td>the entity has attempted to send restricted XML features.</td>
* </tr>
* <tr>
* <td>see-other-host</td>
* <td>the server will not provide service to the initiating entity but is redirecting traffic to
* another host.</td>
* </tr>
* <tr>
* <td>system-shutdown</td>
* <td>the server is being shut down and all active streams are being closed.</td>
* </tr>
* <tr>
* <td>undefined-condition</td>
* <td>the error condition is not one of those defined by the other conditions in this list.</td>
* </tr>
* <tr>
* <td>unsupported-encoding</td>
* <td>the initiating entity has encoded the stream in an encoding that is not supported.</td>
* </tr>
* <tr>
* <td>unsupported-stanza-type</td>
* <td>the initiating entity has sent a first-level child of the stream that is not supported.</td>
* </tr>
* <tr>
* <td>unsupported-version</td>
* <td>the value of the 'version' attribute provided by the initiating entity in the stream header
* specifies a version of XMPP that is not supported.</td>
* </tr>
* <tr>
* <td>xml-not-well-formed</td>
* <td>the initiating entity has sent XML that is not well-formed.</td>
* </tr>
* </table>
* @author Gaston Dombiak
*/
public class StreamError {
private String code;
public StreamError(String code) {
super();
this.code = code;
}
/**
* Returns the error code.
* @return the error code.
*/
public String getCode() {
return code;
}
@Override
public String toString() {
StringBuilder txt = new StringBuilder();
txt.append("stream:error (").append(code).append(")");
return txt.toString();
}
}
| apache-2.0 |
EliasMG/brewer | src/main/java/com/algaworks/brewer/controller/converter/GrupoConverter.java | 470 | package com.algaworks.brewer.controller.converter;
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;
import com.algaworks.brewer.model.Grupo;
public class GrupoConverter implements Converter<String, Grupo> {
@Override
public Grupo convert(String codigo) {
if(!StringUtils.isEmpty(codigo)) {
Grupo grupo = new Grupo();
grupo.setCodigo(Long.valueOf(codigo));
return grupo;
}
return null;
}
}
| apache-2.0 |
retz/retz | retz-common/src/test/java/io/github/retz/auth/ProtocolTesterTest.java | 2202 | /**
* Retz
* Copyright (C) 2016-2017 Nautilus Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.retz.auth;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ProtocolTesterTest {
void testVersions(String server, String client, boolean ok) {
if (ok) {
assertTrue(new ProtocolTester(server, client).validate());
} else {
assertFalse(new ProtocolTester(server, client).validate());
}
}
@Test
public void test() {
{
String server = "retz-server-0.1.2 (0.1.1-15-g6341986)";
String client = "retz-client-0.1.2 (0.1.1-15-g6341986)";
testVersions(server, client, true);
}
{
String server = "retz-server-0.2.0 (0.2.0-15-asdfasdf)";
String client = "retz-client-0.2.1 (0.2.1-15-asdfasdf)";
testVersions(server, client, true);
}
{
String server = "retz-server-0.1.2-SNAPSHOT (0.1.1-15-g6341986)";
String client = "retz-client-0.1.2-SNAPSHOT (0.1.1-15-g6341986)";
testVersions(server, client, true);
}
{
String server = "retz-server-1.1.2 (0.1.1-15-g6341986)";
String client = "retz-client-0.1.2 (0.1.1-15-g6341986)";
testVersions(server, client, false);
}
{
String server = "retz-server-0.2.2-SNAPSHOT (0.1.1-15-g6341986)";
String client = "retz-client-0.1.2 (0.1.1-15-g6341986)";
testVersions(server, client, false);
}
}
}
| apache-2.0 |
blucas/netty | example/src/main/java/io/netty/example/http/upload/HttpUploadClient.java | 75923 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.example.http.upload;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.QueryStringEncoder;
import io.netty.handler.codec.http.cookie.ClientCookieEncoder;
import io.netty.handler.codec.http.cookie.DefaultCookie;
import io.netty.handler.codec.http.multipart.DefaultHttpDataFactory;
import io.netty.handler.codec.http.multipart.DiskAttribute;
import io.netty.handler.codec.http.multipart.DiskFileUpload;
import io.netty.handler.codec.http.multipart.HttpDataFactory;
import io.netty.handler.codec.http.multipart.HttpPostRequestEncoder;
import io.netty.handler.codec.http.multipart.InterfaceHttpData;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.util.internal.SocketUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.URI;
import java.util.List;
import java.util.Map.Entry;
/**
* This class is meant to be run against {@link HttpUploadServer}.
*/
public final class HttpUploadClient {
static final String BASE_URL = System.getProperty("baseUrl", "http://127.0.0.1:8080/");
static final String FILE = System.getProperty("file", "upload.txt");
public static void main(String[] args) throws Exception {
String postSimple, postFile, get;
if (BASE_URL.endsWith("/")) {
postSimple = BASE_URL + "formpost";
postFile = BASE_URL + "formpostmultipart";
get = BASE_URL + "formget";
} else {
postSimple = BASE_URL + "/formpost";
postFile = BASE_URL + "/formpostmultipart";
get = BASE_URL + "/formget";
}
URI uriSimple = new URI(postSimple);
String scheme = uriSimple.getScheme() == null? "http" : uriSimple.getScheme();
String host = uriSimple.getHost() == null? "127.0.0.1" : uriSimple.getHost();
int port = uriSimple.getPort();
if (port == -1) {
if ("http".equalsIgnoreCase(scheme)) {
port = 80;
} else if ("https".equalsIgnoreCase(scheme)) {
port = 443;
}
}
if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
System.err.println("Only HTTP(S) is supported.");
return;
}
final boolean ssl = "https".equalsIgnoreCase(scheme);
final SslContext sslCtx;
if (ssl) {
sslCtx = SslContextBuilder.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE).build();
} else {
sslCtx = null;
}
URI uriFile = new URI(postFile);
File file = new File(FILE);
if (!file.canRead()) {
throw new FileNotFoundException(FILE);
}
// Configure the client.
EventLoopGroup group = new NioEventLoopGroup();
// setup the factory: here using a mixed memory/disk based on size threshold
HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); // Disk if MINSIZE exceed
DiskFileUpload.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit)
DiskFileUpload.baseDirectory = null; // system temp directory
DiskAttribute.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit)
DiskAttribute.baseDirectory = null; // system temp directory
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class).handler(new HttpUploadClientIntializer(sslCtx));
// Simple Get form: no factory used (not usable)
List<Entry<String, String>> headers = formget(b, host, port, get, uriSimple);
if (headers == null) {
factory.cleanAllHttpData();
return;
}
// Simple Post form: factory used for big attributes
List<InterfaceHttpData> bodylist = formpost(b, host, port, uriSimple, file, factory, headers);
if (bodylist == null) {
factory.cleanAllHttpData();
return;
}
// Multipart Post form: factory used
formpostmultipart(b, host, port, uriFile, factory, headers, bodylist);
} finally {
// Shut down executor threads to exit.
group.shutdownGracefully();
// Really clean all temporary files if they still exist
factory.cleanAllHttpData();
}
}
/**
* Standard usage of HTTP API in Netty without file Upload (get is not able to achieve File upload
* due to limitation on request size).
*
* @return the list of headers that will be used in every example after
**/
private static List<Entry<String, String>> formget(
Bootstrap bootstrap, String host, int port, String get, URI uriSimple) throws Exception {
// XXX /formget
// No use of HttpPostRequestEncoder since not a POST
Channel channel = bootstrap.connect(host, port).sync().channel();
// Prepare the HTTP request.
QueryStringEncoder encoder = new QueryStringEncoder(get);
// add Form attribute
encoder.addParam("getform", "GET");
encoder.addParam("info", "first value");
encoder.addParam("secondinfo", "secondvalue ���&");
// not the big one since it is not compatible with GET size
// encoder.addParam("thirdinfo", textArea);
encoder.addParam("thirdinfo", "third value\r\ntest second line\r\n\r\nnew line\r\n");
encoder.addParam("Send", "Send");
URI uriGet = new URI(encoder.toString());
HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uriGet.toASCIIString());
HttpHeaders headers = request.headers();
headers.set(HttpHeaderNames.HOST, host);
headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
headers.set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP + "," + HttpHeaderValues.DEFLATE);
headers.set(HttpHeaderNames.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
headers.set(HttpHeaderNames.ACCEPT_LANGUAGE, "fr");
headers.set(HttpHeaderNames.REFERER, uriSimple.toString());
headers.set(HttpHeaderNames.USER_AGENT, "Netty Simple Http Client side");
headers.set(HttpHeaderNames.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
//connection will not close but needed
// headers.set("Connection","keep-alive");
// headers.set("Keep-Alive","300");
headers.set(
HttpHeaderNames.COOKIE, ClientCookieEncoder.STRICT.encode(
new DefaultCookie("my-cookie", "foo"),
new DefaultCookie("another-cookie", "bar"))
);
// send request
channel.writeAndFlush(request);
// Wait for the server to close the connection.
channel.closeFuture().sync();
// convert headers to list
return headers.entries();
}
/**
* Standard post without multipart but already support on Factory (memory management)
*
* @return the list of HttpData object (attribute and file) to be reused on next post
*/
private static List<InterfaceHttpData> formpost(
Bootstrap bootstrap,
String host, int port, URI uriSimple, File file, HttpDataFactory factory,
List<Entry<String, String>> headers) throws Exception {
// XXX /formpost
// Start the connection attempt.
ChannelFuture future = bootstrap.connect(SocketUtils.socketAddress(host, port));
// Wait until the connection attempt succeeds or fails.
Channel channel = future.sync().channel();
// Prepare the HTTP request.
HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriSimple.toASCIIString());
// Use the PostBody encoder
HttpPostRequestEncoder bodyRequestEncoder =
new HttpPostRequestEncoder(factory, request, false); // false => not multipart
// it is legal to add directly header or cookie into the request until finalize
for (Entry<String, String> entry : headers) {
request.headers().set(entry.getKey(), entry.getValue());
}
// add Form attribute
bodyRequestEncoder.addBodyAttribute("getform", "POST");
bodyRequestEncoder.addBodyAttribute("info", "first value");
bodyRequestEncoder.addBodyAttribute("secondinfo", "secondvalue ���&");
bodyRequestEncoder.addBodyAttribute("thirdinfo", textArea);
bodyRequestEncoder.addBodyAttribute("fourthinfo", textAreaLong);
bodyRequestEncoder.addBodyFileUpload("myfile", file, "application/x-zip-compressed", false);
// finalize request
request = bodyRequestEncoder.finalizeRequest();
// Create the bodylist to be reused on the last version with Multipart support
List<InterfaceHttpData> bodylist = bodyRequestEncoder.getBodyListAttributes();
// send request
channel.write(request);
// test if request was chunked and if so, finish the write
if (bodyRequestEncoder.isChunked()) { // could do either request.isChunked()
// either do it through ChunkedWriteHandler
channel.write(bodyRequestEncoder);
}
channel.flush();
// Do not clear here since we will reuse the InterfaceHttpData on the next request
// for the example (limit action on client side). Take this as a broadcast of the same
// request on both Post actions.
//
// On standard program, it is clearly recommended to clean all files after each request
// bodyRequestEncoder.cleanFiles();
// Wait for the server to close the connection.
channel.closeFuture().sync();
return bodylist;
}
/**
* Multipart example
*/
private static void formpostmultipart(
Bootstrap bootstrap, String host, int port, URI uriFile, HttpDataFactory factory,
Iterable<Entry<String, String>> headers, List<InterfaceHttpData> bodylist) throws Exception {
// XXX /formpostmultipart
// Start the connection attempt.
ChannelFuture future = bootstrap.connect(SocketUtils.socketAddress(host, port));
// Wait until the connection attempt succeeds or fails.
Channel channel = future.sync().channel();
// Prepare the HTTP request.
HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriFile.toASCIIString());
// Use the PostBody encoder
HttpPostRequestEncoder bodyRequestEncoder =
new HttpPostRequestEncoder(factory, request, true); // true => multipart
// it is legal to add directly header or cookie into the request until finalize
for (Entry<String, String> entry : headers) {
request.headers().set(entry.getKey(), entry.getValue());
}
// add Form attribute from previous request in formpost()
bodyRequestEncoder.setBodyHttpDatas(bodylist);
// finalize request
bodyRequestEncoder.finalizeRequest();
// send request
channel.write(request);
// test if request was chunked and if so, finish the write
if (bodyRequestEncoder.isChunked()) {
channel.write(bodyRequestEncoder);
}
channel.flush();
// Now no more use of file representation (and list of HttpData)
bodyRequestEncoder.cleanFiles();
// Wait for the server to close the connection.
channel.closeFuture().sync();
}
// use to simulate a small TEXTAREA field in a form
private static final String textArea = "short text";
// use to simulate a big TEXTAREA field in a form
private static final String textAreaLong =
"lkjlkjlKJLKJLKJLKJLJlkj lklkj\r\n\r\nLKJJJJJJJJKKKKKKKKKKKKKKK ����&\r\n\r\n" +
"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\r\n" +
"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\r\n" +
"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\r\n" +
"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM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MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\r\n" +
"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\r\n" +
"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\r\n" +
"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\r\n";
}
| apache-2.0 |
riftsaw/riftsaw-ode | bpel-test/src/test/java/org/apache/ode/test/BasicActivities20Test.java | 4644 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ode.test;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.xml.namespace.QName;
import org.apache.ode.bpel.iapi.ContextException;
import org.apache.ode.bpel.iapi.MessageExchange;
import org.junit.Ignore;
import org.junit.Test;
public class BasicActivities20Test extends BPELTestAbstract {
@Test public void testHelloWorld2() throws Throwable {
go("/bpel/2.0/HelloWorld2");
}
@Test public void testNegativeTargetNS1() throws Throwable {
/**
* Test for an invalid targetNamespace has been entered into the WSDL. See JIRA ODE-67 Test for a specific exception
* message.
*/
Deployment deployment = addDeployment("/bpel/2.0/NegativeTargetNSTest1");
deployment.expectedException = ContextException.class;
go();
}
@Test public void testTimer() throws Throwable {
go("/bpel/2.0/TestTimer");
}
@Test public void testIf() throws Throwable {
go("/bpel/2.0/TestIf");
}
@Test public void testIfBoolean() throws Throwable {
go("/bpel/2.0/TestIfBoolean");
}
/**
* Tests the wait "for" syntax.
* @throws Throwable
*/
@Test public void testWaitFor() throws Throwable {
deploy("/bpel/2.0/TestWait1");
Invocation inv = addInvoke("Wait1#1", new QName("http://ode/bpel/unit-test.wsdl", "testService"), "testOperation",
"<message><TestPart/><Time/></message>",
null);
inv.minimumWaitMs=5*1000L;
inv.maximumWaitMs=7*1000L;
inv.expectedStatus = MessageExchange.Status.ASYNC;
inv.expectedFinalStatus = MessageExchange.Status.RESPONSE;
go();
}
/**
* Test the wait "until" syntax.
*/
@Test public void testWaitUntil() throws Throwable {
deploy("/bpel/2.0/TestWaitUntil");
DateFormat idf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
String isountil = idf.format(new Date(System.currentTimeMillis()+5000));
Invocation inv = addInvoke("WaitUntil", new QName("http://ode/bpel/unit-test.wsdl", "testService"), "testOperation",
"<message><TestPart/><Time>"+isountil+"</Time></message>",
null);
inv.minimumWaitMs=4*1000L;
inv.maximumWaitMs=7*1000L;
inv.expectedStatus = MessageExchange.Status.ASYNC;
inv.expectedFinalStatus = MessageExchange.Status.RESPONSE;
go();
}
/**
* Test the wait "until" syntax.
*/
@Ignore("RIFTSAW-248")
@Test public void testWaitUntilPast() throws Throwable {
deploy("/bpel/2.0/TestWaitUntil");
DateFormat idf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
String isountil = idf.format(new Date(System.currentTimeMillis()-5000));
Invocation inv = addInvoke("WaitUntil", new QName("http://ode/bpel/unit-test.wsdl", "testService"), "testOperation",
"<message><TestPart/><Time>"+isountil+"</Time></message>",
null);
inv.maximumWaitMs=2*1000L;
inv.expectedStatus = MessageExchange.Status.ASYNC;
inv.expectedFinalStatus = MessageExchange.Status.RESPONSE;
go();
}
/**
* Tests the wait "for" syntax.
* @throws Throwable
*/
@Test public void testOnAlarm() throws Throwable {
deploy("/bpel/2.0/TestAlarm");
Invocation inv = addInvoke("Wait1#1", new QName("http://ode.apache.org/example", "CanonicServiceForClient"), "receive",
"<message><body><start xmlns=\"http://ode.apache.org/example\">start</start></body></message>",
null);
inv.maximumWaitMs=20*1000L;
inv.expectedStatus = MessageExchange.Status.ASYNC;
inv.expectedFinalStatus = MessageExchange.Status.RESPONSE;
go();
}
}
| apache-2.0 |
bedatadriven/renjin-statet | org.renjin.core/src/org/renjin/primitives/vector/ConstantDoubleVector.java | 815 | package org.renjin.primitives.vector;
import org.renjin.sexp.AttributeMap;
import org.renjin.sexp.DoubleVector;
import org.renjin.sexp.SEXP;
public class ConstantDoubleVector extends DoubleVector {
private double value;
private int length;
public ConstantDoubleVector(double value, int length) {
this.value = value;
this.length = length;
}
public ConstantDoubleVector(double value, int length, AttributeMap attributes) {
super(attributes);
this.value = value;
this.length = length;
}
@Override
protected SEXP cloneWithNewAttributes(AttributeMap attributes) {
return new ConstantDoubleVector(value, length, attributes);
}
@Override
public double getElementAsDouble(int index) {
return value;
}
@Override
public int length() {
return length;
}
}
| apache-2.0 |
kumareshcr24/cobra-explorer | standalone-gui/src/main/java/com/cobra/gui/dao/DataManager.java | 2192 | package com.cobra.gui.dao;
import net.harawata.appdirs.AppDirs;
import net.harawata.appdirs.AppDirsFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* Created by kumareshcr24 on 1/29/2017.
*/
public class DataManager {
public static void saveToLocalAppData(String fileName, Object object) throws IOException {
AppDirs appDirs = AppDirsFactory.getInstance();
String path = appDirs.getUserDataDir("cobra-hdfs-explorer", "1.0.0", "cobra");
File file = new File(path + File.separator + fileName);
if (file.exists()) {
file.delete();
}
File parentDir = file.getParentFile();
if (!parentDir.exists()) {
parentDir.mkdirs();
}
file.createNewFile();
ObjectOutputStream objectOutputStream = null;
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(object);
}
finally {
if (null!=objectOutputStream) {
objectOutputStream.flush();
objectOutputStream.close();
}
}
}
public static Object readFromLocal(String fileName) throws IOException, ClassNotFoundException {
AppDirs appDirs = AppDirsFactory.getInstance();
String path = appDirs.getUserDataDir("cobra-hdfs-explorer", "1.0.0", "cobra");
File file = new File(path + File.separator + fileName);
if (!file.exists()) {
throw new FileNotFoundException(file.getPath());
}
ObjectInputStream objectInputStream = null;
try {
FileInputStream fileInputStream = new FileInputStream(file);
objectInputStream = new ObjectInputStream(fileInputStream);
Object object = objectInputStream.readObject();
return object;
}
finally {
objectInputStream.close();
}
}
}
| apache-2.0 |