repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
quarkusio/quarkus
integration-tests/main/src/main/java/io/quarkus/it/websocket/Dto.java
375
package io.quarkus.it.websocket; public class Dto { private String content; public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public String toString() { return "Dto{" + "content='" + content + '\'' + '}'; } }
apache-2.0
ReactiveX/RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeDoOnEventTest.java
3143
/* * Copyright (c) 2016-present, RxJava 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 io.reactivex.rxjava3.internal.operators.maybe; import static org.junit.Assert.assertTrue; import java.util.List; import org.junit.Test; import io.reactivex.rxjava3.core.*; import io.reactivex.rxjava3.disposables.*; import io.reactivex.rxjava3.exceptions.TestException; import io.reactivex.rxjava3.functions.*; import io.reactivex.rxjava3.plugins.RxJavaPlugins; import io.reactivex.rxjava3.subjects.PublishSubject; import io.reactivex.rxjava3.testsupport.TestHelper; public class MaybeDoOnEventTest extends RxJavaTest { @Test public void dispose() { TestHelper.checkDisposed(PublishSubject.<Integer>create().singleElement().doOnEvent(new BiConsumer<Integer, Throwable>() { @Override public void accept(Integer v, Throwable e) throws Exception { // irrelevant } })); } @Test public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeMaybe(new Function<Maybe<Integer>, MaybeSource<Integer>>() { @Override public MaybeSource<Integer> apply(Maybe<Integer> m) throws Exception { return m.doOnEvent(new BiConsumer<Integer, Throwable>() { @Override public void accept(Integer v, Throwable e) throws Exception { // irrelevant } }); } }); } @Test public void onSubscribeCrash() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { final Disposable bs = Disposable.empty(); new Maybe<Integer>() { @Override protected void subscribeActual(MaybeObserver<? super Integer> observer) { observer.onSubscribe(bs); observer.onError(new TestException("Second")); observer.onComplete(); observer.onSuccess(1); } } .doOnSubscribe(new Consumer<Disposable>() { @Override public void accept(Disposable d) throws Exception { throw new TestException("First"); } }) .to(TestHelper.<Integer>testConsumer()) .assertFailureAndMessage(TestException.class, "First"); assertTrue(bs.isDisposed()); TestHelper.assertUndeliverable(errors, 0, TestException.class, "Second"); } finally { RxJavaPlugins.reset(); } } }
apache-2.0
sdw2330976/Research-jetty-9.2.5
jetty-util/src/test/java/org/eclipse/jetty/util/resource/ResourceAliasTest.java
3795
// // ======================================================================== // Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // // You may elect to redistribute this code under either of these licenses. // ======================================================================== // package org.eclipse.jetty.util.resource; import java.io.File; import java.net.MalformedURLException; import org.eclipse.jetty.toolchain.test.FS; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class ResourceAliasTest { static File __dir; @BeforeClass public static void beforeClass() { __dir=MavenTestingUtils.getTargetTestingDir("RAT"); } @Before public void before() { FS.ensureDirExists(__dir); FS.ensureEmpty(__dir); } /* ------------------------------------------------------------ */ @Test public void testNullCharEndingFilename() throws Exception { File file=new File(__dir,"test.txt"); Assert.assertFalse(file.exists()); Assert.assertTrue(file.createNewFile()); Assert.assertTrue(file.exists()); File file0=new File(__dir,"test.txt\0"); if (!file0.exists()) return; // this file system does not suffer this problem Assert.assertTrue(file0.exists()); // This is an alias! Resource dir = Resource.newResource(__dir); // Test not alias paths Resource resource = Resource.newResource(file); Assert.assertTrue(resource.exists()); Assert.assertNull(resource.getAlias()); resource = Resource.newResource(file.getAbsoluteFile()); Assert.assertTrue(resource.exists()); Assert.assertNull(resource.getAlias()); resource = Resource.newResource(file.toURI()); Assert.assertTrue(resource.exists()); Assert.assertNull(resource.getAlias()); resource = Resource.newResource(file.toURI().toString()); Assert.assertTrue(resource.exists()); Assert.assertNull(resource.getAlias()); resource = dir.addPath("test.txt"); Assert.assertTrue(resource.exists()); Assert.assertNull(resource.getAlias()); // Test alias paths resource = Resource.newResource(file0); Assert.assertTrue(resource.exists()); Assert.assertNotNull(resource.getAlias()); resource = Resource.newResource(file0.getAbsoluteFile()); Assert.assertTrue(resource.exists()); Assert.assertNotNull(resource.getAlias()); resource = Resource.newResource(file0.toURI()); Assert.assertTrue(resource.exists()); Assert.assertNotNull(resource.getAlias()); resource = Resource.newResource(file0.toURI().toString()); Assert.assertTrue(resource.exists()); Assert.assertNotNull(resource.getAlias()); try { resource = dir.addPath("test.txt\0"); Assert.assertTrue(resource.exists()); Assert.assertNotNull(resource.getAlias()); } catch(MalformedURLException e) { Assert.assertTrue(true); } } }
apache-2.0
ZSD123/uniqueWeather
src/activity/guanYuAct.java
3249
package activity; import java.util.ArrayList; import java.util.List; import com.sharefriend.app.R; import activity.manageAct.ViewHolder; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; public class guanYuAct extends baseActivity { private ListView listView; class ViewHolder{ TextView textView; } ViewHolder viewHolder; private SharedPreferences pre; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.guanyu); pre=PreferenceManager.getDefaultSharedPreferences(this); LinearLayout lin=(LinearLayout)findViewById(R.id.lin); CustomFontTextView textView=(CustomFontTextView)findViewById(R.id.text_EndRain); TextView v1=(TextView)findViewById(R.id.v1); final int designNum=pre.getInt("design", 0); if(designNum==4){ lin.setBackgroundColor(Color.parseColor("#051C3D")); textView.setTextColor(Color.parseColor("#A2C0DE")); v1.setTextColor(Color.parseColor("#A2C0DE")); } listView=(ListView)findViewById(R.id.listview); final List<String> list=new ArrayList<String>(); list.add("¹¦ÄܽéÉÜ"); list.add("·´À¡"); BaseAdapter baseAdapter=new BaseAdapter() { @Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView==null){ convertView=getLayoutInflater().inflate(R.layout.item_account, null); viewHolder=new ViewHolder(); viewHolder.textView=(TextView)convertView.findViewById(R.id.text); convertView.setTag(viewHolder); }else { viewHolder=(ViewHolder)convertView.getTag(); } if(designNum==4){ viewHolder.textView.setTextColor(Color.parseColor("#A2C0DE")); } viewHolder.textView.setText(list.get(position)); return convertView; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return list.get(position); } @Override public int getCount() { // TODO Auto-generated method stub return list.size(); } }; listView.setAdapter(baseAdapter); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if(position==0){ Intent intent=new Intent(guanYuAct.this,functionAct.class); startActivity(intent); }else if(position==1){ Intent intent=new Intent(guanYuAct.this,fankuiAct.class); startActivity(intent); } } }); } }
apache-2.0
pkarmstr/NYBC
solr-4.2.1/lucene/core/src/java/org/apache/lucene/search/ScoreCachingWrappingScorer.java
2863
package org.apache.lucene.search; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.util.Collection; import java.util.Collections; /** * A {@link Scorer} which wraps another scorer and caches the score of the * current document. Successive calls to {@link #score()} will return the same * result and will not invoke the wrapped Scorer's score() method, unless the * current document has changed.<br> * This class might be useful due to the changes done to the {@link Collector} * interface, in which the score is not computed for a document by default, only * if the collector requests it. Some collectors may need to use the score in * several places, however all they have in hand is a {@link Scorer} object, and * might end up computing the score of a document more than once. */ public class ScoreCachingWrappingScorer extends Scorer { private final Scorer scorer; private int curDoc = -1; private float curScore; /** Creates a new instance by wrapping the given scorer. */ public ScoreCachingWrappingScorer(Scorer scorer) { super(scorer.weight); this.scorer = scorer; } @Override public boolean score(Collector collector, int max, int firstDocID) throws IOException { return scorer.score(collector, max, firstDocID); } @Override public float score() throws IOException { int doc = scorer.docID(); if (doc != curDoc) { curScore = scorer.score(); curDoc = doc; } return curScore; } @Override public int freq() throws IOException { return scorer.freq(); } @Override public int docID() { return scorer.docID(); } @Override public int nextDoc() throws IOException { return scorer.nextDoc(); } @Override public void score(Collector collector) throws IOException { scorer.score(collector); } @Override public int advance(int target) throws IOException { return scorer.advance(target); } @Override public Collection<ChildScorer> getChildren() { return Collections.singleton(new ChildScorer(scorer, "CACHED")); } }
apache-2.0
EBISPOT/webulous
populous-oppl/src/main/java/uk/ac/ebi/spot/webulous/entity/SimpleOWLEntityCreationSet.java
2234
package uk.ac.ebi.spot.webulous.entity; import org.semanticweb.owlapi.model.OWLEntity; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyChange; import uk.ac.ebi.spot.webulous.model.OWLEntityCreationSet; import java.util.ArrayList; import java.util.List;/* * Copyright (C) 2007, University of Manchester * * Modifications to the initial code base are copyright of their * respective authors, or their employers as appropriate. Authorship * of the modifications may be determined from the ChangeLog placed at * the end of this file. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /** * Author: Simon Jupp<br> * Date: Jan 4, 2011<br> * The University of Manchester<br> * Bio-Health Informatics Group<br> */ public class SimpleOWLEntityCreationSet<E extends OWLEntity> implements OWLEntityCreationSet{ private E owlEntity; private List<OWLOntologyChange> changes; public SimpleOWLEntityCreationSet(E owlEntity, List<? extends OWLOntologyChange> changes) { this.owlEntity = owlEntity; this.changes = new ArrayList<OWLOntologyChange>(changes); } public SimpleOWLEntityCreationSet(E owlEntity, OWLOntology ontology) { this.owlEntity = owlEntity; changes = new ArrayList<OWLOntologyChange>(); // changes.add(new AddEntity(ontology, owlEntity, null)); } public E getOWLEntity() { return owlEntity; } public List<? extends OWLOntologyChange> getOntologyChanges() { return changes; } }
apache-2.0
softindex/datakernel
test/src/main/java/io/datakernel/test/rules/LambdaStatement.java
1087
/* * Copyright (C) 2015-2018 SoftIndex 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 io.datakernel.test.rules; import org.junit.runners.model.Statement; public final class LambdaStatement extends Statement { public static final Statement EMPTY = new LambdaStatement(() -> {}); private final ThrowingRunnable body; public LambdaStatement(ThrowingRunnable body) { this.body = body; } @Override public void evaluate() throws Throwable { body.run(); } @FunctionalInterface public interface ThrowingRunnable { void run() throws Throwable; } }
apache-2.0
googleapis/java-datastream
proto-google-cloud-datastream-v1/src/main/java/com/google/cloud/datastream/v1/SourceObjectIdentifier.java
100961
/* * 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/datastream/v1/datastream_resources.proto package com.google.cloud.datastream.v1; /** * * * <pre> * Represents an identifier of an object in the data source. * </pre> * * Protobuf type {@code google.cloud.datastream.v1.SourceObjectIdentifier} */ public final class SourceObjectIdentifier extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.datastream.v1.SourceObjectIdentifier) SourceObjectIdentifierOrBuilder { private static final long serialVersionUID = 0L; // Use SourceObjectIdentifier.newBuilder() to construct. private SourceObjectIdentifier(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private SourceObjectIdentifier() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new SourceObjectIdentifier(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private SourceObjectIdentifier( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier.Builder subBuilder = null; if (sourceIdentifierCase_ == 1) { subBuilder = ((com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier) sourceIdentifier_) .toBuilder(); } sourceIdentifier_ = input.readMessage( com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier .parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom( (com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier) sourceIdentifier_); sourceIdentifier_ = subBuilder.buildPartial(); } sourceIdentifierCase_ = 1; break; } case 18: { com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier.Builder subBuilder = null; if (sourceIdentifierCase_ == 2) { subBuilder = ((com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier) sourceIdentifier_) .toBuilder(); } sourceIdentifier_ = input.readMessage( com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier .parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom( (com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier) sourceIdentifier_); sourceIdentifier_ = subBuilder.buildPartial(); } sourceIdentifierCase_ = 2; break; } default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.datastream.v1.DatastreamResourcesProto .internal_static_google_cloud_datastream_v1_SourceObjectIdentifier_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.datastream.v1.DatastreamResourcesProto .internal_static_google_cloud_datastream_v1_SourceObjectIdentifier_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.datastream.v1.SourceObjectIdentifier.class, com.google.cloud.datastream.v1.SourceObjectIdentifier.Builder.class); } public interface OracleObjectIdentifierOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * Required. The schema name. * </pre> * * <code>string schema = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The schema. */ java.lang.String getSchema(); /** * * * <pre> * Required. The schema name. * </pre> * * <code>string schema = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for schema. */ com.google.protobuf.ByteString getSchemaBytes(); /** * * * <pre> * Required. The table name. * </pre> * * <code>string table = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The table. */ java.lang.String getTable(); /** * * * <pre> * Required. The table name. * </pre> * * <code>string table = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for table. */ com.google.protobuf.ByteString getTableBytes(); } /** * * * <pre> * Oracle data source object identifier. * </pre> * * Protobuf type {@code google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier} */ public static final class OracleObjectIdentifier extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier) OracleObjectIdentifierOrBuilder { private static final long serialVersionUID = 0L; // Use OracleObjectIdentifier.newBuilder() to construct. private OracleObjectIdentifier(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private OracleObjectIdentifier() { schema_ = ""; table_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new OracleObjectIdentifier(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private OracleObjectIdentifier( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); schema_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); table_ = s; break; } default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.datastream.v1.DatastreamResourcesProto .internal_static_google_cloud_datastream_v1_SourceObjectIdentifier_OracleObjectIdentifier_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.datastream.v1.DatastreamResourcesProto .internal_static_google_cloud_datastream_v1_SourceObjectIdentifier_OracleObjectIdentifier_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier.class, com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier.Builder .class); } public static final int SCHEMA_FIELD_NUMBER = 1; private volatile java.lang.Object schema_; /** * * * <pre> * Required. The schema name. * </pre> * * <code>string schema = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The schema. */ @java.lang.Override public java.lang.String getSchema() { java.lang.Object ref = schema_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); schema_ = s; return s; } } /** * * * <pre> * Required. The schema name. * </pre> * * <code>string schema = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for schema. */ @java.lang.Override public com.google.protobuf.ByteString getSchemaBytes() { java.lang.Object ref = schema_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); schema_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int TABLE_FIELD_NUMBER = 2; private volatile java.lang.Object table_; /** * * * <pre> * Required. The table name. * </pre> * * <code>string table = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The table. */ @java.lang.Override public java.lang.String getTable() { java.lang.Object ref = table_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); table_ = s; return s; } } /** * * * <pre> * Required. The table name. * </pre> * * <code>string table = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for table. */ @java.lang.Override public com.google.protobuf.ByteString getTableBytes() { java.lang.Object ref = table_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); table_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(schema_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, schema_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(table_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, table_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(schema_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, schema_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(table_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, table_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier)) { return super.equals(obj); } com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier other = (com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier) obj; if (!getSchema().equals(other.getSchema())) return false; if (!getTable().equals(other.getTable())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + SCHEMA_FIELD_NUMBER; hash = (53 * hash) + getSchema().hashCode(); hash = (37 * hash) + TABLE_FIELD_NUMBER; hash = (53 * hash) + getTable().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Oracle data source object identifier. * </pre> * * Protobuf type {@code * google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier) com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifierOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.datastream.v1.DatastreamResourcesProto .internal_static_google_cloud_datastream_v1_SourceObjectIdentifier_OracleObjectIdentifier_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.datastream.v1.DatastreamResourcesProto .internal_static_google_cloud_datastream_v1_SourceObjectIdentifier_OracleObjectIdentifier_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier.class, com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier.Builder .class); } // Construct using // com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } @java.lang.Override public Builder clear() { super.clear(); schema_ = ""; table_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.datastream.v1.DatastreamResourcesProto .internal_static_google_cloud_datastream_v1_SourceObjectIdentifier_OracleObjectIdentifier_descriptor; } @java.lang.Override public com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier getDefaultInstanceForType() { return com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier .getDefaultInstance(); } @java.lang.Override public com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier build() { com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier buildPartial() { com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier result = new com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier(this); result.schema_ = schema_; result.table_ = table_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier) { return mergeFrom( (com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier other) { if (other == com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier .getDefaultInstance()) return this; if (!other.getSchema().isEmpty()) { schema_ = other.schema_; onChanged(); } if (!other.getTable().isEmpty()) { table_ = other.table_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object schema_ = ""; /** * * * <pre> * Required. The schema name. * </pre> * * <code>string schema = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The schema. */ public java.lang.String getSchema() { java.lang.Object ref = schema_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); schema_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The schema name. * </pre> * * <code>string schema = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for schema. */ public com.google.protobuf.ByteString getSchemaBytes() { java.lang.Object ref = schema_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); schema_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The schema name. * </pre> * * <code>string schema = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The schema to set. * @return This builder for chaining. */ public Builder setSchema(java.lang.String value) { if (value == null) { throw new NullPointerException(); } schema_ = value; onChanged(); return this; } /** * * * <pre> * Required. The schema name. * </pre> * * <code>string schema = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearSchema() { schema_ = getDefaultInstance().getSchema(); onChanged(); return this; } /** * * * <pre> * Required. The schema name. * </pre> * * <code>string schema = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for schema to set. * @return This builder for chaining. */ public Builder setSchemaBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); schema_ = value; onChanged(); return this; } private java.lang.Object table_ = ""; /** * * * <pre> * Required. The table name. * </pre> * * <code>string table = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The table. */ public java.lang.String getTable() { java.lang.Object ref = table_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); table_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The table name. * </pre> * * <code>string table = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for table. */ public com.google.protobuf.ByteString getTableBytes() { java.lang.Object ref = table_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); table_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The table name. * </pre> * * <code>string table = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The table to set. * @return This builder for chaining. */ public Builder setTable(java.lang.String value) { if (value == null) { throw new NullPointerException(); } table_ = value; onChanged(); return this; } /** * * * <pre> * Required. The table name. * </pre> * * <code>string table = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearTable() { table_ = getDefaultInstance().getTable(); onChanged(); return this; } /** * * * <pre> * Required. The table name. * </pre> * * <code>string table = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for table to set. * @return This builder for chaining. */ public Builder setTableBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); table_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier) } // @@protoc_insertion_point(class_scope:google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier) private static final com.google.cloud.datastream.v1.SourceObjectIdentifier .OracleObjectIdentifier DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier(); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<OracleObjectIdentifier> PARSER = new com.google.protobuf.AbstractParser<OracleObjectIdentifier>() { @java.lang.Override public OracleObjectIdentifier parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new OracleObjectIdentifier(input, extensionRegistry); } }; public static com.google.protobuf.Parser<OracleObjectIdentifier> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<OracleObjectIdentifier> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface MysqlObjectIdentifierOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * Required. The database name. * </pre> * * <code>string database = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The database. */ java.lang.String getDatabase(); /** * * * <pre> * Required. The database name. * </pre> * * <code>string database = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for database. */ com.google.protobuf.ByteString getDatabaseBytes(); /** * * * <pre> * Required. The table name. * </pre> * * <code>string table = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The table. */ java.lang.String getTable(); /** * * * <pre> * Required. The table name. * </pre> * * <code>string table = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for table. */ com.google.protobuf.ByteString getTableBytes(); } /** * * * <pre> * Mysql data source object identifier. * </pre> * * Protobuf type {@code google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier} */ public static final class MysqlObjectIdentifier extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier) MysqlObjectIdentifierOrBuilder { private static final long serialVersionUID = 0L; // Use MysqlObjectIdentifier.newBuilder() to construct. private MysqlObjectIdentifier(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private MysqlObjectIdentifier() { database_ = ""; table_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new MysqlObjectIdentifier(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MysqlObjectIdentifier( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); database_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); table_ = s; break; } default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.datastream.v1.DatastreamResourcesProto .internal_static_google_cloud_datastream_v1_SourceObjectIdentifier_MysqlObjectIdentifier_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.datastream.v1.DatastreamResourcesProto .internal_static_google_cloud_datastream_v1_SourceObjectIdentifier_MysqlObjectIdentifier_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier.class, com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier.Builder .class); } public static final int DATABASE_FIELD_NUMBER = 1; private volatile java.lang.Object database_; /** * * * <pre> * Required. The database name. * </pre> * * <code>string database = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The database. */ @java.lang.Override public java.lang.String getDatabase() { java.lang.Object ref = database_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); database_ = s; return s; } } /** * * * <pre> * Required. The database name. * </pre> * * <code>string database = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for database. */ @java.lang.Override public com.google.protobuf.ByteString getDatabaseBytes() { java.lang.Object ref = database_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); database_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int TABLE_FIELD_NUMBER = 2; private volatile java.lang.Object table_; /** * * * <pre> * Required. The table name. * </pre> * * <code>string table = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The table. */ @java.lang.Override public java.lang.String getTable() { java.lang.Object ref = table_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); table_ = s; return s; } } /** * * * <pre> * Required. The table name. * </pre> * * <code>string table = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for table. */ @java.lang.Override public com.google.protobuf.ByteString getTableBytes() { java.lang.Object ref = table_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); table_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(database_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, database_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(table_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, table_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(database_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, database_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(table_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, table_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier)) { return super.equals(obj); } com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier other = (com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier) obj; if (!getDatabase().equals(other.getDatabase())) return false; if (!getTable().equals(other.getTable())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + DATABASE_FIELD_NUMBER; hash = (53 * hash) + getDatabase().hashCode(); hash = (37 * hash) + TABLE_FIELD_NUMBER; hash = (53 * hash) + getTable().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Mysql data source object identifier. * </pre> * * Protobuf type {@code google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier) com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifierOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.datastream.v1.DatastreamResourcesProto .internal_static_google_cloud_datastream_v1_SourceObjectIdentifier_MysqlObjectIdentifier_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.datastream.v1.DatastreamResourcesProto .internal_static_google_cloud_datastream_v1_SourceObjectIdentifier_MysqlObjectIdentifier_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier.class, com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier.Builder .class); } // Construct using // com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } @java.lang.Override public Builder clear() { super.clear(); database_ = ""; table_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.datastream.v1.DatastreamResourcesProto .internal_static_google_cloud_datastream_v1_SourceObjectIdentifier_MysqlObjectIdentifier_descriptor; } @java.lang.Override public com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier getDefaultInstanceForType() { return com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier .getDefaultInstance(); } @java.lang.Override public com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier build() { com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier buildPartial() { com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier result = new com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier(this); result.database_ = database_; result.table_ = table_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier) { return mergeFrom( (com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier other) { if (other == com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier .getDefaultInstance()) return this; if (!other.getDatabase().isEmpty()) { database_ = other.database_; onChanged(); } if (!other.getTable().isEmpty()) { table_ = other.table_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object database_ = ""; /** * * * <pre> * Required. The database name. * </pre> * * <code>string database = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The database. */ public java.lang.String getDatabase() { java.lang.Object ref = database_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); database_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The database name. * </pre> * * <code>string database = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for database. */ public com.google.protobuf.ByteString getDatabaseBytes() { java.lang.Object ref = database_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); database_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The database name. * </pre> * * <code>string database = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The database to set. * @return This builder for chaining. */ public Builder setDatabase(java.lang.String value) { if (value == null) { throw new NullPointerException(); } database_ = value; onChanged(); return this; } /** * * * <pre> * Required. The database name. * </pre> * * <code>string database = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearDatabase() { database_ = getDefaultInstance().getDatabase(); onChanged(); return this; } /** * * * <pre> * Required. The database name. * </pre> * * <code>string database = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for database to set. * @return This builder for chaining. */ public Builder setDatabaseBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); database_ = value; onChanged(); return this; } private java.lang.Object table_ = ""; /** * * * <pre> * Required. The table name. * </pre> * * <code>string table = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The table. */ public java.lang.String getTable() { java.lang.Object ref = table_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); table_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The table name. * </pre> * * <code>string table = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for table. */ public com.google.protobuf.ByteString getTableBytes() { java.lang.Object ref = table_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); table_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The table name. * </pre> * * <code>string table = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The table to set. * @return This builder for chaining. */ public Builder setTable(java.lang.String value) { if (value == null) { throw new NullPointerException(); } table_ = value; onChanged(); return this; } /** * * * <pre> * Required. The table name. * </pre> * * <code>string table = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearTable() { table_ = getDefaultInstance().getTable(); onChanged(); return this; } /** * * * <pre> * Required. The table name. * </pre> * * <code>string table = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for table to set. * @return This builder for chaining. */ public Builder setTableBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); table_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier) } // @@protoc_insertion_point(class_scope:google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier) private static final com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier(); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<MysqlObjectIdentifier> PARSER = new com.google.protobuf.AbstractParser<MysqlObjectIdentifier>() { @java.lang.Override public MysqlObjectIdentifier parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MysqlObjectIdentifier(input, extensionRegistry); } }; public static com.google.protobuf.Parser<MysqlObjectIdentifier> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<MysqlObjectIdentifier> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } private int sourceIdentifierCase_ = 0; private java.lang.Object sourceIdentifier_; public enum SourceIdentifierCase implements com.google.protobuf.Internal.EnumLite, com.google.protobuf.AbstractMessage.InternalOneOfEnum { ORACLE_IDENTIFIER(1), MYSQL_IDENTIFIER(2), SOURCEIDENTIFIER_NOT_SET(0); private final int value; private SourceIdentifierCase(int value) { this.value = value; } /** * @param value The number of the enum to look for. * @return The enum associated with the given number. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static SourceIdentifierCase valueOf(int value) { return forNumber(value); } public static SourceIdentifierCase forNumber(int value) { switch (value) { case 1: return ORACLE_IDENTIFIER; case 2: return MYSQL_IDENTIFIER; case 0: return SOURCEIDENTIFIER_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public SourceIdentifierCase getSourceIdentifierCase() { return SourceIdentifierCase.forNumber(sourceIdentifierCase_); } public static final int ORACLE_IDENTIFIER_FIELD_NUMBER = 1; /** * * * <pre> * Oracle data source object identifier. * </pre> * * <code> * .google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier oracle_identifier = 1; * </code> * * @return Whether the oracleIdentifier field is set. */ @java.lang.Override public boolean hasOracleIdentifier() { return sourceIdentifierCase_ == 1; } /** * * * <pre> * Oracle data source object identifier. * </pre> * * <code> * .google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier oracle_identifier = 1; * </code> * * @return The oracleIdentifier. */ @java.lang.Override public com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier getOracleIdentifier() { if (sourceIdentifierCase_ == 1) { return (com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier) sourceIdentifier_; } return com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier .getDefaultInstance(); } /** * * * <pre> * Oracle data source object identifier. * </pre> * * <code> * .google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier oracle_identifier = 1; * </code> */ @java.lang.Override public com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifierOrBuilder getOracleIdentifierOrBuilder() { if (sourceIdentifierCase_ == 1) { return (com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier) sourceIdentifier_; } return com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier .getDefaultInstance(); } public static final int MYSQL_IDENTIFIER_FIELD_NUMBER = 2; /** * * * <pre> * Mysql data source object identifier. * </pre> * * <code> * .google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier mysql_identifier = 2; * </code> * * @return Whether the mysqlIdentifier field is set. */ @java.lang.Override public boolean hasMysqlIdentifier() { return sourceIdentifierCase_ == 2; } /** * * * <pre> * Mysql data source object identifier. * </pre> * * <code> * .google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier mysql_identifier = 2; * </code> * * @return The mysqlIdentifier. */ @java.lang.Override public com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier getMysqlIdentifier() { if (sourceIdentifierCase_ == 2) { return (com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier) sourceIdentifier_; } return com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier .getDefaultInstance(); } /** * * * <pre> * Mysql data source object identifier. * </pre> * * <code> * .google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier mysql_identifier = 2; * </code> */ @java.lang.Override public com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifierOrBuilder getMysqlIdentifierOrBuilder() { if (sourceIdentifierCase_ == 2) { return (com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier) sourceIdentifier_; } return com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier .getDefaultInstance(); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (sourceIdentifierCase_ == 1) { output.writeMessage( 1, (com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier) sourceIdentifier_); } if (sourceIdentifierCase_ == 2) { output.writeMessage( 2, (com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier) sourceIdentifier_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (sourceIdentifierCase_ == 1) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 1, (com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier) sourceIdentifier_); } if (sourceIdentifierCase_ == 2) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 2, (com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier) sourceIdentifier_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.datastream.v1.SourceObjectIdentifier)) { return super.equals(obj); } com.google.cloud.datastream.v1.SourceObjectIdentifier other = (com.google.cloud.datastream.v1.SourceObjectIdentifier) obj; if (!getSourceIdentifierCase().equals(other.getSourceIdentifierCase())) return false; switch (sourceIdentifierCase_) { case 1: if (!getOracleIdentifier().equals(other.getOracleIdentifier())) return false; break; case 2: if (!getMysqlIdentifier().equals(other.getMysqlIdentifier())) return false; break; case 0: default: } if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); switch (sourceIdentifierCase_) { case 1: hash = (37 * hash) + ORACLE_IDENTIFIER_FIELD_NUMBER; hash = (53 * hash) + getOracleIdentifier().hashCode(); break; case 2: hash = (37 * hash) + MYSQL_IDENTIFIER_FIELD_NUMBER; hash = (53 * hash) + getMysqlIdentifier().hashCode(); break; case 0: default: } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.datastream.v1.SourceObjectIdentifier parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.datastream.v1.SourceObjectIdentifier prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Represents an identifier of an object in the data source. * </pre> * * Protobuf type {@code google.cloud.datastream.v1.SourceObjectIdentifier} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.datastream.v1.SourceObjectIdentifier) com.google.cloud.datastream.v1.SourceObjectIdentifierOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.datastream.v1.DatastreamResourcesProto .internal_static_google_cloud_datastream_v1_SourceObjectIdentifier_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.datastream.v1.DatastreamResourcesProto .internal_static_google_cloud_datastream_v1_SourceObjectIdentifier_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.datastream.v1.SourceObjectIdentifier.class, com.google.cloud.datastream.v1.SourceObjectIdentifier.Builder.class); } // Construct using com.google.cloud.datastream.v1.SourceObjectIdentifier.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } @java.lang.Override public Builder clear() { super.clear(); sourceIdentifierCase_ = 0; sourceIdentifier_ = null; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.datastream.v1.DatastreamResourcesProto .internal_static_google_cloud_datastream_v1_SourceObjectIdentifier_descriptor; } @java.lang.Override public com.google.cloud.datastream.v1.SourceObjectIdentifier getDefaultInstanceForType() { return com.google.cloud.datastream.v1.SourceObjectIdentifier.getDefaultInstance(); } @java.lang.Override public com.google.cloud.datastream.v1.SourceObjectIdentifier build() { com.google.cloud.datastream.v1.SourceObjectIdentifier result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.datastream.v1.SourceObjectIdentifier buildPartial() { com.google.cloud.datastream.v1.SourceObjectIdentifier result = new com.google.cloud.datastream.v1.SourceObjectIdentifier(this); if (sourceIdentifierCase_ == 1) { if (oracleIdentifierBuilder_ == null) { result.sourceIdentifier_ = sourceIdentifier_; } else { result.sourceIdentifier_ = oracleIdentifierBuilder_.build(); } } if (sourceIdentifierCase_ == 2) { if (mysqlIdentifierBuilder_ == null) { result.sourceIdentifier_ = sourceIdentifier_; } else { result.sourceIdentifier_ = mysqlIdentifierBuilder_.build(); } } result.sourceIdentifierCase_ = sourceIdentifierCase_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.datastream.v1.SourceObjectIdentifier) { return mergeFrom((com.google.cloud.datastream.v1.SourceObjectIdentifier) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.datastream.v1.SourceObjectIdentifier other) { if (other == com.google.cloud.datastream.v1.SourceObjectIdentifier.getDefaultInstance()) return this; switch (other.getSourceIdentifierCase()) { case ORACLE_IDENTIFIER: { mergeOracleIdentifier(other.getOracleIdentifier()); break; } case MYSQL_IDENTIFIER: { mergeMysqlIdentifier(other.getMysqlIdentifier()); break; } case SOURCEIDENTIFIER_NOT_SET: { break; } } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.datastream.v1.SourceObjectIdentifier parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.datastream.v1.SourceObjectIdentifier) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int sourceIdentifierCase_ = 0; private java.lang.Object sourceIdentifier_; public SourceIdentifierCase getSourceIdentifierCase() { return SourceIdentifierCase.forNumber(sourceIdentifierCase_); } public Builder clearSourceIdentifier() { sourceIdentifierCase_ = 0; sourceIdentifier_ = null; onChanged(); return this; } private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier, com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier.Builder, com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifierOrBuilder> oracleIdentifierBuilder_; /** * * * <pre> * Oracle data source object identifier. * </pre> * * <code> * .google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier oracle_identifier = 1; * </code> * * @return Whether the oracleIdentifier field is set. */ @java.lang.Override public boolean hasOracleIdentifier() { return sourceIdentifierCase_ == 1; } /** * * * <pre> * Oracle data source object identifier. * </pre> * * <code> * .google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier oracle_identifier = 1; * </code> * * @return The oracleIdentifier. */ @java.lang.Override public com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier getOracleIdentifier() { if (oracleIdentifierBuilder_ == null) { if (sourceIdentifierCase_ == 1) { return (com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier) sourceIdentifier_; } return com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier .getDefaultInstance(); } else { if (sourceIdentifierCase_ == 1) { return oracleIdentifierBuilder_.getMessage(); } return com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier .getDefaultInstance(); } } /** * * * <pre> * Oracle data source object identifier. * </pre> * * <code> * .google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier oracle_identifier = 1; * </code> */ public Builder setOracleIdentifier( com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier value) { if (oracleIdentifierBuilder_ == null) { if (value == null) { throw new NullPointerException(); } sourceIdentifier_ = value; onChanged(); } else { oracleIdentifierBuilder_.setMessage(value); } sourceIdentifierCase_ = 1; return this; } /** * * * <pre> * Oracle data source object identifier. * </pre> * * <code> * .google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier oracle_identifier = 1; * </code> */ public Builder setOracleIdentifier( com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier.Builder builderForValue) { if (oracleIdentifierBuilder_ == null) { sourceIdentifier_ = builderForValue.build(); onChanged(); } else { oracleIdentifierBuilder_.setMessage(builderForValue.build()); } sourceIdentifierCase_ = 1; return this; } /** * * * <pre> * Oracle data source object identifier. * </pre> * * <code> * .google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier oracle_identifier = 1; * </code> */ public Builder mergeOracleIdentifier( com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier value) { if (oracleIdentifierBuilder_ == null) { if (sourceIdentifierCase_ == 1 && sourceIdentifier_ != com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier .getDefaultInstance()) { sourceIdentifier_ = com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier .newBuilder( (com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier) sourceIdentifier_) .mergeFrom(value) .buildPartial(); } else { sourceIdentifier_ = value; } onChanged(); } else { if (sourceIdentifierCase_ == 1) { oracleIdentifierBuilder_.mergeFrom(value); } oracleIdentifierBuilder_.setMessage(value); } sourceIdentifierCase_ = 1; return this; } /** * * * <pre> * Oracle data source object identifier. * </pre> * * <code> * .google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier oracle_identifier = 1; * </code> */ public Builder clearOracleIdentifier() { if (oracleIdentifierBuilder_ == null) { if (sourceIdentifierCase_ == 1) { sourceIdentifierCase_ = 0; sourceIdentifier_ = null; onChanged(); } } else { if (sourceIdentifierCase_ == 1) { sourceIdentifierCase_ = 0; sourceIdentifier_ = null; } oracleIdentifierBuilder_.clear(); } return this; } /** * * * <pre> * Oracle data source object identifier. * </pre> * * <code> * .google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier oracle_identifier = 1; * </code> */ public com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier.Builder getOracleIdentifierBuilder() { return getOracleIdentifierFieldBuilder().getBuilder(); } /** * * * <pre> * Oracle data source object identifier. * </pre> * * <code> * .google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier oracle_identifier = 1; * </code> */ @java.lang.Override public com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifierOrBuilder getOracleIdentifierOrBuilder() { if ((sourceIdentifierCase_ == 1) && (oracleIdentifierBuilder_ != null)) { return oracleIdentifierBuilder_.getMessageOrBuilder(); } else { if (sourceIdentifierCase_ == 1) { return (com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier) sourceIdentifier_; } return com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier .getDefaultInstance(); } } /** * * * <pre> * Oracle data source object identifier. * </pre> * * <code> * .google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier oracle_identifier = 1; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier, com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier.Builder, com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifierOrBuilder> getOracleIdentifierFieldBuilder() { if (oracleIdentifierBuilder_ == null) { if (!(sourceIdentifierCase_ == 1)) { sourceIdentifier_ = com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier .getDefaultInstance(); } oracleIdentifierBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier, com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier .Builder, com.google.cloud.datastream.v1.SourceObjectIdentifier .OracleObjectIdentifierOrBuilder>( (com.google.cloud.datastream.v1.SourceObjectIdentifier.OracleObjectIdentifier) sourceIdentifier_, getParentForChildren(), isClean()); sourceIdentifier_ = null; } sourceIdentifierCase_ = 1; onChanged(); ; return oracleIdentifierBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier, com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier.Builder, com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifierOrBuilder> mysqlIdentifierBuilder_; /** * * * <pre> * Mysql data source object identifier. * </pre> * * <code> * .google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier mysql_identifier = 2; * </code> * * @return Whether the mysqlIdentifier field is set. */ @java.lang.Override public boolean hasMysqlIdentifier() { return sourceIdentifierCase_ == 2; } /** * * * <pre> * Mysql data source object identifier. * </pre> * * <code> * .google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier mysql_identifier = 2; * </code> * * @return The mysqlIdentifier. */ @java.lang.Override public com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier getMysqlIdentifier() { if (mysqlIdentifierBuilder_ == null) { if (sourceIdentifierCase_ == 2) { return (com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier) sourceIdentifier_; } return com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier .getDefaultInstance(); } else { if (sourceIdentifierCase_ == 2) { return mysqlIdentifierBuilder_.getMessage(); } return com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier .getDefaultInstance(); } } /** * * * <pre> * Mysql data source object identifier. * </pre> * * <code> * .google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier mysql_identifier = 2; * </code> */ public Builder setMysqlIdentifier( com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier value) { if (mysqlIdentifierBuilder_ == null) { if (value == null) { throw new NullPointerException(); } sourceIdentifier_ = value; onChanged(); } else { mysqlIdentifierBuilder_.setMessage(value); } sourceIdentifierCase_ = 2; return this; } /** * * * <pre> * Mysql data source object identifier. * </pre> * * <code> * .google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier mysql_identifier = 2; * </code> */ public Builder setMysqlIdentifier( com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier.Builder builderForValue) { if (mysqlIdentifierBuilder_ == null) { sourceIdentifier_ = builderForValue.build(); onChanged(); } else { mysqlIdentifierBuilder_.setMessage(builderForValue.build()); } sourceIdentifierCase_ = 2; return this; } /** * * * <pre> * Mysql data source object identifier. * </pre> * * <code> * .google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier mysql_identifier = 2; * </code> */ public Builder mergeMysqlIdentifier( com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier value) { if (mysqlIdentifierBuilder_ == null) { if (sourceIdentifierCase_ == 2 && sourceIdentifier_ != com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier .getDefaultInstance()) { sourceIdentifier_ = com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier .newBuilder( (com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier) sourceIdentifier_) .mergeFrom(value) .buildPartial(); } else { sourceIdentifier_ = value; } onChanged(); } else { if (sourceIdentifierCase_ == 2) { mysqlIdentifierBuilder_.mergeFrom(value); } mysqlIdentifierBuilder_.setMessage(value); } sourceIdentifierCase_ = 2; return this; } /** * * * <pre> * Mysql data source object identifier. * </pre> * * <code> * .google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier mysql_identifier = 2; * </code> */ public Builder clearMysqlIdentifier() { if (mysqlIdentifierBuilder_ == null) { if (sourceIdentifierCase_ == 2) { sourceIdentifierCase_ = 0; sourceIdentifier_ = null; onChanged(); } } else { if (sourceIdentifierCase_ == 2) { sourceIdentifierCase_ = 0; sourceIdentifier_ = null; } mysqlIdentifierBuilder_.clear(); } return this; } /** * * * <pre> * Mysql data source object identifier. * </pre> * * <code> * .google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier mysql_identifier = 2; * </code> */ public com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier.Builder getMysqlIdentifierBuilder() { return getMysqlIdentifierFieldBuilder().getBuilder(); } /** * * * <pre> * Mysql data source object identifier. * </pre> * * <code> * .google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier mysql_identifier = 2; * </code> */ @java.lang.Override public com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifierOrBuilder getMysqlIdentifierOrBuilder() { if ((sourceIdentifierCase_ == 2) && (mysqlIdentifierBuilder_ != null)) { return mysqlIdentifierBuilder_.getMessageOrBuilder(); } else { if (sourceIdentifierCase_ == 2) { return (com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier) sourceIdentifier_; } return com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier .getDefaultInstance(); } } /** * * * <pre> * Mysql data source object identifier. * </pre> * * <code> * .google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier mysql_identifier = 2; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier, com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier.Builder, com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifierOrBuilder> getMysqlIdentifierFieldBuilder() { if (mysqlIdentifierBuilder_ == null) { if (!(sourceIdentifierCase_ == 2)) { sourceIdentifier_ = com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier .getDefaultInstance(); } mysqlIdentifierBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier, com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier.Builder, com.google.cloud.datastream.v1.SourceObjectIdentifier .MysqlObjectIdentifierOrBuilder>( (com.google.cloud.datastream.v1.SourceObjectIdentifier.MysqlObjectIdentifier) sourceIdentifier_, getParentForChildren(), isClean()); sourceIdentifier_ = null; } sourceIdentifierCase_ = 2; onChanged(); ; return mysqlIdentifierBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.datastream.v1.SourceObjectIdentifier) } // @@protoc_insertion_point(class_scope:google.cloud.datastream.v1.SourceObjectIdentifier) private static final com.google.cloud.datastream.v1.SourceObjectIdentifier DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.datastream.v1.SourceObjectIdentifier(); } public static com.google.cloud.datastream.v1.SourceObjectIdentifier getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<SourceObjectIdentifier> PARSER = new com.google.protobuf.AbstractParser<SourceObjectIdentifier>() { @java.lang.Override public SourceObjectIdentifier parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new SourceObjectIdentifier(input, extensionRegistry); } }; public static com.google.protobuf.Parser<SourceObjectIdentifier> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<SourceObjectIdentifier> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.datastream.v1.SourceObjectIdentifier getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache-2.0
yiliangz/summer
summer-spider/src/main/java/com/summer/spider/service/TeamService.java
287
package com.summer.spider.service; import com.summer.common.service.CrudServiceImpl; import com.summer.spider.domain.Team; import org.springframework.stereotype.Service; /** * Created by Allen on 2015/5/4. */ @Service public class TeamService extends CrudServiceImpl<Team,Long> { }
apache-2.0
quarkusio/quarkus
integration-tests/maven/src/test/java/io/quarkus/maven/it/NativeImageIT.java
3758
package io.quarkus.maven.it; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.Test; import io.quarkus.maven.it.verifier.MavenProcessInvocationResult; import io.quarkus.maven.it.verifier.RunningInvoker; import io.quarkus.test.devmode.util.DevModeTestUtils; @EnableForNative public class NativeImageIT extends MojoTestBase { /** * Tests that the {@code java.library.path} can be overridden/configurable by passing the system property * when launching the generated application's native image. * * @throws Exception */ @Test public void testJavaLibraryPathAtRuntime() throws Exception { final File testDir = initProject("projects/native-image-app", "projects/native-image-app-output"); final RunningInvoker running = new RunningInvoker(testDir, false); // trigger mvn package -Pnative -Dquarkus.ssl.native=true final String[] mvnArgs = new String[] { "package", "-DskipTests", "-Pnative", "-Dquarkus.ssl.native=true" }; final MavenProcessInvocationResult result = running.execute(Arrays.asList(mvnArgs), Collections.emptyMap()); await().atMost(10, TimeUnit.MINUTES).until(() -> result.getProcess() != null && !result.getProcess().isAlive()); final String processLog = running.log(); try { assertThat(processLog).containsIgnoringCase("BUILD SUCCESS"); } catch (AssertionError ae) { // skip this test (instead of failing), if the native-image command wasn't available. // Bit brittle to rely on the log message, but it's OK in the context of this test Assumptions.assumeFalse(processLog.contains("Cannot find the `native-image"), "Skipping test since native-image tool isn't available"); // native-image command was available but the build failed for some reason, throw the original error throw ae; } finally { running.stop(); } // now that the native image is built, run it final Path nativeImageRunner = testDir.toPath().toAbsolutePath().resolve(Paths.get("target/acme-1.0-SNAPSHOT-runner")); final Path tmpDir = Files.createTempDirectory("native-image-test"); tmpDir.toFile().deleteOnExit(); final Process nativeImageRunWithAdditionalLibPath = runNativeImage(nativeImageRunner, new String[] { "-Djava.library.path=" + tmpDir.toString() }); try { final String response = DevModeTestUtils.getHttpResponse("/hello/javaLibraryPath"); Assertions.assertTrue(response.contains(tmpDir.toString()), "Response " + response + " for java.library.path was expected to contain the " + tmpDir + ", but didn't"); } finally { nativeImageRunWithAdditionalLibPath.destroy(); } } private static Process runNativeImage(final Path nativeImageRunnerFile, final String[] params) throws Exception { final List<String> commands = new ArrayList<>(); commands.add(nativeImageRunnerFile.toString()); if (params != null) { commands.addAll(Arrays.asList(params)); } final ProcessBuilder processBuilder = new ProcessBuilder(commands.toArray(new String[0])); processBuilder.inheritIO(); return processBuilder.start(); } }
apache-2.0
mcollovati/camel
components/camel-braintree/src/generated/java/org/apache/camel/component/braintree/DiscountGatewayEndpointConfigurationConfigurer.java
5915
/* Generated by camel build tools - do NOT edit this file! */ package org.apache.camel.component.braintree; import java.util.Map; import org.apache.camel.CamelContext; import org.apache.camel.spi.ConfigurerStrategy; import org.apache.camel.spi.GeneratedPropertyConfigurer; import org.apache.camel.spi.PropertyConfigurerGetter; import org.apache.camel.util.CaseInsensitiveMap; import org.apache.camel.component.braintree.DiscountGatewayEndpointConfiguration; /** * Generated by camel build tools - do NOT edit this file! */ @SuppressWarnings("unchecked") public class DiscountGatewayEndpointConfigurationConfigurer extends org.apache.camel.support.component.PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { private static final Map<String, Object> ALL_OPTIONS; static { Map<String, Object> map = new CaseInsensitiveMap(); map.put("AccessToken", java.lang.String.class); map.put("ApiName", org.apache.camel.component.braintree.internal.BraintreeApiName.class); map.put("Environment", java.lang.String.class); map.put("HttpLogLevel", java.lang.String.class); map.put("HttpLogName", java.lang.String.class); map.put("HttpReadTimeout", java.lang.Integer.class); map.put("LogHandlerEnabled", boolean.class); map.put("MerchantId", java.lang.String.class); map.put("MethodName", java.lang.String.class); map.put("PrivateKey", java.lang.String.class); map.put("ProxyHost", java.lang.String.class); map.put("ProxyPort", java.lang.Integer.class); map.put("PublicKey", java.lang.String.class); ALL_OPTIONS = map; ConfigurerStrategy.addConfigurerClearer(DiscountGatewayEndpointConfigurationConfigurer::clearConfigurers); } @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { org.apache.camel.component.braintree.DiscountGatewayEndpointConfiguration target = (org.apache.camel.component.braintree.DiscountGatewayEndpointConfiguration) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "accesstoken": case "AccessToken": target.setAccessToken(property(camelContext, java.lang.String.class, value)); return true; case "apiname": case "ApiName": target.setApiName(property(camelContext, org.apache.camel.component.braintree.internal.BraintreeApiName.class, value)); return true; case "environment": case "Environment": target.setEnvironment(property(camelContext, java.lang.String.class, value)); return true; case "httploglevel": case "HttpLogLevel": target.setHttpLogLevel(property(camelContext, java.lang.String.class, value)); return true; case "httplogname": case "HttpLogName": target.setHttpLogName(property(camelContext, java.lang.String.class, value)); return true; case "httpreadtimeout": case "HttpReadTimeout": target.setHttpReadTimeout(property(camelContext, java.lang.Integer.class, value)); return true; case "loghandlerenabled": case "LogHandlerEnabled": target.setLogHandlerEnabled(property(camelContext, boolean.class, value)); return true; case "merchantid": case "MerchantId": target.setMerchantId(property(camelContext, java.lang.String.class, value)); return true; case "methodname": case "MethodName": target.setMethodName(property(camelContext, java.lang.String.class, value)); return true; case "privatekey": case "PrivateKey": target.setPrivateKey(property(camelContext, java.lang.String.class, value)); return true; case "proxyhost": case "ProxyHost": target.setProxyHost(property(camelContext, java.lang.String.class, value)); return true; case "proxyport": case "ProxyPort": target.setProxyPort(property(camelContext, java.lang.Integer.class, value)); return true; case "publickey": case "PublicKey": target.setPublicKey(property(camelContext, java.lang.String.class, value)); return true; default: return false; } } @Override public Map<String, Object> getAllOptions(Object target) { return ALL_OPTIONS; } public static void clearBootstrapConfigurers() { } public static void clearConfigurers() { ALL_OPTIONS.clear(); } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { org.apache.camel.component.braintree.DiscountGatewayEndpointConfiguration target = (org.apache.camel.component.braintree.DiscountGatewayEndpointConfiguration) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "accesstoken": case "AccessToken": return target.getAccessToken(); case "apiname": case "ApiName": return target.getApiName(); case "environment": case "Environment": return target.getEnvironment(); case "httploglevel": case "HttpLogLevel": return target.getHttpLogLevel(); case "httplogname": case "HttpLogName": return target.getHttpLogName(); case "httpreadtimeout": case "HttpReadTimeout": return target.getHttpReadTimeout(); case "loghandlerenabled": case "LogHandlerEnabled": return target.isLogHandlerEnabled(); case "merchantid": case "MerchantId": return target.getMerchantId(); case "methodname": case "MethodName": return target.getMethodName(); case "privatekey": case "PrivateKey": return target.getPrivateKey(); case "proxyhost": case "ProxyHost": return target.getProxyHost(); case "proxyport": case "ProxyPort": return target.getProxyPort(); case "publickey": case "PublicKey": return target.getPublicKey(); default: return null; } } }
apache-2.0
xuzhikethinker/t4f-data
structure/core/src/main/java/aos/data/structure/ChainedHashtableIterator.java
3382
/**************************************************************** * Licensed to the AOS Community (AOS) under one or more * * contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The AOS 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 aos.data.structure; import java.util.Iterator; /** * An iterator to traverse chained hash tables. * * @version $Id: ChainedHashtableIterator.java 8 2006-08-02 19:03:11Z bailey $ * @author, 2001 duane a. bailey */ class ChainedHashtableIterator extends AbstractIterator { /** * The list of values within the table. */ protected List data; /** * The iterator over the elements of the list. */ protected Iterator elements; /** * Construct an iterator over a chained hashtable. * * @post constructs a new hash table iterator * @param table The array of lists to be traversed. */ public ChainedHashtableIterator(List[] table) { int i; int capacity = table.length; data = new SinglyLinkedList(); for (i = 0; i < capacity; i++) { if (table[i] != null) { Iterator els = table[i].iterator(); while (els.hasNext()) { data.addFirst(els.next()); } } } elements = data.iterator(); } /** * Resets the iterator to point to the beginning of the chained table. * * @post resets iterator to beginning of hash table */ public void reset() { ((AbstractIterator)elements).reset(); } /** * Returns true iff there are unconsidered elements within the table. * * @post returns true if there are unvisited elements * * @return True iff there are elements yet to be considered within table. */ public boolean hasNext() { return elements.hasNext(); } /** * Returns current value and increments iterator. * * @pre hasNext() * @post returns current element, increments iterator * * @return The current value, before incrementing. */ public Object next() { return elements.next(); } /** * Get current value of iterator. * * @post returns current element * * @return The current value. */ public Object get() { return ((AbstractIterator)elements).get(); } }
apache-2.0
oehme/analysing-gradle-performance
my-app/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p371/Test7429.java
2174
package org.gradle.test.performance.mediummonolithicjavaproject.p371; import org.junit.Test; import static org.junit.Assert.*; public class Test7429 { Production7429 objectUnderTest = new Production7429(); @Test public void testProperty0() { Production7426 value = new Production7426(); objectUnderTest.setProperty0(value); assertEquals(value, objectUnderTest.getProperty0()); } @Test public void testProperty1() { Production7427 value = new Production7427(); objectUnderTest.setProperty1(value); assertEquals(value, objectUnderTest.getProperty1()); } @Test public void testProperty2() { Production7428 value = new Production7428(); objectUnderTest.setProperty2(value); assertEquals(value, objectUnderTest.getProperty2()); } @Test public void testProperty3() { String value = "value"; objectUnderTest.setProperty3(value); assertEquals(value, objectUnderTest.getProperty3()); } @Test public void testProperty4() { String value = "value"; objectUnderTest.setProperty4(value); assertEquals(value, objectUnderTest.getProperty4()); } @Test public void testProperty5() { String value = "value"; objectUnderTest.setProperty5(value); assertEquals(value, objectUnderTest.getProperty5()); } @Test public void testProperty6() { String value = "value"; objectUnderTest.setProperty6(value); assertEquals(value, objectUnderTest.getProperty6()); } @Test public void testProperty7() { String value = "value"; objectUnderTest.setProperty7(value); assertEquals(value, objectUnderTest.getProperty7()); } @Test public void testProperty8() { String value = "value"; objectUnderTest.setProperty8(value); assertEquals(value, objectUnderTest.getProperty8()); } @Test public void testProperty9() { String value = "value"; objectUnderTest.setProperty9(value); assertEquals(value, objectUnderTest.getProperty9()); } }
apache-2.0
engek1/easygraph
src/easygraph/events/VertexLeftClickEvent.java
600
package easygraph.events; import javafx.event.Event; import javafx.event.EventType; import easygraph.guielements.GuiVertex; public class VertexLeftClickEvent extends Event { private GuiVertex guiVertex; private static final long serialVersionUID = 1L; public static final EventType<VertexLeftClickEvent> VERTEX_LEFT_CLICK = new EventType<VertexLeftClickEvent>(ANY, "VERTEX_LEFT_CLICK"); public VertexLeftClickEvent(GuiVertex guiVertex) { super(VERTEX_LEFT_CLICK); this.guiVertex = guiVertex; } public GuiVertex getGuiVertex() { return this.guiVertex; } }
apache-2.0
radut/Podcast-Server
src/test/java/lan/dk/podcastserver/service/WorkerServiceTest.java
3264
package lan.dk.podcastserver.service; import lan.dk.podcastserver.entity.Item; import lan.dk.podcastserver.entity.Podcast; import lan.dk.podcastserver.manager.worker.downloader.Downloader; import lan.dk.podcastserver.manager.worker.selector.DownloaderSelector; import lan.dk.podcastserver.manager.worker.selector.UpdaterSelector; import lan.dk.podcastserver.manager.worker.updater.*; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.context.ApplicationContext; import java.util.Arrays; import java.util.List; import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; /** * Created by kevin on 17/07/15 for Podcast Server */ @RunWith(MockitoJUnitRunner.class) public class WorkerServiceTest { @Mock UpdaterSelector updaterSelector; @Mock DownloaderSelector downloaderSelector; @Mock ApplicationContext context; List<Updater> updaters; WorkerService workerService; @Before public void beforeEach() { updaters = Arrays.asList(new BeInSportsUpdater(), new CanalPlusUpdater(), new YoutubeUpdater()); workerService = new WorkerService(updaterSelector, downloaderSelector, updaters); workerService.setApplicationContext(context); } @Test public void should_expose_all_types() { /* When */ Set<AbstractUpdater.Type> types = workerService.types(); /* Then */ assertThat(types) .hasSize(3) .extracting("key") .contains("BeInSports", "CanalPlus", "Youtube"); } @Test public void should_get_updater_from_context() { /* Given */ Class clazz = WorkerServiceTest.class; Updater mockUpdater = mock(Updater.class); when(updaterSelector.of(any())).thenReturn(clazz); when(context.getBean(any(String.class))).thenReturn(mockUpdater); Podcast podcast = new Podcast().setUrl("http://fake.url/"); /* When */ Updater updater = workerService.updaterOf(podcast); /* Then */ assertThat(updater).isSameAs(mockUpdater); verify(updaterSelector, times(1)).of(eq(podcast.getUrl())); verify(context, times(1)).getBean(eq(clazz.getSimpleName())); } @Test public void should_get_downloader_by_type_from_context() { /* Given */ Class clazz = WorkerServiceTest.class; Downloader downloader = mock(Downloader.class); when(downloaderSelector.of(any())).thenReturn(clazz); when(context.getBean(any(String.class))).thenReturn(downloader); when(downloader.setItem(any())).thenReturn(downloader); Item item = new Item().setUrl("http://fake.url/"); /* When */ Downloader downloaderSelected = workerService.getDownloaderByType(item); /* Then */ assertThat(downloaderSelected).isSameAs(downloader); verify(downloaderSelector, times(1)).of(eq(item.getUrl())); verify(context, times(1)).getBean(eq(clazz.getSimpleName())); verify(downloader, times(1)).setItem(refEq(item)); } }
apache-2.0
dbflute-test/dbflute-test-dbms-db2
src/main/java/org/docksidestage/db2/dbflute/bsbhv/BsAliasRefExceptBhv.java
66285
package org.docksidestage.db2.dbflute.bsbhv; import java.util.List; import org.dbflute.*; import org.dbflute.bhv.*; import org.dbflute.bhv.readable.*; import org.dbflute.bhv.writable.*; import org.dbflute.bhv.referrer.*; import org.dbflute.cbean.*; import org.dbflute.cbean.chelper.HpSLSFunction; import org.dbflute.cbean.result.*; import org.dbflute.exception.*; import org.dbflute.optional.OptionalEntity; import org.dbflute.outsidesql.executor.*; import org.docksidestage.db2.dbflute.exbhv.*; import org.docksidestage.db2.dbflute.bsbhv.loader.*; import org.docksidestage.db2.dbflute.exentity.*; import org.docksidestage.db2.dbflute.bsentity.dbmeta.*; import org.docksidestage.db2.dbflute.cbean.*; /** * The behavior of ALIAS_REF_EXCEPT as ALIAS. <br> * <pre> * [primary key] * REF_EXCEPT_ID * * [column] * REF_EXCEPT_ID, EXCEPT_ID * * [sequence] * * * [identity] * * * [version-no] * * * [foreign table] * ALIAS_EXCEPT * * [referrer table] * * * [foreign property] * aliasExcept * * [referrer property] * * </pre> * @author DBFlute(AutoGenerator) */ public abstract class BsAliasRefExceptBhv extends AbstractBehaviorWritable<AliasRefExcept, AliasRefExceptCB> { // =================================================================================== // Definition // ========== /*df:beginQueryPath*/ /*df:endQueryPath*/ // =================================================================================== // DB Meta // ======= /** {@inheritDoc} */ public AliasRefExceptDbm asDBMeta() { return AliasRefExceptDbm.getInstance(); } /** {@inheritDoc} */ public String asTableDbName() { return "ALIAS_REF_EXCEPT"; } // =================================================================================== // New Instance // ============ /** {@inheritDoc} */ public AliasRefExceptCB newConditionBean() { return new AliasRefExceptCB(); } // =================================================================================== // Count Select // ============ /** * Select the count of uniquely-selected records by the condition-bean. {IgnorePagingCondition, IgnoreSpecifyColumn}<br> * SpecifyColumn is ignored but you can use it only to remove text type column for union's distinct. * <pre> * <span style="color: #70226C">int</span> count = <span style="color: #0000C0">aliasRefExceptBhv</span>.<span style="color: #CC4747">selectCount</span>(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().set... * }); * </pre> * @param cbLambda The callback for condition-bean of AliasRefExcept. (NotNull) * @return The count for the condition. (NotMinus) */ public int selectCount(CBCall<AliasRefExceptCB> cbLambda) { return facadeSelectCount(createCB(cbLambda)); } /** * Select the count of uniquely-selected records by the condition-bean. {IgnorePagingCondition, IgnoreSpecifyColumn}<br> * SpecifyColumn is ignored but you can use it only to remove text type column for union's distinct. * <pre> * AliasRefExceptCB cb = <span style="color: #70226C">new</span> AliasRefExceptCB(); * cb.query().setFoo...(value); * <span style="color: #70226C">int</span> count = <span style="color: #0000C0">aliasRefExceptBhv</span>.<span style="color: #CC4747">selectCount</span>(cb); * </pre> * @param cb The condition-bean of AliasRefExcept. (NotNull) * @return The count for the condition. (NotMinus) */ public int selectCount(AliasRefExceptCB cb) { return facadeSelectCount(cb); } // =================================================================================== // Entity Select // ============= /** * Select the entity by the condition-bean. #beforejava8 <br> * <span style="color: #AD4747; font-size: 120%">The return might be null if no data, so you should have null check.</span> <br> * <span style="color: #AD4747; font-size: 120%">If the data is always present as your business rule, use selectEntityWithDeletedCheck().</span> * <pre> * AliasRefExcept aliasRefExcept = <span style="color: #0000C0">aliasRefExceptBhv</span>.<span style="color: #CC4747">selectEntity</span>(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().set... * }); * <span style="color: #70226C">if</span> (aliasRefExcept != <span style="color: #70226C">null</span>) { <span style="color: #3F7E5E">// null check</span> * ... = aliasRefExcept.get...(); * } <span style="color: #70226C">else</span> { * ... * } * </pre> * @param cbLambda The callback for condition-bean of AliasRefExcept. (NotNull) * @return The entity selected by the condition. (NullAllowed: if no data, it returns null) * @throws EntityDuplicatedException When the entity has been duplicated. * @throws SelectEntityConditionNotFoundException When the condition for selecting an entity is not found. */ public OptionalEntity<AliasRefExcept> selectEntity(CBCall<AliasRefExceptCB> cbLambda) { return doSelectOptionalEntity(createCB(cbLambda), typeOfSelectedEntity()); } /** * Select the entity by the condition-bean. #beforejava8 <br> * <span style="color: #AD4747; font-size: 120%">The return might be null if no data, so you should have null check.</span> <br> * <span style="color: #AD4747; font-size: 120%">If the data always exists as your business rule, use selectEntityWithDeletedCheck().</span> * <pre> * AliasRefExceptCB cb = <span style="color: #70226C">new</span> AliasRefExceptCB(); * cb.query().setFoo...(value); * AliasRefExcept aliasRefExcept = <span style="color: #0000C0">aliasRefExceptBhv</span>.<span style="color: #DD4747">selectEntity</span>(cb); * <span style="color: #70226C">if</span> (aliasRefExcept != <span style="color: #70226C">null</span>) { <span style="color: #3F7E5E">// null check</span> * ... = aliasRefExcept.get...(); * } <span style="color: #70226C">else</span> { * ... * } * </pre> * @param cb The condition-bean of AliasRefExcept. (NotNull) * @return The entity selected by the condition. (NullAllowed: if no data, it returns null) * @throws EntityDuplicatedException When the entity has been duplicated. * @throws SelectEntityConditionNotFoundException When the condition for selecting an entity is not found. */ public AliasRefExcept selectEntity(AliasRefExceptCB cb) { return facadeSelectEntity(cb); } protected AliasRefExcept facadeSelectEntity(AliasRefExceptCB cb) { return doSelectEntity(cb, typeOfSelectedEntity()); } protected <ENTITY extends AliasRefExcept> OptionalEntity<ENTITY> doSelectOptionalEntity(AliasRefExceptCB cb, Class<? extends ENTITY> tp) { return createOptionalEntity(doSelectEntity(cb, tp), cb); } protected Entity doReadEntity(ConditionBean cb) { return facadeSelectEntity(downcast(cb)); } /** * Select the entity by the condition-bean with deleted check. <br> * <span style="color: #AD4747; font-size: 120%">If the data is always present as your business rule, this method is good.</span> * <pre> * AliasRefExcept <span style="color: #553000">aliasRefExcept</span> = <span style="color: #0000C0">aliasRefExceptBhv</span>.<span style="color: #CC4747">selectEntityWithDeletedCheck</span>(cb <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> cb.acceptPK(1)); * ... = <span style="color: #553000">aliasRefExcept</span>.get...(); <span style="color: #3F7E5E">// the entity always be not null</span> * </pre> * @param cbLambda The callback for condition-bean of AliasRefExcept. (NotNull) * @return The entity selected by the condition. (NotNull: if no data, throws exception) * @throws EntityAlreadyDeletedException When the entity has already been deleted. (not found) * @throws EntityDuplicatedException When the entity has been duplicated. * @throws SelectEntityConditionNotFoundException When the condition for selecting an entity is not found. */ public AliasRefExcept selectEntityWithDeletedCheck(CBCall<AliasRefExceptCB> cbLambda) { return facadeSelectEntityWithDeletedCheck(createCB(cbLambda)); } /** * Select the entity by the condition-bean with deleted check. <br> * <span style="color: #AD4747; font-size: 120%">If the data is always present as your business rule, this method is good.</span> * <pre> * AliasRefExceptCB cb = <span style="color: #70226C">new</span> AliasRefExceptCB(); * cb.query().set...; * AliasRefExcept aliasRefExcept = <span style="color: #0000C0">aliasRefExceptBhv</span>.<span style="color: #CC4747">selectEntityWithDeletedCheck</span>(cb); * ... = aliasRefExcept.get...(); <span style="color: #3F7E5E">// the entity always be not null</span> * </pre> * @param cb The condition-bean of AliasRefExcept. (NotNull) * @return The entity selected by the condition. (NotNull: if no data, throws exception) * @throws EntityAlreadyDeletedException When the entity has already been deleted. (not found) * @throws EntityDuplicatedException When the entity has been duplicated. * @throws SelectEntityConditionNotFoundException When the condition for selecting an entity is not found. */ public AliasRefExcept selectEntityWithDeletedCheck(AliasRefExceptCB cb) { return facadeSelectEntityWithDeletedCheck(cb); } /** * Select the entity by the primary-key value. * @param refExceptId : PK, NotNull, DECIMAL(16). (NotNull) * @return The entity selected by the PK. (NullAllowed: if no data, it returns null) * @throws EntityDuplicatedException When the entity has been duplicated. * @throws SelectEntityConditionNotFoundException When the condition for selecting an entity is not found. */ public AliasRefExcept selectByPK(Long refExceptId) { return facadeSelectByPK(refExceptId); } protected AliasRefExcept facadeSelectByPK(Long refExceptId) { return doSelectByPK(refExceptId, typeOfSelectedEntity()); } protected <ENTITY extends AliasRefExcept> ENTITY doSelectByPK(Long refExceptId, Class<? extends ENTITY> tp) { return doSelectEntity(xprepareCBAsPK(refExceptId), tp); } protected <ENTITY extends AliasRefExcept> OptionalEntity<ENTITY> doSelectOptionalByPK(Long refExceptId, Class<? extends ENTITY> tp) { return createOptionalEntity(doSelectByPK(refExceptId, tp), refExceptId); } protected AliasRefExceptCB xprepareCBAsPK(Long refExceptId) { assertObjectNotNull("refExceptId", refExceptId); return newConditionBean().acceptPK(refExceptId); } // =================================================================================== // List Select // =========== /** * Select the list as result bean. * <pre> * ListResultBean&lt;AliasRefExcept&gt; <span style="color: #553000">aliasRefExceptList</span> = <span style="color: #0000C0">aliasRefExceptBhv</span>.<span style="color: #CC4747">selectList</span>(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().set...; * <span style="color: #553000">cb</span>.query().addOrderBy...; * }); * <span style="color: #70226C">for</span> (AliasRefExcept <span style="color: #553000">aliasRefExcept</span> : <span style="color: #553000">aliasRefExceptList</span>) { * ... = <span style="color: #553000">aliasRefExcept</span>.get...; * } * </pre> * @param cbLambda The callback for condition-bean of AliasRefExcept. (NotNull) * @return The result bean of selected list. (NotNull: if no data, returns empty list) * @throws DangerousResultSizeException When the result size is over the specified safety size. */ public ListResultBean<AliasRefExcept> selectList(CBCall<AliasRefExceptCB> cbLambda) { return facadeSelectList(createCB(cbLambda)); } /** * Select the list as result bean. * <pre> * AliasRefExceptCB cb = <span style="color: #70226C">new</span> AliasRefExceptCB(); * cb.query().set...; * cb.query().addOrderBy...; * ListResultBean&lt;AliasRefExcept&gt; <span style="color: #553000">aliasRefExceptList</span> = <span style="color: #0000C0">aliasRefExceptBhv</span>.<span style="color: #CC4747">selectList</span>(cb); * <span style="color: #70226C">for</span> (AliasRefExcept aliasRefExcept : <span style="color: #553000">aliasRefExceptList</span>) { * ... = aliasRefExcept.get...; * } * </pre> * @param cb The condition-bean of AliasRefExcept. (NotNull) * @return The result bean of selected list. (NotNull: if no data, returns empty list) * @throws DangerousResultSizeException When the result size is over the specified safety size. */ public ListResultBean<AliasRefExcept> selectList(AliasRefExceptCB cb) { return facadeSelectList(cb); } @Override protected boolean isEntityDerivedMappable() { return true; } // =================================================================================== // Page Select // =========== /** * Select the page as result bean. <br> * (both count-select and paging-select are executed) * <pre> * PagingResultBean&lt;AliasRefExcept&gt; <span style="color: #553000">page</span> = <span style="color: #0000C0">aliasRefExceptBhv</span>.<span style="color: #CC4747">selectPage</span>(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().set... * <span style="color: #553000">cb</span>.query().addOrderBy... * <span style="color: #553000">cb</span>.<span style="color: #CC4747">paging</span>(20, 3); <span style="color: #3F7E5E">// 20 records per a page and current page number is 3</span> * }); * <span style="color: #70226C">int</span> allRecordCount = <span style="color: #553000">page</span>.getAllRecordCount(); * <span style="color: #70226C">int</span> allPageCount = <span style="color: #553000">page</span>.getAllPageCount(); * <span style="color: #70226C">boolean</span> isExistPrePage = <span style="color: #553000">page</span>.isExistPrePage(); * <span style="color: #70226C">boolean</span> isExistNextPage = <span style="color: #553000">page</span>.isExistNextPage(); * ... * <span style="color: #70226C">for</span> (AliasRefExcept aliasRefExcept : <span style="color: #553000">page</span>) { * ... = aliasRefExcept.get...; * } * </pre> * @param cbLambda The callback for condition-bean of AliasRefExcept. (NotNull) * @return The result bean of selected page. (NotNull: if no data, returns bean as empty list) * @throws DangerousResultSizeException When the result size is over the specified safety size. */ public PagingResultBean<AliasRefExcept> selectPage(CBCall<AliasRefExceptCB> cbLambda) { return facadeSelectPage(createCB(cbLambda)); } /** * Select the page as result bean. <br> * (both count-select and paging-select are executed) * <pre> * AliasRefExceptCB cb = <span style="color: #70226C">new</span> AliasRefExceptCB(); * cb.query().setFoo...(value); * cb.query().addOrderBy_Bar...(); * cb.<span style="color: #CC4747">paging</span>(20, 3); <span style="color: #3F7E5E">// 20 records per a page and current page number is 3</span> * PagingResultBean&lt;AliasRefExcept&gt; <span style="color: #553000">page</span> = <span style="color: #0000C0">aliasRefExceptBhv</span>.<span style="color: #CC4747">selectPage</span>(cb); * <span style="color: #70226C">int</span> allRecordCount = <span style="color: #553000">page</span>.getAllRecordCount(); * <span style="color: #70226C">int</span> allPageCount = <span style="color: #553000">page</span>.getAllPageCount(); * <span style="color: #70226C">boolean</span> isExistPrePage = <span style="color: #553000">page</span>.isExistPrePage(); * <span style="color: #70226C">boolean</span> isExistNextPage = <span style="color: #553000">page</span>.isExistNextPage(); * ... * <span style="color: #70226C">for</span> (AliasRefExcept aliasRefExcept : <span style="color: #553000">page</span>) { * ... = aliasRefExcept.get...(); * } * </pre> * @param cb The condition-bean of AliasRefExcept. (NotNull) * @return The result bean of selected page. (NotNull: if no data, returns bean as empty list) * @throws DangerousResultSizeException When the result size is over the specified safety size. */ public PagingResultBean<AliasRefExcept> selectPage(AliasRefExceptCB cb) { return facadeSelectPage(cb); } // =================================================================================== // Cursor Select // ============= /** * Select the cursor by the condition-bean. * <pre> * <span style="color: #0000C0">aliasRefExceptBhv</span>.<span style="color: #CC4747">selectCursor</span>(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().set... * }, <span style="color: #553000">member</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * ... = <span style="color: #553000">member</span>.getMemberName(); * }); * </pre> * @param cbLambda The callback for condition-bean of AliasRefExcept. (NotNull) * @param entityLambda The handler of entity row of AliasRefExcept. (NotNull) */ public void selectCursor(CBCall<AliasRefExceptCB> cbLambda, EntityRowHandler<AliasRefExcept> entityLambda) { facadeSelectCursor(createCB(cbLambda), entityLambda); } /** * Select the cursor by the condition-bean. * <pre> * AliasRefExceptCB cb = <span style="color: #70226C">new</span> AliasRefExceptCB(); * cb.query().set... * <span style="color: #0000C0">aliasRefExceptBhv</span>.<span style="color: #CC4747">selectCursor</span>(cb, <span style="color: #553000">member</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * ... = <span style="color: #553000">member</span>.getMemberName(); * }); * </pre> * @param cb The condition-bean of AliasRefExcept. (NotNull) * @param entityRowHandler The handler of entity row of AliasRefExcept. (NotNull) */ public void selectCursor(AliasRefExceptCB cb, EntityRowHandler<AliasRefExcept> entityRowHandler) { facadeSelectCursor(cb, entityRowHandler); } // =================================================================================== // Scalar Select // ============= /** * Select the scalar value derived by a function from uniquely-selected records. <br> * You should call a function method after this method called like as follows: * <pre> * <span style="color: #0000C0">aliasRefExceptBhv</span>.<span style="color: #CC4747">selectScalar</span>(Date.class).max(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.specify().<span style="color: #CC4747">column...</span>; <span style="color: #3F7E5E">// required for the function</span> * <span style="color: #553000">cb</span>.query().set... * }); * </pre> * @param <RESULT> The type of result. * @param resultType The type of result. (NotNull) * @return The scalar function object to specify function for scalar value. (NotNull) */ public <RESULT> HpSLSFunction<AliasRefExceptCB, RESULT> selectScalar(Class<RESULT> resultType) { return facadeScalarSelect(resultType); } // =================================================================================== // Sequence // ======== @Override protected Number doReadNextVal() { String msg = "This table is NOT related to sequence: " + asTableDbName(); throw new UnsupportedOperationException(msg); } // =================================================================================== // Load Referrer // ============= /** * Load referrer for the list by the referrer loader. * <pre> * List&lt;Member&gt; <span style="color: #553000">memberList</span> = <span style="color: #0000C0">memberBhv</span>.selectList(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().set... * }); * memberBhv.<span style="color: #CC4747">load</span>(<span style="color: #553000">memberList</span>, <span style="color: #553000">memberLoader</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">memberLoader</span>.<span style="color: #CC4747">loadPurchase</span>(<span style="color: #553000">purchaseCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">purchaseCB</span>.setupSelect... * <span style="color: #553000">purchaseCB</span>.query().set... * <span style="color: #553000">purchaseCB</span>.query().addOrderBy... * }); <span style="color: #3F7E5E">// you can also load nested referrer from here</span> * <span style="color: #3F7E5E">//}).withNestedReferrer(purchaseLoader -&gt; {</span> * <span style="color: #3F7E5E">// purchaseLoader.loadPurchasePayment(...);</span> * <span style="color: #3F7E5E">//});</span> * * <span style="color: #3F7E5E">// you can also pull out foreign table and load its referrer</span> * <span style="color: #3F7E5E">// (setupSelect of the foreign table should be called)</span> * <span style="color: #3F7E5E">//memberLoader.pulloutMemberStatus().loadMemberLogin(...)</span> * }); * <span style="color: #70226C">for</span> (Member member : <span style="color: #553000">memberList</span>) { * List&lt;Purchase&gt; purchaseList = member.<span style="color: #CC4747">getPurchaseList()</span>; * <span style="color: #70226C">for</span> (Purchase purchase : purchaseList) { * ... * } * } * </pre> * About internal policy, the value of primary key (and others too) is treated as case-insensitive. <br> * The condition-bean, which the set-upper provides, has order by FK before callback. * @param aliasRefExceptList The entity list of aliasRefExcept. (NotNull) * @param loaderLambda The callback to handle the referrer loader for actually loading referrer. (NotNull) */ public void load(List<AliasRefExcept> aliasRefExceptList, ReferrerLoaderHandler<LoaderOfAliasRefExcept> loaderLambda) { xassLRArg(aliasRefExceptList, loaderLambda); loaderLambda.handle(new LoaderOfAliasRefExcept().ready(aliasRefExceptList, _behaviorSelector)); } /** * Load referrer for the entity by the referrer loader. * <pre> * Member <span style="color: #553000">member</span> = <span style="color: #0000C0">memberBhv</span>.selectEntityWithDeletedCheck(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> <span style="color: #553000">cb</span>.acceptPK(1)); * <span style="color: #0000C0">memberBhv</span>.<span style="color: #CC4747">load</span>(<span style="color: #553000">member</span>, <span style="color: #553000">memberLoader</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">memberLoader</span>.<span style="color: #CC4747">loadPurchase</span>(<span style="color: #553000">purchaseCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">purchaseCB</span>.setupSelect... * <span style="color: #553000">purchaseCB</span>.query().set... * <span style="color: #553000">purchaseCB</span>.query().addOrderBy... * }); <span style="color: #3F7E5E">// you can also load nested referrer from here</span> * <span style="color: #3F7E5E">//}).withNestedReferrer(purchaseLoader -&gt; {</span> * <span style="color: #3F7E5E">// purchaseLoader.loadPurchasePayment(...);</span> * <span style="color: #3F7E5E">//});</span> * * <span style="color: #3F7E5E">// you can also pull out foreign table and load its referrer</span> * <span style="color: #3F7E5E">// (setupSelect of the foreign table should be called)</span> * <span style="color: #3F7E5E">//memberLoader.pulloutMemberStatus().loadMemberLogin(...)</span> * }); * List&lt;Purchase&gt; purchaseList = <span style="color: #553000">member</span>.<span style="color: #CC4747">getPurchaseList()</span>; * <span style="color: #70226C">for</span> (Purchase purchase : purchaseList) { * ... * } * </pre> * About internal policy, the value of primary key (and others too) is treated as case-insensitive. <br> * The condition-bean, which the set-upper provides, has order by FK before callback. * @param aliasRefExcept The entity of aliasRefExcept. (NotNull) * @param loaderLambda The callback to handle the referrer loader for actually loading referrer. (NotNull) */ public void load(AliasRefExcept aliasRefExcept, ReferrerLoaderHandler<LoaderOfAliasRefExcept> loaderLambda) { xassLRArg(aliasRefExcept, loaderLambda); loaderLambda.handle(new LoaderOfAliasRefExcept().ready(xnewLRAryLs(aliasRefExcept), _behaviorSelector)); } // =================================================================================== // Pull out Relation // ================= /** * Pull out the list of foreign table 'AliasExcept'. * @param aliasRefExceptList The list of aliasRefExcept. (NotNull, EmptyAllowed) * @return The list of foreign table. (NotNull, EmptyAllowed, NotNullElement) */ public List<AliasExcept> pulloutAliasExcept(List<AliasRefExcept> aliasRefExceptList) { return helpPulloutInternally(aliasRefExceptList, "aliasExcept"); } // =================================================================================== // Extract Column // ============== /** * Extract the value list of (single) primary key refExceptId. * @param aliasRefExceptList The list of aliasRefExcept. (NotNull, EmptyAllowed) * @return The list of the column value. (NotNull, EmptyAllowed, NotNullElement) */ public List<Long> extractRefExceptIdList(List<AliasRefExcept> aliasRefExceptList) { return helpExtractListInternally(aliasRefExceptList, "refExceptId"); } // =================================================================================== // Entity Update // ============= /** * Insert the entity modified-only. (DefaultConstraintsEnabled) * <pre> * AliasRefExcept aliasRefExcept = <span style="color: #70226C">new</span> AliasRefExcept(); * <span style="color: #3F7E5E">// if auto-increment, you don't need to set the PK value</span> * aliasRefExcept.setFoo...(value); * aliasRefExcept.setBar...(value); * <span style="color: #3F7E5E">// you don't need to set values of common columns</span> * <span style="color: #3F7E5E">//aliasRefExcept.setRegisterUser(value);</span> * <span style="color: #3F7E5E">//aliasRefExcept.set...;</span> * <span style="color: #0000C0">aliasRefExceptBhv</span>.<span style="color: #CC4747">insert</span>(aliasRefExcept); * ... = aliasRefExcept.getPK...(); <span style="color: #3F7E5E">// if auto-increment, you can get the value after</span> * </pre> * <p>While, when the entity is created by select, all columns are registered.</p> * @param aliasRefExcept The entity of insert. (NotNull, PrimaryKeyNullAllowed: when auto-increment) * @throws EntityAlreadyExistsException When the entity already exists. (unique constraint violation) */ public void insert(AliasRefExcept aliasRefExcept) { doInsert(aliasRefExcept, null); } /** * Update the entity modified-only. (ZeroUpdateException, NonExclusiveControl) <br> * By PK as default, and also you can update by unique keys using entity's uniqueOf(). * <pre> * AliasRefExcept aliasRefExcept = <span style="color: #70226C">new</span> AliasRefExcept(); * aliasRefExcept.setPK...(value); <span style="color: #3F7E5E">// required</span> * aliasRefExcept.setFoo...(value); <span style="color: #3F7E5E">// you should set only modified columns</span> * <span style="color: #3F7E5E">// you don't need to set values of common columns</span> * <span style="color: #3F7E5E">//aliasRefExcept.setRegisterUser(value);</span> * <span style="color: #3F7E5E">//aliasRefExcept.set...;</span> * <span style="color: #3F7E5E">// if exclusive control, the value of concurrency column is required</span> * aliasRefExcept.<span style="color: #CC4747">setVersionNo</span>(value); * <span style="color: #0000C0">aliasRefExceptBhv</span>.<span style="color: #CC4747">update</span>(aliasRefExcept); * </pre> * @param aliasRefExcept The entity of update. (NotNull, PrimaryKeyNotNull) * @throws EntityAlreadyDeletedException When the entity has already been deleted. (not found) * @throws EntityDuplicatedException When the entity has been duplicated. * @throws EntityAlreadyExistsException When the entity already exists. (unique constraint violation) */ public void update(AliasRefExcept aliasRefExcept) { doUpdate(aliasRefExcept, null); } /** * Insert or update the entity modified-only. (DefaultConstraintsEnabled, NonExclusiveControl) <br> * if (the entity has no PK) { insert() } else { update(), but no data, insert() } <br> * <p><span style="color: #994747; font-size: 120%">Also you can update by unique keys using entity's uniqueOf().</span></p> * @param aliasRefExcept The entity of insert or update. (NotNull, ...depends on insert or update) * @throws EntityAlreadyDeletedException When the entity has already been deleted. (not found) * @throws EntityDuplicatedException When the entity has been duplicated. * @throws EntityAlreadyExistsException When the entity already exists. (unique constraint violation) */ public void insertOrUpdate(AliasRefExcept aliasRefExcept) { doInsertOrUpdate(aliasRefExcept, null, null); } /** * Delete the entity. (ZeroUpdateException, NonExclusiveControl) <br> * By PK as default, and also you can delete by unique keys using entity's uniqueOf(). * <pre> * AliasRefExcept aliasRefExcept = <span style="color: #70226C">new</span> AliasRefExcept(); * aliasRefExcept.setPK...(value); <span style="color: #3F7E5E">// required</span> * <span style="color: #3F7E5E">// if exclusive control, the value of concurrency column is required</span> * aliasRefExcept.<span style="color: #CC4747">setVersionNo</span>(value); * <span style="color: #70226C">try</span> { * <span style="color: #0000C0">aliasRefExceptBhv</span>.<span style="color: #CC4747">delete</span>(aliasRefExcept); * } <span style="color: #70226C">catch</span> (EntityAlreadyUpdatedException e) { <span style="color: #3F7E5E">// if concurrent update</span> * ... * } * </pre> * @param aliasRefExcept The entity of delete. (NotNull, PrimaryKeyNotNull) * @throws EntityAlreadyDeletedException When the entity has already been deleted. (not found) * @throws EntityDuplicatedException When the entity has been duplicated. */ public void delete(AliasRefExcept aliasRefExcept) { doDelete(aliasRefExcept, null); } // =================================================================================== // Batch Update // ============ /** * Batch-insert the entity list modified-only of same-set columns. (DefaultConstraintsEnabled) <br> * This method uses executeBatch() of java.sql.PreparedStatement. <br> * <p><span style="color: #CC4747; font-size: 120%">The columns of least common multiple are registered like this:</span></p> * <pre> * <span style="color: #70226C">for</span> (... : ...) { * AliasRefExcept aliasRefExcept = <span style="color: #70226C">new</span> AliasRefExcept(); * aliasRefExcept.setFooName("foo"); * <span style="color: #70226C">if</span> (...) { * aliasRefExcept.setFooPrice(123); * } * <span style="color: #3F7E5E">// FOO_NAME and FOO_PRICE (and record meta columns) are registered</span> * <span style="color: #3F7E5E">// FOO_PRICE not-called in any entities are registered as null without default value</span> * <span style="color: #3F7E5E">// columns not-called in all entities are registered as null or default value</span> * aliasRefExceptList.add(aliasRefExcept); * } * <span style="color: #0000C0">aliasRefExceptBhv</span>.<span style="color: #CC4747">batchInsert</span>(aliasRefExceptList); * </pre> * <p>While, when the entities are created by select, all columns are registered.</p> * <p>And if the table has an identity, entities after the process don't have incremented values. * (When you use the (normal) insert(), you can get the incremented value from your entity)</p> * @param aliasRefExceptList The list of the entity. (NotNull, EmptyAllowed, PrimaryKeyNullAllowed: when auto-increment) * @return The array of inserted count. (NotNull, EmptyAllowed) */ public int[] batchInsert(List<AliasRefExcept> aliasRefExceptList) { return doBatchInsert(aliasRefExceptList, null); } /** * Batch-update the entity list modified-only of same-set columns. (NonExclusiveControl) <br> * This method uses executeBatch() of java.sql.PreparedStatement. <br> * <span style="color: #CC4747; font-size: 120%">You should specify same-set columns to all entities like this:</span> * <pre> * for (... : ...) { * AliasRefExcept aliasRefExcept = <span style="color: #70226C">new</span> AliasRefExcept(); * aliasRefExcept.setFooName("foo"); * <span style="color: #70226C">if</span> (...) { * aliasRefExcept.setFooPrice(123); * } <span style="color: #70226C">else</span> { * aliasRefExcept.setFooPrice(null); <span style="color: #3F7E5E">// updated as null</span> * <span style="color: #3F7E5E">//aliasRefExcept.setFooDate(...); // *not allowed, fragmented</span> * } * <span style="color: #3F7E5E">// FOO_NAME and FOO_PRICE (and record meta columns) are updated</span> * <span style="color: #3F7E5E">// (others are not updated: their values are kept)</span> * aliasRefExceptList.add(aliasRefExcept); * } * <span style="color: #0000C0">aliasRefExceptBhv</span>.<span style="color: #CC4747">batchUpdate</span>(aliasRefExceptList); * </pre> * @param aliasRefExceptList The list of the entity. (NotNull, EmptyAllowed, PrimaryKeyNotNull) * @return The array of updated count. (NotNull, EmptyAllowed) * @throws EntityAlreadyDeletedException When the entity has already been deleted. (not found) */ public int[] batchUpdate(List<AliasRefExcept> aliasRefExceptList) { return doBatchUpdate(aliasRefExceptList, null); } /** * Batch-delete the entity list. (NonExclusiveControl) <br> * This method uses executeBatch() of java.sql.PreparedStatement. * @param aliasRefExceptList The list of the entity. (NotNull, EmptyAllowed, PrimaryKeyNotNull) * @return The array of deleted count. (NotNull, EmptyAllowed) * @throws EntityAlreadyDeletedException When the entity has already been deleted. (not found) */ public int[] batchDelete(List<AliasRefExcept> aliasRefExceptList) { return doBatchDelete(aliasRefExceptList, null); } // =================================================================================== // Query Update // ============ /** * Insert the several entities by query (modified-only for fixed value). * <pre> * <span style="color: #0000C0">aliasRefExceptBhv</span>.<span style="color: #CC4747">queryInsert</span>(new QueryInsertSetupper&lt;AliasRefExcept, AliasRefExceptCB&gt;() { * public ConditionBean setup(AliasRefExcept entity, AliasRefExceptCB intoCB) { * FooCB cb = FooCB(); * cb.setupSelect_Bar(); * * <span style="color: #3F7E5E">// mapping</span> * intoCB.specify().columnMyName().mappedFrom(cb.specify().columnFooName()); * intoCB.specify().columnMyCount().mappedFrom(cb.specify().columnFooCount()); * intoCB.specify().columnMyDate().mappedFrom(cb.specify().specifyBar().columnBarDate()); * entity.setMyFixedValue("foo"); <span style="color: #3F7E5E">// fixed value</span> * <span style="color: #3F7E5E">// you don't need to set values of common columns</span> * <span style="color: #3F7E5E">//entity.setRegisterUser(value);</span> * <span style="color: #3F7E5E">//entity.set...;</span> * <span style="color: #3F7E5E">// you don't need to set a value of concurrency column</span> * <span style="color: #3F7E5E">//entity.setVersionNo(value);</span> * * return cb; * } * }); * </pre> * @param manyArgLambda The callback to set up query-insert. (NotNull) * @return The inserted count. */ public int queryInsert(QueryInsertSetupper<AliasRefExcept, AliasRefExceptCB> manyArgLambda) { return doQueryInsert(manyArgLambda, null); } /** * Update the several entities by query non-strictly modified-only. (NonExclusiveControl) * <pre> * AliasRefExcept aliasRefExcept = <span style="color: #70226C">new</span> AliasRefExcept(); * <span style="color: #3F7E5E">// you don't need to set PK value</span> * <span style="color: #3F7E5E">//aliasRefExcept.setPK...(value);</span> * aliasRefExcept.setFoo...(value); <span style="color: #3F7E5E">// you should set only modified columns</span> * <span style="color: #3F7E5E">// you don't need to set values of common columns</span> * <span style="color: #3F7E5E">//aliasRefExcept.setRegisterUser(value);</span> * <span style="color: #3F7E5E">//aliasRefExcept.set...;</span> * <span style="color: #3F7E5E">// you don't need to set a value of concurrency column</span> * <span style="color: #3F7E5E">// (auto-increment for version number is valid though non-exclusive control)</span> * <span style="color: #3F7E5E">//aliasRefExcept.setVersionNo(value);</span> * <span style="color: #0000C0">aliasRefExceptBhv</span>.<span style="color: #CC4747">queryUpdate</span>(aliasRefExcept, <span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().setFoo... * }); * </pre> * @param aliasRefExcept The entity that contains update values. (NotNull, PrimaryKeyNullAllowed) * @param cbLambda The callback for condition-bean of AliasRefExcept. (NotNull) * @return The updated count. * @throws NonQueryUpdateNotAllowedException When the query has no condition. */ public int queryUpdate(AliasRefExcept aliasRefExcept, CBCall<AliasRefExceptCB> cbLambda) { return doQueryUpdate(aliasRefExcept, createCB(cbLambda), null); } /** * Update the several entities by query non-strictly modified-only. (NonExclusiveControl) * <pre> * AliasRefExcept aliasRefExcept = <span style="color: #70226C">new</span> AliasRefExcept(); * <span style="color: #3F7E5E">// you don't need to set PK value</span> * <span style="color: #3F7E5E">//aliasRefExcept.setPK...(value);</span> * aliasRefExcept.setFoo...(value); <span style="color: #3F7E5E">// you should set only modified columns</span> * <span style="color: #3F7E5E">// you don't need to set values of common columns</span> * <span style="color: #3F7E5E">//aliasRefExcept.setRegisterUser(value);</span> * <span style="color: #3F7E5E">//aliasRefExcept.set...;</span> * <span style="color: #3F7E5E">// you don't need to set a value of concurrency column</span> * <span style="color: #3F7E5E">// (auto-increment for version number is valid though non-exclusive control)</span> * <span style="color: #3F7E5E">//aliasRefExcept.setVersionNo(value);</span> * AliasRefExceptCB cb = <span style="color: #70226C">new</span> AliasRefExceptCB(); * cb.query().setFoo...(value); * <span style="color: #0000C0">aliasRefExceptBhv</span>.<span style="color: #CC4747">queryUpdate</span>(aliasRefExcept, cb); * </pre> * @param aliasRefExcept The entity that contains update values. (NotNull, PrimaryKeyNullAllowed) * @param cb The condition-bean of AliasRefExcept. (NotNull) * @return The updated count. * @throws NonQueryUpdateNotAllowedException When the query has no condition. */ public int queryUpdate(AliasRefExcept aliasRefExcept, AliasRefExceptCB cb) { return doQueryUpdate(aliasRefExcept, cb, null); } /** * Delete the several entities by query. (NonExclusiveControl) * <pre> * <span style="color: #0000C0">aliasRefExceptBhv</span>.<span style="color: #CC4747">queryDelete</span>(aliasRefExcept, <span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().setFoo... * }); * </pre> * @param cbLambda The callback for condition-bean of AliasRefExcept. (NotNull) * @return The deleted count. * @throws NonQueryDeleteNotAllowedException When the query has no condition. */ public int queryDelete(CBCall<AliasRefExceptCB> cbLambda) { return doQueryDelete(createCB(cbLambda), null); } /** * Delete the several entities by query. (NonExclusiveControl) * <pre> * AliasRefExceptCB cb = new AliasRefExceptCB(); * cb.query().setFoo...(value); * <span style="color: #0000C0">aliasRefExceptBhv</span>.<span style="color: #CC4747">queryDelete</span>(aliasRefExcept, cb); * </pre> * @param cb The condition-bean of AliasRefExcept. (NotNull) * @return The deleted count. * @throws NonQueryDeleteNotAllowedException When the query has no condition. */ public int queryDelete(AliasRefExceptCB cb) { return doQueryDelete(cb, null); } // =================================================================================== // Varying Update // ============== // ----------------------------------------------------- // Entity Update // ------------- /** * Insert the entity with varying requests. <br> * For example, disableCommonColumnAutoSetup(), disablePrimaryKeyIdentity(). <br> * Other specifications are same as insert(entity). * <pre> * AliasRefExcept aliasRefExcept = <span style="color: #70226C">new</span> AliasRefExcept(); * <span style="color: #3F7E5E">// if auto-increment, you don't need to set the PK value</span> * aliasRefExcept.setFoo...(value); * aliasRefExcept.setBar...(value); * <span style="color: #0000C0">aliasRefExceptBhv</span>.<span style="color: #CC4747">varyingInsert</span>(aliasRefExcept, <span style="color: #553000">op</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #3F7E5E">// you can insert by your values for common columns</span> * <span style="color: #553000">op</span>.disableCommonColumnAutoSetup(); * }); * ... = aliasRefExcept.getPK...(); <span style="color: #3F7E5E">// if auto-increment, you can get the value after</span> * </pre> * @param aliasRefExcept The entity of insert. (NotNull, PrimaryKeyNullAllowed: when auto-increment) * @param opLambda The callback for option of insert for varying requests. (NotNull) * @throws EntityAlreadyExistsException When the entity already exists. (unique constraint violation) */ public void varyingInsert(AliasRefExcept aliasRefExcept, WritableOptionCall<AliasRefExceptCB, InsertOption<AliasRefExceptCB>> opLambda) { doInsert(aliasRefExcept, createInsertOption(opLambda)); } /** * Update the entity with varying requests modified-only. (ZeroUpdateException, NonExclusiveControl) <br> * For example, self(selfCalculationSpecification), specify(updateColumnSpecification), disableCommonColumnAutoSetup(). <br> * Other specifications are same as update(entity). * <pre> * AliasRefExcept aliasRefExcept = <span style="color: #70226C">new</span> AliasRefExcept(); * aliasRefExcept.setPK...(value); <span style="color: #3F7E5E">// required</span> * aliasRefExcept.setOther...(value); <span style="color: #3F7E5E">// you should set only modified columns</span> * <span style="color: #3F7E5E">// if exclusive control, the value of concurrency column is required</span> * aliasRefExcept.<span style="color: #CC4747">setVersionNo</span>(value); * <span style="color: #3F7E5E">// you can update by self calculation values</span> * <span style="color: #0000C0">aliasRefExceptBhv</span>.<span style="color: #CC4747">varyingUpdate</span>(aliasRefExcept, <span style="color: #553000">op</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">op</span>.self(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.specify().<span style="color: #CC4747">columnXxxCount()</span>; * }).plus(1); <span style="color: #3F7E5E">// XXX_COUNT = XXX_COUNT + 1</span> * }); * </pre> * @param aliasRefExcept The entity of update. (NotNull, PrimaryKeyNotNull) * @param opLambda The callback for option of update for varying requests. (NotNull) * @throws EntityAlreadyDeletedException When the entity has already been deleted. (not found) * @throws EntityDuplicatedException When the entity has been duplicated. * @throws EntityAlreadyExistsException When the entity already exists. (unique constraint violation) */ public void varyingUpdate(AliasRefExcept aliasRefExcept, WritableOptionCall<AliasRefExceptCB, UpdateOption<AliasRefExceptCB>> opLambda) { doUpdate(aliasRefExcept, createUpdateOption(opLambda)); } /** * Insert or update the entity with varying requests. (ExclusiveControl: when update) <br> * Other specifications are same as insertOrUpdate(entity). * @param aliasRefExcept The entity of insert or update. (NotNull) * @param insertOpLambda The callback for option of insert for varying requests. (NotNull) * @param updateOpLambda The callback for option of update for varying requests. (NotNull) * @throws EntityAlreadyDeletedException When the entity has already been deleted. (not found) * @throws EntityDuplicatedException When the entity has been duplicated. * @throws EntityAlreadyExistsException When the entity already exists. (unique constraint violation) */ public void varyingInsertOrUpdate(AliasRefExcept aliasRefExcept, WritableOptionCall<AliasRefExceptCB, InsertOption<AliasRefExceptCB>> insertOpLambda, WritableOptionCall<AliasRefExceptCB, UpdateOption<AliasRefExceptCB>> updateOpLambda) { doInsertOrUpdate(aliasRefExcept, createInsertOption(insertOpLambda), createUpdateOption(updateOpLambda)); } /** * Delete the entity with varying requests. (ZeroUpdateException, NonExclusiveControl) <br> * Now a valid option does not exist. <br> * Other specifications are same as delete(entity). * @param aliasRefExcept The entity of delete. (NotNull, PrimaryKeyNotNull, ConcurrencyColumnNotNull) * @param opLambda The callback for option of delete for varying requests. (NotNull) * @throws EntityAlreadyDeletedException When the entity has already been deleted. (not found) * @throws EntityDuplicatedException When the entity has been duplicated. */ public void varyingDelete(AliasRefExcept aliasRefExcept, WritableOptionCall<AliasRefExceptCB, DeleteOption<AliasRefExceptCB>> opLambda) { doDelete(aliasRefExcept, createDeleteOption(opLambda)); } // ----------------------------------------------------- // Batch Update // ------------ /** * Batch-insert the list with varying requests. <br> * For example, disableCommonColumnAutoSetup() * , disablePrimaryKeyIdentity(), limitBatchInsertLogging(). <br> * Other specifications are same as batchInsert(entityList). * @param aliasRefExceptList The list of the entity. (NotNull, EmptyAllowed, PrimaryKeyNotNull) * @param opLambda The callback for option of insert for varying requests. (NotNull) * @return The array of updated count. (NotNull, EmptyAllowed) */ public int[] varyingBatchInsert(List<AliasRefExcept> aliasRefExceptList, WritableOptionCall<AliasRefExceptCB, InsertOption<AliasRefExceptCB>> opLambda) { return doBatchInsert(aliasRefExceptList, createInsertOption(opLambda)); } /** * Batch-update the list with varying requests. <br> * For example, self(selfCalculationSpecification), specify(updateColumnSpecification) * , disableCommonColumnAutoSetup(), limitBatchUpdateLogging(). <br> * Other specifications are same as batchUpdate(entityList). * @param aliasRefExceptList The list of the entity. (NotNull, EmptyAllowed, PrimaryKeyNotNull) * @param opLambda The callback for option of update for varying requests. (NotNull) * @return The array of updated count. (NotNull, EmptyAllowed) */ public int[] varyingBatchUpdate(List<AliasRefExcept> aliasRefExceptList, WritableOptionCall<AliasRefExceptCB, UpdateOption<AliasRefExceptCB>> opLambda) { return doBatchUpdate(aliasRefExceptList, createUpdateOption(opLambda)); } /** * Batch-delete the list with varying requests. <br> * For example, limitBatchDeleteLogging(). <br> * Other specifications are same as batchDelete(entityList). * @param aliasRefExceptList The list of the entity. (NotNull, EmptyAllowed, PrimaryKeyNotNull) * @param opLambda The callback for option of delete for varying requests. (NotNull) * @return The array of deleted count. (NotNull, EmptyAllowed) */ public int[] varyingBatchDelete(List<AliasRefExcept> aliasRefExceptList, WritableOptionCall<AliasRefExceptCB, DeleteOption<AliasRefExceptCB>> opLambda) { return doBatchDelete(aliasRefExceptList, createDeleteOption(opLambda)); } // ----------------------------------------------------- // Query Update // ------------ /** * Insert the several entities by query with varying requests (modified-only for fixed value). <br> * For example, disableCommonColumnAutoSetup(), disablePrimaryKeyIdentity(). <br> * Other specifications are same as queryInsert(entity, setupper). * @param manyArgLambda The set-upper of query-insert. (NotNull) * @param opLambda The callback for option of insert for varying requests. (NotNull) * @return The inserted count. */ public int varyingQueryInsert(QueryInsertSetupper<AliasRefExcept, AliasRefExceptCB> manyArgLambda, WritableOptionCall<AliasRefExceptCB, InsertOption<AliasRefExceptCB>> opLambda) { return doQueryInsert(manyArgLambda, createInsertOption(opLambda)); } /** * Update the several entities by query with varying requests non-strictly modified-only. {NonExclusiveControl} <br> * For example, self(selfCalculationSpecification), specify(updateColumnSpecification) * , disableCommonColumnAutoSetup(), allowNonQueryUpdate(). <br> * Other specifications are same as queryUpdate(entity, cb). * <pre> * <span style="color: #3F7E5E">// ex) you can update by self calculation values</span> * AliasRefExcept aliasRefExcept = <span style="color: #70226C">new</span> AliasRefExcept(); * <span style="color: #3F7E5E">// you don't need to set PK value</span> * <span style="color: #3F7E5E">//aliasRefExcept.setPK...(value);</span> * aliasRefExcept.setOther...(value); <span style="color: #3F7E5E">// you should set only modified columns</span> * <span style="color: #3F7E5E">// you don't need to set a value of concurrency column</span> * <span style="color: #3F7E5E">// (auto-increment for version number is valid though non-exclusive control)</span> * <span style="color: #3F7E5E">//aliasRefExcept.setVersionNo(value);</span> * <span style="color: #0000C0">aliasRefExceptBhv</span>.<span style="color: #CC4747">varyingQueryUpdate</span>(aliasRefExcept, <span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().setFoo... * }, <span style="color: #553000">op</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">op</span>.self(<span style="color: #553000">colCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">colCB</span>.specify().<span style="color: #CC4747">columnFooCount()</span>; * }).plus(1); <span style="color: #3F7E5E">// FOO_COUNT = FOO_COUNT + 1</span> * }); * </pre> * @param aliasRefExcept The entity that contains update values. (NotNull) {PrimaryKeyNotRequired} * @param cbLambda The callback for condition-bean of AliasRefExcept. (NotNull) * @param opLambda The callback for option of update for varying requests. (NotNull) * @return The updated count. * @throws NonQueryUpdateNotAllowedException When the query has no condition (if not allowed). */ public int varyingQueryUpdate(AliasRefExcept aliasRefExcept, CBCall<AliasRefExceptCB> cbLambda, WritableOptionCall<AliasRefExceptCB, UpdateOption<AliasRefExceptCB>> opLambda) { return doQueryUpdate(aliasRefExcept, createCB(cbLambda), createUpdateOption(opLambda)); } /** * Update the several entities by query with varying requests non-strictly modified-only. {NonExclusiveControl} <br> * For example, self(selfCalculationSpecification), specify(updateColumnSpecification) * , disableCommonColumnAutoSetup(), allowNonQueryUpdate(). <br> * Other specifications are same as queryUpdate(entity, cb). * <pre> * <span style="color: #3F7E5E">// ex) you can update by self calculation values</span> * AliasRefExcept aliasRefExcept = <span style="color: #70226C">new</span> AliasRefExcept(); * <span style="color: #3F7E5E">// you don't need to set PK value</span> * <span style="color: #3F7E5E">//aliasRefExcept.setPK...(value);</span> * aliasRefExcept.setOther...(value); <span style="color: #3F7E5E">// you should set only modified columns</span> * <span style="color: #3F7E5E">// you don't need to set a value of concurrency column</span> * <span style="color: #3F7E5E">// (auto-increment for version number is valid though non-exclusive control)</span> * <span style="color: #3F7E5E">//aliasRefExcept.setVersionNo(value);</span> * AliasRefExceptCB cb = <span style="color: #70226C">new</span> AliasRefExceptCB(); * cb.query().setFoo...(value); * <span style="color: #0000C0">aliasRefExceptBhv</span>.<span style="color: #CC4747">varyingQueryUpdate</span>(aliasRefExcept, cb, <span style="color: #553000">op</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">op</span>.self(<span style="color: #553000">colCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">colCB</span>.specify().<span style="color: #CC4747">columnFooCount()</span>; * }).plus(1); <span style="color: #3F7E5E">// FOO_COUNT = FOO_COUNT + 1</span> * }); * </pre> * @param aliasRefExcept The entity that contains update values. (NotNull) {PrimaryKeyNotRequired} * @param cb The condition-bean of AliasRefExcept. (NotNull) * @param opLambda The callback for option of update for varying requests. (NotNull) * @return The updated count. * @throws NonQueryUpdateNotAllowedException When the query has no condition (if not allowed). */ public int varyingQueryUpdate(AliasRefExcept aliasRefExcept, AliasRefExceptCB cb, WritableOptionCall<AliasRefExceptCB, UpdateOption<AliasRefExceptCB>> opLambda) { return doQueryUpdate(aliasRefExcept, cb, createUpdateOption(opLambda)); } /** * Delete the several entities by query with varying requests non-strictly. <br> * For example, allowNonQueryDelete(). <br> * Other specifications are same as queryDelete(cb). * <pre> * <span style="color: #0000C0">aliasRefExceptBhv</span>.<span style="color: #CC4747">queryDelete</span>(aliasRefExcept, <span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().setFoo... * }, <span style="color: #553000">op</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">op</span>... * }); * </pre> * @param cbLambda The callback for condition-bean of AliasRefExcept. (NotNull) * @param opLambda The callback for option of delete for varying requests. (NotNull) * @return The deleted count. * @throws NonQueryDeleteNotAllowedException When the query has no condition (if not allowed). */ public int varyingQueryDelete(CBCall<AliasRefExceptCB> cbLambda, WritableOptionCall<AliasRefExceptCB, DeleteOption<AliasRefExceptCB>> opLambda) { return doQueryDelete(createCB(cbLambda), createDeleteOption(opLambda)); } /** * Delete the several entities by query with varying requests non-strictly. <br> * For example, allowNonQueryDelete(). <br> * Other specifications are same as queryDelete(cb). * @param cb The condition-bean of AliasRefExcept. (NotNull) * @param opLambda The callback for option of delete for varying requests. (NotNull) * @return The deleted count. * @throws NonQueryDeleteNotAllowedException When the query has no condition (if not allowed). */ public int varyingQueryDelete(AliasRefExceptCB cb, WritableOptionCall<AliasRefExceptCB, DeleteOption<AliasRefExceptCB>> opLambda) { return doQueryDelete(cb, createDeleteOption(opLambda)); } // =================================================================================== // OutsideSql // ========== /** * Prepare the all facade executor of outside-SQL to execute it. * <pre> * <span style="color: #3F7E5E">// main style</span> * aliasRefExceptBhv.outideSql().selectEntity(pmb); <span style="color: #3F7E5E">// optional</span> * aliasRefExceptBhv.outideSql().selectList(pmb); <span style="color: #3F7E5E">// ListResultBean</span> * aliasRefExceptBhv.outideSql().selectPage(pmb); <span style="color: #3F7E5E">// PagingResultBean</span> * aliasRefExceptBhv.outideSql().selectPagedListOnly(pmb); <span style="color: #3F7E5E">// ListResultBean</span> * aliasRefExceptBhv.outideSql().selectCursor(pmb, handler); <span style="color: #3F7E5E">// (by handler)</span> * aliasRefExceptBhv.outideSql().execute(pmb); <span style="color: #3F7E5E">// int (updated count)</span> * aliasRefExceptBhv.outideSql().call(pmb); <span style="color: #3F7E5E">// void (pmb has OUT parameters)</span> * * <span style="color: #3F7E5E">// traditional style</span> * aliasRefExceptBhv.outideSql().traditionalStyle().selectEntity(path, pmb, entityType); * aliasRefExceptBhv.outideSql().traditionalStyle().selectList(path, pmb, entityType); * aliasRefExceptBhv.outideSql().traditionalStyle().selectPage(path, pmb, entityType); * aliasRefExceptBhv.outideSql().traditionalStyle().selectPagedListOnly(path, pmb, entityType); * aliasRefExceptBhv.outideSql().traditionalStyle().selectCursor(path, pmb, handler); * aliasRefExceptBhv.outideSql().traditionalStyle().execute(path, pmb); * * <span style="color: #3F7E5E">// options</span> * aliasRefExceptBhv.outideSql().removeBlockComment().selectList() * aliasRefExceptBhv.outideSql().removeLineComment().selectList() * aliasRefExceptBhv.outideSql().formatSql().selectList() * </pre> * <p>The invoker of behavior command should be not null when you call this method.</p> * @return The new-created all facade executor of outside-SQL. (NotNull) */ public OutsideSqlBasicExecutor<AliasRefExceptBhv> outsideSql() { OutsideSqlAllFacadeExecutor<AliasRefExceptBhv> facadeExecutor = doOutsideSql(); return facadeExecutor.xbasicExecutor(); // variable to resolve generic type } // =================================================================================== // Type Helper // =========== protected Class<? extends AliasRefExcept> typeOfSelectedEntity() { return AliasRefExcept.class; } protected Class<AliasRefExcept> typeOfHandlingEntity() { return AliasRefExcept.class; } protected Class<AliasRefExceptCB> typeOfHandlingConditionBean() { return AliasRefExceptCB.class; } }
apache-2.0
mhlx/blog5
src/main/java/me/qyh/blog/plugin/staticfile/validator/StaticFileQueryParamValidator.java
1679
/* * Copyright 2016 qyh.me * * 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 me.qyh.blog.plugin.staticfile.validator; import java.util.stream.Collectors; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import me.qyh.blog.plugin.staticfile.vo.StaticFileQueryParam; @Component public class StaticFileQueryParamValidator implements Validator { private static final int MAX_NAME_LENGTH = 20; private static final int MAX_EXTENSION_LENGTH = 5; @Override public boolean supports(Class<?> clazz) { return StaticFileQueryParam.class.isAssignableFrom(clazz); } @Override public void validate(Object target, Errors errors) { StaticFileQueryParam param = (StaticFileQueryParam) target; if (param.getCurrentPage() < 1) { param.setCurrentPage(1); } String name = param.getName(); if (name != null && name.length() > MAX_NAME_LENGTH) { param.setName(name.substring(0, MAX_NAME_LENGTH)); } // 最多只允许 5 个后缀 param.setExtensions(param.getExtensions().stream().limit(MAX_EXTENSION_LENGTH).collect(Collectors.toSet())); } }
apache-2.0
bzixilu/dotplugin
src/org/plugin/dot/DotRefactoringSupportProvider.java
933
package org.plugin.dot; import com.intellij.lang.refactoring.RefactoringSupportProvider; import com.intellij.psi.PsiElement; import org.plugin.dot.psi.DotId; /** * Class defines the refactoring support features which can be used in dot language files. * At the moment the only DotIDs renaming is supported refactoring feature dot language files * This can be changed in future. */ public class DotRefactoringSupportProvider extends RefactoringSupportProvider { /** * The method checks whether provided element is to be renamed or not. * Only DotId elements are expected to be renamed at the moment. * This rule can be extended in future. * @param element for refactoring * @param context for refactoring * @return whether element is to be renamed or not */ @Override public boolean isMemberInplaceRenameAvailable(PsiElement element, PsiElement context) { return element instanceof DotId; } }
apache-2.0
JoelMarcey/buck
src-gen/com/facebook/buck/artifact_cache/thrift/BuckCacheRequestType.java
1237
/** * Autogenerated by Thrift Compiler (0.12.0) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package com.facebook.buck.artifact_cache.thrift; @javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.12.0)") public enum BuckCacheRequestType implements org.apache.thrift.TEnum { UNKNOWN(0), FETCH(100), STORE(101), MULTI_FETCH(102), DELETE_REQUEST(105), CONTAINS(107); private final int value; private BuckCacheRequestType(int value) { this.value = value; } /** * Get the integer value of this enum value, as defined in the Thrift IDL. */ public int getValue() { return value; } /** * Find a the enum type by its integer value, as defined in the Thrift IDL. * @return null if the value is not found. */ @org.apache.thrift.annotation.Nullable public static BuckCacheRequestType findByValue(int value) { switch (value) { case 0: return UNKNOWN; case 100: return FETCH; case 101: return STORE; case 102: return MULTI_FETCH; case 105: return DELETE_REQUEST; case 107: return CONTAINS; default: return null; } } }
apache-2.0
JIGAsoftSTP/NICON
src/java/mensagem/Mensagem.java
1243
package mensagem; import javax.faces.application.FacesMessage; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.faces.context.Flash; /** * * @author Helcio */ public class Mensagem { public static void addInfoMsg(String mensagem) { FacesContext facesContext = FacesContext.getCurrentInstance(); FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_INFO, mensagem, mensagem); FacesContext context = FacesContext.getCurrentInstance(); context.addMessage(null, fm); } public static void addErrorMsg(String mensagem) { FacesContext facesContext = FacesContext.getCurrentInstance(); FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_ERROR, mensagem, mensagem); FacesContext context = FacesContext.getCurrentInstance(); context.addMessage(null, fm); } public static void addWarningMsg(String mensagem) { FacesContext facesContext = FacesContext.getCurrentInstance(); FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_WARN, mensagem, mensagem); FacesContext context = FacesContext.getCurrentInstance(); context.addMessage(null, fm); } }
apache-2.0
lestard/EasyDI
src/test/java/eu/lestard/easydi/InstanceProviderTest.java
1834
package eu.lestard.easydi; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import javax.inject.Singleton; import static org.assertj.core.api.Assertions.assertThat; /** * This test is used to show how one can get an universal provider of instances without * directly injecting the EasyDI context itself. */ @DisplayName("InstanceProvider as alternative to context-injection") class InstanceProviderTest { public interface InstanceProvider { <T> T getInstance(Class<T> type); } public static class Example { } @Singleton public static class SingletonExample { } private EasyDI context; @BeforeEach void setup() { context = new EasyDI(); } @Test @DisplayName("InstanceProvider works for normal class") void success_instanceProvider() { context.bindProvider(InstanceProvider.class, () -> context::getInstance); final InstanceProvider provider = context.getInstance(InstanceProvider.class); final Example example = provider.getInstance(Example.class); assertThat(example).isNotNull(); } @Test @DisplayName("InstanceProvider works for singletons") void success_singleton() { context.bindProvider(InstanceProvider.class, () -> context::getInstance); final InstanceProvider provider = context.getInstance(InstanceProvider.class); final SingletonExample singleton1 = provider.getInstance(SingletonExample.class); final SingletonExample singleton2 = provider.getInstance(SingletonExample.class); final SingletonExample singleton3 = context.getInstance(SingletonExample.class); assertThat(singleton1).isSameAs(singleton2); assertThat(singleton2).isSameAs(singleton3); } }
apache-2.0
MOBX/Thor
thor-rpc/src/main/java/com/mob/thor/rpc/remoting/api/telnet/support/command/ExitTelnetHandler.java
568
package com.mob.thor.rpc.remoting.api.telnet.support.command; import com.mob.thor.rpc.common.extension.Activate; import com.mob.thor.rpc.remoting.api.ThorChannel; import com.mob.thor.rpc.remoting.api.telnet.TelnetHandler; import com.mob.thor.rpc.remoting.api.telnet.support.Help; @Activate @Help(parameter = "", summary = "Exit the telnet.", detail = "Exit the telnet.") public class ExitTelnetHandler implements TelnetHandler { public String telnet(ThorChannel channel, String message) { channel.close(); return null; } }
apache-2.0
vivitas/hashdb
src/hashdb/storage/protocol/internal/InternalProtocol.java
451
package hashdb.storage.protocol.internal; import hashdb.storage.entities.fields.EntryKeyLink; /** * The Interface InternalProtocol. */ public interface InternalProtocol { int getFirstPosition(EntryKeyLink key); int getNextPosition(EntryKeyLink key, int previous); int getNthPosition(EntryKeyLink key, int n); int getFirstPosition(byte[] key); int getNextPosition(byte[] key, int previous); int getNthPosition(byte[] key, int n); }
apache-2.0
fabric8io/kubernetes-client
kubernetes-model-generator/kubernetes-model-core/src/generated/java/io/fabric8/kubernetes/api/model/EmptyDirVolumeSource.java
2472
package io.fabric8.kubernetes.api.model; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import io.sundr.builder.annotations.Buildable; import lombok.EqualsAndHashCode; import lombok.Setter; import lombok.ToString; import lombok.experimental.Accessors; @JsonDeserialize(using = com.fasterxml.jackson.databind.JsonDeserializer.None.class) @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "apiVersion", "kind", "metadata", "medium", "sizeLimit" }) @ToString @EqualsAndHashCode @Setter @Accessors(prefix = { "_", "" }) @Buildable(editableEnabled = false, validationEnabled = false, generateBuilderPackage = true, lazyCollectionInitEnabled = false, builderPackage = "io.fabric8.kubernetes.api.builder") public class EmptyDirVolumeSource implements KubernetesResource { @JsonProperty("medium") private String medium; @JsonProperty("sizeLimit") private Quantity sizeLimit; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); /** * No args constructor for use in serialization * */ public EmptyDirVolumeSource() { } /** * * @param sizeLimit * @param medium */ public EmptyDirVolumeSource(String medium, Quantity sizeLimit) { super(); this.medium = medium; this.sizeLimit = sizeLimit; } @JsonProperty("medium") public String getMedium() { return medium; } @JsonProperty("medium") public void setMedium(String medium) { this.medium = medium; } @JsonProperty("sizeLimit") public Quantity getSizeLimit() { return sizeLimit; } @JsonProperty("sizeLimit") public void setSizeLimit(Quantity sizeLimit) { this.sizeLimit = sizeLimit; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } }
apache-2.0
taegeonum/incubator-reef
lang/java/reef-wake/wake/src/test/java/org/apache/reef/wake/test/examples/TestJoin.java
1484
/* * 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.reef.wake.test.examples; import org.apache.reef.wake.examples.join.EventPrinter; import org.apache.reef.wake.examples.join.NonBlockingJoin; import org.apache.reef.wake.examples.join.TupleEvent; import org.apache.reef.wake.examples.join.TupleSource; import org.junit.Test; public class TestJoin { @Test public void testJoin() throws Exception { EventPrinter<TupleEvent> printer = new EventPrinter<>(); NonBlockingJoin join = new NonBlockingJoin(printer); TupleSource left = new TupleSource(join.wireLeft(), 256, 8, true); TupleSource right = new TupleSource(join.wireRight(), 256, 8, false); left.close(); right.close(); } }
apache-2.0
adbrucker/SecureBPMN
designer/src/org.activiti.designer.model/src/main/java/org/eclipse/bpmn2/DataOutput.java
5908
/** * <copyright> * * Copyright (c) 2010 SAP AG. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Reiner Hille-Doering (SAP AG) - initial API and implementation and/or initial documentation * * </copyright> */ package org.eclipse.bpmn2; import java.util.List; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Data Output</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link org.eclipse.bpmn2.DataOutput#getOutputSetWithOptional <em>Output Set With Optional</em>}</li> * <li>{@link org.eclipse.bpmn2.DataOutput#getOutputSetWithWhileExecuting <em>Output Set With While Executing</em>}</li> * <li>{@link org.eclipse.bpmn2.DataOutput#getOutputSetRefs <em>Output Set Refs</em>}</li> * <li>{@link org.eclipse.bpmn2.DataOutput#isIsCollection <em>Is Collection</em>}</li> * <li>{@link org.eclipse.bpmn2.DataOutput#getName <em>Name</em>}</li> * </ul> * </p> * * @see org.eclipse.bpmn2.Bpmn2Package#getDataOutput() * @model extendedMetaData="name='tDataOutput' kind='elementOnly'" * @generated */ public interface DataOutput extends ItemAwareElement { /** * Returns the value of the '<em><b>Output Set With Optional</b></em>' reference list. * The list contents are of type {@link org.eclipse.bpmn2.OutputSet}. * It is bidirectional and its opposite is '{@link org.eclipse.bpmn2.OutputSet#getOptionalOutputRefs <em>Optional Output Refs</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Output Set With Optional</em>' reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Output Set With Optional</em>' reference list. * @see org.eclipse.bpmn2.Bpmn2Package#getDataOutput_OutputSetWithOptional() * @see org.eclipse.bpmn2.OutputSet#getOptionalOutputRefs * @model opposite="optionalOutputRefs" transient="true" derived="true" ordered="false" * @generated */ List<OutputSet> getOutputSetWithOptional(); /** * Returns the value of the '<em><b>Output Set With While Executing</b></em>' reference list. * The list contents are of type {@link org.eclipse.bpmn2.OutputSet}. * It is bidirectional and its opposite is '{@link org.eclipse.bpmn2.OutputSet#getWhileExecutingOutputRefs <em>While Executing Output Refs</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Output Set With While Executing</em>' reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Output Set With While Executing</em>' reference list. * @see org.eclipse.bpmn2.Bpmn2Package#getDataOutput_OutputSetWithWhileExecuting() * @see org.eclipse.bpmn2.OutputSet#getWhileExecutingOutputRefs * @model opposite="whileExecutingOutputRefs" transient="true" derived="true" ordered="false" * @generated */ List<OutputSet> getOutputSetWithWhileExecuting(); /** * Returns the value of the '<em><b>Output Set Refs</b></em>' reference list. * The list contents are of type {@link org.eclipse.bpmn2.OutputSet}. * It is bidirectional and its opposite is '{@link org.eclipse.bpmn2.OutputSet#getDataOutputRefs <em>Data Output Refs</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Output Set Refs</em>' reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Output Set Refs</em>' reference list. * @see org.eclipse.bpmn2.Bpmn2Package#getDataOutput_OutputSetRefs() * @see org.eclipse.bpmn2.OutputSet#getDataOutputRefs * @model opposite="dataOutputRefs" required="true" transient="true" derived="true" ordered="false" * @generated */ List<OutputSet> getOutputSetRefs(); /** * Returns the value of the '<em><b>Is Collection</b></em>' attribute. * The default value is <code>"false"</code>. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Is Collection</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Is Collection</em>' attribute. * @see #setIsCollection(boolean) * @see org.eclipse.bpmn2.Bpmn2Package#getDataOutput_IsCollection() * @model default="false" required="true" ordered="false" * extendedMetaData="kind='attribute' name='isCollection'" * @generated */ boolean isIsCollection(); /** * Sets the value of the '{@link org.eclipse.bpmn2.DataOutput#isIsCollection <em>Is Collection</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Is Collection</em>' attribute. * @see #isIsCollection() * @generated */ void setIsCollection(boolean value); /** * Returns the value of the '<em><b>Name</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Name</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Name</em>' attribute. * @see #setName(String) * @see org.eclipse.bpmn2.Bpmn2Package#getDataOutput_Name() * @model ordered="false" * extendedMetaData="kind='attribute' name='name'" * @generated */ String getName(); /** * Sets the value of the '{@link org.eclipse.bpmn2.DataOutput#getName <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Name</em>' attribute. * @see #getName() * @generated */ void setName(String value); } // DataOutput
apache-2.0
NationalSecurityAgency/ghidra
Ghidra/Debug/ProposedUtils/src/main/java/generic/depends/DependentService.java
846
/* ### * 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 generic.depends; import java.lang.annotation.*; @Target({ ElementType.METHOD, ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) public @interface DependentService { Class<?> override() default Sentinel.class; enum Sentinel { // None } }
apache-2.0
omindra/schema_org_java_api
core_with_extensions/src/main/java/org/schema/api/model/thing/intangible/Language.java
2268
package org.schema.api.model.thing.intangible; import org.schema.api.model.thing.action.Action; public class Language extends Intangible { private String additionalType; private String alternateName; private String description; private String disambiguatingDescription; private String identifier;//Notes - Allowed types- [PropertyValue, Text, URL] private String image;//Notes - Allowed types- [ImageObject, URL] private String mainEntityOfPage;//Notes - Allowed types- [CreativeWork, URL, mainEntity] private String name; private Action potentialAction; private String sameAs; private String url; public String getAdditionalType() { return additionalType; } public void setAdditionalType(String additionalType) { this.additionalType = additionalType; } public String getAlternateName() { return alternateName; } public void setAlternateName(String alternateName) { this.alternateName = alternateName; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getDisambiguatingDescription() { return disambiguatingDescription; } public void setDisambiguatingDescription(String disambiguatingDescription) { this.disambiguatingDescription = disambiguatingDescription; } public String getIdentifier() { return identifier; } public void setIdentifier(String identifier) { this.identifier = identifier; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getMainEntityOfPage() { return mainEntityOfPage; } public void setMainEntityOfPage(String mainEntityOfPage) { this.mainEntityOfPage = mainEntityOfPage; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Action getPotentialAction() { return potentialAction; } public void setPotentialAction(Action potentialAction) { this.potentialAction = potentialAction; } public String getSameAs() { return sameAs; } public void setSameAs(String sameAs) { this.sameAs = sameAs; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
apache-2.0
eddumelendez/spring-security
config/src/main/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.java
8810
/* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.config.annotation.web.configuration; import java.util.List; import java.util.Map; import javax.servlet.Filter; import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; import org.springframework.context.annotation.ImportAware; import org.springframework.core.OrderComparator; import org.springframework.core.Ordered; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.core.annotation.Order; import org.springframework.core.type.AnnotationMetadata; import org.springframework.security.access.expression.SecurityExpressionHandler; import org.springframework.security.config.annotation.ObjectPostProcessor; import org.springframework.security.config.annotation.SecurityConfigurer; import org.springframework.security.config.annotation.web.WebSecurityConfigurer; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.crypto.RsaKeyConversionServicePostProcessor; import org.springframework.security.context.DelegatingApplicationListener; import org.springframework.security.web.FilterChainProxy; import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.access.WebInvocationPrivilegeEvaluator; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; /** * Uses a {@link WebSecurity} to create the {@link FilterChainProxy} that performs the web * based security for Spring Security. It then exports the necessary beans. Customizations * can be made to {@link WebSecurity} by extending {@link WebSecurityConfigurerAdapter} * and exposing it as a {@link Configuration} or implementing * {@link WebSecurityConfigurer} and exposing it as a {@link Configuration}. This * configuration is imported when using {@link EnableWebSecurity}. * * @see EnableWebSecurity * @see WebSecurity * * @author Rob Winch * @author Keesun Baik * @since 3.2 */ @Configuration(proxyBeanMethods = false) public class WebSecurityConfiguration implements ImportAware, BeanClassLoaderAware { private WebSecurity webSecurity; private Boolean debugEnabled; private List<SecurityConfigurer<Filter, WebSecurity>> webSecurityConfigurers; private ClassLoader beanClassLoader; @Autowired(required = false) private ObjectPostProcessor<Object> objectObjectPostProcessor; @Bean public static DelegatingApplicationListener delegatingApplicationListener() { return new DelegatingApplicationListener(); } @Bean @DependsOn(AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME) public SecurityExpressionHandler<FilterInvocation> webSecurityExpressionHandler() { return webSecurity.getExpressionHandler(); } /** * Creates the Spring Security Filter Chain * @return the {@link Filter} that represents the security filter chain * @throws Exception */ @Bean(name = AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME) public Filter springSecurityFilterChain() throws Exception { boolean hasConfigurers = webSecurityConfigurers != null && !webSecurityConfigurers.isEmpty(); if (!hasConfigurers) { WebSecurityConfigurerAdapter adapter = objectObjectPostProcessor .postProcess(new WebSecurityConfigurerAdapter() { }); webSecurity.apply(adapter); } return webSecurity.build(); } /** * Creates the {@link WebInvocationPrivilegeEvaluator} that is necessary for the JSP * tag support. * @return the {@link WebInvocationPrivilegeEvaluator} * @throws Exception */ @Bean @DependsOn(AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME) public WebInvocationPrivilegeEvaluator privilegeEvaluator() throws Exception { return webSecurity.getPrivilegeEvaluator(); } /** * Sets the {@code <SecurityConfigurer<FilterChainProxy, WebSecurityBuilder>} * instances used to create the web configuration. * * @param objectPostProcessor the {@link ObjectPostProcessor} used to create a * {@link WebSecurity} instance * @param webSecurityConfigurers the * {@code <SecurityConfigurer<FilterChainProxy, WebSecurityBuilder>} instances used to * create the web configuration * @throws Exception */ @Autowired(required = false) public void setFilterChainProxySecurityConfigurer( ObjectPostProcessor<Object> objectPostProcessor, @Value("#{@autowiredWebSecurityConfigurersIgnoreParents.getWebSecurityConfigurers()}") List<SecurityConfigurer<Filter, WebSecurity>> webSecurityConfigurers) throws Exception { webSecurity = objectPostProcessor .postProcess(new WebSecurity(objectPostProcessor)); if (debugEnabled != null) { webSecurity.debug(debugEnabled); } webSecurityConfigurers.sort(AnnotationAwareOrderComparator.INSTANCE); Integer previousOrder = null; Object previousConfig = null; for (SecurityConfigurer<Filter, WebSecurity> config : webSecurityConfigurers) { Integer order = AnnotationAwareOrderComparator.lookupOrder(config); if (previousOrder != null && previousOrder.equals(order)) { throw new IllegalStateException( "@Order on WebSecurityConfigurers must be unique. Order of " + order + " was already used on " + previousConfig + ", so it cannot be used on " + config + " too."); } previousOrder = order; previousConfig = config; } for (SecurityConfigurer<Filter, WebSecurity> webSecurityConfigurer : webSecurityConfigurers) { webSecurity.apply(webSecurityConfigurer); } this.webSecurityConfigurers = webSecurityConfigurers; } @Bean public static BeanFactoryPostProcessor conversionServicePostProcessor() { return new RsaKeyConversionServicePostProcessor(); } @Bean public static AutowiredWebSecurityConfigurersIgnoreParents autowiredWebSecurityConfigurersIgnoreParents( ConfigurableListableBeanFactory beanFactory) { return new AutowiredWebSecurityConfigurersIgnoreParents(beanFactory); } /** * A custom verision of the Spring provided AnnotationAwareOrderComparator that uses * {@link AnnotationUtils#findAnnotation(Class, Class)} to look on super class * instances for the {@link Order} annotation. * * @author Rob Winch * @since 3.2 */ private static class AnnotationAwareOrderComparator extends OrderComparator { private static final AnnotationAwareOrderComparator INSTANCE = new AnnotationAwareOrderComparator(); @Override protected int getOrder(Object obj) { return lookupOrder(obj); } private static int lookupOrder(Object obj) { if (obj instanceof Ordered) { return ((Ordered) obj).getOrder(); } if (obj != null) { Class<?> clazz = (obj instanceof Class ? (Class<?>) obj : obj.getClass()); Order order = AnnotationUtils.findAnnotation(clazz, Order.class); if (order != null) { return order.value(); } } return Ordered.LOWEST_PRECEDENCE; } } /* * (non-Javadoc) * * @see org.springframework.context.annotation.ImportAware#setImportMetadata(org. * springframework.core.type.AnnotationMetadata) */ public void setImportMetadata(AnnotationMetadata importMetadata) { Map<String, Object> enableWebSecurityAttrMap = importMetadata .getAnnotationAttributes(EnableWebSecurity.class.getName()); AnnotationAttributes enableWebSecurityAttrs = AnnotationAttributes .fromMap(enableWebSecurityAttrMap); debugEnabled = enableWebSecurityAttrs.getBoolean("debug"); if (webSecurity != null) { webSecurity.debug(debugEnabled); } } /* * (non-Javadoc) * * @see * org.springframework.beans.factory.BeanClassLoaderAware#setBeanClassLoader(java. * lang.ClassLoader) */ public void setBeanClassLoader(ClassLoader classLoader) { this.beanClassLoader = classLoader; } }
apache-2.0
Doun2017/StudyCode
DatabaseTest/app/src/main/java/com/example/power/databasetest/MyDatabaseHelper.java
1444
package com.example.power.databasetest; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.widget.Toast; /** * Created by power on 2017/1/4. */ public class MyDatabaseHelper extends SQLiteOpenHelper { public static final String CREATE_BOOK = "create table Book (" + "id integer primary key autoincrement, " + "author text, " + "price real, " + "pages integer, " + "name text)"; public static final String CREATE_CATEGORY = "create table Category (" + "id integer primary key autoincrement, " + "category_name text, " + "category_code integer)"; private Context mContext; public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); mContext = context; } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_BOOK); db.execSQL(CREATE_CATEGORY); Toast.makeText(mContext, "create succeeded", Toast.LENGTH_SHORT).show(); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("drop table if exists Book"); db.execSQL("drop table if exists Category"); onCreate(db); } }
apache-2.0
NoExceptionwgl/PanadaTV
app/src/main/java/com/qf/administrator/xiongmao/ui/fragments/homefragments/PandaFragment.java
4381
package com.qf.administrator.xiongmao.ui.fragments.homefragments; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.google.gson.Gson; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.qf.administrator.xiongmao.R; import com.qf.administrator.xiongmao.adapters.homepandadapter.PandaAdapter; import com.qf.administrator.xiongmao.models.homemodel.PandaModel; import com.qf.administrator.xiongmao.ui.fragments.BaseFragment; import com.qf.administrator.xiongmao.ui.gameactivitys.GameItemTwoActivity; import com.qf.administrator.xiongmao.util.PullToRefreshRecyclerView; import org.xutils.common.Callback; import org.xutils.http.RequestParams; import org.xutils.x; import java.net.URL; import java.util.List; /** * 熊猫星宿 */ public class PandaFragment extends BaseFragment implements PullToRefreshBase.OnRefreshListener2, PandaAdapter.OnClickListener { public static final String TAG = PandaFragment.class.getSimpleName(); private PullToRefreshRecyclerView mRecyclerView; private GridLayoutManager mGrid; private int pageno = 1; private String URL = "http://api.m.panda.tv/ajax_get_live_list_by_cate?cate=yzdr&pageno=" + pageno + "&pagenum=20&sproom=1&__version=1.2.0.1441&__plat=android&banner=1"; private PandaAdapter adapter; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { layout = inflater.inflate(R.layout.fragment_panda, container, false); return layout; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initView(); setUpView(State.DOWN); } @Override public void onItemListener(int position) { Intent intent = new Intent(getActivity(), GameItemTwoActivity.class); startActivity(intent); } enum State { DOWN, UP } private void setUpView(final State state) { final RequestParams requestParams = new RequestParams(URL); x.http().get(requestParams, new Callback.CommonCallback<String>() { @Override public void onSuccess(String result) { Log.e(TAG, "onSuccess: " + result); Gson gson = new Gson(); PandaModel pandaModel = gson.fromJson(result, PandaModel.class); List<PandaModel.DataBean.ItemsBean> items = pandaModel.getData().getItems(); switch (state) { case DOWN: adapter.setDataRes(items); break; case UP: adapter.addDataRes(items); break; } } @Override public void onError(Throwable ex, boolean isOnCallback) { Log.e(TAG, "onError: "); } @Override public void onCancelled(CancelledException cex) { Log.e(TAG, "onCancelled: "); } @Override public void onFinished() { Log.e(TAG, "onFinished: "); mRecyclerView.onRefreshComplete(); } }); } private void initView() { mRecyclerView = ((PullToRefreshRecyclerView) layout.findViewById(R.id.panda_recyclerview)); mRecyclerView.setMode(PullToRefreshBase.Mode.BOTH); mRecyclerView.setOnRefreshListener(this); RecyclerView refreshableView = mRecyclerView.getRefreshableView(); mGrid = new GridLayoutManager(getActivity(), 2); refreshableView.setLayoutManager(mGrid); adapter = new PandaAdapter(getActivity(),null); adapter.setListener(this); refreshableView.setAdapter(adapter); } @Override public void onPullDownToRefresh(PullToRefreshBase refreshView) { pageno = 1; setUpView(State.DOWN); } @Override public void onPullUpToRefresh(PullToRefreshBase refreshView) { pageno++; setUpView(State.UP); } }
apache-2.0
reidwang/-mpsdk4j
src/main/java/org/elkan1788/osc/weixin/mp/vo/BaseMsg.java
2884
package org.elkan1788.osc.weixin.mp.vo; /** * 微信消息实体基类 * * @author 凡梦星尘(senhuili@mdc.cn) * @since 2014/11/7 * @version 1.0.0 */ public abstract class BaseMsg { /** * 消息唯一ID(64位整型) */ protected long msgId; /** * 消息创建时间 (整型) */ protected long createTime; /** * 消息类型(text, image, video, voice, location, link,event) */ protected String msgType; /** * 消息事件: * subscribe:订阅 * unsubscribe:取消订阅 * SCAN:关注后场景扫描 * LOCATION:主动上传位置 * VIEW,CLICK:菜单点击事件 * TEMPLATESENDJOBFINISH:模板消息推送 */ protected String event; /** * 接收消息用户ID */ protected String toUserName; /** * 消息来自用户ID */ protected String fromUserName; /** * 文本消息内容 */ protected String content; /** * 多媒体消息ID(微信服务器有效时间为3天) */ protected String mediaId; /** * 链接,文章消息标题 */ protected String title; /** * 详细描述 */ protected String description; /** * 视频消息缩略图的媒体id */ protected String thumbMediaId; public long getMsgId() { return msgId; } public void setMsgId(long msgId) { this.msgId = msgId; } public long getCreateTime() { return createTime; } public void setCreateTime(long createTime) { this.createTime = createTime; } public String getMsgType() { return msgType; } public void setMsgType(String msgType) { this.msgType = msgType; } public String getEvent() { return event; } public void setEvent(String event) { this.event = event; } public String getToUserName() { return toUserName; } public void setToUserName(String toUserName) { this.toUserName = toUserName; } public String getFromUserName() { return fromUserName; } public void setFromUserName(String fromUserName) { this.fromUserName = fromUserName; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getMediaId() { return mediaId; } public void setMediaId(String mediaId) { this.mediaId = mediaId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getThumbMediaId() { return thumbMediaId; } public void setThumbMediaId(String thumbMediaId) { this.thumbMediaId = thumbMediaId; } }
apache-2.0
xloye/tddl5
tddl-sample/src/main/java/com/taobao/tddl/sample/Simba2Sample.java
2841
package com.taobao.tddl.sample; import java.io.FileNotFoundException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import org.springframework.util.Log4jConfigurer; import com.taobao.tddl.common.exception.TddlException; import com.taobao.tddl.common.model.App; import com.taobao.tddl.common.properties.ConnectionProperties; import com.taobao.tddl.matrix.jdbc.TDataSource; import com.taobao.tddl.util.SqlFileUtil; public class Simba2Sample { public static void main(String[] args) throws TddlException, SQLException, FileNotFoundException { Log4jConfigurer.initLogging("src/main/resources/log4j.properties"); TDataSource ds = new TDataSource(); // 设置默认db(ob) ds.setAppName("DEV_DPS_APP"); ds.setTopologyFile("tddl-topology-dps.xml"); ds.setRuleFile("tddl-rule-dps-nonmysql.xml"); // 设置simba2的mysql App subApp = new App(); subApp.setAppName("DAILY_SOLAR_MERCURY_APP"); subApp.setRuleFile("tddl-rule-dps-simba2-mysql.xml"); ds.addSubApp(subApp); // 添加subway的mysql subApp = new App(); subApp.setAppName("DEV_SUBWAY_MYSQL"); subApp.setRuleFile("tddl-rule-dps-subway-mysql.xml"); ds.addSubApp(subApp); Map cp = new HashMap(); cp.put("ALLOW_TEMPORARY_TABLE", "True"); cp.put(ConnectionProperties.TEMP_TABLE_DIR, ".\\temp\\"); cp.put(ConnectionProperties.TEMP_TABLE_CUT_ROWS, false); cp.put(ConnectionProperties.TEMP_TABLE_MAX_ROWS, 1000); ds.setConnectionProperties(cp); ds.init(); System.out.println("init done"); // subway_adgroup_list.sql // solar_adgroup_list.sql String sql = SqlFileUtil.getSql("replace.txt"); // sql = SqlFileUtil.getSql("solar_adgroup_list.sql"); Connection conn = ds.getConnection(); { PreparedStatement ps = conn.prepareStatement(sql); long start = System.currentTimeMillis(); ResultSet rs = ps.executeQuery(); while (rs.next()) { StringBuilder sb = new StringBuilder(); int count = rs.getMetaData().getColumnCount(); for (int i = 1; i <= count; i++) { String key = rs.getMetaData().getColumnLabel(i); Object val = rs.getObject(i); sb.append("[" + rs.getMetaData().getTableName(i) + "." + key + "->" + val + "]"); } System.out.println(sb.toString()); } System.out.println("done " + (System.currentTimeMillis() - start)); rs.close(); ps.close(); } conn.close(); } }
apache-2.0
egacl/gatewayio
GatewayProjects/Gateway/src/main/java/cl/io/gateway/AbstractGateway.java
8471
/* * Copyright 2017 GetSoftware (http://www.getsoftware.cl) * * 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 cl.io.gateway; import java.io.IOException; import java.lang.reflect.Method; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cl.io.gateway.InternalElement.MethodParameterType; import cl.io.gateway.InternalElement.PluginField; import cl.io.gateway.classloader.GatewayClassLoader; import cl.io.gateway.exception.GatewayProcessException; import cl.io.gateway.messaging.GatewayMessageContext; import cl.io.gateway.messaging.IGatewayMessageHandler; import cl.io.gateway.messaging.NetworkServiceSource; import cl.io.gateway.network.NetworkMessage; import cl.io.gateway.network.driver.exception.NetworkDriverException; import cl.io.gateway.properties.XProperties; public abstract class AbstractGateway<I, E extends InternalElement<I>> implements IGateway { private static final Logger logger = LoggerFactory.getLogger(AbstractGateway.class); private final Gateway gateway; private final Map<String, InternalMessageHandler<?>> eventsHandlerMap; private final I elementInstance; private final InternalElement<I> element; public AbstractGateway(final Gateway gateway, final InternalElement<I> element) throws Exception { this.gateway = gateway; this.element = element; this.eventsHandlerMap = new ConcurrentHashMap<String, InternalMessageHandler<?>>(); this.elementInstance = this.element.getInstanceableClass().newInstance(); } @SuppressWarnings({ "rawtypes", "unchecked" }) public void init() throws Exception { if (!this.element.getEventMethodMap().isEmpty()) { // Add anotated message handlers for (Map.Entry<String, MethodParameterType> messageHandler : this.element.getEventMethodMap().entrySet()) { // Add listener for event this.gateway.addMessageHandler( messageHandler.getKey(), this.createHandler(messageHandler.getKey(), messageHandler.getValue().getParameterType(), messageHandler.getValue().getMethod()), messageHandler.getValue().getOrigins()); } } if (!this.element.getPluginFieldsList().isEmpty()) { for (PluginField plugin : this.element.getPluginFieldsList()) { plugin.getField().setAccessible(true); // Plugin is requested to instantiate the object to inject into the field plugin.getField().set(this.elementInstance, this.getPlugin(plugin.getPluginId(), plugin.getPluginFieldType())); } } } @Override public <T> T getPlugin(String pluginId, Class<T> pluginType) { InternalGatewayPlugin gwPlugin = this.gateway.getPlugin(pluginId); if (gwPlugin != null) { return gwPlugin.getElementInstance().getPluginInstance(pluginType); } logger.warn("'" + element.getGatewayId() + "' trying to invoke '" + pluginId + "' but not exists"); return null; } @Override public <T> void addMessageHandler(String event, IGatewayMessageHandler<T> handler) throws GatewayProcessException { if (this.eventsHandlerMap.containsKey(event)) { throw new GatewayProcessException("Event '" + event + "' is already associated with another handler"); } final InternalMessageHandler<T> internalHandler = new InternalMessageHandler<T>(event, handler); this.eventsHandlerMap.put(event, internalHandler); this.gateway.addMessageHandler(event, internalHandler); } @Override public void removeMessageHandler(String event) throws GatewayProcessException { final InternalMessageHandler<?> internalHandler = this.eventsHandlerMap.get(event); if (internalHandler.reflection) { throw new GatewayProcessException("Event '" + event + "' is associated with the method " + internalHandler.method + ". It cannot be removed"); } this.eventsHandlerMap.remove(event); this.gateway.removeMessageHandler(event); } @Override public <T> void sendMessage(IGatewayClientSession client, NetworkMessage<T> message, NetworkServiceSource... origin) throws NetworkDriverException { this.gateway.sendMessage(client, message, origin); } @Override public XProperties getProperties(String propertyFileName) throws IOException { GatewayClassLoader ccl = this.gateway.getEnvironmentReader().getPropertiesInicializer().getResourcesLoader() .getServiceContextClassLoader(this.element.getContextId()); return XProperties.loadFromFileOrClasspath(ccl.getPropsPath(), propertyFileName, this.element.getInstanceableClass()); } <T> IGatewayMessageHandler<T> createHandler(final String event, final Class<T> messageType, final Method method) { final InternalMessageHandler<T> internalHandler = new InternalMessageHandler<T>(event, messageType, method); this.eventsHandlerMap.put(event, internalHandler); return internalHandler; } public Gateway getGateway() { return gateway; } public String getContextId() { return this.element.getContextId(); } public String getGatewayId() { return this.element.getGatewayId(); } public Map<String, InternalMessageHandler<?>> getEventsHandlerMap() { return eventsHandlerMap; } public I getElementInstance() { return elementInstance; } public Class<I> getElementInstanceClass() { return this.element.getInstanceableClass(); } public InternalElement<I> getElement() { return this.element; } class InternalMessageHandler<T> implements IGatewayMessageHandler<T> { final boolean reflection; final String event; final Class<T> messageType; final Method method; final IGatewayMessageHandler<T> handler; public InternalMessageHandler(final String event, final Class<T> messageType, final Method method) { this.reflection = true; this.event = event; this.messageType = messageType; this.method = method; this.handler = null; } public InternalMessageHandler(final String event, final IGatewayMessageHandler<T> handler) { this.reflection = false; this.event = event; this.handler = handler; this.method = null; this.messageType = null; } @Override public void onMessage(NetworkMessage<T> message, IGatewayClientSession clientSession) throws Exception { // Create new session with this gateway implementation GatewayClientSession newSession = new GatewayClientSession(AbstractGateway.this, (GatewayClientSession) clientSession); if (this.reflection) { method.invoke(AbstractGateway.this.elementInstance, new GatewayMessageContext<>(message, newSession)); } else { this.handler.onMessage(message, newSession); } } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("InternalMessageHandler [reflection="); builder.append(reflection); builder.append(", event="); builder.append(event); builder.append(", messageType="); builder.append(messageType); builder.append(", method="); builder.append(method); builder.append(", handler="); builder.append(handler); builder.append("]"); return builder.toString(); } } }
apache-2.0
corann95/Pokedeck
Pokedeck/src/EnergyCard.java
497
public class EnergyCard extends Card{ private String energy_type; public EnergyCard(String card_name, String card_type, int collector_card_number, String energy_type) { super(card_name, card_type, collector_card_number); this.energy_type=energy_type; } @Override public String toString() { return ("name:"+this.card_name+" type:"+this.card_type+" energy_type:"+this.energy_type + " collector_number:" +this.collector_card_number+" description:"+this.getDescription()); } }
apache-2.0
ajoymajumdar/metacat
metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris/store/repos/PolarisDatabaseRepository.java
548
package com.netflix.metacat.connector.polaris.store.repos; import com.netflix.metacat.connector.polaris.store.entities.PolarisDatabaseEntity; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.stereotype.Repository; import org.springframework.data.jpa.repository.JpaRepository; /** * JPA repository implementation for storing PolarisDatabaseEntity. */ @Repository public interface PolarisDatabaseRepository extends JpaRepository<PolarisDatabaseEntity, String>, JpaSpecificationExecutor { }
apache-2.0
JAVA201708/Homework
201708/20170825/Team1/SunHongJiang/examples/ex03/Temperature.java
388
public class Temperature { public static void main(String[] args) { double centigrade = 0.0; int item = 1; do { double fahrenheit = centigrade * 9 / 5.0 + 32; System.out.println("第" + item + "条:\t摄氏温度为:" + centigrade + "时,\t华氏温度为:" + fahrenheit); centigrade = centigrade + 20; item++; }while(item <= 10 && centigrade <= 250); } }
apache-2.0
AndroidKnife/Utils
screen/src/main/java/com/hwangjr/utils/screen/DensityConverter.java
1657
package com.hwangjr.utils.screen; import android.content.Context; import android.util.DisplayMetrics; /** * Utility to convert density. */ public class DensityConverter { /** * convert pixel to dp */ public static int px2dp(Context context, float pxValue) { float scale = context.getResources().getDisplayMetrics().density; return (int) (pxValue / scale + 0.5f); } /** * convert dp to px */ public static int dp2px(Context context, float dpValue) { float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } /** * convert px to sp */ public static int px2sp(Context context, float pxValue) { float fontScale = context.getResources().getDisplayMetrics().scaledDensity; return (int) (pxValue / fontScale + 0.5f); } /** * convert sp to px */ public static int sp2px(Context context, float spValue) { float fontScale = context.getResources().getDisplayMetrics().scaledDensity; return (int) (spValue * fontScale + 0.5f); } /** * get screen density. {@link DisplayMetrics#density} */ public static float getDensity(Context context) { DisplayMetrics dm = context.getResources().getDisplayMetrics(); return dm.density; } /** * get scaled density.{@link DisplayMetrics#scaledDensity} * * @param context * @return */ public static float getScaledDensity(Context context) { DisplayMetrics dm = context.getResources().getDisplayMetrics(); return dm.scaledDensity; } }
apache-2.0
granthenke/storm-spring
src/main/java/storm/contrib/spring/topology/component/ComponentConfig.java
1974
package storm.contrib.spring.topology.component; import backtype.storm.Config; import backtype.storm.topology.ComponentConfigurationDeclarer; /** * [Class Description] * * @author Grant Henke * @since 12/4/12 */ public class ComponentConfig implements IComponentConfig { protected Config configuration; protected Boolean debug; protected Integer maxSpoutPending; protected Integer maxTaskParallelism; protected ComponentConfig() { this.configuration = null; this.debug = null; this.maxSpoutPending = null; this.maxTaskParallelism = null; } public Config getConfiguration() { return configuration; } public void setConfiguration(final Config configuration) { this.configuration = configuration; } public Boolean getDebug() { return debug; } public void setDebug(final Boolean debug) { this.debug = debug; } public Integer getMaxSpoutPending() { return maxSpoutPending; } public void setMaxSpoutPending(final Integer maxSpoutPending) { this.maxSpoutPending = maxSpoutPending; } public Integer getMaxTaskParallelism() { return maxTaskParallelism; } public void setMaxTaskParallelism(final Integer maxTaskParallelism) { this.maxTaskParallelism = maxTaskParallelism; } protected void addConfigToComponent(final ComponentConfigurationDeclarer componentConfigurationDeclarer) { if (configuration != null) { componentConfigurationDeclarer.addConfigurations(configuration); } if (debug != null) { componentConfigurationDeclarer.setDebug(debug); } if (maxSpoutPending != null) { componentConfigurationDeclarer.setMaxSpoutPending(maxSpoutPending); } if (maxTaskParallelism != null) { componentConfigurationDeclarer.setMaxTaskParallelism(maxTaskParallelism); } } }
apache-2.0
dbflute-test/dbflute-test-active-dockside
src/main/java/org/docksidestage/dockside/dbflute/exbhv/pmbean/MemberChangedToWithdrawalForcedlyPmb.java
1387
/* * Copyright 2014-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.docksidestage.dockside.dbflute.exbhv.pmbean; import org.docksidestage.dockside.dbflute.bsbhv.pmbean.BsMemberChangedToWithdrawalForcedlyPmb; /** * <!-- df:beginClassDescription --> * The typed parameter-bean of MemberChangedToWithdrawalForcedly. <span style="color: #AD4747">(typed to execute)</span><br> * This is related to "<span style="color: #AD4747">updateMemberChangedToWithdrawalForcedly</span>" on MemberBhv, <br> * described as "Force Withdrawal Update". <br> * <!-- df:endClassDescription --> * <p> * You can implement your original methods here. * This class remains when re-generating. * </p> * @author DBFlute(AutoGenerator) */ public class MemberChangedToWithdrawalForcedlyPmb extends BsMemberChangedToWithdrawalForcedlyPmb { }
apache-2.0
ice-coffee/WormBook
app/src/main/java/com/jie/book/work/download/RequestParams.java
10067
/* Android Asynchronous Http Client Copyright (c) 2011 James Smith <james@loopj.com> http://loopj.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.jie.book.work.download; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.http.HttpEntity; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.message.BasicNameValuePair; /** * A collection of string request parameters or files to send along with * requests made from an {@link AsyncHttpClient} instance. * <p> * For example: * <p> * * <pre> * RequestParams params = new RequestParams(); * params.put(&quot;username&quot;, &quot;james&quot;); * params.put(&quot;password&quot;, &quot;123456&quot;); * params.put(&quot;email&quot;, &quot;my@email.com&quot;); * params.put(&quot;profile_picture&quot;, new File(&quot;pic.jpg&quot;)); // Upload a File * params.put(&quot;profile_picture2&quot;, someInputStream); // Upload an InputStream * params.put(&quot;profile_picture3&quot;, new ByteArrayInputStream(someBytes)); // Upload * // some * // bytes * * AsyncHttpClient client = new AsyncHttpClient(); * client.post(&quot;http://myendpoint.com&quot;, params, responseHandler); * </pre> */ public class RequestParams { private static String ENCODING = "UTF-8"; protected ConcurrentHashMap<String, String> urlParams; protected ConcurrentHashMap<String, FileWrapper> fileParams; protected ConcurrentHashMap<String, ArrayList<String>> urlParamsWithArray; /** * Constructs a new empty <code>RequestParams</code> instance. */ public RequestParams() { init(); } /** * Constructs a new RequestParams instance containing the key/value string * params from the specified map. * * @param source * the source key/value string map to add. */ public RequestParams(Map<String, String> source) { init(); for (Map.Entry<String, String> entry : source.entrySet()) { put(entry.getKey(), entry.getValue()); } } /** * Constructs a new RequestParams instance and populate it with a single * initial key/value string param. * * @param key * the key name for the intial param. * @param value * the value string for the initial param. */ public RequestParams(String key, String value) { init(); put(key, value); } /** * Constructs a new RequestParams instance and populate it with multiple * initial key/value string param. * * @param keysAndValues * a sequence of keys and values. Objects are automatically * converted to Strings (including the value {@code null}). * @throws IllegalArgumentException * if the number of arguments isn't even. */ public RequestParams(Object... keysAndValues) { init(); int len = keysAndValues.length; if (len % 2 != 0) throw new IllegalArgumentException("Supplied arguments must be even"); for (int i = 0; i < len; i += 2) { String key = String.valueOf(keysAndValues[i]); String val = String.valueOf(keysAndValues[i + 1]); put(key, val); } } /** * Adds a key/value string pair to the request. * * @param key * the key name for the new param. * @param value * the value string for the new param. */ public void put(String key, String value) { if (key != null && value != null) { urlParams.put(key, value); } } /** * Adds a file to the request. * * @param key * the key name for the new param. * @param file * the file to add. */ public void put(String key, File file) throws FileNotFoundException { put(key, new FileInputStream(file), file.getName()); } /** * Adds param with more than one value. * * @param key * the key name for the new param. * @param values * is the ArrayList with values for the param. */ public void put(String key, ArrayList<String> values) { if (key != null && values != null) { urlParamsWithArray.put(key, values); } } /** * Adds an input stream to the request. * * @param key * the key name for the new param. * @param stream * the input stream to add. */ public void put(String key, InputStream stream) { put(key, stream, null); } /** * Adds an input stream to the request. * * @param key * the key name for the new param. * @param stream * the input stream to add. * @param fileName * the name of the file. */ public void put(String key, InputStream stream, String fileName) { put(key, stream, fileName, null); } /** * Adds an input stream to the request. * * @param key * the key name for the new param. * @param stream * the input stream to add. * @param fileName * the name of the file. * @param contentType * the content type of the file, eg. application/json */ public void put(String key, InputStream stream, String fileName, String contentType) { if (key != null && stream != null) { fileParams.put(key, new FileWrapper(stream, fileName, contentType)); } } /** * Removes a parameter from the request. * * @param key * the key name for the parameter to remove. */ public void remove(String key) { urlParams.remove(key); fileParams.remove(key); urlParamsWithArray.remove(key); } @Override public String toString() { StringBuilder result = new StringBuilder(); for (ConcurrentHashMap.Entry<String, String> entry : urlParams.entrySet()) { if (result.length() > 0) result.append("&"); result.append(entry.getKey()); result.append("="); result.append(entry.getValue()); } for (ConcurrentHashMap.Entry<String, FileWrapper> entry : fileParams.entrySet()) { if (result.length() > 0) result.append("&"); result.append(entry.getKey()); result.append("="); result.append("FILE"); } for (ConcurrentHashMap.Entry<String, ArrayList<String>> entry : urlParamsWithArray.entrySet()) { if (result.length() > 0) result.append("&"); ArrayList<String> values = entry.getValue(); for (String value : values) { if (values.indexOf(value) != 0) result.append("&"); result.append(entry.getKey()); result.append("="); result.append(value); } } return result.toString(); } /** * Returns an HttpEntity containing all request parameters */ public HttpEntity getEntity() { HttpEntity entity = null; if (!fileParams.isEmpty()) { SimpleMultipartEntity multipartEntity = new SimpleMultipartEntity(); // Add string params for (ConcurrentHashMap.Entry<String, String> entry : urlParams.entrySet()) { multipartEntity.addPart(entry.getKey(), entry.getValue()); } // Add dupe params for (ConcurrentHashMap.Entry<String, ArrayList<String>> entry : urlParamsWithArray.entrySet()) { ArrayList<String> values = entry.getValue(); for (String value : values) { multipartEntity.addPart(entry.getKey(), value); } } // Add file params int currentIndex = 0; int lastIndex = fileParams.entrySet().size() - 1; for (ConcurrentHashMap.Entry<String, FileWrapper> entry : fileParams.entrySet()) { FileWrapper file = entry.getValue(); if (file.inputStream != null) { boolean isLast = currentIndex == lastIndex; if (file.contentType != null) { multipartEntity.addPart(entry.getKey(), file.getFileName(), file.inputStream, file.contentType, isLast); } else { multipartEntity.addPart(entry.getKey(), file.getFileName(), file.inputStream, isLast); } } currentIndex++; } entity = multipartEntity; } else { try { entity = new UrlEncodedFormEntity(getParamsList(), ENCODING); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } return entity; } private void init() { urlParams = new ConcurrentHashMap<String, String>(); fileParams = new ConcurrentHashMap<String, FileWrapper>(); urlParamsWithArray = new ConcurrentHashMap<String, ArrayList<String>>(); } protected List<BasicNameValuePair> getParamsList() { List<BasicNameValuePair> lparams = new LinkedList<BasicNameValuePair>(); for (ConcurrentHashMap.Entry<String, String> entry : urlParams.entrySet()) { lparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } for (ConcurrentHashMap.Entry<String, ArrayList<String>> entry : urlParamsWithArray.entrySet()) { ArrayList<String> values = entry.getValue(); for (String value : values) { lparams.add(new BasicNameValuePair(entry.getKey(), value)); } } return lparams; } protected String getParamString() { return URLEncodedUtils.format(getParamsList(), ENCODING); } private static class FileWrapper { public InputStream inputStream; public String fileName; public String contentType; public FileWrapper(InputStream inputStream, String fileName, String contentType) { this.inputStream = inputStream; this.fileName = fileName; this.contentType = contentType; } public String getFileName() { if (fileName != null) { return fileName; } else { return "nofilename"; } } } }
apache-2.0
sakai-mirror/k2
agnostic/shared/src/main/java/org/sakaiproject/kernel/util/XSDValidator.java
2999
/* * Licensed to the Sakai Foundation (SF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The SF 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.sakaiproject.kernel.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.xml.sax.SAXException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; /** * Validator utility for testing. */ public class XSDValidator { /** * The schema langiage being used. */ private static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema"; protected static final Log LOG = LogFactory.getLog(XSDValidator.class); /** * Validate a xml string against a supplied schema. * * @param xml the xml presented as a string * @param schema an input stream containing the xsd * @return a list of errors or a 0 lenght string if none. */ public static String validate(String xml, InputStream schema) { try { return validate(new ByteArrayInputStream(xml.getBytes("UTF-8")), schema); } catch (UnsupportedEncodingException e) { return e.getMessage(); } } /** * Validate a xml input stream against a supplied schema. * @param xml a stream containing the xml * @param schema a stream containing the schema * @return a list of errors or warnings, a 0 lenght string if none. */ public static String validate(InputStream xml, InputStream schema) { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(true); final StringBuilder errors = new StringBuilder(); try { SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA); Schema s = schemaFactory.newSchema(new StreamSource(schema)); Validator validator = s.newValidator(); validator.validate(new StreamSource(xml)); } catch (IOException e) { errors.append(e.getMessage()).append("\n"); } catch (SAXException e) { errors.append(e.getMessage()).append("\n"); } return errors.toString(); } }
apache-2.0
RoddiPotter/cicstart
cicstart/src/main/java/ca/ualberta/physics/cssdp/dao/type/PersistentDateTime.java
3063
/* ============================================================ * PersistentLocalDateTime.java * ============================================================ * Copyright 2013 University of Alberta * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================ */ package ca.ualberta.physics.cssdp.dao.type; import java.io.Serializable; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import org.hibernate.HibernateException; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.usertype.UserType; import org.joda.time.DateTime; public class PersistentDateTime implements UserType { @Override public int[] sqlTypes() { return new int[] { java.sql.Types.TIMESTAMP }; } @Override public Class<DateTime> returnedClass() { return DateTime.class; } @Override public boolean equals(Object x, Object y) throws HibernateException { if (x == y) { return true; } if (x == null || y == null) { return false; } DateTime dt1 = (DateTime) x; DateTime dt2 = (DateTime) y; return dt1.equals(dt2); } @Override public int hashCode(Object x) throws HibernateException { DateTime dt = (DateTime) x; return dt.hashCode(); } @Override public Object deepCopy(Object value) throws HibernateException { return value; } @Override public boolean isMutable() { return false; } @Override public Serializable disassemble(Object value) throws HibernateException { return (Serializable) value; } @Override public Object assemble(Serializable cached, Object owner) throws HibernateException { return cached; } @Override public Object replace(Object original, Object target, Object owner) throws HibernateException { return original; } @Override public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws HibernateException, SQLException { Timestamp timestamp = rs.getTimestamp(names[0]); if (timestamp != null) { DateTime dateTime = new DateTime(timestamp); return dateTime; } else { return null; } } @Override public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session) throws HibernateException, SQLException { if (value != null) { DateTime dateTime = (DateTime) value; Timestamp timestamp = new Timestamp(dateTime.toDate() .getTime()); st.setTimestamp(index, timestamp); } else { st.setObject(index, null); } } }
apache-2.0
open-infinity/health-monitoring
rrd-http-server/rrd-http-server/src/main/java/org/openinfinity/rrddatareader/http/GroupMetricNamesHandler.java
1639
/* * #%L * Health Monitoring : RRD Data Reader * %% * Copyright (C) 2012 Tieto * %% * 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. * #L% */ package org.openinfinity.rrddatareader.http; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.handler.codec.http.HttpResponse; import org.jboss.netty.handler.codec.http.QueryStringDecoder; import org.openinfinity.rrddatareader.service.MonitoringService; import org.openinfinity.rrddatareader.service.RrdMonitoringService; import org.openinfinity.rrddatareader.util.HttpUtil; public class GroupMetricNamesHandler implements AbstractHandler { @Override public void handle(HttpResponse response, QueryStringDecoder queryStringDecoder) throws Exception { String groupName = HttpUtil.get(queryStringDecoder, "groupName"); String metricType = HttpUtil.get(queryStringDecoder, "metricType"); MonitoringService monitoringService = new RrdMonitoringService(); response.setContent(ChannelBuffers.copiedBuffer(monitoringService.getGroupMetricNames(groupName, metricType).getBytes())); } }
apache-2.0
ryandcarter/hybris-connector
src/main/java/org/mule/modules/hybris/model/PromotionNullActionDTO.java
1127
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // 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: 2013.11.29 at 12:35:53 PM GMT // package org.mule.modules.hybris.model; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for promotionNullActionDTO complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="promotionNullActionDTO"> * &lt;complexContent> * &lt;extension base="{}abstractPromotionActionDTO"> * &lt;sequence> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "promotionNullActionDTO") public class PromotionNullActionDTO extends AbstractPromotionActionDTO { }
apache-2.0
palantir/atlasdb
timestamp-impl/src/main/java/com/palantir/timestamp/DebugLogger.java
2566
/* * (c) Copyright 2018 Palantir Technologies 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.palantir.timestamp; import com.palantir.logsafe.SafeArg; import com.palantir.logsafe.UnsafeArg; import com.palantir.logsafe.logger.SafeLogger; import com.palantir.logsafe.logger.SafeLoggerFactory; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; /** * This is a logger intended for use tracking down problems arising from * https://github.com/palantir/atlasdb/issues/1000. To activate this logging * please follow instructions on * http://palantir.github.io/atlasdb/html/configuration/logging.html#debug-logging-for-multiple-timestamp-services-error */ @SuppressFBWarnings("SLF4J_LOGGER_SHOULD_BE_PRIVATE") public final class DebugLogger { public static final SafeLogger logger = SafeLoggerFactory.get(DebugLogger.class); private DebugLogger() { // Logging utility class } public static void handedOutTimestamps(TimestampRange range) { long count = range.getUpperBound() - range.getLowerBound() + 1L; logger.trace( "Handing out {} timestamps, taking us to {}.", SafeArg.of("count", count), SafeArg.of("rangeUpperBound", range.getUpperBound())); } public static void createdPersistentTimestamp() { logger.info( "Creating PersistentTimestamp object on thread {}." + " If you are running embedded AtlasDB, this should only happen once." + " If you are using Timelock, this should happen once per client per leadership election", UnsafeArg.of("threadName", Thread.currentThread().getName())); } public static void willStoreNewUpperLimit(long newLimit) { logger.trace("storing new upper limit: {}.", SafeArg.of("newLimit", newLimit)); } public static void didStoreNewUpperLimit(long newLimit) { logger.trace("Stored; upper limit is now {}.", SafeArg.of("newLimit", newLimit)); } }
apache-2.0
wso2/carbon-commons
components/tenant-mgt-common/org.wso2.carbon.tenant.common/src/main/java/org/wso2/carbon/stratos/common/exception/TenantManagementServerException.java
1279
/* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.stratos.common.exception; public class TenantManagementServerException extends TenantMgtException { public TenantManagementServerException(String errorCode, String errorDescription) { super(errorCode, errorDescription); } public TenantManagementServerException(String msg) { super(msg); } public TenantManagementServerException(String msg, Exception e) { super(msg, e); } public TenantManagementServerException(String errorCode, String errorDescription, Exception e) { super(errorCode, errorDescription, e); } }
apache-2.0
masgari/microservices-sample
persistence-service/src/main/java/microservices/sample/persistence/ratpack/PersistenceServer.java
2887
package microservices.sample.persistence.ratpack; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import microservices.sample.base.AvailablePortProvider; import microservices.sample.base.NetUtils; import microservices.sample.base.ratpack.BaseModule; import microservices.sample.base.ratpack.BaseServer; import microservices.sample.base.ratpack.ServerException; import microservices.sample.persistence.PersistenceModule; import ratpack.server.ServerEnvironment; import ratpack.server.internal.DefaultServerConfigBuilder; import java.net.InetAddress; import java.net.UnknownHostException; /** * @author mamad * @since 17/03/15. */ public class PersistenceServer extends BaseServer { public static final String VERSION = "v1"; public PersistenceServer(int port, String ip) throws ServerException, UnknownHostException { super(chain -> chain.prefix(VERSION, PersistenceHandlerFactory.class) .handler(ctx -> ctx.render("Persistence Service - " + VERSION)), //create ratpack config DefaultServerConfigBuilder.noBaseDir(ServerEnvironment.env()).port(port).address(InetAddress.getByName(ip)).build(), //add Guice modules spec -> spec.add(new BaseModule()).add(new PersistenceModule(ip, port, VERSION))); } public static void main(String[] args) { Params params = new Params(); JCommander commander = new JCommander(params); try { commander.parse(args); if (params.isHelp()) { commander.usage(); return; } } catch (Exception e) { commander.usage(); return; } try { PersistenceServer server = new PersistenceServer(params.getPort(), params.getIp()); System.out.println("Listening on port:" + params.getPort()); server.start(); } catch (Exception e) { e.printStackTrace(); } } private static class Params { public static final int MIN_PORT = 4100; public static final int MAX_PORT = 4800; @Parameter(names = {"-h", "--help"}, description = "Display help message", help = true) private boolean help; @Parameter(names = {"-p", "--port"}, description = "Server listen port. Default value is in " + "range [" + MIN_PORT + "," + MAX_PORT + "]") private int port = AvailablePortProvider.between(MIN_PORT, MAX_PORT).nextPort(); @Parameter(names = {"-i", "--ip"}, description = "Listen ip address") private String ip = NetUtils.guessIPAddress(); public boolean isHelp() { return help; } public int getPort() { return port; } public String getIp() { return ip; } } }
apache-2.0
cruldra/table2bean
src/main/java/cn/dongjak/table2bean/ui/PluginConfigurationPanel.java
4597
package cn.dongjak.table2bean.ui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.AbstractListModel; import javax.swing.JCheckBox; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListCellRenderer; import javax.swing.ListSelectionModel; import org.apache.commons.lang3.ArrayUtils; import org.dom4j.Element; import cn.dongjak.table2bean.Consts; import cn.dongjak.table2bean.utils.ConfigurationAccessor; public class PluginConfigurationPanel extends JPanel { private static final long serialVersionUID = 2289030491566292707L; private ConfigurationAccessor configurationAccessor = new ConfigurationAccessor( Consts.table2beanXMLFile); private JList<Plugin> list; private Plugin[] plugins = null; public Plugin[] getPlugins() { return plugins; } public void setPlugins(Plugin[] plugins) { this.plugins = plugins; } public PluginConfigurationPanel() { setLayout(new BorderLayout(0, 0)); JScrollPane scrollPane = new JScrollPane(); add(scrollPane); list = new JList<Plugin>(); scrollPane.setViewportView(list); // final CheckListManager checkListManager = new CheckListManager(list); list.setCellRenderer(new PluginListRenderer()); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list.setSelectionBackground(new Color(177, 232, 58));// 186,212,239,177,232,58 list.setSelectionForeground(Color.black); list.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent event) { JList list = (JList) event.getSource(); // Get index of item clicked // »ñµÃÓû§µã»÷ÏîµÄË÷Òý int index = list.locationToIndex(event.getPoint()); Plugin plugin = (Plugin) list.getModel().getElementAt(index); // ÉèÖÃÁбíÖÐÏîµÄÑ¡Ôñ״̬ plugin.enable = !plugin.enable; // ÖØÐ»æÖÆÁбíÖÐÏî list.repaint(list.getCellBounds(index, index)); } // public void mousePressed(MouseEvent e) { // // TODO Auto-generated method stub // first = list.locationToIndex(e.getPoint()); // } // // public void mouseReleased(MouseEvent e) { // // TODO Auto-generated method stub // sec = list.locationToIndex(e.getPoint()); // if (sec != -1) { // if (first != sec) { // String s1 = model.getElementAt(first).toString(); // String s2 = model.getElementAt(sec).toString(); // model.setElementAt(cli[first], sec); // model.setElementAt(cli[sec], first); // model.copyInto(cli); // list.setModel(model); // } // } // } }); addComponentListener(new ComponentAdapter() { @Override public void componentShown(ComponentEvent e) { for (Element element : configurationAccessor.getPluginManager() .getPlugins()) plugins = ArrayUtils .add(plugins, new Plugin(element.elementText("name"), new Boolean(element .elementText("enable")))); list.setModel(new PluginListModel(plugins)); } }); } } class Plugin { String name; boolean enable; public Plugin(String name, boolean enable) { super(); this.name = name; this.enable = enable; } @Override public String toString() { return name; } } class PluginListRenderer extends JCheckBox implements ListCellRenderer<Plugin> { private static final long serialVersionUID = -881457682805555741L; @Override public Component getListCellRendererComponent(JList<? extends Plugin> list, Plugin value, int index, boolean isSelected, boolean cellHasFocus) { setEnabled(list.isEnabled()); setSelected(((Plugin) value).enable); setFont(list.getFont()); if (isSelected) { this.setBackground(list.getSelectionBackground()); this.setForeground(list.getSelectionForeground()); } else { this.setBackground(list.getBackground()); this.setForeground(list.getForeground()); } setText(value.toString()); return this; } } class PluginListModel extends AbstractListModel<Plugin> { private static final long serialVersionUID = 2198696432870337061L; private Plugin[] plugins; public PluginListModel(Plugin[] plugins) { super(); this.plugins = plugins; } @Override public int getSize() { return this.plugins.length; } @Override public Plugin getElementAt(int index) { return this.plugins[index]; } }
apache-2.0
OpenSourceConsulting/athena-chameleon
src/main/java/com/athena/chameleon/engine/entity/xml/application/weblogic/v1_0/ParserFactoryType.java
3885
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0-b52-fcs // 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.09.12 at 01:39:08 오후 KST // package com.athena.chameleon.engine.entity.xml.application.weblogic.v1_0; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for parser-factoryType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="parser-factoryType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="saxparser-factory" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="document-builder-factory" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="transformer-factory" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "parser-factoryType", namespace = "http://www.bea.com/ns/weblogic/weblogic-application", propOrder = { "saxparserFactory", "documentBuilderFactory", "transformerFactory" }) public class ParserFactoryType { @XmlElement(name = "saxparser-factory", namespace = "http://www.bea.com/ns/weblogic/weblogic-application") protected java.lang.String saxparserFactory; @XmlElement(name = "document-builder-factory", namespace = "http://www.bea.com/ns/weblogic/weblogic-application") protected java.lang.String documentBuilderFactory; @XmlElement(name = "transformer-factory", namespace = "http://www.bea.com/ns/weblogic/weblogic-application") protected java.lang.String transformerFactory; /** * Gets the value of the saxparserFactory property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getSaxparserFactory() { return saxparserFactory; } /** * Sets the value of the saxparserFactory property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setSaxparserFactory(java.lang.String value) { this.saxparserFactory = value; } /** * Gets the value of the documentBuilderFactory property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getDocumentBuilderFactory() { return documentBuilderFactory; } /** * Sets the value of the documentBuilderFactory property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setDocumentBuilderFactory(java.lang.String value) { this.documentBuilderFactory = value; } /** * Gets the value of the transformerFactory property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getTransformerFactory() { return transformerFactory; } /** * Sets the value of the transformerFactory property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setTransformerFactory(java.lang.String value) { this.transformerFactory = value; } }
apache-2.0
VictorAlbertos/RxCache
compiler/src/test/java/io/rx_cache2/Mock.java
1056
/* * Copyright 2016 Victor Albertos * * 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.rx_cache2; public class Mock { final private String message; public Mock(String message) { this.message = message; } public String getMessage() { return message; } public class InnerMock { final private String message; public InnerMock(String message) { this.message = message; } public String getMessage() { return message; } } }
apache-2.0
pawel-nn/proj_app_bd_sem7
ProjAppBD/src/main/java/app/model/Country.java
894
package app.model; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Entity @Table(name= "countries") @Data @AllArgsConstructor @NoArgsConstructor public class Country { public Country(String countryName, String countryCode) { this.countryName = countryName; this.countryCode = countryCode; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "country_id", unique = true, nullable = false) private Integer countryId; @Column(name = "country_name", nullable = false, length = 45) private String countryName; @Column(name = "country_code", nullable = false, length = 6) private String countryCode; }
apache-2.0
androidx/media
libraries/test_session_current/src/main/java/androidx/media3/session/RemoteMediaSession.java
26672
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.media3.session; import static androidx.media3.test.session.common.CommonConstants.ACTION_MEDIA3_SESSION; import static androidx.media3.test.session.common.CommonConstants.KEY_AUDIO_ATTRIBUTES; import static androidx.media3.test.session.common.CommonConstants.KEY_BUFFERED_PERCENTAGE; import static androidx.media3.test.session.common.CommonConstants.KEY_BUFFERED_POSITION; import static androidx.media3.test.session.common.CommonConstants.KEY_CONTENT_BUFFERED_POSITION; import static androidx.media3.test.session.common.CommonConstants.KEY_CONTENT_DURATION; import static androidx.media3.test.session.common.CommonConstants.KEY_CONTENT_POSITION; import static androidx.media3.test.session.common.CommonConstants.KEY_CURRENT_AD_GROUP_INDEX; import static androidx.media3.test.session.common.CommonConstants.KEY_CURRENT_AD_INDEX_IN_AD_GROUP; import static androidx.media3.test.session.common.CommonConstants.KEY_CURRENT_CUES; import static androidx.media3.test.session.common.CommonConstants.KEY_CURRENT_LIVE_OFFSET; import static androidx.media3.test.session.common.CommonConstants.KEY_CURRENT_MEDIA_ITEM_INDEX; import static androidx.media3.test.session.common.CommonConstants.KEY_CURRENT_PERIOD_INDEX; import static androidx.media3.test.session.common.CommonConstants.KEY_CURRENT_POSITION; import static androidx.media3.test.session.common.CommonConstants.KEY_DEVICE_INFO; import static androidx.media3.test.session.common.CommonConstants.KEY_DEVICE_MUTED; import static androidx.media3.test.session.common.CommonConstants.KEY_DEVICE_VOLUME; import static androidx.media3.test.session.common.CommonConstants.KEY_DURATION; import static androidx.media3.test.session.common.CommonConstants.KEY_IS_LOADING; import static androidx.media3.test.session.common.CommonConstants.KEY_IS_PLAYING; import static androidx.media3.test.session.common.CommonConstants.KEY_IS_PLAYING_AD; import static androidx.media3.test.session.common.CommonConstants.KEY_MAX_SEEK_TO_PREVIOUS_POSITION_MS; import static androidx.media3.test.session.common.CommonConstants.KEY_MEDIA_METADATA; import static androidx.media3.test.session.common.CommonConstants.KEY_PLAYBACK_PARAMETERS; import static androidx.media3.test.session.common.CommonConstants.KEY_PLAYBACK_STATE; import static androidx.media3.test.session.common.CommonConstants.KEY_PLAYBACK_SUPPRESSION_REASON; import static androidx.media3.test.session.common.CommonConstants.KEY_PLAYER_ERROR; import static androidx.media3.test.session.common.CommonConstants.KEY_PLAYLIST_METADATA; import static androidx.media3.test.session.common.CommonConstants.KEY_PLAY_WHEN_READY; import static androidx.media3.test.session.common.CommonConstants.KEY_REPEAT_MODE; import static androidx.media3.test.session.common.CommonConstants.KEY_SEEK_BACK_INCREMENT_MS; import static androidx.media3.test.session.common.CommonConstants.KEY_SEEK_FORWARD_INCREMENT_MS; import static androidx.media3.test.session.common.CommonConstants.KEY_SHUFFLE_MODE_ENABLED; import static androidx.media3.test.session.common.CommonConstants.KEY_TIMELINE; import static androidx.media3.test.session.common.CommonConstants.KEY_TOTAL_BUFFERED_DURATION; import static androidx.media3.test.session.common.CommonConstants.KEY_TRACK_SELECTION_PARAMETERS; import static androidx.media3.test.session.common.CommonConstants.KEY_VIDEO_SIZE; import static androidx.media3.test.session.common.CommonConstants.KEY_VOLUME; import static androidx.media3.test.session.common.CommonConstants.MEDIA3_SESSION_PROVIDER_SERVICE; import static androidx.media3.test.session.common.TestUtils.SERVICE_CONNECTION_TIMEOUT_MS; import static com.google.common.truth.Truth.assertWithMessage; import static java.util.concurrent.TimeUnit.MILLISECONDS; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.support.v4.media.session.MediaSessionCompat; import androidx.annotation.Nullable; import androidx.media3.common.AudioAttributes; import androidx.media3.common.DeviceInfo; import androidx.media3.common.MediaMetadata; import androidx.media3.common.PlaybackException; import androidx.media3.common.PlaybackParameters; import androidx.media3.common.Player; import androidx.media3.common.Player.DiscontinuityReason; import androidx.media3.common.Player.PositionInfo; import androidx.media3.common.Timeline; import androidx.media3.common.TrackSelectionParameters; import androidx.media3.common.VideoSize; import androidx.media3.common.text.Cue; import androidx.media3.common.util.BundleableUtil; import androidx.media3.common.util.Log; import androidx.media3.common.util.UnstableApi; import androidx.media3.test.session.common.IRemoteMediaSession; import androidx.media3.test.session.common.TestUtils; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; /** * Represents remote {@link MediaSession} in the service app's MediaSessionProviderService. Users * can run {@link MediaSession} methods remotely with this object. */ @UnstableApi public class RemoteMediaSession { private static final String TAG = "RemoteMediaSession"; private final Context context; private final String sessionId; private final Bundle tokenExtras; private ServiceConnection serviceConnection; private IRemoteMediaSession binder; private RemoteMockPlayer remotePlayer; private CountDownLatch countDownLatch; /** Create a {@link MediaSession} in the service app. Should NOT be called in main thread. */ public RemoteMediaSession(String sessionId, Context context, @Nullable Bundle tokenExtras) throws RemoteException { this.sessionId = sessionId; this.context = context; countDownLatch = new CountDownLatch(1); serviceConnection = new MyServiceConnection(); this.tokenExtras = tokenExtras; if (!connect()) { assertWithMessage("Failed to connect to the MediaSessionProviderService.").fail(); } create(); } public void cleanUp() { try { release(); disconnect(); } catch (RemoteException e) { // Maybe expected if cleanUp() is called already or service is crashed as expected. } } /** * Gets {@link RemoteMockPlayer} for interact with the remote MockPlayer. Users can run MockPlayer * methods remotely with this object. */ public RemoteMockPlayer getMockPlayer() { return remotePlayer; } //////////////////////////////////////////////////////////////////////////////// // MediaSession methods //////////////////////////////////////////////////////////////////////////////// /** * Gets {@link SessionToken} from the service app. Should be used after the creation of the * session through {@link #create()}. * * @return A {@link SessionToken} object. */ @Nullable public SessionToken getToken() throws RemoteException { return SessionToken.CREATOR.fromBundle(binder.getToken(sessionId)); } /** * Gets {@link MediaSessionCompat.Token} from the service app. Should be used after the creation * of the session through {@link #create()}. * * @return A {@link SessionToken} object. */ @Nullable public MediaSessionCompat.Token getCompatToken() throws RemoteException { Bundle bundle = binder.getCompatToken(sessionId); bundle.setClassLoader(MediaSession.class.getClassLoader()); return MediaSessionCompat.Token.fromBundle(bundle); } public void setSessionPositionUpdateDelayMs(long updateDelayMs) throws RemoteException { binder.setSessionPositionUpdateDelayMs(sessionId, updateDelayMs); } public void setPlayer(Bundle config) throws RemoteException { binder.setPlayer(sessionId, config); } public void broadcastCustomCommand(SessionCommand command, Bundle args) throws RemoteException { binder.broadcastCustomCommand(sessionId, command.toBundle(), args); } public void sendCustomCommand(SessionCommand command, Bundle args) throws RemoteException { binder.sendCustomCommand(sessionId, command.toBundle(), args); } public void release() throws RemoteException { binder.release(sessionId); } public void setAvailableCommands(SessionCommands sessionCommands, Player.Commands playerCommands) throws RemoteException { binder.setAvailableCommands(sessionId, sessionCommands.toBundle(), playerCommands.toBundle()); } public void setCustomLayout(List<CommandButton> layout) throws RemoteException { List<Bundle> bundleList = new ArrayList<>(); for (CommandButton button : layout) { bundleList.add(button.toBundle()); } binder.setCustomLayout(sessionId, bundleList); } //////////////////////////////////////////////////////////////////////////////// // RemoteMockPlayer methods //////////////////////////////////////////////////////////////////////////////// /** RemoteMockPlayer */ public class RemoteMockPlayer { public void notifyPlayerError(@Nullable PlaybackException playerError) throws RemoteException { binder.notifyPlayerError(sessionId, BundleableUtil.toNullableBundle(playerError)); } public void setPlayWhenReady( boolean playWhenReady, @Player.PlaybackSuppressionReason int reason) throws RemoteException { binder.setPlayWhenReady(sessionId, playWhenReady, reason); } public void setPlaybackState(@Player.State int state) throws RemoteException { binder.setPlaybackState(sessionId, state); } public void setCurrentPosition(long pos) throws RemoteException { binder.setCurrentPosition(sessionId, pos); } public void setBufferedPosition(long pos) throws RemoteException { binder.setBufferedPosition(sessionId, pos); } public void setDuration(long duration) throws RemoteException { binder.setDuration(sessionId, duration); } public void setBufferedPercentage(int bufferedPercentage) throws RemoteException { binder.setBufferedPercentage(sessionId, bufferedPercentage); } public void setTotalBufferedDuration(long totalBufferedDuration) throws RemoteException { binder.setTotalBufferedDuration(sessionId, totalBufferedDuration); } public void setCurrentLiveOffset(long currentLiveOffset) throws RemoteException { binder.setCurrentLiveOffset(sessionId, currentLiveOffset); } public void setContentDuration(long contentDuration) throws RemoteException { binder.setContentDuration(sessionId, contentDuration); } public void setContentPosition(long contentPosition) throws RemoteException { binder.setContentPosition(sessionId, contentPosition); } public void setContentBufferedPosition(long contentBufferedPosition) throws RemoteException { binder.setContentBufferedPosition(sessionId, contentBufferedPosition); } public void setPlaybackParameters(PlaybackParameters playbackParameters) throws RemoteException { binder.setPlaybackParameters(sessionId, playbackParameters.toBundle()); } public void setIsPlayingAd(boolean isPlayingAd) throws RemoteException { binder.setIsPlayingAd(sessionId, isPlayingAd); } public void setCurrentAdGroupIndex(int currentAdGroupIndex) throws RemoteException { binder.setCurrentAdGroupIndex(sessionId, currentAdGroupIndex); } public void setCurrentAdIndexInAdGroup(int currentAdIndexInAdGroup) throws RemoteException { binder.setCurrentAdIndexInAdGroup(sessionId, currentAdIndexInAdGroup); } public void notifyPlayWhenReadyChanged( boolean playWhenReady, @Player.PlaybackSuppressionReason int reason) throws RemoteException { binder.notifyPlayWhenReadyChanged(sessionId, playWhenReady, reason); } public void notifyPlaybackStateChanged(@Player.State int state) throws RemoteException { binder.notifyPlaybackStateChanged(sessionId, state); } public void notifyIsPlayingChanged(boolean isPlaying) throws RemoteException { binder.notifyIsPlayingChanged(sessionId, isPlaying); } public void notifyIsLoadingChanged(boolean isLoading) throws RemoteException { binder.notifyIsLoadingChanged(sessionId, isLoading); } public void notifyPositionDiscontinuity( PositionInfo oldPosition, PositionInfo newPosition, @DiscontinuityReason int reason) throws RemoteException { binder.notifyPositionDiscontinuity( sessionId, oldPosition.toBundle(), newPosition.toBundle(), reason); } public void notifyPlaybackParametersChanged(PlaybackParameters playbackParameters) throws RemoteException { binder.notifyPlaybackParametersChanged(sessionId, playbackParameters.toBundle()); } public void notifyMediaItemTransition(int index, @Player.MediaItemTransitionReason int reason) throws RemoteException { binder.notifyMediaItemTransition(sessionId, index, reason); } public void notifyAudioAttributesChanged(AudioAttributes audioAttributes) throws RemoteException { binder.notifyAudioAttributesChanged(sessionId, audioAttributes.toBundle()); } public void notifyAvailableCommandsChanged(Player.Commands commands) throws RemoteException { binder.notifyAvailableCommandsChanged(sessionId, commands.toBundle()); } public void setTimeline(Timeline timeline) throws RemoteException { binder.setTimeline(sessionId, timeline.toBundle()); } /** * Service app will automatically create a timeline of size {@code windowCount}, and sets it to * the player. * * <p>Each item's media ID will be {@link TestUtils#getMediaIdInFakeTimeline(int)}. */ public void createAndSetFakeTimeline(int windowCount) throws RemoteException { binder.createAndSetFakeTimeline(sessionId, windowCount); } public void setPlaylistMetadata(MediaMetadata playlistMetadata) throws RemoteException { binder.setPlaylistMetadata(sessionId, playlistMetadata.toBundle()); } public void setRepeatMode(@Player.RepeatMode int repeatMode) throws RemoteException { binder.setRepeatMode(sessionId, repeatMode); } public void setShuffleModeEnabled(boolean shuffleModeEnabled) throws RemoteException { binder.setShuffleModeEnabled(sessionId, shuffleModeEnabled); } public void setCurrentMediaItemIndex(int index) throws RemoteException { binder.setCurrentMediaItemIndex(sessionId, index); } public void setTrackSelectionParameters(TrackSelectionParameters parameters) throws RemoteException { binder.setTrackSelectionParameters(sessionId, parameters.toBundle()); } public void notifyTimelineChanged(@Player.TimelineChangeReason int reason) throws RemoteException { binder.notifyTimelineChanged(sessionId, reason); } public void notifyPlaylistMetadataChanged() throws RemoteException { binder.notifyPlaylistMetadataChanged(sessionId); } public void notifyShuffleModeEnabledChanged() throws RemoteException { binder.notifyShuffleModeEnabledChanged(sessionId); } public void notifyRepeatModeChanged() throws RemoteException { binder.notifyRepeatModeChanged(sessionId); } public void notifySeekBackIncrementChanged(long seekBackIncrementMs) throws RemoteException { binder.notifySeekBackIncrementChanged(sessionId, seekBackIncrementMs); } public void notifySeekForwardIncrementChanged(long seekForwardIncrementMs) throws RemoteException { binder.notifySeekForwardIncrementChanged(sessionId, seekForwardIncrementMs); } public void notifyVideoSizeChanged(VideoSize videoSize) throws RemoteException { binder.notifyVideoSizeChanged(sessionId, videoSize.toBundle()); } public boolean surfaceExists() throws RemoteException { return binder.surfaceExists(sessionId); } public void notifyDeviceVolumeChanged(int volume, boolean muted) throws RemoteException { binder.notifyDeviceVolumeChanged(sessionId, volume, muted); } public void notifyCuesChanged(List<Cue> cues) throws RemoteException { binder.notifyCuesChanged(sessionId, BundleableUtil.toBundleList(cues)); } public void notifyDeviceInfoChanged(DeviceInfo deviceInfo) throws RemoteException { binder.notifyDeviceInfoChanged(sessionId, deviceInfo.toBundle()); } public void notifyMediaMetadataChanged(MediaMetadata mediaMetadata) throws RemoteException { binder.notifyMediaMetadataChanged(sessionId, mediaMetadata.toBundle()); } public void notifyRenderedFirstFrame() throws RemoteException { binder.notifyRenderedFirstFrame(sessionId); } public void notifyMaxSeekToPreviousPositionChanged(long maxSeekToPreviousPositionMs) throws RemoteException { binder.notifyMaxSeekToPreviousPositionChanged(sessionId, maxSeekToPreviousPositionMs); } public void notifyTrackSelectionParametersChanged(TrackSelectionParameters parameters) throws RemoteException { binder.notifyTrackSelectionParametersChanged(sessionId, parameters.toBundle()); } } //////////////////////////////////////////////////////////////////////////////// // Non-public methods //////////////////////////////////////////////////////////////////////////////// /** * Connects to service app's MediaSessionProviderService. Should NOT be called in main thread. * * @return true if connected successfully, false if failed to connect. */ private boolean connect() { Intent intent = new Intent(ACTION_MEDIA3_SESSION); intent.setComponent(MEDIA3_SESSION_PROVIDER_SERVICE); boolean bound = false; try { bound = context.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE); } catch (RuntimeException e) { Log.e(TAG, "Failed binding to the MediaSessionProviderService of the service app", e); } if (bound) { try { countDownLatch.await(SERVICE_CONNECTION_TIMEOUT_MS, MILLISECONDS); } catch (InterruptedException e) { Log.e(TAG, "InterruptedException while waiting for onServiceConnected.", e); } } return binder != null; } /** Disconnects from service app's MediaSessionProviderService. */ private void disconnect() { if (serviceConnection != null) { context.unbindService(serviceConnection); } serviceConnection = null; } /** * Create a {@link MediaSession} in the service app. Should be used after successful connection * through {@link #connect}. */ private void create() throws RemoteException { binder.create(sessionId, tokenExtras); remotePlayer = new RemoteMockPlayer(); } class MyServiceConnection implements ServiceConnection { @Override public void onServiceConnected(ComponentName name, IBinder service) { Log.d(TAG, "Connected to service app's MediaSessionProviderService."); binder = IRemoteMediaSession.Stub.asInterface(service); countDownLatch.countDown(); } @Override public void onServiceDisconnected(ComponentName name) { Log.d(TAG, "Disconnected from the service."); } } /** * Builder to build a {@link Bundle} which represents a configuration of {@link Player} in order * to create a new mock player in the service app. The bundle can be passed to {@link * #setPlayer(Bundle)}. */ public static final class MockPlayerConfigBuilder { private final Bundle bundle; public MockPlayerConfigBuilder() { bundle = new Bundle(); } public MockPlayerConfigBuilder setPlayerError(@Nullable PlaybackException playerError) { bundle.putBundle(KEY_PLAYER_ERROR, BundleableUtil.toNullableBundle(playerError)); return this; } public MockPlayerConfigBuilder setDuration(long duration) { bundle.putLong(KEY_DURATION, duration); return this; } public MockPlayerConfigBuilder setCurrentPosition(long pos) { bundle.putLong(KEY_CURRENT_POSITION, pos); return this; } public MockPlayerConfigBuilder setBufferedPosition(long buffPos) { bundle.putLong(KEY_BUFFERED_POSITION, buffPos); return this; } public MockPlayerConfigBuilder setBufferedPercentage(int bufferedPercentage) { bundle.putInt(KEY_BUFFERED_PERCENTAGE, bufferedPercentage); return this; } public MockPlayerConfigBuilder setTotalBufferedDuration(long totalBufferedDuration) { bundle.putLong(KEY_TOTAL_BUFFERED_DURATION, totalBufferedDuration); return this; } public MockPlayerConfigBuilder setCurrentLiveOffset(long currentLiveOffset) { bundle.putLong(KEY_CURRENT_LIVE_OFFSET, currentLiveOffset); return this; } public MockPlayerConfigBuilder setContentDuration(long contentDuration) { bundle.putLong(KEY_CONTENT_DURATION, contentDuration); return this; } public MockPlayerConfigBuilder setContentPosition(long contentPosition) { bundle.putLong(KEY_CONTENT_POSITION, contentPosition); return this; } public MockPlayerConfigBuilder setContentBufferedPosition(long contentBufferedPosition) { bundle.putLong(KEY_CONTENT_BUFFERED_POSITION, contentBufferedPosition); return this; } public MockPlayerConfigBuilder setIsPlayingAd(boolean isPlayingAd) { bundle.putBoolean(KEY_IS_PLAYING_AD, isPlayingAd); return this; } public MockPlayerConfigBuilder setCurrentAdGroupIndex(int currentAdGroupIndex) { bundle.putInt(KEY_CURRENT_AD_GROUP_INDEX, currentAdGroupIndex); return this; } public MockPlayerConfigBuilder setCurrentAdIndexInAdGroup(int currentAdIndexInAdGroup) { bundle.putInt(KEY_CURRENT_AD_INDEX_IN_AD_GROUP, currentAdIndexInAdGroup); return this; } public MockPlayerConfigBuilder setPlaybackParameters(PlaybackParameters playbackParameters) { bundle.putBundle(KEY_PLAYBACK_PARAMETERS, playbackParameters.toBundle()); return this; } public MockPlayerConfigBuilder setAudioAttributes(AudioAttributes audioAttributes) { bundle.putBundle(KEY_AUDIO_ATTRIBUTES, audioAttributes.toBundle()); return this; } public MockPlayerConfigBuilder setTimeline(Timeline timeline) { bundle.putBundle(KEY_TIMELINE, timeline.toBundle()); return this; } public MockPlayerConfigBuilder setCurrentMediaItemIndex(int index) { bundle.putInt(KEY_CURRENT_MEDIA_ITEM_INDEX, index); return this; } public MockPlayerConfigBuilder setCurrentPeriodIndex(int index) { bundle.putInt(KEY_CURRENT_PERIOD_INDEX, index); return this; } public MockPlayerConfigBuilder setPlaylistMetadata(MediaMetadata playlistMetadata) { bundle.putBundle(KEY_PLAYLIST_METADATA, playlistMetadata.toBundle()); return this; } public MockPlayerConfigBuilder setVideoSize(VideoSize videoSize) { bundle.putBundle(KEY_VIDEO_SIZE, videoSize.toBundle()); return this; } public MockPlayerConfigBuilder setVolume(float volume) { bundle.putFloat(KEY_VOLUME, volume); return this; } public MockPlayerConfigBuilder setCurrentCues(List<Cue> cues) { bundle.putParcelableArrayList(KEY_CURRENT_CUES, BundleableUtil.toBundleArrayList(cues)); return this; } public MockPlayerConfigBuilder setDeviceInfo(DeviceInfo deviceInfo) { bundle.putBundle(KEY_DEVICE_INFO, deviceInfo.toBundle()); return this; } public MockPlayerConfigBuilder setDeviceVolume(int volume) { bundle.putInt(KEY_DEVICE_VOLUME, volume); return this; } public MockPlayerConfigBuilder setDeviceMuted(boolean muted) { bundle.putBoolean(KEY_DEVICE_MUTED, muted); return this; } public MockPlayerConfigBuilder setPlayWhenReady(boolean playWhenReady) { bundle.putBoolean(KEY_PLAY_WHEN_READY, playWhenReady); return this; } public MockPlayerConfigBuilder setPlaybackSuppressionReason( @Player.PlaybackSuppressionReason int playbackSuppressionReason) { bundle.putInt(KEY_PLAYBACK_SUPPRESSION_REASON, playbackSuppressionReason); return this; } public MockPlayerConfigBuilder setPlaybackState(@Player.State int state) { bundle.putInt(KEY_PLAYBACK_STATE, state); return this; } public MockPlayerConfigBuilder setIsPlaying(boolean isPlaying) { bundle.putBoolean(KEY_IS_PLAYING, isPlaying); return this; } public MockPlayerConfigBuilder setIsLoading(boolean isLoading) { bundle.putBoolean(KEY_IS_LOADING, isLoading); return this; } public MockPlayerConfigBuilder setRepeatMode(@Player.RepeatMode int repeatMode) { bundle.putInt(KEY_REPEAT_MODE, repeatMode); return this; } public MockPlayerConfigBuilder setShuffleModeEnabled(boolean shuffleModeEnabled) { bundle.putBoolean(KEY_SHUFFLE_MODE_ENABLED, shuffleModeEnabled); return this; } public MockPlayerConfigBuilder setSeekBackIncrement(long seekBackIncrementMs) { bundle.putLong(KEY_SEEK_BACK_INCREMENT_MS, seekBackIncrementMs); return this; } public MockPlayerConfigBuilder setSeekForwardIncrement(long seekForwardIncrementMs) { bundle.putLong(KEY_SEEK_FORWARD_INCREMENT_MS, seekForwardIncrementMs); return this; } public MockPlayerConfigBuilder setMediaMetadata(MediaMetadata mediaMetadata) { bundle.putBundle(KEY_MEDIA_METADATA, mediaMetadata.toBundle()); return this; } public MockPlayerConfigBuilder setMaxSeekToPreviousPositionMs( long maxSeekToPreviousPositionMs) { bundle.putLong(KEY_MAX_SEEK_TO_PREVIOUS_POSITION_MS, maxSeekToPreviousPositionMs); return this; } public MockPlayerConfigBuilder setTrackSelectionParameters( TrackSelectionParameters parameters) { bundle.putBundle(KEY_TRACK_SELECTION_PARAMETERS, parameters.toBundle()); return this; } public Bundle build() { return bundle; } } }
apache-2.0
chewaca/gtsSolution
GtsSoftware/src/GtsSoftware/activo/AccionBuscarPopUpRepuesto.java
1104
package GtsSoftware.activo; import java.util.Vector; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import GtsSoftware.general.CoAccion; import GtsSoftware.general.CoException; public class AccionBuscarPopUpRepuesto extends CoAccion { @Override public void ejecutar(ServletContext sc, HttpServletRequest request, HttpServletResponse response) throws CoException { // TODO Auto-generated method stub ActivoBeanFuncion activoFuncion=ActivoBeanFuncion.getInstanceS(); CriterioActivoBeanData criterioActivoData =new CriterioActividadBeanFuncion().crearCriterioRepuesto(request, response); Vector<ResultadoActivoBeanData> resultados=new CriterioActividadBeanFuncion().buscarPlantillaRepuesto(criterioActivoData); Vector<ResultadoActivoBeanData> resultadosRepuestos=activoFuncion.buscarPlantillaRepuestos(resultados); request.setAttribute("resultadosActivo", resultadosRepuestos); this.direccionar(sc, request, response, "/Gts/activo/seleccionarrepuesto.jsp"); } }
apache-2.0
leafclick/intellij-community
platform/lang-api/src/com/intellij/build/events/BuildEvent.java
1412
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.build.events; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * @author Vladislav.Soroka */ public interface BuildEvent { /** * Returns an id that uniquely identifies the event. * * @return The event id. */ @NotNull Object getId(); /** * Returns the parent event id, if any. * * @return The parent event id. */ @Nullable Object getParentId(); /** * Returns the time this event was triggered. * * @return The event time, in milliseconds since the epoch. */ long getEventTime(); /** * Returns textual representation of the event. * * @return The event text message. */ @NotNull String getMessage(); @Nullable String getHint(); @Nullable String getDescription(); }
apache-2.0
CAMTeam/fitman-cam
COMMON/Portal_LsaService/src/main/java/it/eng/sso/lsa/components/UserNotAllowedException.java
612
package it.eng.sso.lsa.components; /** * Thrown when user exists but is not allowed to login (e.g. has been locked or otherwise deactivated) */ public class UserNotAllowedException extends Exception { /** * */ private static final long serialVersionUID = -6605845005490777590L; public UserNotAllowedException() { } public UserNotAllowedException(String message) { super(message); } public UserNotAllowedException(String message, Throwable cause) { super(message, cause); } public UserNotAllowedException(Throwable cause) { super(cause); } }
apache-2.0
chhh/MSFTBX
MSFileToolbox/src/main/java/umich/ms/fileio/filetypes/pepxml/jaxb/standard/AnalysisResult.java
3525
/* * Copyright (c) 2017 Dmitry Avtonomov * * 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 umich.ms.fileio.filetypes.pepxml.jaxb.standard; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; import org.w3c.dom.Element; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;any processContents='lax' maxOccurs="unbounded"/> * &lt;/sequence> * &lt;attribute name="analysis" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="id" type="{http://regis-web.systemsbiology.net/pepXML}positiveInt" default="1" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "any" }) public class AnalysisResult { @XmlAnyElement(lax = true) protected List<Object> any; @XmlAttribute(name = "analysis", required = true) protected String analysis; @XmlAttribute(name = "id") protected Long id; /** * Gets the value of the any property. * * <p> * This accessor method returns a reference to the live list, not a snapshot. Therefore any * modification you make to the returned list will be present inside the JAXB object. This is why * there is not a <CODE>set</CODE> method for the any property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAny().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list {@link Object } {@link Element } */ public List<Object> getAny() { if (any == null) { any = new ArrayList<Object>(1); } return this.any; } /** * Gets the value of the analysis property. * * @return possible object is {@link String } */ public String getAnalysis() { return analysis; } /** * Sets the value of the analysis property. * * @param value allowed object is {@link String } */ public void setAnalysis(String value) { this.analysis = value; } /** * Gets the value of the id property. * * @return possible object is {@link Long } */ public long getId() { if (id == null) { return 1L; } else { return id; } } /** * Sets the value of the id property. * * @param value allowed object is {@link Long } */ public void setId(Long value) { this.id = value; } }
apache-2.0
zms351/ZPC
src/com/zms/zpc/emulator/board/helper/DMATransferCapable.java
288
package com.zms.zpc.emulator.board.helper; import com.zms.zpc.emulator.board.DMAController; /** * Created by 张小美 on 2019-06-19. * Copyright 2002-2016 */ public interface DMATransferCapable { int handleTransfer(DMAController.DMAChannel channel, int position, int size); }
apache-2.0
ResidualSuspense/TopLine
app/src/main/java/com/jessyan/xs/topline/app/service/DemoService.java
265
package com.jessyan.xs.topline.app.service; import com.jess.arms.base.BaseService; /** * Created by jess on 9/7/16 16:59 * Contact with jess.yan.effort@gmail.com */ public class DemoService extends BaseService { @Override public void init() { } }
apache-2.0
qed-/Aeron
aeron-common/src/main/java/uk/co/real_logic/aeron/common/event/EventLogger.java
7008
/* * Copyright 2014 Real Logic Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.real_logic.aeron.common.event; import uk.co.real_logic.agrona.MutableDirectBuffer; import uk.co.real_logic.agrona.concurrent.UnsafeBuffer; import uk.co.real_logic.agrona.concurrent.ringbuffer.ManyToOneRingBuffer; import java.io.File; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import static uk.co.real_logic.aeron.common.event.EventCode.EXCEPTION; import static uk.co.real_logic.aeron.common.event.EventCode.INVOCATION; /** * Event logger interface for applications/libraries */ public class EventLogger { private static final ThreadLocal<MutableDirectBuffer> ENCODING_BUFFER = ThreadLocal.withInitial( () -> new UnsafeBuffer(ByteBuffer.allocateDirect(EventConfiguration.MAX_EVENT_LENGTH))); private static final long ENABLED_EVENT_CODES = EventConfiguration.getEnabledEventCodes(); /** * The index in the stack trace of the method that called logException(). * * NB: stack[0] is Thread.currentThread().getStackTrace() and * stack[1] is logException(). */ private static final int INVOKING_METHOD_INDEX = 2; private final ManyToOneRingBuffer ringBuffer; public EventLogger(final ByteBuffer buffer) { if (null != buffer) { this.ringBuffer = new ManyToOneRingBuffer(new UnsafeBuffer(buffer)); } else { this.ringBuffer = null; } } public void log(final EventCode code, final MutableDirectBuffer buffer, final int offset, final int length) { if (isEnabled(code, ENABLED_EVENT_CODES)) { final MutableDirectBuffer encodedBuffer = ENCODING_BUFFER.get(); final int encodedLength = EventCodec.encode(encodedBuffer, buffer, offset, length); ringBuffer.write(code.id(), encodedBuffer, 0, encodedLength); } } public void log( final EventCode code, final ByteBuffer buffer, final int offset, final int length, final InetSocketAddress dstAddress) { if (isEnabled(code, ENABLED_EVENT_CODES)) { final MutableDirectBuffer encodedBuffer = ENCODING_BUFFER.get(); final int encodedLength = EventCodec.encode(encodedBuffer, buffer, offset, length, dstAddress); ringBuffer.write(code.id(), encodedBuffer, 0, encodedLength); } } public void log( final EventCode code, final ByteBuffer buffer, final InetSocketAddress dstAddress) { if (isEnabled(code, ENABLED_EVENT_CODES)) { final MutableDirectBuffer encodedBuffer = ENCODING_BUFFER.get(); final int encodedLength = EventCodec.encode(encodedBuffer, buffer, buffer.position(), buffer.remaining(), dstAddress); ringBuffer.write(code.id(), encodedBuffer, 0, encodedLength); } } public void log(final EventCode code, final File file) { if (isEnabled(code, ENABLED_EVENT_CODES)) { logString(code, file.toString()); } } public void logIncompleteSend(final CharSequence type, final int sent, final int expected) { if (isEnabled(EventCode.FRAME_OUT_INCOMPLETE_SEND, ENABLED_EVENT_CODES)) { logString(EventCode.FRAME_OUT_INCOMPLETE_SEND, String.format("%s %d/%d", type, sent, expected)); } } public void logPublicationRemoval(final CharSequence uri, final int sessionId, final int streamId) { if (isEnabled(EventCode.REMOVE_PUBLICATION_CLEANUP, ENABLED_EVENT_CODES)) { logString(EventCode.REMOVE_PUBLICATION_CLEANUP, String.format("%s %x:%x", uri, sessionId, streamId)); } } public void logSubscriptionRemoval(final CharSequence uri, final int streamId, final long id) { if (isEnabled(EventCode.REMOVE_SUBSCRIPTION_CLEANUP, ENABLED_EVENT_CODES)) { logString(EventCode.REMOVE_SUBSCRIPTION_CLEANUP, String.format("%s %x %d", uri, streamId, id)); } } public void logConnectionRemoval(final CharSequence uri, final int sessionId, final int streamId) { if (isEnabled(EventCode.REMOVE_CONNECTION_CLEANUP, ENABLED_EVENT_CODES)) { logString(EventCode.REMOVE_CONNECTION_CLEANUP, String.format("%s %x:%x", uri, sessionId, streamId)); } } public void logOverRun(final long proposedPos, final long subscriberPos, final long windowSize) { if (isEnabled(EventCode.FLOW_CONTROL_OVERRUN, ENABLED_EVENT_CODES)) { logString(EventCode.FLOW_CONTROL_OVERRUN, String.format("%x > %x + %d", proposedPos, subscriberPos, windowSize)); } } public void logChannelCreated(String description) { if (isEnabled(EventCode.CHANNEL_CREATION, ENABLED_EVENT_CODES)) { logString(EventCode.CHANNEL_CREATION, description); } } public void logInvocation() { if (isEnabled(INVOCATION, ENABLED_EVENT_CODES)) { final StackTraceElement[] stack = Thread.currentThread().getStackTrace(); final MutableDirectBuffer encodedBuffer = ENCODING_BUFFER.get(); final int encodedLength = EventCodec.encode(encodedBuffer, stack[INVOKING_METHOD_INDEX]); ringBuffer.write(INVOCATION.id(), encodedBuffer, 0, encodedLength); } } public void logException(final Throwable ex) { if (isEnabled(EXCEPTION, ENABLED_EVENT_CODES)) { final MutableDirectBuffer encodedBuffer = ENCODING_BUFFER.get(); final int encodedLength = EventCodec.encode(encodedBuffer, ex); while (!ringBuffer.write(EXCEPTION.id(), encodedBuffer, 0, encodedLength)) { Thread.yield(); } } else { ex.printStackTrace(); } } private void logString(final EventCode code, final String value) { final MutableDirectBuffer encodedBuffer = ENCODING_BUFFER.get(); final int encodingLength = EventCodec.encode(encodedBuffer, value); ringBuffer.write(code.id(), encodedBuffer, 0, encodingLength); } private static boolean isEnabled(final EventCode code, final long enabledEventCodes) { final long tagBit = code.tagBit(); return (enabledEventCodes & tagBit) == tagBit; } }
apache-2.0
paplorinc/intellij-community
platform/util/src/com/intellij/util/ui/FontInfo.java
7103
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.ui; import java.awt.*; import java.awt.font.FontRenderContext; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import static java.util.Locale.ENGLISH; /** * @author Sergey.Malenkov */ public final class FontInfo { private static final FontInfoComparator COMPARATOR = new FontInfoComparator(); private static final FontRenderContext DEFAULT_CONTEXT = new FontRenderContext(null, false, false); private static final String[] WRONG_SUFFIX = {".plain", ".bold", ".italic", ".bolditalic"}; private static final String[] DEFAULT = {Font.DIALOG, Font.DIALOG_INPUT, Font.MONOSPACED, Font.SANS_SERIF, Font.SERIF}; private static final int DEFAULT_SIZE = 12; private final String myName; private final int myDefaultSize; private final boolean myMonospaced; private volatile Font myFont; private FontInfo(String name, Font font, boolean monospaced) { myName = name; myFont = font; myDefaultSize = font.getSize(); myMonospaced = monospaced; } /** * @return {@code true} if font is monospaced, {@code false} otherwise */ public boolean isMonospaced() { return myMonospaced; } /** * @return a font with the default size */ public Font getFont() { return getFont(myDefaultSize); } /** * @param size required font size * @return a font with the specified size */ public Font getFont(int size) { Font font = myFont; if (size != font.getSize()) { font = font.deriveFont((float)size); myFont = font; } return font; } /** * @return a font name */ @Override public String toString() { return myName != null ? myName : myFont.getFontName(ENGLISH); } /** * @param name the font name to validate * @return an information about the specified font name, * or {@code null} a font cannot render english letters * @see GraphicsEnvironment#isHeadless */ public static FontInfo get(String name) { return name == null || GraphicsEnvironment.isHeadless() ? null : find(LazyListByName.LIST, name); } /** * @param font the font to validate * @return an information about the specified font name, * or {@code null} a font cannot render english letters * @see GraphicsEnvironment#isHeadless */ public static FontInfo get(Font font) { return font == null || GraphicsEnvironment.isHeadless() ? null : find(LazyListByFont.LIST, font.getFontName(ENGLISH)); } /** * @param withAllStyles {@code true} - all fonts, {@code false} - all plain fonts * @return a shared list of fonts according to the specified parameter * @see GraphicsEnvironment#isHeadless */ public static List<FontInfo> getAll(boolean withAllStyles) { return GraphicsEnvironment.isHeadless() ? Collections.emptyList() : withAllStyles ? LazyListByFont.LIST : LazyListByName.LIST; } private static FontInfo find(List<FontInfo> list, String name) { for (FontInfo info : list) { if (info.toString().equalsIgnoreCase(name)) { return info; } } return null; } private static FontInfo byName(String name) { return isWrongSuffix(name) ? null : create(name, null); } private static List<FontInfo> byName() { String[] names = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames(ENGLISH); List<FontInfo> list = new ArrayList<>(names.length); for (String name : names) { FontInfo info = byName(name); if (info != null) list.add(info); } for (String name : DEFAULT) { if (find(list, name) == null) { FontInfo info = byName(name); if (info != null) list.add(info); } } list.sort(COMPARATOR); return Collections.unmodifiableList(list); } private static FontInfo byFont(Font font) { return isWrongSuffix(font.getFontName(ENGLISH)) ? null : create(null, font); } private static List<FontInfo> byFont() { Font[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts(); List<FontInfo> list = new ArrayList<>(fonts.length); for (Font font : fonts) { FontInfo info = byFont(font); if (info != null) list.add(info); } for (String name : DEFAULT) { FontInfo info = find(list, name); if (info != null) list.remove(info); } list.sort(COMPARATOR); return Collections.unmodifiableList(list); } private static FontInfo create(String name, Font font) { boolean plainOnly = name == null; try { if (font == null) { font = new Font(name, Font.PLAIN, DEFAULT_SIZE); // Java uses Dialog family for nonexistent fonts if (!Font.DIALOG.equals(name) && UIUtil.isDialogFont(font)) { throw new IllegalArgumentException("not supported " + font); } } else if (DEFAULT_SIZE != font.getSize()) { font = font.deriveFont((float)DEFAULT_SIZE); name = font.getFontName(ENGLISH); } int width = getFontWidth(font, Font.PLAIN); if (!plainOnly) { if (width != 0 && width != getFontWidth(font, Font.BOLD)) width = 0; if (width != 0 && width != getFontWidth(font, Font.ITALIC)) width = 0; if (width != 0 && width != getFontWidth(font, Font.BOLD | Font.ITALIC)) width = 0; } return new FontInfo(name, font, width > 0); } catch (Throwable ignored) { return null; // skip font that cannot be processed } } private static boolean isWrongSuffix(String name) { for (String suffix : WRONG_SUFFIX) { if (name.endsWith(suffix)) { return true; } } return false; } private static int getFontWidth(Font font, int mask) { if (mask != Font.PLAIN) { //noinspection MagicConstant font = font.deriveFont(mask ^ font.getStyle()); } int width = getCharWidth(font, ' '); return width == getCharWidth(font, 'l') && width == getCharWidth(font, 'W') ? width : 0; } public static boolean isMonospaced(Font font) { return getFontWidth(font, Font.PLAIN) > 0; } private static int getCharWidth(Font font, char ch) { if (font.canDisplay(ch)) { Rectangle bounds = font.getStringBounds(new char[]{ch}, 0, 1, DEFAULT_CONTEXT).getBounds(); if (!bounds.isEmpty()) return bounds.width; } return 0; } private static final class LazyListByName { private static final List<FontInfo> LIST = byName(); } private static final class LazyListByFont { private static final List<FontInfo> LIST = byFont(); } private static final class FontInfoComparator implements Comparator<FontInfo> { @Override public int compare(FontInfo one, FontInfo two) { if (one.isMonospaced() && !two.isMonospaced()) return -1; if (!one.isMonospaced() && two.isMonospaced()) return 1; return one.toString().compareToIgnoreCase(two.toString()); } } }
apache-2.0
jhawo82882/MDP3Sample
test/java/uk/co/real_logic/sbe/generation/java/PackageOutputManagerTest.java
1814
/* * Copyright 2013 Real Logic Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.real_logic.sbe.generation.java; import org.junit.Test; import java.io.File; import java.io.Writer; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import static org.junit.Assert.assertTrue; public class PackageOutputManagerTest { private final String tempDirName = System.getProperty("java.io.tmpdir"); @Test public void shouldCreateFileWithinPackage() throws Exception { final String packageName = "uk.co.real_logic.test"; final String exampleClassName = "ExampleClassName"; final PackageOutputManager pom = new PackageOutputManager(tempDirName, packageName); Writer out = pom.createOutput(exampleClassName); out.close(); final String fullyQualifiedFilename = (tempDirName.endsWith("" + File.separatorChar) ? tempDirName : tempDirName + File.separatorChar) + packageName.replace('.', File.separatorChar) + File.separatorChar + exampleClassName + ".java"; final Path path = FileSystems.getDefault().getPath(fullyQualifiedFilename); final boolean exists = Files.exists(path); Files.delete(path); assertTrue(exists); } }
apache-2.0
nafae/developer
modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201402/video/VideoCampaignCriterionService.java
3177
package com.google.api.ads.adwords.jaxws.v201402.video; import java.net.MalformedURLException; import java.net.URL; import javax.xml.namespace.QName; import javax.xml.ws.Service; import javax.xml.ws.WebEndpoint; import javax.xml.ws.WebServiceClient; import javax.xml.ws.WebServiceException; import javax.xml.ws.WebServiceFeature; /** * This class was generated by the JAX-WS RI. * JAX-WS RI 2.2.4-b01 * Generated source version: 2.1 * */ @WebServiceClient(name = "VideoCampaignCriterionService", targetNamespace = "https://adwords.google.com/api/adwords/video/v201402", wsdlLocation = "https://adwords.google.com/api/adwords/video/v201402/VideoCampaignCriterionService?wsdl") public class VideoCampaignCriterionService extends Service { private final static URL VIDEOCAMPAIGNCRITERIONSERVICE_WSDL_LOCATION; private final static WebServiceException VIDEOCAMPAIGNCRITERIONSERVICE_EXCEPTION; private final static QName VIDEOCAMPAIGNCRITERIONSERVICE_QNAME = new QName("https://adwords.google.com/api/adwords/video/v201402", "VideoCampaignCriterionService"); static { URL url = null; WebServiceException e = null; try { url = new URL("https://adwords.google.com/api/adwords/video/v201402/VideoCampaignCriterionService?wsdl"); } catch (MalformedURLException ex) { e = new WebServiceException(ex); } VIDEOCAMPAIGNCRITERIONSERVICE_WSDL_LOCATION = url; VIDEOCAMPAIGNCRITERIONSERVICE_EXCEPTION = e; } public VideoCampaignCriterionService() { super(__getWsdlLocation(), VIDEOCAMPAIGNCRITERIONSERVICE_QNAME); } public VideoCampaignCriterionService(URL wsdlLocation, QName serviceName) { super(wsdlLocation, serviceName); } /** * * @return * returns VideoCampaignCriterionServiceInterface */ @WebEndpoint(name = "VideoCampaignCriterionServiceInterfacePort") public VideoCampaignCriterionServiceInterface getVideoCampaignCriterionServiceInterfacePort() { return super.getPort(new QName("https://adwords.google.com/api/adwords/video/v201402", "VideoCampaignCriterionServiceInterfacePort"), VideoCampaignCriterionServiceInterface.class); } /** * * @param features * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values. * @return * returns VideoCampaignCriterionServiceInterface */ @WebEndpoint(name = "VideoCampaignCriterionServiceInterfacePort") public VideoCampaignCriterionServiceInterface getVideoCampaignCriterionServiceInterfacePort(WebServiceFeature... features) { return super.getPort(new QName("https://adwords.google.com/api/adwords/video/v201402", "VideoCampaignCriterionServiceInterfacePort"), VideoCampaignCriterionServiceInterface.class, features); } private static URL __getWsdlLocation() { if (VIDEOCAMPAIGNCRITERIONSERVICE_EXCEPTION!= null) { throw VIDEOCAMPAIGNCRITERIONSERVICE_EXCEPTION; } return VIDEOCAMPAIGNCRITERIONSERVICE_WSDL_LOCATION; } }
apache-2.0
mesutcelik/hazelcast
hazelcast/src/test/java/com/hazelcast/map/merge/MapSplitBrainStressTest.java
6477
/* * Copyright (c) 2008-2020, 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.map.merge; import com.hazelcast.config.Config; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.LifecycleEvent; import com.hazelcast.core.LifecycleListener; import com.hazelcast.logging.ILogger; import com.hazelcast.logging.Logger; import com.hazelcast.map.IMap; import com.hazelcast.spi.merge.PassThroughMergePolicy; import com.hazelcast.test.HazelcastSerialClassRunner; import com.hazelcast.test.SplitBrainTestSupport; import com.hazelcast.test.annotation.NightlyTest; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import static java.lang.String.format; import static org.junit.Assert.assertEquals; /** * Runs several iterations of a split-brain and split-brain healing cycle on a constant data set. * <p> * There are {@value #MAP_COUNT} maps which are filled with {@value #ENTRY_COUNT} entries each. * The configured pass through merge policy will trigger the split-brain healing and some merge code, * but will not change any data. */ @RunWith(HazelcastSerialClassRunner.class) @Category(NightlyTest.class) public class MapSplitBrainStressTest extends SplitBrainTestSupport { static final int ITERATION_COUNT = 50; static final int MAP_COUNT = 100; static final int ENTRY_COUNT = 100; static final int FIRST_BRAIN_SIZE = 3; static final int SECOND_BRAIN_SIZE = 2; static final Class MERGE_POLICY = PassThroughMergePolicy.class; static final int TEST_TIMEOUT_IN_MILLIS = 15 * 60 * 1000; static final String MAP_NAME_PREFIX = MapSplitBrainStressTest.class.getSimpleName() + "-"; static final ILogger LOGGER = Logger.getLogger(MapSplitBrainStressTest.class); final Map<HazelcastInstance, UUID> listenerRegistry = new ConcurrentHashMap<HazelcastInstance, UUID>(); final Map<Integer, String> mapNames = new ConcurrentHashMap<Integer, String>(); MergeLifecycleListener mergeLifecycleListener; int iteration = 1; @Override protected Config config() { Config config = super.config(); config.getMapConfig(MAP_NAME_PREFIX + "*") .getMergePolicyConfig() .setPolicy(MERGE_POLICY.getName()); return config; } @Override protected int[] brains() { return new int[]{FIRST_BRAIN_SIZE, SECOND_BRAIN_SIZE}; } @Override protected int iterations() { return ITERATION_COUNT; } @Test(timeout = TEST_TIMEOUT_IN_MILLIS) @Override public void testSplitBrain() throws Exception { super.testSplitBrain(); } @Override protected void onBeforeSplitBrainCreated(HazelcastInstance[] instances) { LOGGER.info("Starting iteration " + iteration); if (iteration == 1) { for (int mapIndex = 0; mapIndex < MAP_COUNT; mapIndex++) { LOGGER.info("Filling map " + mapIndex + "/" + MAP_COUNT + " with " + ENTRY_COUNT + " entries"); String mapName = MAP_NAME_PREFIX + randomMapName(); mapNames.put(mapIndex, mapName); IMap<Integer, Integer> mapOnFirstBrain = instances[0].getMap(mapName); for (int key = 0; key < ENTRY_COUNT; key++) { mapOnFirstBrain.put(key, key); } } } } @Override protected void onAfterSplitBrainCreated(HazelcastInstance[] firstBrain, HazelcastInstance[] secondBrain) { mergeLifecycleListener = new MergeLifecycleListener(secondBrain.length); for (HazelcastInstance instance : secondBrain) { UUID listener = instance.getLifecycleService().addLifecycleListener(mergeLifecycleListener); listenerRegistry.put(instance, listener); } assertEquals(FIRST_BRAIN_SIZE, firstBrain.length); assertEquals(SECOND_BRAIN_SIZE, secondBrain.length); } @Override protected void onAfterSplitBrainHealed(HazelcastInstance[] instances) { // wait until merge completes mergeLifecycleListener.await(); for (Map.Entry<HazelcastInstance, UUID> entry : listenerRegistry.entrySet()) { entry.getKey().getLifecycleService().removeLifecycleListener(entry.getValue()); } int expectedClusterSize = FIRST_BRAIN_SIZE + SECOND_BRAIN_SIZE; assertEquals("expected cluster size " + expectedClusterSize, expectedClusterSize, instances.length); for (int mapIndex = 0; mapIndex < MAP_COUNT; mapIndex++) { String mapName = mapNames.get(mapIndex); IMap<Integer, Integer> map = instances[0].getMap(mapName); assertEquals(format("expected %d entries in map %d/%d (iteration %d)", ENTRY_COUNT, mapIndex, MAP_COUNT, iteration), ENTRY_COUNT, map.size()); for (int key = 0; key < ENTRY_COUNT; key++) { int value = map.get(key); assertEquals(format("expected value %d for key %d in map %d/%d (iteration %d)", value, key, mapIndex, MAP_COUNT, iteration), key, value); } } iteration++; } private static class MergeLifecycleListener implements LifecycleListener { private final CountDownLatch latch; MergeLifecycleListener(int mergingClusterSize) { latch = new CountDownLatch(mergingClusterSize); } @Override public void stateChanged(LifecycleEvent event) { if (event.getState() == LifecycleEvent.LifecycleState.MERGED) { latch.countDown(); } } public void await() { assertOpenEventually(latch); } } }
apache-2.0
linma9/tryAndroidAnimation
Application/build/generated/source/buildConfig/debug/com/example/android/cardview/BuildConfig.java
458
/** * Automatically generated file. DO NOT MODIFY */ package com.example.android.cardview; public final class BuildConfig { public static final boolean DEBUG = Boolean.parseBoolean("true"); public static final String PACKAGE_NAME = "com.example.android.cardview"; public static final String BUILD_TYPE = "debug"; public static final String FLAVOR = ""; public static final int VERSION_CODE = 1; public static final String VERSION_NAME = ""; }
apache-2.0
Union-Investment/Crud2Go
eai-portal-webapp-administration/src/main/java/de/unioninvestment/eai/portal/portlet/crud/mvp/views/DefaultFormView.java
12463
/* * 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 de.unioninvestment.eai.portal.portlet.crud.mvp.views; import java.util.Date; import java.util.Locale; import java.util.Set; import com.vaadin.event.Action; import com.vaadin.event.Action.Handler; import com.vaadin.event.ShortcutAction; import com.vaadin.event.ShortcutAction.KeyCode; import com.vaadin.shared.ui.MarginInfo; import com.vaadin.ui.AbstractComponent; import com.vaadin.ui.AbstractSelect; import com.vaadin.ui.AbstractSelect.ItemCaptionMode; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Button.ClickListener; import com.vaadin.ui.CheckBox; import com.vaadin.ui.ComboBox; import com.vaadin.ui.CssLayout; import com.vaadin.ui.Field; import com.vaadin.ui.FormLayout; import com.vaadin.ui.GridLayout; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Label; import com.vaadin.ui.Layout; import com.vaadin.ui.ListSelect; import com.vaadin.ui.Panel; import com.vaadin.ui.PopupDateField; import com.vaadin.ui.TextField; import com.vaadin.ui.UI; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.themes.LiferayTheme; import de.unioninvestment.eai.portal.portlet.crud.domain.form.SearchFormAction; import de.unioninvestment.eai.portal.portlet.crud.domain.model.CheckBoxFormField; import de.unioninvestment.eai.portal.portlet.crud.domain.model.DateFormField; import de.unioninvestment.eai.portal.portlet.crud.domain.model.FormAction; import de.unioninvestment.eai.portal.portlet.crud.domain.model.FormActions; import de.unioninvestment.eai.portal.portlet.crud.domain.model.FormField; import de.unioninvestment.eai.portal.portlet.crud.domain.model.FormFields; import de.unioninvestment.eai.portal.portlet.crud.domain.model.MultiOptionListFormField; import de.unioninvestment.eai.portal.portlet.crud.domain.model.OptionList; import de.unioninvestment.eai.portal.portlet.crud.domain.model.OptionListFormField; import de.unioninvestment.eai.portal.portlet.crud.mvp.views.ui.OptionListContainer; import de.unioninvestment.eai.portal.portlet.crud.scripting.domain.FormSelectionContext; import de.unioninvestment.eai.portal.support.vaadin.date.DateUtils; import de.unioninvestment.eai.portal.support.vaadin.mvp.View; import de.unioninvestment.eai.portal.support.vaadin.support.ConvertablePropertyWrapper; import de.unioninvestment.eai.portal.support.vaadin.validation.FieldValidator; /** * {@link View} für Formularansicht. Bei einspaltiger Ansicht werden die Felder * untereinander, und links davon als Label jeweils die Titel angezeigt. Bei * mehrspaltiger Ansicht werden die Label über den Eingabefeldern angezeigt. * * Unter den Eingabefeldern werden Aktions-Buttons horizontal angeordnet * dargestellt. * * @author carsten.mjartan */ public class DefaultFormView extends Panel implements FormView, Handler { private static final long serialVersionUID = 1L; private static final Action ACTION_ENTER = new ShortcutAction("Enter", KeyCode.ENTER, null); private static final Action[] FORM_ACTIONS = { ACTION_ENTER }; private Presenter presenter; private FormAction searchAction; private VerticalLayout rootLayout; private Layout fieldLayout; @Override public void initialize(Presenter presenter, de.unioninvestment.eai.portal.portlet.crud.domain.model.Form model) { // @since 1.45 if (model.getWidth() != null) { setWidth(model.getWidth()); } // @since 1.45 if (model.getHeight() != null) { setHeight(model.getHeight()); } this.presenter = presenter; int columns = model.getColumns(); FormFields fields = model.getFields(); FormActions actions = model.getActions(); rootLayout = new VerticalLayout(); setStyleName(LiferayTheme.PANEL_LIGHT); addStyleName("c2g-form"); setContent(rootLayout); addActionHandler(this); if (columns > 1) { fieldLayout = layoutAsGrid(columns, fields.count()); } else { fieldLayout = layoutAsForm(); } populateFields(fields, columns); rootLayout.addComponent(fieldLayout); createFooterAndPopulateActions(actions); } private Layout layoutAsForm() { return new FormLayout(); } private GridLayout layoutAsGrid(int columns, int fieldCount) { int rows = calculateRowCount(columns, fieldCount); GridLayout grid = new GridLayout(columns, rows); grid.setMargin(new MarginInfo(true, false, true, false)); grid.setSpacing(true); grid.setWidth("100%"); return grid; } private void populateFields(FormFields fields, int columns) { for (FormField field : fields) { Field<?> vaadinField; if (field instanceof MultiOptionListFormField) { vaadinField = createMultiSelect((MultiOptionListFormField) field); } else if (field instanceof OptionListFormField) { vaadinField = createSelect((OptionListFormField) field); } else if (field instanceof CheckBoxFormField) { vaadinField = createCheckBox(field, columns); } else if (field instanceof DateFormField) { vaadinField = createDateFormField(field); } else { vaadinField = createTextField(field); } applyValidators(field, vaadinField); if (!(field instanceof CheckBoxFormField)) { addFieldToLayout(field, vaadinField); } } } private Field<Date> createDateFormField(FormField field) { DateFormField dff = (DateFormField) field; PopupDateField datetime = new PopupDateField(field.getTitle()); datetime.setInputPrompt(field.getInputPrompt()); datetime.setDateFormat(dff.getDateFormat()); datetime.setLocale(Locale.GERMAN); datetime.setResolution(DateUtils.getVaadinResolution(dff .getResolution())); ConvertablePropertyWrapper<Date, String> wrapper = new ConvertablePropertyWrapper<Date, String>( dff.getProperty(), dff.getConverter(), UI.getCurrent() .getLocale()); datetime.setPropertyDataSource(wrapper); datetime.setImmediate(true); datetime.addStyleName(field.getName()); return datetime; } private Field<String> createTextField(FormField field) { TextField textField = new TextField(field.getTitle(), field.getProperty()); // applyValidators(field, textField); textField.setNullSettingAllowed(true); textField.setNullRepresentation(""); textField.setImmediate(true); textField.addStyleName(field.getName()); applyInputPrompt(field, textField); return textField; } private void addFieldToLayout(FormField field, Field<?> vaadinField) { fieldLayout.addComponent(vaadinField); if (fieldLayout instanceof GridLayout) { vaadinField.setWidth("100%"); if (field.getTitle().length() > 15) { if (vaadinField instanceof AbstractComponent) { ((AbstractComponent) vaadinField).setDescription(field .getTitle()); } } ((GridLayout) fieldLayout).setComponentAlignment(vaadinField, Alignment.BOTTOM_LEFT); } } private void applyValidators(FormField field, Field<?> textField) { if (field.getValidators() != null) { for (FieldValidator validator : field.getValidators()) { validator.apply(textField); } } } private Field<?> createSelect(OptionListFormField field) { AbstractSelect select; if (field.getVisibleRows() <= 1) { select = new ComboBox(field.getTitle()); } else { select = new ListSelect(field.getTitle()); ((ListSelect) select).setRows(field.getVisibleRows()); } fillOptions(field.getOptionList(), select, new FormSelectionContext( field)); // addOptionListChangeListener(field, select, new FormSelectionContext( // field)); select.setPropertyDataSource(field.getProperty()); select.setInvalidAllowed(false); select.setImmediate(true); select.setMultiSelect(false); select.addStyleName(field.getName()); return select; } private Field<?> createMultiSelect(MultiOptionListFormField field) { ListSelect select = new ListSelect(field.getTitle()); fillOptions(field.getOptionList(), select, new FormSelectionContext( field)); // addOptionListChangeListener(field, select, new FormSelectionContext( // field)); select.setMultiSelect(true); select.setPropertyDataSource(field.getListProperty()); select.setInvalidAllowed(false); select.setImmediate(true); select.setRows(field.getVisibleRows()); select.addStyleName(field.getName()); return select; } private void fillOptions(OptionList optionList, AbstractSelect select, FormSelectionContext ctx) { Object currentValue = select.getValue(); select.setContainerDataSource(new OptionListContainer(optionList, ctx)); select.setItemCaptionMode(ItemCaptionMode.PROPERTY); select.setItemCaptionPropertyId("title"); reapplyCurrentValue(select, currentValue); } private void reapplyCurrentValue(AbstractSelect select, Object currentValue) { if (currentValue != null) { if (select.isMultiSelect()) { for (Object element : (Set<?>) currentValue) { if (select.containsId(element)) { select.select(element); } } } else { if (select.containsId(currentValue)) { select.setValue(currentValue); } } } } private Field<Boolean> createCheckBox(FormField field, int columns) { CheckBoxFormField checkBoxFormField = (CheckBoxFormField) field; Layout checkboxLayout = null; if (columns == 1) { checkboxLayout = new HorizontalLayout(); checkboxLayout.setCaption(field.getTitle()); } else { checkboxLayout = new VerticalLayout(); Label checkBoxLabel = new Label(field.getTitle()); checkboxLayout.addComponent(checkBoxLabel); } CheckBox checkBoxField = new CheckBox(); checkboxLayout.addComponent(checkBoxField); checkBoxField.setConverter(checkBoxFormField.getConverter()); checkBoxField.setPropertyDataSource(checkBoxFormField.getProperty()); checkBoxField.setImmediate(true); checkBoxField.addStyleName(field.getName()); // addField(field.getName(), checkBoxField); fieldLayout.addComponent(checkboxLayout); return checkBoxField; } private void applyInputPrompt(FormField field, TextField textField) { String inputPrompt = field.getInputPrompt(); if (inputPrompt != null) { textField.setInputPrompt(inputPrompt); } } @SuppressWarnings("serial") private void createFooterAndPopulateActions(FormActions actions) { CssLayout buttons = new CssLayout(); buttons.setStyleName("actions"); boolean allHidden = true; for (final FormAction action : actions) { final Button button = new Button(action.getTitle()); button.setDisableOnClick(true); button.addClickListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { try { presenter.executeAction(action); } finally { button.setEnabled(true); } } }); if (action.getActionHandler() instanceof SearchFormAction) { if (searchAction == null) { searchAction = action; // button.setClickShortcut(KeyCode.ENTER); } } if (action.isHidden()) { button.setVisible(false); } else { allHidden = false; } buttons.addComponent(button); } if (!allHidden) { rootLayout.addComponent(buttons); } } /** * Berechnet die Anzahl der Zeilen. * * @param columns * Spalten * @param fieldCount * Anzahl Felder * @return Anzahl Zeilen */ static int calculateRowCount(int columns, int fieldCount) { return ((fieldCount - 1) / columns) + 1; } @Override public FormAction getSearchAction() { return searchAction; } @Override public Action[] getActions(Object target, Object sender) { if (searchAction != null && sender == this) { return FORM_ACTIONS; } return null; } @Override public void handleAction(Action action, Object sender, Object target) { if (action == ACTION_ENTER) { presenter.executeAction(searchAction); } } }
apache-2.0
RakickayaKaterina/Java-training
task7/courseplanner-services/src/com/senla/rakickaya/courseplanner/services/TimeTableService.java
5596
package com.senla.rakickaya.courseplanner.services; import java.util.ArrayList; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import com.senla.rakickaya.courseplanner.api.beans.ICourse; import com.senla.rakickaya.courseplanner.api.beans.ILecture; import com.senla.rakickaya.courseplanner.api.beans.ILesson; import com.senla.rakickaya.courseplanner.api.repositories.ICoursesRepository; import com.senla.rakickaya.courseplanner.api.repositories.ITimeTable; import com.senla.rakickaya.courseplanner.api.services.ITimeTableService; import com.senla.rakickaya.courseplanner.beans.Lesson; import com.senla.rakickaya.courseplanner.configuration.Config; import com.senla.rakickaya.courseplanner.csv.converters.ConverterFromCsv; import com.senla.rakickaya.courseplanner.csv.converters.ConverterToCsv; import com.senla.rakickaya.courseplanner.csv.converters.entities.CsvResponse; import com.senla.rakickaya.courseplanner.exception.EntityNotFoundException; import com.senla.rakickaya.courseplanner.repositories.CoursesRepository; import com.senla.rakickaya.courseplanner.repositories.TimeTable; import com.senla.rakickaya.courseplanner.utils.DateWorker; import com.senla.rakickaya.courseplanner.utils.FileWorker; import com.senla.rakickaya.courseplanner.utils.GeneratorId; import com.senla.rakickaya.courseplanner.utils.ListWorker; public class TimeTableService implements ITimeTableService { private static final Logger logger = Logger.getLogger(TimeTableService.class.getName()); private final ITimeTable mTimeTable; private final ICoursesRepository mRepositoryCourses; public TimeTableService() { super(); this.mTimeTable = TimeTable.getInstance(); this.mRepositoryCourses = CoursesRepository.getInstance(); } @Override public void addLesson(ILesson pLesson) { mTimeTable.addLesson(pLesson); } @Override public void createLesson(long idLecture, Date dateForLecture, int countStudent) throws Exception { ILecture lecture = getLectureCourse(idLecture); List<ILesson> timeTable = getLessons(dateForLecture); int amount = 0; for (ILesson lesson : timeTable) { amount += lesson.getCountStudent(); } if (lecture != null && amount + countStudent <= Config.getInstance().getAmountStudents()) { mTimeTable.addLesson( new Lesson(0L, lecture, dateForLecture, countStudent)); } else { throw new Exception("Limit Students"); } } @Override public void removeLesson(long pId) { mTimeTable.removeLesson(pId); } @Override public void updateLesson(ILesson pLesson) { mTimeTable.updateLesson(pLesson); } @Override public ILesson getLesson(long pId) { return mTimeTable.getLesson(pId); } @Override public List<ILesson> getLessons(Date pDate) { List<ILesson> resultList = new ArrayList<>(); List<ILesson> allLessons = mTimeTable.getLessons(); for (int i = 0; i < allLessons.size(); i++) { if (DateWorker.isEqualsDate(pDate, allLessons.get(i).getDate())) resultList.add(allLessons.get(i)); } return resultList; } @Override public void removeLessonByLecture(long idLecture) throws EntityNotFoundException { List<ILesson> lessons = mTimeTable.getLessons(); boolean exist = false; for (int i = 0; i < lessons.size(); i++) { ILecture lecture = lessons.get(i).getLecture(); if (lecture.getId() == idLecture) { ListWorker.removeItemById(lessons, lessons.get(i).getId()); exist = true; } } if (!exist) { throw new EntityNotFoundException(); } } private ILecture getLectureCourse(long id) { for (ICourse course : mRepositoryCourses.getCourses()) { for (ILecture lecture : course.getLectures()) { if (lecture.getId() == id) { return lecture; } } } return null; } @Override public void exportCSV(String path) { FileWorker worker = new FileWorker(path); List<String> csvEntities = new ArrayList<>(); List<ILesson> lessons = mTimeTable.getLessons(); for (ILesson lesson : lessons) { try { String csvString; csvString = ConverterToCsv.convert(lesson); csvEntities.add(csvString); } catch (Exception e) { logger.error(e.getMessage()); } } worker.write(csvEntities); } @Override public void importCSV(String path) { final String LECTURE = "mLecture"; List<ILesson> lessons = new ArrayList<>(); try { FileWorker worker = new FileWorker(path); List<String> list = worker.read(); for (String str : list) { CsvResponse response = ConverterFromCsv.convert(str, Lesson.class); ILesson lesson = (ILesson) response.getEntity(); Map<String, Object> map = response.getRelation(); if (map.containsKey(LECTURE)) { Long idLecture = (Long) map.get(LECTURE); ILecture lecture = getLectureCourse(idLecture); lesson.setLecture(lecture); } lessons.add(lesson); } } catch (Exception e) { logger.error(e.getMessage()); } for (ILesson lesson : lessons) { if (!mTimeTable.addLesson(lesson)) { mTimeTable.updateLesson(lesson); } else { GeneratorId generatorId = GeneratorId.getInstance(); long id = generatorId.getIdLesson(); if (lesson.getId() > id) { generatorId.setIdLesson(id); } } } } @Override public List<ILesson> getSortedList(Comparator<ILesson> pComparator) { List<ILesson> listLesson = mTimeTable.getLessons(); listLesson.sort(pComparator); return listLesson; } }
apache-2.0
leafclick/intellij-community
platform/platform-api/src/com/intellij/ide/ui/LafManagerListener.java
685
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.ui; import com.intellij.util.messages.Topic; import org.jetbrains.annotations.NotNull; import java.util.EventListener; /** * If you are interested in listening UI changes you have to * use this listener instead of registering {@code PropertyChangeListener} * into {@code UIManager} * * @author Vladimir Kondratyev */ public interface LafManagerListener extends EventListener { Topic<LafManagerListener> TOPIC = new Topic<>(LafManagerListener.class); void lookAndFeelChanged(@NotNull LafManager source); }
apache-2.0
Unicon/cas
support/cas-server-support-saml-sp-integrations/src/main/java/org/apereo/cas/config/CasSamlSPAcademicWorksConfiguration.java
789
package org.apereo.cas.config; import org.apereo.cas.configuration.CasConfigurationProperties; import org.apereo.cas.configuration.model.support.saml.sps.AbstractSamlSPProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Configuration; /** * This is {@link CasSamlSPAcademicWorksConfiguration}. * * @author Misagh Moayyed * @since 5.1.0 */ @Configuration("casSamlSPAcademicWorksConfiguration") @EnableConfigurationProperties(CasConfigurationProperties.class) public class CasSamlSPAcademicWorksConfiguration extends BaseCasSamlSPConfiguration { @Override protected AbstractSamlSPProperties getServiceProvider() { return casProperties.getSamlSp().getAcademicWorks(); } }
apache-2.0
deepjava/runtime-library
src/org/deepjava/runtime/mpc555/test/FlashTest1.java
1559
/* * Copyright 2011 - 2013 NTB University of Applied Sciences in Technology * Buchs, Switzerland, http://www.ntb.ch/inf * * 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.deepjava.runtime.mpc555.test; import java.io.PrintStream; import org.deepjava.runtime.mpc555.IntbMpc555HB; import org.deepjava.runtime.mpc555.driver.SCI; import org.deepjava.runtime.mpc555.driver.ffs.AM29LV160; import org.deepjava.unsafe.US; /*changes: * 2.5.11 NTB/GRAU creation */ public class FlashTest1 implements IntbMpc555HB { static final int flashAddr = extFlashBase + 0x20008; static { SCI sci = SCI.getInstance(SCI.pSCI2); sci.start(9600, SCI.NO_PARITY, (short)8); System.out = new PrintStream(sci.out); System.out.println("flash test"); System.out.printHexln(US.GET4(flashAddr)); // AM29LV160.programShort(flashAddr, (short)0xaaaa); // AM29LV160.programShort(flashAddr+2, (short)0x8888); AM29LV160.eraseSector(flashAddr); System.out.printHexln(US.GET4(flashAddr)); } }
apache-2.0
tobyweston/tempus-fugit
src/test/java/com/google/code/tempusfugit/concurrency/CallableAdapterTest.java
2805
/* * Copyright (c) 2009-2018, toby weston & tempus-fugit committers * * 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.code.tempusfugit.concurrency; import com.google.code.tempusfugit.temporal.Condition; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.api.Action; import org.jmock.integration.junit4.JMock; import org.junit.Test; import org.junit.runner.RunWith; import java.util.concurrent.Callable; import static com.google.code.tempusfugit.concurrency.CallableAdapter.condition; import static com.google.code.tempusfugit.concurrency.CallableAdapter.runnable; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.jmock.Expectations.returnValue; import static org.jmock.Expectations.throwException; @RunWith(JMock.class) public class CallableAdapterTest { private final Mockery context = new Mockery(); private final Callable callable = context.mock(Callable.class); private static final Object RESULT = new Object(); @Test public void callableToRunnableDelegates() throws Exception { callableWill(returnValue(RESULT)); runnable(callable).run(); } @Test(expected = RuntimeException.class) public void callableToRunnableExceptionPropagates() throws Exception { callableWill(throwException(new Exception())); runnable(callable).run(); } @Test public void callableToConditionWorksReturningTrue() throws Exception { callableWill(returnValue(true)); Condition condition = condition(callable); assertThat(condition.isSatisfied(), is(true)); } @Test public void callableToConditionWorksReturningFalse() throws Exception { callableWill(returnValue(false)); Condition condition = condition(callable); assertThat(condition.isSatisfied(), is(false)); } @Test public void callableToConditionReturnsFalseWhenCallableThrowsException() throws Exception { callableWill(throwException(new Exception())); Condition condition = condition(callable); assertThat(condition.isSatisfied(), is(false)); } private void callableWill(final Action action) throws Exception { context.checking(new Expectations() {{ oneOf(callable).call(); will(action); }}); } }
apache-2.0
BCProgramming/ChestRandomizer
src/com/BASeCamp/SurvivalChests/RandomizerCommand.java
48156
package com.BASeCamp.SurvivalChests; import java.awt.Rectangle; import java.awt.geom.Rectangle2D; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Random; import java.util.Timer; import me.ryanhamshire.GriefPrevention.Claim; import org.bukkit.*; import org.bukkit.World.Environment; import org.bukkit.block.*; import org.bukkit.command.*; import org.bukkit.entity.Creeper; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.entity.minecart.StorageMinecart; import org.bukkit.generator.ChunkGenerator; import org.bukkit.inventory.*; import org.bukkit.potion.PotionEffect; import org.bukkit.scoreboard.DisplaySlot; import org.bukkit.scoreboard.Objective; import org.bukkit.scoreboard.Score; import org.bukkit.scoreboard.Scoreboard; import org.bukkit.scoreboard.ScoreboardManager; //import org.fusesource.jansi.Ansi.Color; import BASeCamp.Configuration.INIFile; import com.BASeCamp.SurvivalChests.*; import com.BASeCamp.SurvivalChests.Events.GameStartEvent; import com.BASeCamp.SurvivalChests.Events.ParticipantJoinEvent; import com.sk89q.worldedit.Vector; public class RandomizerCommand implements CommandExecutor { private BCRandomizer _Owner = null; private LinkedList<Player> joinedplayers = new LinkedList<Player>(); // list // of // players // that // accepted // to // join // a // game. private LinkedList<Player> spectating = new LinkedList<Player>(); // list of // players // ready // to // spectate // a // preparing // game. private boolean accepting = false; private boolean MobArenaMode = false; private boolean AutoPrepare = true; public int JoinStartDelay = 0; private int JoinDelayTaskID=0; private int ChestTimeout=400; private int uselives = 1; //number of lives, defaults to one. private boolean HardcoreHealth=false; private Location _SpawnSpot = null; private int MobTimeout = 0; //0 means no mobtimeout at all. any other value is a number of seconds //before Mob spawning will be force-enabled. public int getChestTimeout() { return ChestTimeout;} public void setChestTimeout(int value) { ChestTimeout = value;} public boolean getaccepting() { return accepting; } public LinkedList<Player> getjoinedplayers() { return joinedplayers; } World playingWorld = null; public HashMap<Player, ReturnData> returninfo = new HashMap<Player, ReturnData>(); public BCRandomizer getOwner() { return _Owner; } public void setOwner(BCRandomizer value) { _Owner = value; } public RandomizerCommand(BCRandomizer Owner) { _Owner = Owner; } private String TeamList(Player[] listing) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < listing.length; i++) { sb.append(listing[i]); if (i < listing.length - 1) sb.append(","); } return sb.toString(); } public List<Player> getAllPlayers() { LinkedList<Player> createlist = new LinkedList<Player>(); for (World w : Bukkit.getWorlds()) { for (Player p : w.getPlayers()) { createlist.add(p); } } return createlist; } public static List<String> getPlayerNames(List<Player> source) { LinkedList<String> retval = new LinkedList<String>(); for (Player Playerp : source) { retval.add(Playerp.getName()); } return retval; } private void addSpectator(Player p) { spectating.add(p); // if there is a game in progress, we need to also give them fly and // vanish them. if (isGameActive()) { p.setAllowFlight(true); for (Player pp : joinedplayers) { pp.hidePlayer(p); } } } private void enableMobSpawns() { for(GameTracker gt:_Owner.ActiveGames){ gt.getWorld().setGameRuleValue("doMobSpawns", "true"); } } private void CreateBorder(final World useworld,Location BorderA,Location BorderB){ final int XMin = Math.min(BorderA.getBlockX(),BorderB.getBlockX()); final int ZMin = Math.min(BorderA.getBlockZ(), BorderB.getBlockZ()); final int XMax = Math.max(BorderA.getBlockX(), BorderB.getBlockX()); final int ZMax = Math.max(BorderA.getBlockZ(),BorderB.getBlockZ()); final boolean createceiling=true; //we want to fill in from 0 to 128 of each Y coordinate. //wall one: xMin side. //schedule each. Bukkit.getScheduler().scheduleSyncDelayedTask(_Owner, new Runnable(){ public void run() { for(int currz = ZMin;currz<ZMax;currz++){ for(int usey=0;usey<256;usey++){ useworld.getBlockAt(XMin,usey,currz).setType(Material.BEDROCK); } } //wall 2: xMax side. for(int currz = ZMin;currz<ZMax;currz++){ for(int usey=0;usey<256;usey++){ useworld.getBlockAt(XMax,usey,currz).setType(Material.BEDROCK); } } //wall 3, ZMin side. for(int currx=XMin;currx<XMax;currx++){ for(int usey = 0;usey<128;usey++){ useworld.getBlockAt(currx,usey,ZMin).setType(Material.BEDROCK); } } //wall 4, ZMax side. for(int currx=XMin;currx<XMax;currx++){ for(int usey = 0;usey<128;usey++){ useworld.getBlockAt(currx,usey,ZMax).setType(Material.BEDROCK); } } if(createceiling){ /*for(int currx=XMin;currx<XMax;currx++){ for(int currz=ZMin;currz<ZMax;currz++){ useworld.getBlockAt(currx,128,currz).setType(Material.BEDROCK); } }*/ } }}); } private double MinimumDistance(List<Location> check,Location loc){ double currmin = Double.MAX_VALUE; double grabdist=0; if(check.size()==0) return Double.MAX_VALUE; for(Location iterate:check){ grabdist = distance(iterate.getBlockX(),iterate.getBlockY(),loc.getBlockX(),loc.getBlockY()); if((grabdist<currmin)) { currmin = grabdist; } } return grabdist; } private double distance(float Ax,float Ay,float Bx,float By){ float xs = (Bx-Ax)*(Bx-Ax); float ys = (By-Ay)*(By-Ay); return Math.sqrt((xs+ys)); } private void CreateFeatures(World inWorld,float featuredensity,Location BorderA,Location BorderB){ LinkedList<Location> AddedLocation = new LinkedList<Location>(); LinkedList<Rectangle> SavedRegions = new LinkedList<Rectangle>(); final int XMin = Math.min(BorderA.getBlockX(),BorderB.getBlockX())+10; final int ZMin = Math.min(BorderA.getBlockZ(), BorderB.getBlockZ())+10; final int XMax = Math.max(BorderA.getBlockX(), BorderB.getBlockX())-10; final int ZMax = Math.max(BorderA.getBlockZ(),BorderB.getBlockZ())-10; /* for(int i=0;i<featuredensity;i++){ //choose a random location. int XPos = RandomData.rgen.nextInt(XMax-XMin) + XMin; int ZPos = RandomData.rgen.nextInt(ZMax-ZMin) + ZMin; int YPos = inWorld.getHighestBlockYAt(XPos, ZPos); Location addlocation = new Location(inWorld,XPos,YPos,ZPos); if(MinimumDistance(AddedLocation,addlocation)>32){ AddedLocation.add(addlocation); ArenaGenerationFeature agf = RandomData.rgen.nextFloat()>0.2f? new OutsideChestFeature():new BrokenWall(); agf.GenerateFeature(inWorld.getBlockAt(XPos,YPos,ZPos).getLocation()); } }*/ for(int i=0;i<featuredensity*Math.sqrt((XMax-XMin)+(ZMax-ZMin));i++){ //SchematicImporter.Init(_Owner); int rmaker = RandomData.rgen.nextInt(3)+2; for(SchematicImporter si:SchematicImporter.Schematics.values()){ int XPos = RandomData.rgen.nextInt(XMax-XMin) + XMin; int ZPos = RandomData.rgen.nextInt(ZMax-ZMin) + ZMin; //int YPos = inWorld.getHighestBlockYAt(XPos, ZPos); int YPos=0; YPos = BCRandomizer.getHighestBlockYAt(inWorld,XPos,YPos); System.out.println("placing schematic at " + XPos + " " + YPos + " " + ZPos); Location loc = new Location(inWorld,XPos,YPos,ZPos); si.getClip().rotate2D(90*RandomData.rgen.nextInt(4)); Rectangle thispos = new Rectangle(XPos-1,ZPos-1,si.getClip().getWidth()+1,si.getClip().getLength()+1); boolean foundintersection = false; for(Rectangle iterate:SavedRegions){ if(iterate.intersects(thispos)){ foundintersection=true; break; } } if(!foundintersection){ if(si.Place(inWorld, new Location(inWorld,XPos,YPos,ZPos), RandomData.rgen.nextInt(4))){ AddedLocation.add(loc); SavedRegions.add(thispos); System.out.println("Placing Schematic"); } } } } } public static LinkedList<String> ArenaNames = new LinkedList<String>(); //prepares a NEW arena. //tasks: //create a new, random map. //create border. we center the arena around the origin. This will be bedrock surrounding the map. //spawn the chests around the arena. //teleport the calling player to the created world. private void PrepareArena(Player pCaller,String worldName,int XSize,int ZSize,float featuredensity){ ArenaNames.add(worldName); Bukkit.broadcastMessage(BCRandomizer.Prefix + "Creating Arena."); Bukkit.broadcastMessage(BCRandomizer.Prefix + "Name:" + worldName + " Dimensions:" + XSize + "," + ZSize +" "); WorldCreator wc = new WorldCreator(worldName); wc.environment(Environment.NORMAL); wc.generateStructures(true); wc.type(WorldType.NORMAL); World spawnworld = wc.createWorld(); //get the topmost block at 0,0. int Ypos = spawnworld.getHighestBlockYAt(0,0); Location usespawn = new Location(spawnworld,0,Ypos,0); spawnworld.setSpawnLocation(0,Ypos,0); Location BorderA = new Location(spawnworld,-XSize/2,0,-ZSize/2); Location BorderB = new Location(spawnworld,XSize/2,0,ZSize/2); useBorderA = BorderA; useBorderB = BorderB; CreateFeatures(spawnworld,featuredensity,BorderA,BorderB); CreateBorder(spawnworld,BorderA,BorderB); spawnworld.getSpawnLocation().getChunk().load(); //teleport the player to this world. //ideally the player knows to use /mwtp to leave a world. pCaller.teleport(spawnworld.getSpawnLocation()); pCaller.setBedSpawnLocation(spawnworld.getSpawnLocation()); } private void saveborder(World w) { String borderfile = BCRandomizer.pluginMainDir + File.separatorChar + w.getName() + ".border"; File bfile = new File(borderfile); try { BufferedWriter fw = new BufferedWriter(new FileWriter(bfile)); fw.write(String.valueOf(useBorderA.getBlockX()) + "\n"); fw.write(String.valueOf(useBorderA.getBlockY()) + "\n"); fw.write(String.valueOf(useBorderA.getBlockZ()) + "\n"); fw.write(String.valueOf(useBorderB.getBlockX()) + "\n"); fw.write(String.valueOf(useBorderB.getBlockY()) + "\n"); fw.write(String.valueOf(useBorderB.getBlockZ()) + "\n"); fw.close(); } catch(IOException iox) { } } private void loadborder(World w) { //look for <worldname.border> in plugin folder. String borderfile = BCRandomizer.pluginMainDir + File.separatorChar + w.getName() + ".border"; File bfile = new File(borderfile); if(bfile.exists()){ try { BufferedReader fr = new BufferedReader(new FileReader(bfile)); //read a few ints... 6, 3 for each border. int ax,ay,az; ax = Integer.parseInt(fr.readLine()); ay = Integer.parseInt(fr.readLine()); az = Integer.parseInt(fr.readLine()); int bx,by,bz; bx = Integer.parseInt(fr.readLine()); by = Integer.parseInt(fr.readLine()); bz = Integer.parseInt(fr.readLine()); fr.close(); useBorderA = new Location(w,ax,ay,az); useBorderB = new Location(w,bx,by,bz); } catch(IOException iox){} } } @Override public boolean onCommand(CommandSender sender, Command arg1, String arg2, String[] arg3) { // TODO Auto-generated method stub BCRandomizer.emitmessage("onCommand:" + arg2); Player p = null; if (sender instanceof Player) { // make sure they have permission. p = (Player) sender; String usecmd = arg2.toLowerCase(); String WorldName = p.getWorld().getName().toLowerCase(); String permnode = "chestrandomizer." + WorldName + "." + usecmd; if(usecmd.equalsIgnoreCase("strike")) { Block b = p.getTargetBlock(new HashSet<Byte>(), 200); Location l = b.getLocation(); l.getWorld().strikeLightning(l); } if (!p.hasPermission(permnode) && !arg2.equalsIgnoreCase("joingame") && !arg2.equalsIgnoreCase("spectategame")) { if (!p.isOp()) { if (p.getGameMode() == GameMode.CREATIVE) p.setGameMode(GameMode.ADVENTURE); p.getWorld().strikeLightning(p.getLocation()); p.getWorld().strikeLightningEffect(p.getLocation()); p.damage(50); Bukkit .broadcastMessage(ChatColor.RED + p.getName() + " tried to use a SurvivalChest command, but isn't an op. punishment applied."); } else { p .sendMessage(BCRandomizer.Prefix + "You do not have permission to use that command."); p.sendMessage(BCRandomizer.Prefix + ChatColor.GREEN + "NODE:" + permnode); } return true; } } if(arg2.equalsIgnoreCase("fixup")){ doFixUp(p); } else if(arg2.equalsIgnoreCase("listworlds")){ //list worlds. StringBuffer sb = new StringBuffer(); p.sendMessage(BCRandomizer.Prefix + "Loaded Worlds(" + String.valueOf(Bukkit.getWorlds().size()) + ":"); for(World iterateworld:Bukkit.getWorlds()){ p.sendMessage(BCRandomizer.Prefix + iterateworld.getName()); } } else if(arg2.equalsIgnoreCase("hardcorehealth")){ HardcoreHealth=!HardcoreHealth; String usemessage = BCRandomizer.Prefix + " Hardcore Health:" + (HardcoreHealth?"Enabled":"Disabled"); if(p==null) System.out.println(usemessage); else p.sendMessage(usemessage); } else if(arg2.equalsIgnoreCase("mwdel")){ if(arg3.length==0){ p.sendMessage(ChatColor.RED + "mwdel <worldname>"); } else { //find that world. World foundworld = null; String findworld=arg3[0]; for(int i=1;i<arg3.length;i++){ findworld = findworld + " " + arg3[i]; } for(World iterate:Bukkit.getWorlds()){ if(iterate.getName().equalsIgnoreCase(findworld)){ foundworld = iterate; break; } } if(foundworld==null){ p.sendMessage("couldn't find world:" + findworld); } else { if(foundworld.getPlayers().size()>0){ p.sendMessage(BCRandomizer.Prefix + " Cannot delete world. Contains " + foundworld.getPlayers().size() + " Players."); for(Player iterate:foundworld.getPlayers()){ p.sendMessage(BCRandomizer.Prefix + iterate.getDisplayName()); } } else { Bukkit.getWorlds().remove(foundworld); foundworld.getWorldFolder().deleteOnExit(); } } } } else if(arg2.equalsIgnoreCase("mwtp")){ if(arg3.length==0){ p.sendMessage(ChatColor.RED + "mwtp <worldname>"); } else { //find that world. World foundworld = null; String findworld=arg3[0]; for(int i=1;i<arg3.length;i++){ findworld = findworld + " " + arg3[i]; } for(World iterate:Bukkit.getWorlds()){ if(iterate.getName().equalsIgnoreCase(findworld)){ foundworld = iterate; break; } } if(foundworld==null){ p.sendMessage("couldn't find world:" + findworld); } else { p.teleport(foundworld.getSpawnLocation()); } } } else if(arg2.equalsIgnoreCase("newarena")){ if(arg3.length<4){ p.sendMessage(BCRandomizer.Prefix + " syntax: /newarena <worldname> <XSize> <ZSize> <FeatureDensity>"); } else { try { String useworldname = arg3[0]; String XS = arg3[1]; String ZS = arg3[2]; String FeatureDens = arg3[3]; int YSize = Integer.parseInt(XS); int ZSize = Integer.parseInt(ZS); float FeatureDensity = Float.parseFloat(FeatureDens); PrepareArena(p,useworldname,YSize,ZSize,FeatureDensity); } catch(NumberFormatException nfe){ nfe.printStackTrace(); p.sendMessage(BCRandomizer.Prefix + " syntax: /newarena <worldname> <XSize> <ZSize> <FeatureDensity>"); } } } else if (arg2.equalsIgnoreCase("randomizespawners")) { SpawnerRandomizer sr = new SpawnerRandomizer(_Owner); sr.RandomizeSpawners(p.getWorld()); } else if(arg2.equalsIgnoreCase("setlives")){ if(arg3.length==0) { String usemessage = BCRandomizer.Prefix + "Lives:" + String.valueOf(uselives); } else { try { uselives = Integer.parseInt(arg3[0]); if(uselives==0) uselives = Integer.MAX_VALUE; String usemessage = BCRandomizer.Prefix + "Lives set to " + String.valueOf(uselives); if(p!=null) p.sendMessage(usemessage); else System.out.println(usemessage); } catch(NumberFormatException nfe) { } } } else if(arg2.equalsIgnoreCase("repoptimeout")) { ////if no arguments given, show current. if(arg3.length <1) { String usemessage = BCRandomizer.Prefix + "repoptimeout is currently set to " + String.valueOf(this.ChestTimeout/20) + " seconds."; if(p==null) System.out.println(usemessage); else p.sendMessage(usemessage); } else { String usemessage = ""; try { ChestTimeout = Integer.parseInt(arg3[0])*20; usemessage = BCRandomizer.Prefix + "repoptimeout set to " + String.valueOf(ChestTimeout/20) + " seconds."; } catch(NumberFormatException nfe) { usemessage = BCRandomizer.Prefix + " Invalid Input. repoptimeout must be a number."; } if(p==null) System.out.println(usemessage); else p.sendMessage(usemessage); } } else if(arg2.equalsIgnoreCase("autoprepare")){ // } else if(arg2.equalsIgnoreCase("concludegame")) { for(GameTracker it:_Owner.ActiveGames){ it.setGameConcluding(true); } if(p==null){System.out.println("Concluded all games.");} else{p.sendMessage(BCRandomizer.Prefix + " Concluded all games."); } } else if(arg2.equalsIgnoreCase("mobtimeout")){ if(arg3.length < 1) if(p==null) System.out.println("insufficient arguments"); else {p.sendMessage(BCRandomizer.Prefix + "syntax: /mobtimeout <numberofseconds>"); p.sendMessage(BCRandomizer.Prefix + "current value:" + MobTimeout); } else { try { MobTimeout= Integer.parseInt(arg3[0]); } catch(Exception exx){} } } else if(arg2.equalsIgnoreCase("mobsweeper")){ //force enable mob spawns for active PvP match. enableMobSpawns(); } else if(arg2.equalsIgnoreCase("setfly")){ if(arg3.length < 2) { p.sendMessage(BCRandomizer.Prefix + "Insufficient arguments."); } else { String playername = arg3[0]; boolean flyset = Boolean.parseBoolean(arg3[1]); for(Player pl:Bukkit.getOnlinePlayers()){ pl.setFlying(flyset); p.sendMessage(BCRandomizer.Prefix + "Player " + pl.getName() + " flying set to " + flyset); } } }else if(arg2.equalsIgnoreCase("saveborder")) { saveborder(p.getWorld()); } else if(arg2.equalsIgnoreCase("loadborder")){ loadborder(p.getWorld()); } else if(arg2.equalsIgnoreCase("borders")){ p.sendMessage(BCRandomizer.Prefix + ChatColor.AQUA + "BorderB set to (X,Z)=" + useBorderB.getBlockX() + "," + useBorderB.getBlockZ()); p.sendMessage(BCRandomizer.Prefix + ChatColor.AQUA + "BorderA set to (X,Z)=" + useBorderA.getBlockX() + "," + useBorderA.getBlockZ()); } else if (arg2.equalsIgnoreCase("arenaborder1")) { useBorderA = p.getLocation(); p.sendMessage(BCRandomizer.Prefix + ChatColor.AQUA + "BorderA set to (X,Z)=" + useBorderA.getBlockX() + "," + useBorderA.getBlockZ()); } else if (arg2.equalsIgnoreCase("arenaborder2")) { useBorderB = p.getLocation(); p.sendMessage(BCRandomizer.Prefix + ChatColor.AQUA + "BorderB set to (X,Z)=" + useBorderB.getBlockX() + "," + useBorderB.getBlockZ()); } else if (arg2.equalsIgnoreCase("clearborder")) { useBorderA = useBorderB = null; p.sendMessage(BCRandomizer.Prefix + ChatColor.AQUA + "Borders cleared."); } if (arg2.equalsIgnoreCase("gamestate")) { // output information about running games. int currgame = 1; p.sendMessage(BCRandomizer.Prefix + ChatColor.RED + "Currently running games:" + _Owner.ActiveGames.size()); for (GameTracker gt : _Owner.ActiveGames) { p.sendMessage(BCRandomizer.Prefix + ChatColor.RED + "Game:" + currgame); p.sendMessage(BCRandomizer.Prefix + ChatColor.RED + "Alive:" + StringUtil.Join(getPlayerNames(gt.getStillAlive()), ",")); p.sendMessage(BCRandomizer.Prefix + ChatColor.GRAY + "Dead:" + StringUtil.Join(getPlayerNames(gt.getDead()), ",")); p.sendMessage(BCRandomizer.Prefix + ChatColor.AQUA + "Spectating:" + StringUtil.Join(getPlayerNames(gt.getSpectating()), ",")); } } if (arg2.equalsIgnoreCase("preparegame")) { // prepare game for the issuing players world. // unless a world is specified, that is. playingWorld = null; if (arg3.length >= 1) { if((Bukkit.getWorld(arg3[0])!=null)) { playingWorld=Bukkit.getWorld(arg3[0]); _SpawnSpot=playingWorld.getSpawnLocation(); } } else if (p != null) { playingWorld = p.getWorld(); _SpawnSpot = p.getLocation(); playingWorld.setSpawnLocation((int) _SpawnSpot.getX(), (int) _SpawnSpot.getY(), (int) _SpawnSpot.getZ()); } int numseconds=0; //number of seconds will be passed to PrepareGame. if(arg3.length>=2){ //check for number of seconds... try { numseconds = Integer.parseInt(arg3[1]); } catch(NumberFormatException nfe){ numseconds=0; } } int preparetime = 0; if(arg3.length>=3){ try {preparetime = Integer.parseInt(arg3[2]);}catch(NumberFormatException nfe){preparetime=0;}} prepareGame(p,playingWorld,numseconds,preparetime); } else if (arg2.equalsIgnoreCase("joingame")) { if(playingWorld==null) playingWorld = p.getWorld(); if (!accepting && !AutoPrepare) { p .sendMessage(BCRandomizer.Prefix + ChatColor.RED + "You cannot join a game still in progress. use /spectategame if you want to observe."); return false; } else if(AutoPrepare && _Owner.ActiveGames.size()==0){ Bukkit.broadcastMessage(BCRandomizer.Prefix + " A Game is being auto-prepared!"); prepareGame(p,playingWorld,30,50); //onCommand(sender,arg1,"preparegame",new String[]{"40"}); } if (p == null) return false; // fire the event. ParticipantJoinEvent joinevent = new ParticipantJoinEvent(p); Bukkit.getPluginManager().callEvent(joinevent); if (joinevent.getCancelled()) return false; if (p.getWorld() != playingWorld) { // teleport them to the world the game is in. returninfo.put(p, new ReturnData(p)); Location spawnspot = _SpawnSpot; p.teleport(spawnspot); p.setBedSpawnLocation(spawnspot); } if (spectating.contains(p)) { spectating.remove(p); } if (!joinedplayers.contains(p)) { joinedplayers.add(p); } else { p .sendMessage(BCRandomizer.Prefix + ChatColor.RED + " You are already participating!"); return false; } Bukkit.broadcastMessage(BCRandomizer.Prefix +p.getDisplayName() + ChatColor.AQUA + " is participating.(" + joinedplayers.size() + " players)"); Bukkit.broadcastMessage(BCRandomizer.Prefix +"Current participants:" + StringUtil.Join(getPlayerNames(joinedplayers), ",")); final Player lasttojoin = p; //finally, if the timeout is non-zero... if(JoinStartDelay>0){ if(joinedplayers.size() > (MobArenaMode?0:1)) //if the join task ID is non-zero, cancel it and set it to zero. if(JoinDelayTaskID!=0){ Bukkit.getScheduler().cancelTask(JoinDelayTaskID); JoinDelayTaskID=0; } //create a new delayed task. JoinDelayTaskID = Bukkit.getScheduler().scheduleSyncDelayedTask(_Owner,new Runnable(){ public void run(){ StartGame(lasttojoin, 30, MobArenaMode); } }, JoinStartDelay*20); Bukkit.broadcastMessage(BCRandomizer.Prefix + "Game will start in " + JoinStartDelay + " seconds."); } } else if(arg2.equalsIgnoreCase("joinstartdelay")){ try { String firstargument = arg3[0]; int parsed = Integer.parseInt(firstargument); JoinStartDelay = parsed; String usemessage = BCRandomizer.Prefix + "JoinStartDelay set to " + JoinStartDelay; } catch(Exception exx){ String usemessage = BCRandomizer.Prefix + "syntax: /joinstartdelay <seconds>"; if(p!=null) p.sendMessage(usemessage); else System.out.println(usemessage); } } else if(arg2.equalsIgnoreCase("prepareinfo")){ if(p==null) return false; String[] Participants = new String[joinedplayers.size()]; String[] Spectators = new String[spectating.size()]; int currparticipant = 0; for(Player participant:joinedplayers){ Participants[currparticipant] = participant.getDisplayName(); } int currspectator = 0; for(Player spectator:spectating){ Spectators[currspectator] = spectator.getDisplayName(); } String Joined = StringUtil.Join(Participants, ","); String spectates = StringUtil.Join(Spectators, ","); p.sendMessage(BCRandomizer.Prefix + joinedplayers.size() + " participants:"); p.sendMessage(BCRandomizer.Prefix + Joined); p.sendMessage(BCRandomizer.Prefix + spectating.size() + " Spectating:"); p.sendMessage(BCRandomizer.Prefix + spectates); } else if (arg2.equalsIgnoreCase("spectategame")) { if (p == null) return false; if (p.getWorld() == playingWorld) { if (joinedplayers.contains(p)) { joinedplayers.remove(p); // remove them from the // participation list. } if (!spectating.contains(p)) { addSpectator(p); } else { p.sendMessage(ChatColor.YELLOW + "you are already spectating!"); return false; } } else { returninfo.put(p, new ReturnData(p)); Location spawnspot = playingWorld.getSpawnLocation(); p.teleport(spawnspot); p.setBedSpawnLocation(_SpawnSpot); } Bukkit.broadcastMessage(ChatColor.LIGHT_PURPLE + p.getDisplayName() + " is spectating."); // if a game is in progress, make them invisible and flying. if (!accepting) { p.setAllowFlight(true); GameTracker gotgt = _Owner.getWorldGame(p.getWorld()); if (gotgt != null) gotgt.deathwatcher.hidetoParticipants(p); } } else if (arg2.equalsIgnoreCase("mobmode")) { MobArenaMode = !MobArenaMode; p.sendMessage(BCRandomizer.Prefix + "mob arena mode set to '" + MobArenaMode + "'"); } if (arg2.equalsIgnoreCase("teamsplit")) { // get all online Players. // unused! LinkedList<Player> onlineplayers = new LinkedList<Player>(); for (Player checkonline : p.getWorld().getPlayers()) { if (checkonline.isOnline()) { onlineplayers.add(checkonline); } } // now split contents of onlineplayers in half. LinkedList<Player> TeamA = new LinkedList<Player>(); LinkedList<Player> TeamB = new LinkedList<Player>(); for (int i = 0; i < onlineplayers.size() / 2; i++) { Player[] theplayers = new Player[onlineplayers.size()]; onlineplayers.toArray(theplayers); Player addteamA = RandomData.Choose(theplayers); TeamA.add(addteamA); onlineplayers.remove(addteamA); } TeamB = onlineplayers; Player[] TeamAArr = new Player[TeamA.size()]; Player[] TeamBArr = new Player[TeamB.size()]; TeamA.toArray(TeamAArr); TeamB.toArray(TeamBArr); Bukkit.broadcastMessage("Team A is " + TeamList(TeamAArr)); Bukkit.broadcastMessage("Team B is " + TeamList(TeamBArr)); for (Player APlayer : TeamAArr) { APlayer.setDisplayName("[TEAM A]" + APlayer.getDisplayName()); APlayer.sendMessage(ChatColor.YELLOW + "You are on Team A!"); } for (Player BPlayer : TeamBArr) { BPlayer.setDisplayName("[TEAM B]" + BPlayer.getDisplayName()); BPlayer.sendMessage(ChatColor.YELLOW + "You are on Team B!"); } } if (arg2.equalsIgnoreCase("startgame")) { int numseconds = 30; if (arg3.length > 0) { try { numseconds = Integer.parseInt(arg3[0]); } catch (Exception exx) { numseconds = 30; } } StartGame(p, numseconds, MobArenaMode); return false; } if (arg2.equalsIgnoreCase("friendly")) { String friendly = (CoreEventHandler.getFriendlyNameFor(p .getItemInHand())); p.sendMessage(ChatColor.YELLOW + "Name of item is " + friendly); } if (arg2.equalsIgnoreCase("stopallgames")) { int numgames = 0; numgames = stopAllGames(); _Owner.ActiveGames = new LinkedList<GameTracker>(); p.sendMessage(numgames + " games stopped."); } if (arg2.equalsIgnoreCase("repopchests")) { String usesource = ""; if (arg3.length > 0) { usesource = arg3[0]; } repopulateChests(usesource, p.getWorld()); } return false; } private void doFixUp(Player p) { //this method has a simple task: //It attempts to "fix" all running games. //this consists of making sure all spectators can fly and participants cannot, and ensuring consistent visibility settings //between them. //of p is a Player, it will send any relevant information to them. //particularly when a fixup needs to be applied. //first, check fly and not flying... if(_Owner.ActiveGames.size() ==0 ){ if (p!=null) p.sendMessage(BCRandomizer.Prefix + ChatColor.RED + " No Active games to apply fixups. resetting all players."); if(p!=null){ for(Player fixplayer:p.getWorld().getPlayers()){ if(fixplayer.getAllowFlight()){ if(p!=null) p.sendMessage("Reverting AllowFlight and Flight for " + fixplayer.getDisplayName()); fixplayer.setAllowFlight(false); fixplayer.setFlying(false); } } } return; } if (p!=null) p.sendMessage(BCRandomizer.Prefix + ChatColor.RED + " Attempting fixups on " + ChatColor.AQUA + _Owner.ActiveGames.size() + " Games..."); for(GameTracker iterate :_Owner.ActiveGames){ //make sure all participants are "grounded"... for(Player participant:iterate.getStillAlive()){ if(participant.getAllowFlight()){ if(p!=null) p.sendMessage(BCRandomizer.Prefix + ChatColor.RED + " clearing set Flight for participant " + participant.getDisplayName()); participant.setAllowFlight(false); participant.setFlying(false); } } //make sure spectators can fly... for(Player spectator: iterate.getSpectating()){ if(!spectator.getAllowFlight()){ if(p!=null) p.sendMessage(BCRandomizer.Prefix + ChatColor.RED + " setting flight for spectator " + spectator.getDisplayName()); spectator.setAllowFlight(true); } } //now, we first reset ALL visibility statuses... for(Player x:iterate.getWorld().getPlayers()){ for(Player y:iterate.getWorld().getPlayers()){ if(x!=y){ x.showPlayer(y); } } } //and now, we make spectators invisible to participants. for(Player participator:iterate.getStillAlive()){ for(Player hidespectator:iterate.getSpectating()){ participator.hidePlayer(hidespectator); } } } } private int stopAllGames() { int retval = 0; for (GameTracker iterate : _Owner.ActiveGames) { // inform the players they're game was cancelled. for (Player tellem : iterate.getStillAlive()) { tellem.sendMessage(ChatColor.RED + "SURVIVAL:" + "The game you are in has been cancelled!"); } iterate.gamecomplete = true; retval++; } return retval; } private void prepareGame(final Player p,World inWorld,int delaystart,final int prepatorydelay) { PrepareGameEvent pge = new PrepareGameEvent(); Bukkit.getPluginManager().callEvent(pge); if (pge.getCancelled()) { // preparegame cancelled... accepting = false; return; } playingWorld = inWorld; playingWorld.setPVP(false); accepting = true; joinedplayers.clear(); spectating.clear(); for (Player px : getAllPlayers()) { if (MobArenaMode) { px.sendMessage(BCRandomizer.Prefix + ChatColor.YELLOW + " A Mob Arena game is being prepared in " + playingWorld.getName()); px .sendMessage(BCRandomizer.Prefix + ChatColor.YELLOW + " use /joingame to participate before the game starts."); } else { px.sendMessage(BCRandomizer.Prefix + ChatColor.YELLOW + " A Survival game is being prepared in " + playingWorld.getName()); px .sendMessage(BCRandomizer.Prefix + ChatColor.YELLOW + " use /joingame to participate before the game starts."); } if(delaystart >0){ px.sendMessage(BCRandomizer.Prefix + "ChatColor.YELLOW" + "Game will start in " + delaystart + " seconds."); } } if(delaystart > 0){ Bukkit.getScheduler().runTaskLater(_Owner, new Runnable() { public void run(){ StartGame(p,playingWorld,prepatorydelay,MobArenaMode); } }, delaystart); } } public boolean isGameActive() { return _Owner.ActiveGames.size() > 0; } private ResumePvP rp = null; Location useBorderA = null; Location useBorderB = null; private void StartGame(Player p,int numseconds,boolean MobArena){ StartGame(p,null,numseconds,MobArena); } /*private void StartGame(World w,int numseconds,boolean MobArena){ StartGame(null,w,numseconds,MobArena); }*/ private void SethardcoreRecipes() { Iterator<Recipe> iter = Bukkit.recipeIterator(); while(iter.hasNext()){ Recipe current = iter.next(); if(current.getResult().getType()==Material.SPECKLED_MELON) iter.remove(); else if(current.getResult().getType()==Material.GOLDEN_APPLE) iter.remove(); } ShapedRecipe newapple = new ShapedRecipe(new ItemStack(Material.GOLDEN_APPLE,1)); newapple.setIngredient('G', Material.GOLD_INGOT); newapple.setIngredient('M',Material.APPLE); newapple.shape("GGG","GMG","GGG"); Bukkit.addRecipe(newapple); ShapelessRecipe newmelon = new ShapelessRecipe(new ItemStack(Material.SPECKLED_MELON,1)); newmelon.addIngredient(Material.GOLD_BLOCK); newmelon.addIngredient(Material.MELON); Bukkit.addRecipe(newmelon); } private void RemovehardcoreRecipes(){ Iterator<Recipe> iter = Bukkit.recipeIterator(); while(iter.hasNext()){ Recipe current = iter.next(); if(current.getResult().getType()==Material.SPECKLED_MELON) iter.remove(); else if(current.getResult().getType()==Material.GOLDEN_APPLE) iter.remove(); } ShapedRecipe newapple = new ShapedRecipe(new ItemStack(Material.GOLDEN_APPLE,1)); newapple.setIngredient('G', Material.GOLD_NUGGET); newapple.setIngredient('M',Material.APPLE); newapple.shape("GGG","GMG","GGG"); Bukkit.addRecipe(newapple); ShapelessRecipe newmelon = new ShapelessRecipe(new ItemStack(Material.SPECKLED_MELON,1)); newmelon.addIngredient(Material.GOLD_NUGGET); newmelon.addIngredient(Material.MELON); Bukkit.addRecipe(newmelon); } private void StartGame(Player p,World w, int numseconds, boolean MobArena) { accepting = false; if (joinedplayers.size() == 0) { if (p != null) p.sendMessage(BCRandomizer.Prefix + "No players participating! Cannot start game."); else System.out .println("No players participating! Cannot start game."); accepting = true; return; } if (_Owner.ActiveGames.size() > 0) { // this is for debugging. Right now it will only allow one game at a // time. if (p != null) p .sendMessage(BCRandomizer.Prefix + ChatColor.YELLOW + "Game is already in progress! use /stopallgames to stop current games."); else System.out .println("Game in progress. use /stopallgames to stop current games."); return; } String ignoreplayer = null; final World grabworld = (w==null?(p!=null?p.getWorld():playingWorld):w); //extra logic: if neither arenaborder is set, we will see if we are in a GP claim. if(useBorderA==null || useBorderB==null){ if(_Owner.gp!=null){ Claim grabclaim = _Owner.gp.dataStore.getClaimAt(p.getLocation(), true, null); if(grabclaim!=null){ useBorderA = grabclaim.getLesserBoundaryCorner(); useBorderB = grabclaim.getGreaterBoundaryCorner(); } } } Scoreboard ss = Bukkit.getScoreboardManager().getMainScoreboard(); ss.clearSlot(DisplaySlot.SIDEBAR); Objective scoreget = ss.getObjective("Score"); if(scoreget==null) { scoreget = ss.registerNewObjective("Score", "dummy"); scoreget.setDisplayName("Score"); scoreget.setDisplaySlot(DisplaySlot.SIDEBAR); } scoreget.setDisplayName("Score"); scoreget.setDisplaySlot(DisplaySlot.SIDEBAR); if (_Owner.Randomcommand.MobArenaMode) numseconds = 0; rp = new ResumePvP(p,_Owner, grabworld, numseconds, joinedplayers, spectating,uselives,useBorderA,useBorderB,ss); rp.getTracker().setAllowHealthRegen(!HardcoreHealth); GameStartEvent eventobj = new GameStartEvent(joinedplayers, spectating, MobArena,rp.getTracker()); Bukkit.getServer().getPluginManager().callEvent(eventobj); Bukkit.broadcastMessage(BCRandomizer.Prefix + ChatColor.GOLD + "Survival Event " + ChatColor.GREEN + " has begun in world " + ChatColor.DARK_AQUA + grabworld.getName() + "!"); Bukkit.broadcastMessage(joinedplayers.size() + " Players."); grabworld.setPVP(false); // iterate through all online players. for (Player pl : joinedplayers) { ss.resetScores(pl); scoreget.getScore(pl).setScore(0); if (pl.isOnline()) { pl .sendMessage(BCRandomizer.Prefix + ChatColor.BLUE + "Your Inventory has been cleared. No outside food, please."); BCRandomizer.clearPlayerInventory(pl); for (PotionEffect iterate : pl.getActivePotionEffects()) pl.removePotionEffect(iterate.getType()); pl.setExp(0); pl.setLevel(0); pl.setHealth(20); pl.setExhaustion(20); pl.setSaturation(20); pl.setGameMode(GameMode.ADVENTURE); pl.setFlying(false); pl.playSound(pl.getLocation(), Sound.ENTITY_ENDERMEN_HURT, 1.0f, 1.0f); for(Player spectator :spectating){ spectator.hidePlayer(pl); pl.showPlayer(spectator); } } } for(Player spectator : spectating){ //set flying. spectator.setFlying(false); spectator.setAllowFlight(true); } ChestRandomizer.resetStorage(); repopulateChests("", p.getWorld(), true); ShufflePlayers(joinedplayers); ResumePvP.BroadcastWorld(grabworld, BCRandomizer.Prefix + ChatColor.LIGHT_PURPLE + " Containers randomized."); // GameStartEvent eventobj= new // GameStartEvent(joinedplayers,spectating,MobArena); rp.getTracker().deathwatcher.onGameStart(eventobj); if (!_Owner.Randomcommand.getMobArenaMode()) { ResumePvP.BroadcastWorld(grabworld, BCRandomizer.Prefix + ChatColor.GREEN + "PvP will be re-enabled in " + ChatColor.RED + numseconds + ChatColor.GREEN + " Seconds! get ready."); ResumePvP.BroadcastWorld(grabworld, BCRandomizer.Prefix + ChatColor.GREEN + "Mob spawns will start in " +ChatColor.RED + + MobTimeout + ChatColor.GREEN + " seconds... try to conclude the match before that, they tend to make a mess."); } if(MobTimeout >0){ Bukkit.getScheduler().runTaskLater(_Owner, new Runnable() { public void run(){ ResumePvP.BroadcastWorld(grabworld, ChatColor.DARK_GREEN + "Yummy contestants for Hungry Mobs!"); enableMobSpawns(); } }, MobTimeout*20); } Thread thr = new Thread(rp); thr.start(); } private void ShufflePlayers(List<Player> shufflethese){ //shuffle all players that are "StillAlive" within the arena border. //if no border is set, we don't shuffle, and log to the console. //_Owner.Randomcommand; GameTracker usetracker = null; if(shufflethese.size()>0){ usetracker = _Owner.getGame(shufflethese.get(0)); } for(Player p:shufflethese){ p.teleport(GameTracker.deathwatcher.handleGameSpawn(p)); } /* if(usetracker.getBorderA()!=null && usetracker.getBorderB()!=null){ Location ba = usetracker.getBorderA(); Location bb = usetracker.getBorderB(); double XMinimum = Math.min(ba.getX(), bb.getX()); double XMaximum = Math.max(ba.getX(), bb.getX()); double ZMinimum = Math.min(ba.getZ(), bb.getZ()); double ZMaximum = Math.max(ba.getZ(), bb.getZ()); //iterate through each Player... Random rgen = RandomData.rgen; for(Player participant:shufflethese){ double chosenY=0; double chosenX=0,chosenZ=0; while(chosenY==0){ //choose a random X and Z... chosenX = rgen.nextDouble()*(XMaximum-XMinimum)+XMinimum; chosenZ = rgen.nextDouble()*(ZMaximum-ZMinimum)+ZMinimum; //now, our task: get the highest block at... chosenY = (double)participant.getWorld().getHighestBlockYAt((int)chosenX, (int)chosenZ); } Location chosenlocation = new Location(participant.getWorld(),chosenX,chosenY,chosenZ); participant.teleport(chosenlocation); System.out.println("Teleported " + participant.getName() + " to " + chosenlocation.toString()); } } */ } private PopulationManager PopulationInfo = new PopulationManager(); public void repopulateChests(String Source, World w) { repopulateChests(Source, w, false); } public boolean hasBlockBeneath(Block testblock, Material testmaterial) { Location spotbelow = new Location(testblock.getWorld(), testblock .getX(), testblock.getY() - 1, testblock.getZ()); return testblock.getWorld().getBlockAt(spotbelow).getType().equals( testmaterial); } public void repopulateChests(final String Source, final World w, final boolean silent) { int populatedamount = 0; LinkedList<Chest> allchests = new LinkedList<Chest>(); LinkedList<Furnace> allfurnaces = new LinkedList<Furnace>(); LinkedList<Dispenser> alldispensers = new LinkedList<Dispenser>(); LinkedList<StorageMinecart> allstoragecarts = new LinkedList<StorageMinecart>(); LinkedList<Dropper> allDroppers = new LinkedList<Dropper>(); LinkedList<Hopper> allHoppers = new LinkedList<Hopper>(); LinkedList<BrewingStand> allbrewingstands = new LinkedList<BrewingStand>(); World gotworld = w; if (!silent) Bukkit.broadcastMessage(BCRandomizer.Prefix + "BASeCamp Chest Randomizer- Running..."); String sourcefile = Source; // randomize the enderchest contents, too :D for (Player popplayer : gotworld.getPlayers()) { Inventory grabinv = popplayer.getEnderChest(); ChestRandomizer cr = new ChestRandomizer(_Owner, grabinv, sourcefile); cr.setMinItems(grabinv.getSize()); cr.setMaxItems(grabinv.getSize()); cr.Shuffle(); } Chunk[] iteratechunks = gotworld.getLoadedChunks(); // iterate through all the chunks... for (Chunk iteratechunk : iteratechunks) { // go through all tileentities and look for Chests. BlockState[] entities = iteratechunk.getTileEntities(); for (BlockState iteratestate : entities) { if(iteratestate instanceof InventoryHolder) { //if it has an inventory... PopulationInfo.setPopulated(gotworld, (InventoryHolder)iteratestate); //set it as populated. } if(iteratestate instanceof Hopper){ Hopper casted = (Hopper)iteratestate; allHoppers.add(casted); ChestRandomizer cr = new ChestRandomizer(_Owner,casted.getInventory(),sourcefile); populatedamount+=cr.Shuffle(); } else if(iteratestate instanceof Dropper){ Dropper casted = (Dropper)iteratestate; allDroppers.add(casted); ChestRandomizer cr = new ChestRandomizer(_Owner,casted.getInventory(),sourcefile); populatedamount+=cr.Shuffle(); } if(iteratestate instanceof StorageMinecart){ StorageMinecart casted = (StorageMinecart)iteratestate; allstoragecarts.add(casted); ChestRandomizer cr = new ChestRandomizer(_Owner,casted.getInventory(),sourcefile); populatedamount+=cr.Shuffle(); } else if(iteratestate instanceof BrewingStand){ BrewingStand casted = (BrewingStand)iteratestate; ChestRandomizer br = new ChestRandomizer(_Owner,casted,sourcefile); allbrewingstands.add(casted); populatedamount+=br.Shuffle(); } if (iteratestate instanceof Chest) { Chest casted = (Chest) iteratestate; // randomize! if (!hasBlockBeneath(iteratestate.getBlock(), Material.WOOL)) { allchests.add(casted); ChestRandomizer cr = new ChestRandomizer(_Owner, casted, sourcefile); populatedamount += cr.Shuffle(); } else { //System.out.println("Storing inventory for a chest"); ChestRandomizer.StoreInventory(casted); } } else if (iteratestate instanceof Furnace) { Furnace casted = (Furnace) iteratestate; allfurnaces.add(casted); ChestRandomizer cr = new ChestRandomizer(_Owner, casted .getInventory(), sourcefile); populatedamount += cr.Shuffle(); casted.getInventory().setResult(null); } else if (iteratestate instanceof Dispenser) { Dispenser casted = (Dispenser) iteratestate; alldispensers.add(casted); ChestRandomizer cr = new ChestRandomizer(_Owner, casted .getInventory(), sourcefile); populatedamount += cr.Shuffle(); System.out.println(populatedamount); } } } // turn chest LinkedList into an array. Chest[] chestchoose = new Chest[allchests.size()]; allchests.toArray(chestchoose); int StaticAdded = 0; if (!silent) { ResumePvP.BroadcastWorld(w,ChatColor.AQUA.toString() + allchests.size() + ChatColor.YELLOW + " Chests Populated."); Bukkit.broadcastMessage(ChatColor.AQUA.toString() + allfurnaces.size() + ChatColor.RED + " Furnaces " + ChatColor.YELLOW + "Populated."); ResumePvP.BroadcastWorld(w,ChatColor.AQUA + "" + alldispensers.size() + ChatColor.GREEN + " Dispensers " + ChatColor.YELLOW + " Populated."); ResumePvP.BroadcastWorld(w,ChatColor.AQUA.toString() + ChatColor.LIGHT_PURPLE + allbrewingstands.size() + ChatColor.RED + " Brewing Stands" + ChatColor.YELLOW + " Populated."); ResumePvP.BroadcastWorld(w,ChatColor.AQUA.toString() + allDroppers.size() + ChatColor.DARK_GREEN + " Droppers" + ChatColor.YELLOW + " Populated."); ResumePvP.BroadcastWorld(w,ChatColor.AQUA.toString() + allDroppers.size() + ChatColor.GRAY + " Hoppers" + ChatColor.YELLOW + " Populated."); ResumePvP.BroadcastWorld(w,ChatColor.YELLOW + "Populated " + ChatColor.AQUA.toString() + populatedamount + ChatColor.YELLOW + " slots."); } for (RandomData iterate : ChestRandomizer.getRandomData(_Owner)) { ItemStack result = iterate.Generate(); if (result != null) { // choose a random chest. Chest chosen = RandomData.Choose(chestchoose); Inventory iv = chosen.getBlockInventory(); BCRandomizer.emitmessage("Added Static Item:" + result.toString()); iv.addItem(result); StaticAdded++; } } if (!silent) Bukkit.broadcastMessage(ChatColor.YELLOW + "Added " + ChatColor.AQUA.toString() + StaticAdded + ChatColor.YELLOW + " Static items."); } public boolean getMobArenaMode() { // TODO Auto-generated method stub return MobArenaMode; } }
bsd-2-clause
zhangjunfang/eclipse-dir
nsp_ocean/src/main/java/com/rop/RopContext.java
1303
package com.rop; import com.rop.session.SessionManager; import java.util.Map; /** * <pre> * ROP服务方法的处理者的注册表 * </pre> */ public interface RopContext { /** * 注册一个服务处理器 * * @param methodName * @param version * @param serviceMethodHandler */ void addServiceMethod(String methodName, String version, ServiceMethodHandler serviceMethodHandler); /** * 获取服务处理器 * * @param methodName * @return */ ServiceMethodHandler getServiceMethodHandler(String methodName, String version); /** * 是否是合法的服务方法 * * @param methodName * @return */ boolean isValidMethod(String methodName); /** * 是否是合法服务方法版本号 * * @param methodName * @param version * @return */ boolean isValidMethodVersion(String methodName, String version); /** * 获取所有的处理器列表 * * @return */ Map<String, ServiceMethodHandler> getAllServiceMethodHandlers(); /** * 是开启签名功能 * * @return */ boolean isSignEnable(); /** * 获取会话管理器 * @return */ SessionManager getSessionManager(); }
bsd-2-clause
atlassian/commonmark-java
commonmark/src/main/java/org/commonmark/renderer/html/AttributeProviderContext.java
300
package org.commonmark.renderer.html; /** * The context for attribute providers. * <p>Note: There are currently no methods here, this is for future extensibility.</p> * <p><em>This interface is not intended to be implemented by clients.</em></p> */ public interface AttributeProviderContext { }
bsd-2-clause
Pushjet/Pushjet-Android
gradle/wrapper/dists/gradle-2.2.1-all/c64ydeuardnfqctvr1gm30w53/gradle-2.2.1/src/core/org/gradle/util/SingleMessageLogger.java
6565
/* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.util; import io.jcip.annotations.ThreadSafe; import org.gradle.api.logging.Logger; import org.gradle.api.logging.Logging; import org.gradle.internal.Factory; import org.gradle.internal.featurelifecycle.DeprecatedFeatureUsage; import org.gradle.internal.featurelifecycle.LoggingDeprecatedFeatureHandler; import org.gradle.internal.featurelifecycle.UsageLocationReporter; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; @ThreadSafe public class SingleMessageLogger { private static final Logger LOGGER = Logging.getLogger(DeprecationLogger.class); private static final Set<String> FEATURES = Collections.synchronizedSet(new HashSet<String>()); private static final ThreadLocal<Boolean> ENABLED = new ThreadLocal<Boolean>() { @Override protected Boolean initialValue() { return true; } }; public static final String ORG_GRADLE_DEPRECATION_TRACE_PROPERTY_NAME = "org.gradle.deprecation.trace"; public static final String INCUBATION_MESSAGE = "%s is an incubating feature."; private static final Lock LOCK = new ReentrantLock(); private static LoggingDeprecatedFeatureHandler handler = new LoggingDeprecatedFeatureHandler(); private static String deprecationMessage; public static String getDeprecationMessage() { LOCK.lock(); try { if (deprecationMessage == null) { String messageBase = "has been deprecated and is scheduled to be removed in"; GradleVersion currentVersion = GradleVersion.current(); String when = String.format("Gradle %s", currentVersion.getNextMajor().getVersion()); deprecationMessage = String.format("%s %s", messageBase, when); } return deprecationMessage; } finally { LOCK.unlock(); } } public static void reset() { FEATURES.clear(); LOCK.lock(); try { handler = new LoggingDeprecatedFeatureHandler(); } finally { LOCK.unlock(); } } public static void useLocationReporter(UsageLocationReporter reporter) { LOCK.lock(); try { handler.setLocationReporter(reporter); } finally { LOCK.unlock(); } } public static void nagUserOfReplacedPlugin(String pluginName, String replacement) { nagUserWith(String.format( "The %s plugin %s. Please use the %s plugin instead.", pluginName, getDeprecationMessage(), replacement)); } public static void nagUserOfReplacedTaskType(String taskName, String replacement) { nagUserWith(String.format( "The %s task type %s. Please use the %s instead.", taskName, getDeprecationMessage(), replacement)); } public static void nagUserOfReplacedMethod(String methodName, String replacement) { nagUserWith(String.format( "The %s method %s. Please use the %s method instead.", methodName, getDeprecationMessage(), replacement)); } public static void nagUserOfReplacedProperty(String propertyName, String replacement) { nagUserWith(String.format( "The %s property %s. Please use the %s property instead.", propertyName, getDeprecationMessage(), replacement)); } public static void nagUserOfDiscontinuedMethod(String methodName) { nagUserWith(String.format("The %s method %s.", methodName, getDeprecationMessage())); } public static void nagUserOfDiscontinuedProperty(String propertyName, String advice) { nagUserWith(String.format("The %s property %s. %s", propertyName, getDeprecationMessage(), advice)); } public static void nagUserOfReplacedNamedParameter(String parameterName, String replacement) { nagUserWith(String.format( "The %s named parameter %s. Please use the %s named parameter instead.", parameterName, getDeprecationMessage(), replacement)); } /** * Try to avoid using this nagging method. The other methods use a consistent wording for when things will be removed. */ public static void nagUserWith(String message) { if (isEnabled()) { LOCK.lock(); try { handler.deprecatedFeatureUsed(new DeprecatedFeatureUsage(message, SingleMessageLogger.class)); } finally { LOCK.unlock(); } } } /** * Avoid using this method, use the variant with an explanation instead. */ public static void nagUserOfDeprecated(String thing) { nagUserWith(String.format("%s %s", thing, getDeprecationMessage())); } public static void nagUserOfDeprecated(String thing, String explanation) { nagUserWith(String.format("%s %s. %s.", thing, getDeprecationMessage(), explanation)); } public static void nagUserOfDeprecatedBehaviour(String behaviour) { nagUserOfDeprecated(String.format("%s. This behaviour", behaviour)); } public static <T> T whileDisabled(Factory<T> factory) { ENABLED.set(false); try { return factory.create(); } finally { ENABLED.set(true); } } public static void whileDisabled(Runnable action) { ENABLED.set(false); try { action.run(); } finally { ENABLED.set(true); } } private static boolean isEnabled() { return ENABLED.get(); } public static void incubatingFeatureUsed(String incubatingFeature) { if (FEATURES.add(incubatingFeature)) { LOGGER.lifecycle(String.format(INCUBATION_MESSAGE, incubatingFeature)); } } }
bsd-2-clause
UniquePassive/runelite
runescape-client/src/main/java/PacketBuffer.java
61172
import net.runelite.mapping.Export; import net.runelite.mapping.Hook; import net.runelite.mapping.Implements; import net.runelite.mapping.ObfuscatedGetter; import net.runelite.mapping.ObfuscatedName; import net.runelite.mapping.ObfuscatedSignature; @ObfuscatedName("gs") @Implements("PacketBuffer") public final class PacketBuffer extends Buffer { @ObfuscatedName("x") static final int[] field2602; @ObfuscatedName("cz") @ObfuscatedSignature( signature = "Ljn;" ) @Export("indexTrack1") static IndexData indexTrack1; @ObfuscatedName("u") @ObfuscatedSignature( signature = "Lgx;" ) @Export("cipher") ISAACCipher cipher; @ObfuscatedName("y") @ObfuscatedGetter( intValue = -1880035895 ) @Export("bitPosition") int bitPosition; static { field2602 = new int[]{0, 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535, 131071, 262143, 524287, 1048575, 2097151, 4194303, 8388607, 16777215, 33554431, 67108863, 134217727, 268435455, 536870911, 1073741823, Integer.MAX_VALUE, -1}; } public PacketBuffer(int var1) { super(var1); } @ObfuscatedName("ic") @ObfuscatedSignature( signature = "([II)V", garbageValue = "2103552332" ) @Export("seed") public void seed(int[] var1) { this.cipher = new ISAACCipher(var1); } @ObfuscatedName("ii") @ObfuscatedSignature( signature = "(Lgx;I)V", garbageValue = "-2032050418" ) @Export("setIsaacCipher") public void setIsaacCipher(ISAACCipher var1) { this.cipher = var1; } @ObfuscatedName("it") @ObfuscatedSignature( signature = "(II)V", garbageValue = "-167498009" ) @Export("putOpcode") public void putOpcode(int var1) { super.payload[++super.offset - 1] = (byte)(var1 + this.cipher.nextInt()); } @ObfuscatedName("in") @ObfuscatedSignature( signature = "(I)I", garbageValue = "-389958961" ) @Export("readOpcode") public int readOpcode() { return super.payload[++super.offset - 1] - this.cipher.nextInt() & 255; } @ObfuscatedName("im") @ObfuscatedSignature( signature = "(B)Z", garbageValue = "100" ) public boolean method3780() { int var1 = super.payload[super.offset] - this.cipher.method3813() & 255; return var1 >= 128; } @ObfuscatedName("ir") @ObfuscatedSignature( signature = "(I)I", garbageValue = "1434838342" ) public int method3783() { int var1 = super.payload[++super.offset - 1] - this.cipher.nextInt() & 255; return var1 < 128?var1:(var1 - 128 << 8) + (super.payload[++super.offset - 1] - this.cipher.nextInt() & 255); } @ObfuscatedName("iu") @ObfuscatedSignature( signature = "(I)V", garbageValue = "-1326744811" ) @Export("bitAccess") public void bitAccess() { this.bitPosition = super.offset * 8; } @ObfuscatedName("iv") @ObfuscatedSignature( signature = "(II)I", garbageValue = "740978969" ) @Export("getBits") public int getBits(int var1) { int var2 = this.bitPosition >> 3; int var3 = 8 - (this.bitPosition & 7); int var4 = 0; for(this.bitPosition += var1; var1 > var3; var3 = 8) { var4 += (super.payload[var2++] & field2602[var3]) << var1 - var3; var1 -= var3; } if(var3 == var1) { var4 += super.payload[var2] & field2602[var3]; } else { var4 += super.payload[var2] >> var3 - var1 & field2602[var1]; } return var4; } @ObfuscatedName("il") @ObfuscatedSignature( signature = "(I)V", garbageValue = "-1348619132" ) @Export("byteAccess") public void byteAccess() { super.offset = (this.bitPosition + 7) / 8; } @ObfuscatedName("ia") @ObfuscatedSignature( signature = "(IS)I", garbageValue = "-2320" ) @Export("bitsAvail") public int bitsAvail(int var1) { return var1 * 8 - this.bitPosition; } @ObfuscatedName("h") @ObfuscatedSignature( signature = "(ILcr;ZI)I", garbageValue = "1319314475" ) static int method3806(int var0, Script var1, boolean var2) { int var4 = -1; Widget var3; if(var0 >= 2000) { var0 -= 1000; var4 = class81.intStack[--WorldComparator.intStackSize]; var3 = class44.getWidget(var4); } else { var3 = var2?class81.field1285:Signlink.field2218; } if(var0 == 1100) { WorldComparator.intStackSize -= 2; var3.scrollX = class81.intStack[WorldComparator.intStackSize]; if(var3.scrollX > var3.scrollWidth - var3.width) { var3.scrollX = var3.scrollWidth - var3.width; } if(var3.scrollX < 0) { var3.scrollX = 0; } var3.scrollY = class81.intStack[WorldComparator.intStackSize + 1]; if(var3.scrollY > var3.scrollHeight - var3.height) { var3.scrollY = var3.scrollHeight - var3.height; } if(var3.scrollY < 0) { var3.scrollY = 0; } FontName.method5490(var3); return 1; } else if(var0 == 1101) { var3.textColor = class81.intStack[--WorldComparator.intStackSize]; FontName.method5490(var3); return 1; } else if(var0 == 1102) { var3.filled = class81.intStack[--WorldComparator.intStackSize] == 1; FontName.method5490(var3); return 1; } else if(var0 == 1103) { var3.opacity = class81.intStack[--WorldComparator.intStackSize]; FontName.method5490(var3); return 1; } else if(var0 == 1104) { var3.lineWidth = class81.intStack[--WorldComparator.intStackSize]; FontName.method5490(var3); return 1; } else if(var0 == 1105) { var3.spriteId = class81.intStack[--WorldComparator.intStackSize]; FontName.method5490(var3); return 1; } else if(var0 == 1106) { var3.textureId = class81.intStack[--WorldComparator.intStackSize]; FontName.method5490(var3); return 1; } else if(var0 == 1107) { var3.spriteTiling = class81.intStack[--WorldComparator.intStackSize] == 1; FontName.method5490(var3); return 1; } else if(var0 == 1108) { var3.modelType = 1; var3.modelId = class81.intStack[--WorldComparator.intStackSize]; FontName.method5490(var3); return 1; } else if(var0 == 1109) { WorldComparator.intStackSize -= 6; var3.offsetX2d = class81.intStack[WorldComparator.intStackSize]; var3.offsetY2d = class81.intStack[WorldComparator.intStackSize + 1]; var3.rotationX = class81.intStack[WorldComparator.intStackSize + 2]; var3.rotationZ = class81.intStack[WorldComparator.intStackSize + 3]; var3.rotationY = class81.intStack[WorldComparator.intStackSize + 4]; var3.modelZoom = class81.intStack[WorldComparator.intStackSize + 5]; FontName.method5490(var3); return 1; } else { int var9; if(var0 == 1110) { var9 = class81.intStack[--WorldComparator.intStackSize]; if(var9 != var3.field2869) { var3.field2869 = var9; var3.field2935 = 0; var3.field2945 = 0; FontName.method5490(var3); } return 1; } else if(var0 == 1111) { var3.field2879 = class81.intStack[--WorldComparator.intStackSize] == 1; FontName.method5490(var3); return 1; } else if(var0 == 1112) { String var8 = class81.scriptStringStack[--KeyFocusListener.scriptStringStackSize]; if(!var8.equals(var3.text)) { var3.text = var8; FontName.method5490(var3); } return 1; } else if(var0 == 1113) { var3.fontId = class81.intStack[--WorldComparator.intStackSize]; FontName.method5490(var3); return 1; } else if(var0 == 1114) { WorldComparator.intStackSize -= 3; var3.field2885 = class81.intStack[WorldComparator.intStackSize]; var3.field2833 = class81.intStack[WorldComparator.intStackSize + 1]; var3.field2884 = class81.intStack[WorldComparator.intStackSize + 2]; FontName.method5490(var3); return 1; } else if(var0 == 1115) { var3.textShadowed = class81.intStack[--WorldComparator.intStackSize] == 1; FontName.method5490(var3); return 1; } else if(var0 == 1116) { var3.borderThickness = class81.intStack[--WorldComparator.intStackSize]; FontName.method5490(var3); return 1; } else if(var0 == 1117) { var3.sprite2 = class81.intStack[--WorldComparator.intStackSize]; FontName.method5490(var3); return 1; } else if(var0 == 1118) { var3.flippedVertically = class81.intStack[--WorldComparator.intStackSize] == 1; FontName.method5490(var3); return 1; } else if(var0 == 1119) { var3.flippedHorizontally = class81.intStack[--WorldComparator.intStackSize] == 1; FontName.method5490(var3); return 1; } else if(var0 == 1120) { WorldComparator.intStackSize -= 2; var3.scrollWidth = class81.intStack[WorldComparator.intStackSize]; var3.scrollHeight = class81.intStack[WorldComparator.intStackSize + 1]; FontName.method5490(var3); if(var4 != -1 && var3.type == 0) { class86.method1889(MouseRecorder.widgets[var4 >> 16], var3, false); } return 1; } else if(var0 == 1121) { TotalQuantityComparator.method98(var3.id, var3.index); Client.field1033 = var3; FontName.method5490(var3); return 1; } else if(var0 == 1122) { var3.field2858 = class81.intStack[--WorldComparator.intStackSize]; FontName.method5490(var3); return 1; } else if(var0 == 1123) { var3.field2841 = class81.intStack[--WorldComparator.intStackSize]; FontName.method5490(var3); return 1; } else if(var0 == 1124) { var3.field2854 = class81.intStack[--WorldComparator.intStackSize]; FontName.method5490(var3); return 1; } else if(var0 == 1125) { var9 = class81.intStack[--WorldComparator.intStackSize]; class329[] var6 = new class329[]{class329.field3966, class329.field3965, class329.field3968, class329.field3969, class329.field3967}; class329 var7 = (class329)Permission.forOrdinal(var6, var9); if(var7 != null) { var3.field2909 = var7; FontName.method5490(var3); } return 1; } else if(var0 == 1126) { boolean var5 = class81.intStack[--WorldComparator.intStackSize] == 1; var3.field2903 = var5; return 1; } else { return 2; } } } @ObfuscatedName("hl") @ObfuscatedSignature( signature = "(IIIILjava/lang/String;Ljava/lang/String;IIB)V", garbageValue = "-1" ) @Export("menuAction") static final void menuAction(int var0, int var1, int var2, int var3, String var4, String var5, int var6, int var7) { if(var2 >= 2000) { var2 -= 2000; } PacketNode var8; if(var2 == 1) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; Client.destinationX = var0; Client.destinationY = var1; var8 = WorldMapRectangle.method280(ClientPacket.field2393, Client.field957.field1484); var8.packetBuffer.method3550(class2.field16); var8.packetBuffer.method3528(var3 >> 14 & 32767); var8.packetBuffer.method3528(UrlRequester.selectedItemIndex); var8.packetBuffer.method3551(var0 + class138.baseX); var8.packetBuffer.method3559(BoundingBox.field251); var8.packetBuffer.method3541(KeyFocusListener.keyPressed[82]?1:0); var8.packetBuffer.method3528(class23.baseY + var1); Client.field957.method2052(var8); } else if(var2 == 2) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; Client.destinationX = var0; Client.destinationY = var1; var8 = WorldMapRectangle.method280(ClientPacket.field2461, Client.field957.field1484); var8.packetBuffer.method3541(KeyFocusListener.keyPressed[82]?1:0); var8.packetBuffer.method3561(class234.field2768); var8.packetBuffer.method3528(Client.field1025); var8.packetBuffer.putShort(class23.baseY + var1); var8.packetBuffer.method3528(var3 >> 14 & 32767); var8.packetBuffer.method3528(var0 + class138.baseX); Client.field957.method2052(var8); } else if(var2 == 3) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; Client.destinationX = var0; Client.destinationY = var1; var8 = WorldMapRectangle.method280(ClientPacket.field2394, Client.field957.field1484); var8.packetBuffer.putShort(class23.baseY + var1); var8.packetBuffer.method3550(var0 + class138.baseX); var8.packetBuffer.method3543(KeyFocusListener.keyPressed[82]?1:0); var8.packetBuffer.putShort(var3 >> 14 & 32767); Client.field957.method2052(var8); } else if(var2 == 4) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; Client.destinationX = var0; Client.destinationY = var1; var8 = WorldMapRectangle.method280(ClientPacket.field2466, Client.field957.field1484); var8.packetBuffer.putShort(var0 + class138.baseX); var8.packetBuffer.putShort(class23.baseY + var1); var8.packetBuffer.method3541(KeyFocusListener.keyPressed[82]?1:0); var8.packetBuffer.method3528(var3 >> 14 & 32767); Client.field957.method2052(var8); } else if(var2 == 5) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; Client.destinationX = var0; Client.destinationY = var1; var8 = WorldMapRectangle.method280(ClientPacket.field2469, Client.field957.field1484); var8.packetBuffer.method3551(var3 >> 14 & 32767); var8.packetBuffer.method3542(KeyFocusListener.keyPressed[82]?1:0); var8.packetBuffer.method3551(class23.baseY + var1); var8.packetBuffer.putShort(var0 + class138.baseX); Client.field957.method2052(var8); } else if(var2 == 6) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; Client.destinationX = var0; Client.destinationY = var1; var8 = WorldMapRectangle.method280(ClientPacket.field2451, Client.field957.field1484); var8.packetBuffer.method3543(KeyFocusListener.keyPressed[82]?1:0); var8.packetBuffer.putShort(var3 >> 14 & 32767); var8.packetBuffer.method3528(var0 + class138.baseX); var8.packetBuffer.method3550(class23.baseY + var1); Client.field957.method2052(var8); } else { PacketNode var9; NPC var16; if(var2 == 7) { var16 = Client.cachedNPCs[var3]; if(var16 != null) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; Client.destinationX = var0; Client.destinationY = var1; var9 = WorldMapRectangle.method280(ClientPacket.field2427, Client.field957.field1484); var9.packetBuffer.method3561(BoundingBox.field251); var9.packetBuffer.method3543(KeyFocusListener.keyPressed[82]?1:0); var9.packetBuffer.method3550(var3); var9.packetBuffer.method3550(class2.field16); var9.packetBuffer.putShort(UrlRequester.selectedItemIndex); Client.field957.method2052(var9); } } else if(var2 == 8) { var16 = Client.cachedNPCs[var3]; if(var16 != null) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; Client.destinationX = var0; Client.destinationY = var1; var9 = WorldMapRectangle.method280(ClientPacket.field2406, Client.field957.field1484); var9.packetBuffer.method3528(Client.field1025); var9.packetBuffer.method3543(KeyFocusListener.keyPressed[82]?1:0); var9.packetBuffer.method3550(var3); var9.packetBuffer.putInt(class234.field2768); Client.field957.method2052(var9); } } else if(var2 == 9) { var16 = Client.cachedNPCs[var3]; if(var16 != null) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; Client.destinationX = var0; Client.destinationY = var1; var9 = WorldMapRectangle.method280(ClientPacket.field2420, Client.field957.field1484); var9.packetBuffer.method3543(KeyFocusListener.keyPressed[82]?1:0); var9.packetBuffer.method3550(var3); Client.field957.method2052(var9); } } else if(var2 == 10) { var16 = Client.cachedNPCs[var3]; if(var16 != null) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; Client.destinationX = var0; Client.destinationY = var1; var9 = WorldMapRectangle.method280(ClientPacket.field2474, Client.field957.field1484); var9.packetBuffer.method3528(var3); var9.packetBuffer.method3541(KeyFocusListener.keyPressed[82]?1:0); Client.field957.method2052(var9); } } else if(var2 == 11) { var16 = Client.cachedNPCs[var3]; if(var16 != null) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; Client.destinationX = var0; Client.destinationY = var1; var9 = WorldMapRectangle.method280(ClientPacket.field2458, Client.field957.field1484); var9.packetBuffer.method3541(KeyFocusListener.keyPressed[82]?1:0); var9.packetBuffer.method3550(var3); Client.field957.method2052(var9); } } else if(var2 == 12) { var16 = Client.cachedNPCs[var3]; if(var16 != null) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; Client.destinationX = var0; Client.destinationY = var1; var9 = WorldMapRectangle.method280(ClientPacket.field2473, Client.field957.field1484); var9.packetBuffer.method3543(KeyFocusListener.keyPressed[82]?1:0); var9.packetBuffer.putShort(var3); Client.field957.method2052(var9); } } else if(var2 == 13) { var16 = Client.cachedNPCs[var3]; if(var16 != null) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; Client.destinationX = var0; Client.destinationY = var1; var9 = WorldMapRectangle.method280(ClientPacket.field2454, Client.field957.field1484); var9.packetBuffer.method3528(var3); var9.packetBuffer.method3542(KeyFocusListener.keyPressed[82]?1:0); Client.field957.method2052(var9); } } else { Player var18; if(var2 == 14) { var18 = Client.cachedPlayers[var3]; if(var18 != null) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; Client.destinationX = var0; Client.destinationY = var1; var9 = WorldMapRectangle.method280(ClientPacket.field2441, Client.field957.field1484); var9.packetBuffer.putInt(BoundingBox.field251); var9.packetBuffer.method3542(KeyFocusListener.keyPressed[82]?1:0); var9.packetBuffer.putShort(class2.field16); var9.packetBuffer.method3528(UrlRequester.selectedItemIndex); var9.packetBuffer.method3551(var3); Client.field957.method2052(var9); } } else if(var2 == 15) { var18 = Client.cachedPlayers[var3]; if(var18 != null) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; Client.destinationX = var0; Client.destinationY = var1; var9 = WorldMapRectangle.method280(ClientPacket.field2442, Client.field957.field1484); var9.packetBuffer.putByte(KeyFocusListener.keyPressed[82]?1:0); var9.packetBuffer.method3528(Client.field1025); var9.packetBuffer.putInt(class234.field2768); var9.packetBuffer.method3551(var3); Client.field957.method2052(var9); } } else if(var2 == 16) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; Client.destinationX = var0; Client.destinationY = var1; var8 = WorldMapRectangle.method280(ClientPacket.field2419, Client.field957.field1484); var8.packetBuffer.putByte(KeyFocusListener.keyPressed[82]?1:0); var8.packetBuffer.method3528(var0 + class138.baseX); var8.packetBuffer.method3551(var3); var8.packetBuffer.method3551(UrlRequester.selectedItemIndex); var8.packetBuffer.putShort(class2.field16); var8.packetBuffer.method3559(BoundingBox.field251); var8.packetBuffer.method3528(class23.baseY + var1); Client.field957.method2052(var8); } else if(var2 == 17) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; Client.destinationX = var0; Client.destinationY = var1; var8 = WorldMapRectangle.method280(ClientPacket.field2388, Client.field957.field1484); var8.packetBuffer.method3559(class234.field2768); var8.packetBuffer.putShort(class23.baseY + var1); var8.packetBuffer.putShort(Client.field1025); var8.packetBuffer.method3541(KeyFocusListener.keyPressed[82]?1:0); var8.packetBuffer.method3550(var0 + class138.baseX); var8.packetBuffer.method3551(var3); Client.field957.method2052(var8); } else if(var2 == 18) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; Client.destinationX = var0; Client.destinationY = var1; var8 = WorldMapRectangle.method280(ClientPacket.field2453, Client.field957.field1484); var8.packetBuffer.method3528(class23.baseY + var1); var8.packetBuffer.method3550(var0 + class138.baseX); var8.packetBuffer.method3541(KeyFocusListener.keyPressed[82]?1:0); var8.packetBuffer.method3550(var3); Client.field957.method2052(var8); } else if(var2 == 19) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; Client.destinationX = var0; Client.destinationY = var1; var8 = WorldMapRectangle.method280(ClientPacket.field2437, Client.field957.field1484); var8.packetBuffer.method3551(var0 + class138.baseX); var8.packetBuffer.method3550(var3); var8.packetBuffer.putShort(class23.baseY + var1); var8.packetBuffer.putByte(KeyFocusListener.keyPressed[82]?1:0); Client.field957.method2052(var8); } else if(var2 == 20) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; Client.destinationX = var0; Client.destinationY = var1; var8 = WorldMapRectangle.method280(ClientPacket.field2399, Client.field957.field1484); var8.packetBuffer.method3550(var0 + class138.baseX); var8.packetBuffer.method3528(var3); var8.packetBuffer.method3551(class23.baseY + var1); var8.packetBuffer.method3541(KeyFocusListener.keyPressed[82]?1:0); Client.field957.method2052(var8); } else if(var2 == 21) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; Client.destinationX = var0; Client.destinationY = var1; var8 = WorldMapRectangle.method280(ClientPacket.field2416, Client.field957.field1484); var8.packetBuffer.method3528(var0 + class138.baseX); var8.packetBuffer.method3551(class23.baseY + var1); var8.packetBuffer.putShort(var3); var8.packetBuffer.method3542(KeyFocusListener.keyPressed[82]?1:0); Client.field957.method2052(var8); } else if(var2 == 22) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; Client.destinationX = var0; Client.destinationY = var1; var8 = WorldMapRectangle.method280(ClientPacket.field2467, Client.field957.field1484); var8.packetBuffer.method3551(class23.baseY + var1); var8.packetBuffer.putShort(var3); var8.packetBuffer.method3543(KeyFocusListener.keyPressed[82]?1:0); var8.packetBuffer.method3551(var0 + class138.baseX); Client.field957.method2052(var8); } else if(var2 == 23) { if(Client.isMenuOpen) { class255.region.method2997(); } else { class255.region.method2889(BoundingBox3DDrawMode.plane, var0, var1, true); } } else { PacketNode var14; Widget var22; if(var2 == 24) { var22 = class44.getWidget(var1); boolean var13 = true; if(var22.contentType > 0) { var13 = GZipDecompressor.method3461(var22); } if(var13) { var14 = WorldMapRectangle.method280(ClientPacket.field2460, Client.field957.field1484); var14.packetBuffer.putInt(var1); Client.field957.method2052(var14); } } else { if(var2 == 25) { var22 = FontName.getWidgetChild(var1, var0); if(var22 != null) { class154.method3156(); class55.method834(var1, var0, class250.method4502(GroundObject.getWidgetClickMask(var22)), var22.itemId); Client.itemSelectionState = 0; String var24; if(class250.method4502(GroundObject.getWidgetClickMask(var22)) == 0) { var24 = null; } else if(var22.targetVerb != null && var22.targetVerb.trim().length() != 0) { var24 = var22.targetVerb; } else { var24 = null; } Client.field1092 = var24; if(Client.field1092 == null) { Client.field1092 = "Null"; } if(var22.hasScript) { Client.field1028 = var22.opBase + class45.getColTags(16777215); } else { Client.field1028 = class45.getColTags(65280) + var22.spellName + class45.getColTags(16777215); } } return; } if(var2 == 26) { var8 = WorldMapRectangle.method280(ClientPacket.field2428, Client.field957.field1484); Client.field957.method2052(var8); for(WidgetNode var17 = (WidgetNode)Client.componentTable.first(); var17 != null; var17 = (WidgetNode)Client.componentTable.next()) { if(var17.owner == 0 || var17.owner == 3) { class57.closeWidget(var17, true); } } if(Client.field1033 != null) { FontName.method5490(Client.field1033); Client.field1033 = null; } } else { int var10; Widget var19; if(var2 == 28) { var8 = WorldMapRectangle.method280(ClientPacket.field2460, Client.field957.field1484); var8.packetBuffer.putInt(var1); Client.field957.method2052(var8); var19 = class44.getWidget(var1); if(var19.dynamicValues != null && var19.dynamicValues[0][0] == 5) { var10 = var19.dynamicValues[0][1]; class237.clientVarps[var10] = 1 - class237.clientVarps[var10]; class18.method142(var10); } } else if(var2 == 29) { var8 = WorldMapRectangle.method280(ClientPacket.field2460, Client.field957.field1484); var8.packetBuffer.putInt(var1); Client.field957.method2052(var8); var19 = class44.getWidget(var1); if(var19.dynamicValues != null && var19.dynamicValues[0][0] == 5) { var10 = var19.dynamicValues[0][1]; if(class237.clientVarps[var10] != var19.field2936[0]) { class237.clientVarps[var10] = var19.field2936[0]; class18.method142(var10); } } } else if(var2 == 30) { if(Client.field1033 == null) { TotalQuantityComparator.method98(var1, var0); Client.field1033 = FontName.getWidgetChild(var1, var0); FontName.method5490(Client.field1033); } } else if(var2 == 31) { var8 = WorldMapRectangle.method280(ClientPacket.field2444, Client.field957.field1484); var8.packetBuffer.method3559(BoundingBox.field251); var8.packetBuffer.method3561(var1); var8.packetBuffer.method3550(class2.field16); var8.packetBuffer.method3528(UrlRequester.selectedItemIndex); var8.packetBuffer.method3551(var3); var8.packetBuffer.method3528(var0); Client.field957.method2052(var8); Client.mouseCrosshair = 0; class2.field17 = class44.getWidget(var1); Client.pressedItemIndex = var0; } else if(var2 == 32) { var8 = WorldMapRectangle.method280(ClientPacket.field2456, Client.field957.field1484); var8.packetBuffer.method3559(class234.field2768); var8.packetBuffer.method3559(var1); var8.packetBuffer.method3551(var0); var8.packetBuffer.method3550(Client.field1025); var8.packetBuffer.putShort(var3); Client.field957.method2052(var8); Client.mouseCrosshair = 0; class2.field17 = class44.getWidget(var1); Client.pressedItemIndex = var0; } else if(var2 == 33) { var8 = WorldMapRectangle.method280(ClientPacket.field2418, Client.field957.field1484); var8.packetBuffer.method3561(var1); var8.packetBuffer.method3551(var3); var8.packetBuffer.putShort(var0); Client.field957.method2052(var8); Client.mouseCrosshair = 0; class2.field17 = class44.getWidget(var1); Client.pressedItemIndex = var0; } else if(var2 == 34) { var8 = WorldMapRectangle.method280(ClientPacket.field2440, Client.field957.field1484); var8.packetBuffer.method3550(var0); var8.packetBuffer.method3561(var1); var8.packetBuffer.method3551(var3); Client.field957.method2052(var8); Client.mouseCrosshair = 0; class2.field17 = class44.getWidget(var1); Client.pressedItemIndex = var0; } else if(var2 == 35) { var8 = WorldMapRectangle.method280(ClientPacket.field2448, Client.field957.field1484); var8.packetBuffer.method3561(var1); var8.packetBuffer.method3550(var0); var8.packetBuffer.putShort(var3); Client.field957.method2052(var8); Client.mouseCrosshair = 0; class2.field17 = class44.getWidget(var1); Client.pressedItemIndex = var0; } else if(var2 == 36) { var8 = WorldMapRectangle.method280(ClientPacket.field2383, Client.field957.field1484); var8.packetBuffer.method3551(var3); var8.packetBuffer.method3559(var1); var8.packetBuffer.putShort(var0); Client.field957.method2052(var8); Client.mouseCrosshair = 0; class2.field17 = class44.getWidget(var1); Client.pressedItemIndex = var0; } else if(var2 == 37) { var8 = WorldMapRectangle.method280(ClientPacket.field2436, Client.field957.field1484); var8.packetBuffer.method3528(var3); var8.packetBuffer.method3561(var1); var8.packetBuffer.putShort(var0); Client.field957.method2052(var8); Client.mouseCrosshair = 0; class2.field17 = class44.getWidget(var1); Client.pressedItemIndex = var0; } else { if(var2 == 38) { class154.method3156(); var22 = class44.getWidget(var1); Client.itemSelectionState = 1; UrlRequester.selectedItemIndex = var0; BoundingBox.field251 = var1; class2.field16 = var3; FontName.method5490(var22); Client.lastSelectedItemName = class45.getColTags(16748608) + class47.getItemDefinition(var3).name + class45.getColTags(16777215); if(Client.lastSelectedItemName == null) { Client.lastSelectedItemName = "null"; } return; } if(var2 == 39) { var8 = WorldMapRectangle.method280(ClientPacket.field2463, Client.field957.field1484); var8.packetBuffer.putShort(var3); var8.packetBuffer.method3559(var1); var8.packetBuffer.method3528(var0); Client.field957.method2052(var8); Client.mouseCrosshair = 0; class2.field17 = class44.getWidget(var1); Client.pressedItemIndex = var0; } else if(var2 == 40) { var8 = WorldMapRectangle.method280(ClientPacket.field2446, Client.field957.field1484); var8.packetBuffer.method3559(var1); var8.packetBuffer.method3551(var3); var8.packetBuffer.method3528(var0); Client.field957.method2052(var8); Client.mouseCrosshair = 0; class2.field17 = class44.getWidget(var1); Client.pressedItemIndex = var0; } else if(var2 == 41) { var8 = WorldMapRectangle.method280(ClientPacket.field2439, Client.field957.field1484); var8.packetBuffer.method3550(var3); var8.packetBuffer.method3559(var1); var8.packetBuffer.method3528(var0); Client.field957.method2052(var8); Client.mouseCrosshair = 0; class2.field17 = class44.getWidget(var1); Client.pressedItemIndex = var0; } else if(var2 == 42) { var8 = WorldMapRectangle.method280(ClientPacket.field2426, Client.field957.field1484); var8.packetBuffer.method3528(var3); var8.packetBuffer.method3528(var0); var8.packetBuffer.putInt(var1); Client.field957.method2052(var8); Client.mouseCrosshair = 0; class2.field17 = class44.getWidget(var1); Client.pressedItemIndex = var0; } else if(var2 == 43) { var8 = WorldMapRectangle.method280(ClientPacket.field2449, Client.field957.field1484); var8.packetBuffer.method3561(var1); var8.packetBuffer.method3551(var3); var8.packetBuffer.method3528(var0); Client.field957.method2052(var8); Client.mouseCrosshair = 0; class2.field17 = class44.getWidget(var1); Client.pressedItemIndex = var0; } else if(var2 == 44) { var18 = Client.cachedPlayers[var3]; if(var18 != null) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; Client.destinationX = var0; Client.destinationY = var1; var9 = WorldMapRectangle.method280(ClientPacket.field2401, Client.field957.field1484); var9.packetBuffer.method3542(KeyFocusListener.keyPressed[82]?1:0); var9.packetBuffer.method3551(var3); Client.field957.method2052(var9); } } else if(var2 == 45) { var18 = Client.cachedPlayers[var3]; if(var18 != null) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; Client.destinationX = var0; Client.destinationY = var1; var9 = WorldMapRectangle.method280(ClientPacket.field2424, Client.field957.field1484); var9.packetBuffer.putShort(var3); var9.packetBuffer.putByte(KeyFocusListener.keyPressed[82]?1:0); Client.field957.method2052(var9); } } else if(var2 == 46) { var18 = Client.cachedPlayers[var3]; if(var18 != null) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; Client.destinationX = var0; Client.destinationY = var1; var9 = WorldMapRectangle.method280(ClientPacket.field2407, Client.field957.field1484); var9.packetBuffer.method3541(KeyFocusListener.keyPressed[82]?1:0); var9.packetBuffer.method3528(var3); Client.field957.method2052(var9); } } else if(var2 == 47) { var18 = Client.cachedPlayers[var3]; if(var18 != null) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; Client.destinationX = var0; Client.destinationY = var1; var9 = WorldMapRectangle.method280(ClientPacket.field2431, Client.field957.field1484); var9.packetBuffer.putByte(KeyFocusListener.keyPressed[82]?1:0); var9.packetBuffer.putShort(var3); Client.field957.method2052(var9); } } else if(var2 == 48) { var18 = Client.cachedPlayers[var3]; if(var18 != null) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; Client.destinationX = var0; Client.destinationY = var1; var9 = WorldMapRectangle.method280(ClientPacket.field2425, Client.field957.field1484); var9.packetBuffer.putByte(KeyFocusListener.keyPressed[82]?1:0); var9.packetBuffer.method3551(var3); Client.field957.method2052(var9); } } else if(var2 == 49) { var18 = Client.cachedPlayers[var3]; if(var18 != null) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; Client.destinationX = var0; Client.destinationY = var1; var9 = WorldMapRectangle.method280(ClientPacket.field2472, Client.field957.field1484); var9.packetBuffer.putByte(KeyFocusListener.keyPressed[82]?1:0); var9.packetBuffer.method3551(var3); Client.field957.method2052(var9); } } else if(var2 == 50) { var18 = Client.cachedPlayers[var3]; if(var18 != null) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; Client.destinationX = var0; Client.destinationY = var1; var9 = WorldMapRectangle.method280(ClientPacket.field2391, Client.field957.field1484); var9.packetBuffer.putShort(var3); var9.packetBuffer.method3542(KeyFocusListener.keyPressed[82]?1:0); Client.field957.method2052(var9); } } else if(var2 == 51) { var18 = Client.cachedPlayers[var3]; if(var18 != null) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; Client.destinationX = var0; Client.destinationY = var1; var9 = WorldMapRectangle.method280(ClientPacket.field2387, Client.field957.field1484); var9.packetBuffer.method3551(var3); var9.packetBuffer.method3541(KeyFocusListener.keyPressed[82]?1:0); Client.field957.method2052(var9); } } else { label925: { if(var2 != 57) { if(var2 == 58) { var22 = FontName.getWidgetChild(var1, var0); if(var22 != null) { var9 = WorldMapRectangle.method280(ClientPacket.field2400, Client.field957.field1484); var9.packetBuffer.method3552(var1); var9.packetBuffer.method3561(class234.field2768); var9.packetBuffer.method3528(Client.field893); var9.packetBuffer.putShort(var22.itemId); var9.packetBuffer.method3528(var0); var9.packetBuffer.method3550(Client.field1025); Client.field957.method2052(var9); } break label925; } if(var2 == 1001) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; Client.destinationX = var0; Client.destinationY = var1; var8 = WorldMapRectangle.method280(ClientPacket.field2443, Client.field957.field1484); var8.packetBuffer.method3528(class23.baseY + var1); var8.packetBuffer.method3528(var3 >> 14 & 32767); var8.packetBuffer.method3543(KeyFocusListener.keyPressed[82]?1:0); var8.packetBuffer.method3528(var0 + class138.baseX); Client.field957.method2052(var8); break label925; } if(var2 == 1002) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; var8 = WorldMapRectangle.method280(ClientPacket.field2412, Client.field957.field1484); var8.packetBuffer.method3550(var3 >> 14 & 32767); Client.field957.method2052(var8); break label925; } if(var2 == 1003) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; var16 = Client.cachedNPCs[var3]; if(var16 != null) { NPCComposition var23 = var16.composition; if(var23.configs != null) { var23 = var23.transform(); } if(var23 != null) { var14 = WorldMapRectangle.method280(ClientPacket.field2455, Client.field957.field1484); var14.packetBuffer.method3550(var23.id); Client.field957.method2052(var14); } } break label925; } if(var2 == 1004) { Client.lastLeftClickX = var6; Client.lastLeftClickY = var7; Client.cursorState = 2; Client.field972 = 0; var8 = WorldMapRectangle.method280(ClientPacket.field2438, Client.field957.field1484); var8.packetBuffer.method3528(var3); Client.field957.method2052(var8); break label925; } if(var2 == 1005) { var22 = class44.getWidget(var1); if(var22 != null && var22.itemQuantities[var0] >= 100000) { class57.sendGameMessage(27, "", var22.itemQuantities[var0] + " x " + class47.getItemDefinition(var3).name); } else { var9 = WorldMapRectangle.method280(ClientPacket.field2438, Client.field957.field1484); var9.packetBuffer.method3528(var3); Client.field957.method2052(var9); } Client.mouseCrosshair = 0; class2.field17 = class44.getWidget(var1); Client.pressedItemIndex = var0; break label925; } if(var2 != 1007) { if(var2 == 1011 || var2 == 1009 || var2 == 1008 || var2 == 1010 || var2 == 1012) { Preferences.renderOverview.onMapClicked(var2, var3, new Coordinates(var0), new Coordinates(var1)); } break label925; } } var22 = FontName.getWidgetChild(var1, var0); if(var22 != null) { int var20 = var22.itemId; Widget var21 = FontName.getWidgetChild(var1, var0); if(var21 != null) { if(var21.onOpListener != null) { ScriptEvent var11 = new ScriptEvent(); var11.widget = var21; var11.field801 = var3; var11.string = var5; var11.objs = var21.onOpListener; AbstractSoundSystem.method2256(var11); } boolean var15 = true; if(var21.contentType > 0) { var15 = GZipDecompressor.method3461(var21); } if(var15 && DynamicObject.method2021(GroundObject.getWidgetClickMask(var21), var3 - 1)) { PacketNode var12; if(var3 == 1) { var12 = WorldMapRectangle.method280(ClientPacket.field2468, Client.field957.field1484); var12.packetBuffer.putInt(var1); var12.packetBuffer.putShort(var0); var12.packetBuffer.putShort(var20); Client.field957.method2052(var12); } if(var3 == 2) { var12 = WorldMapRectangle.method280(ClientPacket.field2421, Client.field957.field1484); var12.packetBuffer.putInt(var1); var12.packetBuffer.putShort(var0); var12.packetBuffer.putShort(var20); Client.field957.method2052(var12); } if(var3 == 3) { var12 = WorldMapRectangle.method280(ClientPacket.field2417, Client.field957.field1484); var12.packetBuffer.putInt(var1); var12.packetBuffer.putShort(var0); var12.packetBuffer.putShort(var20); Client.field957.method2052(var12); } if(var3 == 4) { var12 = WorldMapRectangle.method280(ClientPacket.field2445, Client.field957.field1484); var12.packetBuffer.putInt(var1); var12.packetBuffer.putShort(var0); var12.packetBuffer.putShort(var20); Client.field957.method2052(var12); } if(var3 == 5) { var12 = WorldMapRectangle.method280(ClientPacket.field2422, Client.field957.field1484); var12.packetBuffer.putInt(var1); var12.packetBuffer.putShort(var0); var12.packetBuffer.putShort(var20); Client.field957.method2052(var12); } if(var3 == 6) { var12 = WorldMapRectangle.method280(ClientPacket.field2478, Client.field957.field1484); var12.packetBuffer.putInt(var1); var12.packetBuffer.putShort(var0); var12.packetBuffer.putShort(var20); Client.field957.method2052(var12); } if(var3 == 7) { var12 = WorldMapRectangle.method280(ClientPacket.field2430, Client.field957.field1484); var12.packetBuffer.putInt(var1); var12.packetBuffer.putShort(var0); var12.packetBuffer.putShort(var20); Client.field957.method2052(var12); } if(var3 == 8) { var12 = WorldMapRectangle.method280(ClientPacket.field2479, Client.field957.field1484); var12.packetBuffer.putInt(var1); var12.packetBuffer.putShort(var0); var12.packetBuffer.putShort(var20); Client.field957.method2052(var12); } if(var3 == 9) { var12 = WorldMapRectangle.method280(ClientPacket.field2403, Client.field957.field1484); var12.packetBuffer.putInt(var1); var12.packetBuffer.putShort(var0); var12.packetBuffer.putShort(var20); Client.field957.method2052(var12); } if(var3 == 10) { var12 = WorldMapRectangle.method280(ClientPacket.field2429, Client.field957.field1484); var12.packetBuffer.putInt(var1); var12.packetBuffer.putShort(var0); var12.packetBuffer.putShort(var20); Client.field957.method2052(var12); } } } } } } } } } } } } if(Client.itemSelectionState != 0) { Client.itemSelectionState = 0; FontName.method5490(class44.getWidget(BoundingBox.field251)); } if(Client.spellSelected) { class154.method3156(); } if(class2.field17 != null && Client.mouseCrosshair == 0) { FontName.method5490(class2.field17); } } }
bsd-2-clause
alexghitulescu/SyncSSH
src/com/adg/sync/ssh/util/AESEncrypt.java
2090
package com.adg.sync.ssh.util; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.Key; /** * Created by adg on 11/06/2015. * */ public class AESEncrypt { private static final String ALGO = "AES"; private static final byte[] keyValue = new byte[]{'T', 'h', 'e', 'B', 'e', 's', 't', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y'}; /** * Encrypts a string that can be later on decrypted using {@link #decrypt(String)}. * This is not designed to be fully secure. It is used to store the password in the ini file. So far * in my usages I always keep that file on my machine, and other people don't have access to it. It's just so * I don't keep my password in plain text in a file. * * @param Data the string to be encrypted * @return an encrypted string * @throws GeneralSecurityException */ public static String encrypt(String Data) throws GeneralSecurityException { Key key = generateKey(); Cipher c = Cipher.getInstance(ALGO); c.init(Cipher.ENCRYPT_MODE, key); byte[] encVal = c.doFinal(Data.getBytes()); return new BASE64Encoder().encode(encVal); } /** * Decrypts a string that was encrypted using {@link #encrypt(String)}. * * @param encryptedData the encrypted string * @return a decrypted string * @throws GeneralSecurityException * @throws IOException */ public static String decrypt(String encryptedData) throws GeneralSecurityException, IOException { Key key = generateKey(); Cipher c = Cipher.getInstance(ALGO); c.init(Cipher.DECRYPT_MODE, key); byte[] decodedValue = new BASE64Decoder().decodeBuffer(encryptedData); byte[] decValue = c.doFinal(decodedValue); return new String(decValue); } private static Key generateKey() { return new SecretKeySpec(keyValue, ALGO); } }
bsd-2-clause
nsavageJVM/logcat-utls
display/src/main/java/com/fishbeans/util/ADB_ERRORS.java
356
package com.fishbeans.util; /** * Created by ubu on 24.08.16. * * FAIL0012device offline (x) */ public enum ADB_ERRORS { FAIL_ERROR("FAIL"), OFFLINE_ERROR("device offline "); String errorKey; ADB_ERRORS(String errorKey) { this.errorKey = errorKey; } public String getErrorKey( ) { return errorKey; } }
bsd-2-clause
dungkhmt/cblsvr
src/localsearch/domainspecific/vehiclerouting/vrp/constraints/eq/EqFunctionFunction.java
14616
package localsearch.domainspecific.vehiclerouting.vrp.constraints.eq; import java.util.ArrayList; import localsearch.domainspecific.vehiclerouting.vrp.IConstraintVR; import localsearch.domainspecific.vehiclerouting.vrp.IFunctionVR; import localsearch.domainspecific.vehiclerouting.vrp.VRManager; import localsearch.domainspecific.vehiclerouting.vrp.entities.Point; public class EqFunctionFunction implements IConstraintVR { private IFunctionVR f1; private IFunctionVR f2; private int violations; public EqFunctionFunction(IFunctionVR f1, IFunctionVR f2){ // f1 <= f2 this.f1 = f1; this.f2 = f2; f1.getVRManager().post(this); } public VRManager getVRManager() { // TODO Auto-generated method stub return f1.getVRManager(); } public void initPropagation() { // TODO Auto-generated method stub violations = f1.getValue() == f2.getValue() ? 0 : (int)Math.abs(f1.getValue() - f2.getValue()); } public void propagateOnePointMove(Point x, Point y) { // TODO Auto-generated method stub initPropagation(); } public void propagateTwoPointsMove(Point x, Point y) { // TODO Auto-generated method stub initPropagation(); } public void propagateTwoOptMove1(Point x, Point y) { // TODO Auto-generated method stub initPropagation(); } public void propagateTwoOptMove2(Point x, Point y) { // TODO Auto-generated method stub initPropagation(); } public void propagateTwoOptMove3(Point x, Point y) { // TODO Auto-generated method stub initPropagation(); } public void propagateTwoOptMove4(Point x, Point y) { // TODO Auto-generated method stub initPropagation(); } public void propagateTwoOptMove5(Point x, Point y) { // TODO Auto-generated method stub initPropagation(); } public void propagateTwoOptMove6(Point x, Point y) { // TODO Auto-generated method stub initPropagation(); } public void propagateTwoOptMove7(Point x, Point y) { // TODO Auto-generated method stub initPropagation(); } public void propagateTwoOptMove8(Point x, Point y) { // TODO Auto-generated method stub initPropagation(); } public void propagateOrOptMove1(Point x1, Point x2, Point y) { // TODO Auto-generated method stub initPropagation(); } public void propagateOrOptMove2(Point x1, Point x2, Point y) { // TODO Auto-generated method stub initPropagation(); } public void propagateThreeOptMove1(Point x, Point y, Point z) { // TODO Auto-generated method stub initPropagation(); } public void propagateThreeOptMove2(Point x, Point y, Point z) { // TODO Auto-generated method stub initPropagation(); } public void propagateThreeOptMove3(Point x, Point y, Point z) { // TODO Auto-generated method stub initPropagation(); } public void propagateThreeOptMove4(Point x, Point y, Point z) { // TODO Auto-generated method stub initPropagation(); } public void propagateThreeOptMove5(Point x, Point y, Point z) { // TODO Auto-generated method stub initPropagation(); } public void propagateThreeOptMove6(Point x, Point y, Point z) { // TODO Auto-generated method stub initPropagation(); } public void propagateThreeOptMove7(Point x, Point y, Point z) { // TODO Auto-generated method stub initPropagation(); } public void propagateThreeOptMove8(Point x, Point y, Point z) { // TODO Auto-generated method stub initPropagation(); } public void propagateCrossExchangeMove(Point x1, Point y1, Point x2, Point y2) { // TODO Auto-generated method stub initPropagation(); } public void propagateTwoPointsMove(Point x1, Point x2, Point y1, Point y2) { // TODO Auto-generated method stub initPropagation(); } public void propagateThreePointsMove(Point x1, Point x2, Point x3, Point y1, Point y2, Point y3) { // TODO Auto-generated method stub initPropagation(); } public void propagateFourPointsMove(Point x1, Point x2, Point x3, Point x4, Point y1, Point y2, Point y3, Point y4) { // TODO Auto-generated method stub initPropagation(); } public void propagateKPointsMove(ArrayList<Point> x, ArrayList<Point> y) { // TODO Auto-generated method stub initPropagation(); } public void propagateAddOnePoint(Point x, Point y) { // TODO Auto-generated method stub initPropagation(); } public void propagateRemoveOnePoint(Point x) { // TODO Auto-generated method stub initPropagation(); } public void propagateAddTwoPoints(Point x1, Point y1, Point x2, Point y2) { // TODO Auto-generated method stub initPropagation(); } public void propagateRemoveTwoPoints(Point x1, Point x2) { // TODO Auto-generated method stub initPropagation(); } public void propagateAddRemovePoints(Point x, Point y, Point z) { // TODO Auto-generated method stub initPropagation(); } public String name() { // TODO Auto-generated method stub return "EqFunctionFunction"; } public int violations() { // TODO Auto-generated method stub return violations; } public int evaluateOnePointMove(Point x, Point y) { // TODO Auto-generated method stub double nf1 = f1.evaluateOnePointMove(x, y) + f1.getValue(); double nf2 = f2.evaluateOnePointMove(x, y) + f2.getValue(); int nv = nf1 == nf2 ? 0 : (int)Math.abs(nf1-nf2); return nv - violations; } public int evaluateTwoPointsMove(Point x, Point y) { // TODO Auto-generated method stub double nf1 = f1.evaluateTwoPointsMove(x, y) + f1.getValue(); double nf2 = f2.evaluateTwoPointsMove(x, y) + f2.getValue(); int nv = nf1 == nf2 ? 0 : (int)Math.abs(nf1-nf2); return nv - violations; } public int evaluateTwoOptMove1(Point x, Point y) { // TODO Auto-generated method stub double nf1 = f1.evaluateTwoOptMove1(x, y) + f1.getValue(); double nf2 = f2.evaluateTwoOptMove1(x, y) + f2.getValue(); int nv = nf1 == nf2 ? 0 : (int)Math.abs(nf1-nf2); return nv - violations; } public int evaluateTwoOptMove2(Point x, Point y) { // TODO Auto-generated method stub double nf1 = f1.evaluateTwoOptMove2(x, y) + f1.getValue(); double nf2 = f2.evaluateTwoOptMove2(x, y) + f2.getValue(); int nv = nf1 == nf2 ? 0 : (int)Math.abs(nf1-nf2); return nv - violations; } public int evaluateTwoOptMove3(Point x, Point y) { // TODO Auto-generated method stub double nf1 = f1.evaluateTwoOptMove3(x, y) + f1.getValue(); double nf2 = f2.evaluateTwoOptMove3(x, y) + f2.getValue(); int nv = nf1 == nf2 ? 0 : (int)Math.abs(nf1-nf2); return nv - violations; } public int evaluateTwoOptMove4(Point x, Point y) { // TODO Auto-generated method stub double nf1 = f1.evaluateTwoOptMove4(x, y) + f1.getValue(); double nf2 = f2.evaluateTwoOptMove4(x, y) + f2.getValue(); int nv = nf1 == nf2 ? 0 : (int)Math.abs(nf1-nf2); return nv - violations; } public int evaluateTwoOptMove5(Point x, Point y) { // TODO Auto-generated method stub double nf1 = f1.evaluateTwoOptMove5(x, y) + f1.getValue(); double nf2 = f2.evaluateTwoOptMove5(x, y) + f2.getValue(); int nv = nf1 == nf2 ? 0 : (int)Math.abs(nf1-nf2); return nv - violations; } public int evaluateTwoOptMove6(Point x, Point y) { // TODO Auto-generated method stub double nf1 = f1.evaluateTwoOptMove6(x, y) + f1.getValue(); double nf2 = f2.evaluateTwoOptMove6(x, y) + f2.getValue(); int nv = nf1 == nf2 ? 0 : (int)Math.abs(nf1-nf2); return nv - violations; } public int evaluateTwoOptMove7(Point x, Point y) { // TODO Auto-generated method stub double nf1 = f1.evaluateTwoOptMove7(x, y) + f1.getValue(); double nf2 = f2.evaluateTwoOptMove7(x, y) + f2.getValue(); int nv = nf1 == nf2 ? 0 : (int)Math.abs(nf1-nf2); return nv - violations; } public int evaluateTwoOptMove8(Point x, Point y) { // TODO Auto-generated method stub double nf1 = f1.evaluateTwoOptMove8(x, y) + f1.getValue(); double nf2 = f2.evaluateTwoOptMove8(x, y) + f2.getValue(); int nv = nf1 == nf2 ? 0 : (int)Math.abs(nf1-nf2); return nv - violations; } public int evaluateOrOptMove1(Point x1, Point x2, Point y) { // TODO Auto-generated method stub double nf1 = f1.evaluateOrOptMove1(x1, x2, y) + f1.getValue(); double nf2 = f2.evaluateOrOptMove1(x1, x2, y) + f2.getValue(); int nv = nf1 == nf2 ? 0 : (int)Math.abs(nf1-nf2); return nv - violations; } public int evaluateOrOptMove2(Point x1, Point x2, Point y) { // TODO Auto-generated method stub double nf1 = f1.evaluateOrOptMove2(x1, x2, y) + f1.getValue(); double nf2 = f2.evaluateOrOptMove2(x1, x2, y) + f2.getValue(); int nv = nf1 == nf2 ? 0 : (int)Math.abs(nf1-nf2); return nv - violations; } public int evaluateThreeOptMove1(Point x, Point y, Point z) { // TODO Auto-generated method stub double nf1 = f1.evaluateThreeOptMove1(x, y, z) + f1.getValue(); double nf2 = f2.evaluateThreeOptMove1(x, y, z) + f2.getValue(); int nv = nf1 == nf2 ? 0 : (int)Math.abs(nf1-nf2); return nv - violations; } public int evaluateThreeOptMove2(Point x, Point y, Point z) { // TODO Auto-generated method stub double nf1 = f1.evaluateThreeOptMove2(x, y, z) + f1.getValue(); double nf2 = f2.evaluateThreeOptMove2(x, y, z) + f2.getValue(); int nv = nf1 == nf2 ? 0 : (int)Math.abs(nf1-nf2); return nv - violations; } public int evaluateThreeOptMove3(Point x, Point y, Point z) { // TODO Auto-generated method stub double nf1 = f1.evaluateThreeOptMove3(x, y, z) + f1.getValue(); double nf2 = f2.evaluateThreeOptMove3(x, y, z) + f2.getValue(); int nv = nf1 == nf2 ? 0 : (int)Math.abs(nf1-nf2); return nv - violations; } public int evaluateThreeOptMove4(Point x, Point y, Point z) { // TODO Auto-generated method stub double nf1 = f1.evaluateThreeOptMove4(x, y, z) + f1.getValue(); double nf2 = f2.evaluateThreeOptMove4(x, y, z) + f2.getValue(); int nv = nf1 == nf2 ? 0 : (int)Math.abs(nf1-nf2); return nv - violations; } public int evaluateThreeOptMove5(Point x, Point y, Point z) { // TODO Auto-generated method stub double nf1 = f1.evaluateThreeOptMove5(x, y, z) + f1.getValue(); double nf2 = f2.evaluateThreeOptMove5(x, y, z) + f2.getValue(); int nv = nf1 == nf2 ? 0 : (int)Math.abs(nf1-nf2); return nv - violations; } public int evaluateThreeOptMove6(Point x, Point y, Point z) { // TODO Auto-generated method stub double nf1 = f1.evaluateThreeOptMove6(x, y, z) + f1.getValue(); double nf2 = f2.evaluateThreeOptMove6(x, y, z) + f2.getValue(); int nv = nf1 == nf2 ? 0 : (int)Math.abs(nf1-nf2); return nv - violations; } public int evaluateThreeOptMove7(Point x, Point y, Point z) { // TODO Auto-generated method stub double nf1 = f1.evaluateThreeOptMove7(x, y, z) + f1.getValue(); double nf2 = f2.evaluateThreeOptMove7(x, y, z) + f2.getValue(); int nv = nf1 == nf2 ? 0 : (int)Math.abs(nf1-nf2); return nv - violations; } public int evaluateThreeOptMove8(Point x, Point y, Point z) { // TODO Auto-generated method stub double nf1 = f1.evaluateThreeOptMove8(x, y, z) + f1.getValue(); double nf2 = f2.evaluateThreeOptMove8(x, y, z) + f2.getValue(); int nv = nf1 == nf2 ? 0 : (int)Math.abs(nf1-nf2); return nv - violations; } public int evaluateCrossExchangeMove(Point x1, Point y1, Point x2, Point y2) { // TODO Auto-generated method stub double nf1 = f1.evaluateCrossExchangeMove(x1, y1, x2, y2) + f1.getValue(); double nf2 = f2.evaluateCrossExchangeMove(x1, y1, x2, y2) + f2.getValue(); int nv = nf1 == nf2 ? 0 : (int)Math.abs(nf1-nf2); return nv - violations; } public int evaluateTwoPointsMove(Point x1, Point x2, Point y1, Point y2) { // TODO Auto-generated method stub double nf1 = f1.evaluateTwoPointsMove(x1, x2, y1, y2) + f1.getValue(); double nf2 = f2.evaluateTwoPointsMove(x1, x2, y1, y2) + f2.getValue(); int nv = nf1 == nf2 ? 0 : (int)Math.abs(nf1-nf2); return nv - violations; } public int evaluateThreePointsMove(Point x1, Point x2, Point x3, Point y1, Point y2, Point y3) { // TODO Auto-generated method stub double nf1 = f1.evaluateThreePointsMove(x1, x2, x3, y1, y2, y3) + f1.getValue(); double nf2 = f2.evaluateThreePointsMove(x1, x2, x3, y1, y2, y3) + f2.getValue(); int nv = nf1 == nf2 ? 0 : (int)Math.abs(nf1-nf2); return nv - violations; } public int evaluateFourPointsMove(Point x1, Point x2, Point x3, Point x4, Point y1, Point y2, Point y3, Point y4) { // TODO Auto-generated method stub double nf1 = f1.evaluateFourPointsMove(x1, x2, x3, x4, y1, y2, y3, y4) + f1.getValue(); double nf2 = f2.evaluateFourPointsMove(x1, x2, x3, x4, y1, y2, y3, y4) + f2.getValue(); int nv = nf1 == nf2 ? 0 : (int)Math.abs(nf1-nf2); return nv - violations; } public int evaluateKPointsMove(ArrayList<Point> x, ArrayList<Point> y) { // TODO Auto-generated method stub double nf1 = f1.evaluateKPointsMove(x, y) + f1.getValue(); double nf2 = f2.evaluateKPointsMove(x, y) + f2.getValue(); int nv = nf1 == nf2 ? 0 : (int)Math.abs(nf1-nf2); return nv - violations; } public int evaluateAddOnePoint(Point x, Point y) { // TODO Auto-generated method stub double nf1 = f1.evaluateAddOnePoint(x, y) + f1.getValue(); double nf2 = f2.evaluateAddOnePoint(x, y) + f2.getValue(); int nv = nf1 == nf2 ? 0 : (int)Math.abs(nf1-nf2); return nv - violations; } public int evaluateRemoveOnePoint(Point x) { // TODO Auto-generated method stub double nf1 = f1.evaluateRemoveOnePoint(x) + f1.getValue(); double nf2 = f2.evaluateRemoveOnePoint(x) + f2.getValue(); int nv = nf1 == nf2 ? 0 : (int)Math.abs(nf1-nf2); return nv - violations; } public int evaluateAddTwoPoints(Point x1, Point y1, Point x2, Point y2) { // TODO Auto-generated method stub double nf1 = f1.evaluateAddTwoPoints(x1, y1, x2, y2) + f1.getValue(); double nf2 = f2.evaluateAddTwoPoints(x1, y1, x2, y2) + f2.getValue(); int nv = nf1 == nf2 ? 0 : (int)Math.abs(nf1-nf2); return nv - violations; } public int evaluateRemoveTwoPoints(Point x1, Point x2) { // TODO Auto-generated method stub double nf1 = f1.evaluateRemoveTwoPoints(x1, x2) + f1.getValue(); double nf2 = f2.evaluateRemoveTwoPoints(x1, x2) + f2.getValue(); int nv = nf1 == nf2 ? 0 : (int)Math.abs(nf1-nf2); return nv - violations; } public int evaluateAddRemovePoints(Point x, Point y, Point z) { // TODO Auto-generated method stub double nf1 = f1.evaluateAddRemovePoints(x, y, z) + f1.getValue(); double nf2 = f2.evaluateAddRemovePoints(x, y, z) + f2.getValue(); int nv = nf1 == nf2 ? 0 : (int)Math.abs(nf1-nf2); return nv - violations; } @Override public void propagateTwoOptMoveOneRoute(Point x, Point y) { // TODO Auto-generated method stub } }
bsd-2-clause
alpha-asp/Alpha
alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/AnswerSetQuery.java
2212
package at.ac.tuwien.kr.alpha.api; import java.util.List; import at.ac.tuwien.kr.alpha.api.programs.atoms.Atom; import at.ac.tuwien.kr.alpha.api.terms.Term; /** * A {@link java.util.function.Predicate} testing {@link Atom}s in order to query {@link AnswerSet}s for {@link Atom}s satisfying a specific * query. * * Copyright (c) 2021, the Alpha Team. */ public interface AnswerSetQuery extends java.util.function.Predicate<Atom> { /** * Adds a filter predicate to apply on terms at the given index position. * * @param termIdx the term index on which to apply the new filter * @param filter a filter predicate * @return this answer set query withthe given filter added */ AnswerSetQuery withFilter(int termIdx, java.util.function.Predicate<Term> filter); /** * Convenience method - adds a filter to match names of symbolic constants against a string. * * @param termIdx * @param str * @return */ AnswerSetQuery withConstantEquals(int termIdx, String str); /** * Convenience method - adds a filter to match values of constant terms against a string. * * @param termIdx * @param str * @return */ AnswerSetQuery withStringEquals(int termIdx, String str); /** * Convenience method - adds a filter to check for function terms with a given function symbol and arity. * * @param termIdx * @param funcSymbol * @param funcArity * @return */ AnswerSetQuery withFunctionTerm(int termIdx, String funcSymbol, int funcArity); /** * Convenience method - adds a filter to check whether a term is equal to a given term. * * @param termIdx * @param otherTerm * @return */ AnswerSetQuery withTermEquals(int termIdx, Term otherTerm); /** * Applies this query to an atom. Filters are worked off in * order of ascending term index in a conjunctive fashion, i.e. for an atom * to match the query, all of its terms must satisfy all filters on these * terms * * @param atom the atom to which to apply the query * @return true iff the atom satisfies the query */ @Override boolean test(Atom atom); /** * Applies this query to an {@link AnswerSet}. * * @param as * @return */ List<Atom> applyTo(AnswerSet as); }
bsd-2-clause
SenshiSentou/SourceFight
slick_dev/tags/Slick0.3/src/org/newdawn/slick/opengl/PNGImageData.java
24465
package org.newdawn.slick.opengl; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.zip.CRC32; import java.util.zip.DataFormatException; import java.util.zip.Inflater; import org.lwjgl.BufferUtils; /** * The PNG imge data source that is pure java reading PNGs * * @author Matthias Mann (original code) */ public class PNGImageData implements LoadableImageData { /** The valid signature of a PNG */ private static final byte[] SIGNATURE = {(byte)137, 80, 78, 71, 13, 10, 26, 10}; /** The header chunk identifer */ private static final int IHDR = 0x49484452; /** The palette chunk identifer */ private static final int PLTE = 0x504C5445; /** The transparency chunk identifier */ private static final int tRNS = 0x74524E53; /** The data chunk identifier */ private static final int IDAT = 0x49444154; /** The end chunk identifier */ private static final int IEND = 0x49454E44; /** Color type for greyscale images */ private static final byte COLOR_GREYSCALE = 0; /** Color type for true colour images */ private static final byte COLOR_TRUECOLOR = 2; /** Color type for indexed palette images */ private static final byte COLOR_INDEXED = 3; /** Color type for greyscale images with alpha */ private static final byte COLOR_GREYALPHA = 4; /** Color type for true colour images with alpha */ private static final byte COLOR_TRUEALPHA = 6; /** The stream we're going to read from */ private InputStream input; /** The CRC for the current chunk */ private final CRC32 crc; /** The buffer we'll use as temporary storage */ private final byte[] buffer; /** The length of the current chunk in bytes */ private int chunkLength; /** The ID of the current chunk */ private int chunkType; /** The number of bytes remaining in the current chunk */ private int chunkRemaining; /** The width of the image read */ private int width; /** The height of the image read */ private int height; /** The type of colours in the PNG data */ private int colorType; /** The number of bytes per pixel */ private int bytesPerPixel; /** The palette data that has been read - RGB only */ private byte[] palette; /** The palette data thats be read from alpha channel */ private byte[] paletteA; /** The transparent pixel description */ private byte[] transPixel; /** The bit depth of the image */ private int bitDepth; /** The width of the texture to be generated */ private int texWidth; /** The height of the texture to be generated */ private int texHeight; /** The scratch buffer used to store the image data */ private ByteBuffer scratch; /** * Create a new PNG image data that can read image data from PNG formated files */ public PNGImageData() { this.crc = new CRC32(); this.buffer = new byte[4096]; } /** * Initialise the PNG data header fields from the input stream * * @param input The input stream to read from * @throws IOException Indicates a failure to read appropriate data from the stream */ private void init(InputStream input) throws IOException { this.input = input; int read = input.read(buffer, 0, SIGNATURE.length); if(read != SIGNATURE.length || !checkSignatur(buffer)) { throw new IOException("Not a valid PNG file"); } openChunk(IHDR); readIHDR(); closeChunk(); searchIDAT: for(;;) { openChunk(); switch (chunkType) { case IDAT: break searchIDAT; case PLTE: readPLTE(); break; case tRNS: readtRNS(); break; } closeChunk(); } } /** * @see org.newdawn.slick.opengl.ImageData#getHeight() */ public int getHeight() { return height; } /** * @see org.newdawn.slick.opengl.ImageData#getWidth() */ public int getWidth() { return width; } /** * Check if this PNG has a an alpha channel * * @return True if the PNG has an alpha channel */ public boolean hasAlpha() { return colorType == COLOR_TRUEALPHA || paletteA != null || transPixel != null; } /** * Check if the PNG is RGB formatted * * @return True if the PNG is RGB formatted */ public boolean isRGB() { return colorType == COLOR_TRUEALPHA || colorType == COLOR_TRUECOLOR || colorType == COLOR_INDEXED; } /** * Decode a PNG into a data buffer * * @param buffer The buffer to read the data into * @param stride The image stride to read (i.e. the number of bytes to skip each line) * @param flip True if the PNG should be flipped * @throws IOException Indicates a failure to read the PNG either invalid data or * not enough room in the buffer */ private void decode(ByteBuffer buffer, int stride, boolean flip) throws IOException { final int offset = buffer.position(); byte[] curLine = new byte[width*bytesPerPixel+1]; byte[] prevLine = new byte[width*bytesPerPixel+1]; final Inflater inflater = new Inflater(); try { for(int yIndex=0 ; yIndex<height ; yIndex++) { int y = yIndex; if (flip) { y = height - 1 - yIndex; } readChunkUnzip(inflater, curLine, 0, curLine.length); unfilter(curLine, prevLine); buffer.position(offset + y*stride); switch (colorType) { case COLOR_TRUECOLOR: case COLOR_TRUEALPHA: copy(buffer, curLine); break; case COLOR_INDEXED: copyExpand(buffer, curLine); break; default: throw new UnsupportedOperationException("Not yet implemented"); } byte[] tmp = curLine; curLine = prevLine; prevLine = tmp; } } finally { inflater.end(); } bitDepth = hasAlpha() ? 32 : 24; } /** * Copy some data into the given byte buffer expanding the * data based on indexing the palette * * @param buffer The buffer to write into * @param curLine The current line of data to copy */ private void copyExpand(ByteBuffer buffer, byte[] curLine) { for (int i=1;i<curLine.length;i++) { int v = curLine[i] & 255; int index = v * 3; for (int j=0;j<3;j++) { buffer.put(palette[index+j]); } if (hasAlpha()) { if (paletteA != null) { buffer.put(paletteA[v]); } else { buffer.put((byte) 255); } } } } /** * Copy the data given directly into the byte buffer (skipping * the filter byte); * * @param buffer The buffer to write into * @param curLine The current line to copy into the buffer */ private void copy(ByteBuffer buffer, byte[] curLine) { buffer.put(curLine, 1, curLine.length-1); } /** * Unfilter the data, i.e. convert it back to it's original form * * @param curLine The line of data just read * @param prevLine The line before * @throws IOException Indicates a failure to unfilter the data due to an unknown * filter type */ private void unfilter(byte[] curLine, byte[] prevLine) throws IOException { switch (curLine[0]) { case 0: // none break; case 1: unfilterSub(curLine); break; case 2: unfilterUp(curLine, prevLine); break; case 3: unfilterAverage(curLine, prevLine); break; case 4: unfilterPaeth(curLine, prevLine); break; default: throw new IOException("invalide filter type in scanline: " + curLine[0]); } } /** * Sub unfilter * {@url http://libpng.nigilist.ru/pub/png/spec/1.2/PNG-Filters.html} * * @param curLine The line of data to be unfiltered */ private void unfilterSub(byte[] curLine) { final int bpp = this.bytesPerPixel; final int lineSize = width*bpp; for(int i=bpp+1 ; i<=lineSize ; ++i) { curLine[i] += curLine[i-bpp]; } } /** * Up unfilter * {@url http://libpng.nigilist.ru/pub/png/spec/1.2/PNG-Filters.html} * * @param prevLine The line of data read before the current * @param curLine The line of data to be unfiltered */ private void unfilterUp(byte[] curLine, byte[] prevLine) { final int bpp = this.bytesPerPixel; final int lineSize = width*bpp; for(int i=1 ; i<=lineSize ; ++i) { curLine[i] += prevLine[i]; } } /** * Average unfilter * {@url http://libpng.nigilist.ru/pub/png/spec/1.2/PNG-Filters.html} * * @param prevLine The line of data read before the current * @param curLine The line of data to be unfiltered */ private void unfilterAverage(byte[] curLine, byte[] prevLine) { final int bpp = this.bytesPerPixel; final int lineSize = width*bpp; int i; for(i=1 ; i<=bpp ; ++i) { curLine[i] += (byte)((prevLine[i] & 0xFF) >>> 1); } for(; i<=lineSize ; ++i) { curLine[i] += (byte)(((prevLine[i] & 0xFF) + (curLine[i - bpp] & 0xFF)) >>> 1); } } /** * Paeth unfilter * {@url http://libpng.nigilist.ru/pub/png/spec/1.2/PNG-Filters.html} * * @param prevLine The line of data read before the current * @param curLine The line of data to be unfiltered */ private void unfilterPaeth(byte[] curLine, byte[] prevLine) { final int bpp = this.bytesPerPixel; final int lineSize = width*bpp; int i; for(i=1 ; i<=bpp ; ++i) { curLine[i] += prevLine[i]; } for(; i<=lineSize ; ++i) { int a = curLine[i - bpp] & 255; int b = prevLine[i] & 255; int c = prevLine[i - bpp] & 255; int p = a + b - c; int pa = p - a; if(pa < 0) pa = -pa; int pb = p - b; if(pb < 0) pb = -pb; int pc = p - c; if(pc < 0) pc = -pc; if(pa<=pb && pa<=pc) c = a; else if(pb<=pc) c = b; curLine[i] += (byte)c; } } /** * Read the header of the PNG * * @throws IOException Indicates a failure to read the header */ private void readIHDR() throws IOException { checkChunkLength(13); readChunk(buffer, 0, 13); width = readInt(buffer, 0); height = readInt(buffer, 4); if(buffer[8] != 8) { throw new IOException("Unsupported bit depth"); } colorType = buffer[9] & 255; switch (colorType) { case COLOR_GREYSCALE: bytesPerPixel = 1; break; case COLOR_TRUECOLOR: bytesPerPixel = 3; break; case COLOR_TRUEALPHA: bytesPerPixel = 4; break; case COLOR_INDEXED: bytesPerPixel = 1; break; default: throw new IOException("unsupported color format"); } if(buffer[10] != 0) { throw new IOException("unsupported compression method"); } if(buffer[11] != 0) { throw new IOException("unsupported filtering method"); } if(buffer[12] != 0) { throw new IOException("unsupported interlace method"); } } /** * Read the palette chunk * * @throws IOException Indicates a failure to fully read the chunk */ private void readPLTE() throws IOException { int paletteEntries = chunkLength / 3; if(paletteEntries < 1 || paletteEntries > 256 || (chunkLength % 3) != 0) { throw new IOException("PLTE chunk has wrong length"); } palette = new byte[paletteEntries*3]; readChunk(palette, 0, palette.length); } /** * Read the transparency chunk * * @throws IOException Indicates a failure to fully read the chunk */ private void readtRNS() throws IOException { switch (colorType) { case COLOR_GREYSCALE: checkChunkLength(2); transPixel = new byte[2]; readChunk(transPixel, 0, 2); break; case COLOR_TRUECOLOR: checkChunkLength(6); transPixel = new byte[6]; readChunk(transPixel, 0, 6); break; case COLOR_INDEXED: if(palette == null) { throw new IOException("tRNS chunk without PLTE chunk"); } paletteA = new byte[palette.length/3]; // initialise default palette values for (int i=0;i<paletteA.length;i++) { paletteA[i] = (byte) 255; } readChunk(paletteA, 0, paletteA.length); break; default: // just ignore it } } /** * Close the current chunk, skip the remaining data * * @throws IOException Indicates a failure to read off redundant data */ private void closeChunk() throws IOException { if(chunkRemaining > 0) { // just skip the rest and the CRC input.skip(chunkRemaining+4); } else { readFully(buffer, 0, 4); int expectedCrc = readInt(buffer, 0); int computedCrc = (int)crc.getValue(); if(computedCrc != expectedCrc) { throw new IOException("Invalid CRC"); } } chunkRemaining = 0; chunkLength = 0; chunkType = 0; } /** * Open the next chunk, determine the type and setup the internal state * * @throws IOException Indicates a failure to determine chunk information from the stream */ private void openChunk() throws IOException { readFully(buffer, 0, 8); chunkLength = readInt(buffer, 0); chunkType = readInt(buffer, 4); chunkRemaining = chunkLength; crc.reset(); crc.update(buffer, 4, 4); // only chunkType } /** * Open a chunk of an expected type * * @param expected The expected type of the next chunk * @throws IOException Indicate a failure to read data or a different chunk on the stream */ private void openChunk(int expected) throws IOException { openChunk(); if(chunkType != expected) { throw new IOException("Expected chunk: " + Integer.toHexString(expected)); } } /** * Check the current chunk has the correct size * * @param expected The expected size of the chunk * @throws IOException Indicate an invalid size */ private void checkChunkLength(int expected) throws IOException { if(chunkLength != expected) { throw new IOException("Chunk has wrong size"); } } /** * Read some data from the current chunk * * @param buffer The buffer to read into * @param offset The offset into the buffer to read into * @param length The amount of data to read * @return The number of bytes read from the chunk * @throws IOException Indicate a failure to read the appropriate data from the chunk */ private int readChunk(byte[] buffer, int offset, int length) throws IOException { if(length > chunkRemaining) { length = chunkRemaining; } readFully(buffer, offset, length); crc.update(buffer, offset, length); chunkRemaining -= length; return length; } /** * Refill the inflating stream with data from the stream * * @param inflater The inflater to fill * @throws IOException Indicates there is no more data left or invalid data has been found on * the stream. */ private void refillInflater(Inflater inflater) throws IOException { while(chunkRemaining == 0) { closeChunk(); openChunk(IDAT); } int read = readChunk(buffer, 0, buffer.length); inflater.setInput(buffer, 0, read); } /** * Read a chunk from the inflater * * @param inflater The inflater to read the data from * @param buffer The buffer to write into * @param offset The offset into the buffer at which to start writing * @param length The number of bytes to read * @throws IOException Indicates a failure to read the complete chunk */ private void readChunkUnzip(Inflater inflater, byte[] buffer, int offset, int length) throws IOException { try { do { int read = inflater.inflate(buffer, offset, length); if(read <= 0) { if(inflater.finished()) { throw new EOFException(); } if(inflater.needsInput()) { refillInflater(inflater); } else { throw new IOException("Can't inflate " + length + " bytes"); } } else { offset += read; length -= read; } } while(length > 0); } catch (DataFormatException ex) { IOException io = new IOException("inflate error"); io.initCause(ex); throw io; } } /** * Read a complete buffer of data from the input stream * * @param buffer The buffer to read into * @param offset The offset to start copying into * @param length The length of bytes to read * @throws IOException Indicates a failure to access the data */ private void readFully(byte[] buffer, int offset, int length) throws IOException { do { int read = input.read(buffer, offset, length); if(read < 0) { throw new EOFException(); } offset += read; length -= read; } while(length > 0); } /** * Read an int from a buffer * * @param buffer The buffer to read from * @param offset The offset into the buffer to read from * @return The int read interpreted in big endian */ private int readInt(byte[] buffer, int offset) { return ((buffer[offset ] ) << 24) | ((buffer[offset+1] & 255) << 16) | ((buffer[offset+2] & 255) << 8) | ((buffer[offset+3] & 255) ); } /** * Check the signature of the PNG to confirm it's a PNG * * @param buffer The buffer to read from * @return True if the PNG signature is correct */ private boolean checkSignatur(byte[] buffer) { for(int i=0 ; i<SIGNATURE.length ; i++) { if(buffer[i] != SIGNATURE[i]) { return false; } } return true; } /** * @see org.newdawn.slick.opengl.ImageData#getDepth() */ public int getDepth() { return bitDepth; } /** * @see org.newdawn.slick.opengl.ImageData#getImageBufferData() */ public ByteBuffer getImageBufferData() { return scratch; } /** * @see org.newdawn.slick.opengl.ImageData#getTexHeight() */ public int getTexHeight() { return texHeight; } /** * @see org.newdawn.slick.opengl.ImageData#getTexWidth() */ public int getTexWidth() { return texWidth; } /** * @see org.newdawn.slick.opengl.LoadableImageData#loadImage(java.io.InputStream) */ public ByteBuffer loadImage(InputStream fis) throws IOException { return loadImage(fis, false, null); } /** * @see org.newdawn.slick.opengl.LoadableImageData#loadImage(java.io.InputStream, boolean, int[]) */ public ByteBuffer loadImage(InputStream fis, boolean flipped, int[] transparent) throws IOException { return loadImage(fis, flipped, false, transparent); } /** * @see org.newdawn.slick.opengl.LoadableImageData#loadImage(java.io.InputStream, boolean, boolean, int[]) */ public ByteBuffer loadImage(InputStream fis, boolean flipped, boolean forceAlpha, int[] transparent) throws IOException { if (transparent != null) { forceAlpha = true; } init(fis); if (!isRGB()) { throw new IOException("Only RGB formatted images are supported by the PNGLoader"); } texWidth = get2Fold(width); texHeight = get2Fold(height); int perPixel = hasAlpha() ? 4 : 3; // Get a pointer to the image memory scratch = BufferUtils.createByteBuffer(texWidth * texHeight * perPixel); decode(scratch, texWidth * perPixel, flipped); if (height < texHeight-1) { int topOffset = (texHeight-1) * (texWidth*perPixel); int bottomOffset = (height-1) * (texWidth*perPixel); for (int x=0;x<texWidth*perPixel;x++) { scratch.put(topOffset+x, scratch.get(x)); scratch.put(bottomOffset+(texWidth*perPixel)+x, scratch.get((texWidth*perPixel)+x)); } } if (width < texWidth-1) { for (int y=0;y<texHeight;y++) { for (int i=0;i<perPixel;i++) { scratch.put(((y+1)*(texWidth*perPixel))-perPixel+i, scratch.get(y*(texWidth*perPixel)+i)); scratch.put((y*(texWidth*perPixel))+(width*perPixel)+i, scratch.get((y*(texWidth*perPixel))+((width-1)*perPixel)+i)); } } } if (!hasAlpha() && forceAlpha) { ByteBuffer temp = BufferUtils.createByteBuffer(texWidth * texHeight * 4); for (int x=0;x<texWidth;x++) { for (int y=0;y<texHeight;y++) { int srcOffset = (y*3)+(x*texHeight*3); int dstOffset = (y*4)+(x*texHeight*4); temp.put(dstOffset, scratch.get(srcOffset)); temp.put(dstOffset+1, scratch.get(srcOffset+1)); temp.put(dstOffset+2, scratch.get(srcOffset+2)); temp.put(dstOffset+3, (byte) 255); } } colorType = COLOR_TRUEALPHA; bitDepth = 32; scratch = temp; } if (transparent != null) { for (int i=0;i<texWidth*texHeight*4;i+=4) { boolean match = true; for (int c=0;c<3;c++) { if (toInt(scratch.get(i+c)) != transparent[c]) { match = false; } } if (match) { scratch.put(i+3, (byte) 0); } } } scratch.position(0); return scratch; } /** * Safe convert byte to int * * @param b The byte to convert * @return The converted byte */ private int toInt(byte b) { if (b < 0) { return 256+b; } return b; } /** * Get the closest greater power of 2 to the fold number * * @param fold The target number * @return The power of 2 */ private int get2Fold(int fold) { int ret = 2; while (ret < fold) { ret *= 2; } return ret; } }
bsd-2-clause
Pushjet/Pushjet-Android
gradle/wrapper/dists/gradle-2.2.1-all/c64ydeuardnfqctvr1gm30w53/gradle-2.2.1/src/core/org/gradle/api/internal/initialization/ClassLoaderScope.java
2836
/* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.internal.initialization; import org.gradle.internal.classpath.ClassPath; /** * Represents a particular node in the ClassLoader graph. * * Certain domain objects (e.g. Gradle, Settings, Project) have an associated class loader scope. This is used for evaluating associated scripts and script plugins. * * Use of this class allows class loader creation to be lazy, and potentially optimised. It also provides a central location for class loader reuse. */ public interface ClassLoaderScope { /** * The classloader for use at this node. * <p> * Contains exported classes of the parent scope and all local and exported additions to this scope. * It is strongly preferable to only call this after {@link #lock() locking} the scope as it allows the structure to be optimized. */ ClassLoader getLocalClassLoader(); /** * The classloader for use by child nodes. * <p> * Contains exported classes of the parent scope and all local and exported additions to this scope. * It is strongly preferable to only call this after {@link #lock() locking} the scope as it allows the structure to be optimized. */ ClassLoader getExportClassLoader(); /** * The parent of this scope. */ ClassLoaderScope getParent(); /** * Makes the provided classes visible to this scope, but not to children. The classes are loaded in their own ClassLoader whose parent is the export * ClassLoader of the parent scope. * * <p>Can not be called after being locked. */ ClassLoaderScope local(ClassPath classPath); /** * Makes the provided classes visible to this scope and its children. The classes are loaded in their own ClassLoader whose parent is the export ClassLoader * of the parent scope. * * <p>Can not be called after being locked. */ ClassLoaderScope export(ClassPath classPath); /** * Creates a scope with this scope as parent. */ ClassLoaderScope createChild(); /** * Signal that no more modifications are to come, allowing the structure to be optimised if possible. */ ClassLoaderScope lock(); boolean isLocked(); }
bsd-2-clause
xranby/nifty-gui
nifty-controls/src/main/java/de/lessvoid/nifty/controls/checkbox/CheckBoxView.java
500
package de.lessvoid.nifty.controls.checkbox; import de.lessvoid.nifty.controls.CheckBoxStateChangedEvent; /** * The representation of a CheckBoxView from the world of a CheckBox. * @author void */ public interface CheckBoxView { /** * Update the View with the new state. * @param checked new state of the checkbox */ void update(final boolean checked); /** * Publish this event. * @param event the event to publish */ void publish(CheckBoxStateChangedEvent event); }
bsd-2-clause
insideo/randomcoder-taglibs
src/main/java/org/randomcoder/taglibs/security/package-info.java
1491
/** * Security tag library. * * <pre> * Copyright (c) 2006, Craig Condit. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * </pre> */ package org.randomcoder.taglibs.security;
bsd-2-clause
MD2Korg/mCerebrum-DataKit
datakit/src/main/java/org/md2k/datakit/router/RoutingManager.java
18641
/* * Copyright (c) 2018, The University of Memphis, MD2K Center of Excellence * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.md2k.datakit.router; import android.content.Context; import android.icu.util.TimeUnit; import android.os.Messenger; import org.md2k.datakit.logger.DatabaseLogger; import org.md2k.datakitapi.datatype.DataType; import org.md2k.datakitapi.datatype.DataTypeDouble; import org.md2k.datakitapi.datatype.DataTypeDoubleArray; import org.md2k.datakitapi.datatype.DataTypeFloat; import org.md2k.datakitapi.datatype.DataTypeFloatArray; import org.md2k.datakitapi.datatype.DataTypeInt; import org.md2k.datakitapi.datatype.DataTypeIntArray; import org.md2k.datakitapi.datatype.DataTypeLong; import org.md2k.datakitapi.datatype.DataTypeLongArray; import org.md2k.datakitapi.datatype.RowObject; import org.md2k.datakitapi.source.application.Application; import org.md2k.datakitapi.source.datasource.DataSource; import org.md2k.datakitapi.source.datasource.DataSourceBuilder; import org.md2k.datakitapi.source.datasource.DataSourceClient; import org.md2k.datakitapi.source.platform.Platform; import org.md2k.datakitapi.source.platformapp.PlatformApp; import org.md2k.datakitapi.status.Status; import org.md2k.utilities.Report.Log; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; /** * Routes messages and method calls to <code>Publishers</code>, <code>Publisher</code>, * <code>MessageSubscriber</code>, and <code>DatabaseSubscriber</code>. */ public class RoutingManager { /** Constant used for logging. <p>Uses <code>class.getSimpleName()</code>.</p> */ private static final String TAG = RoutingManager.class.getSimpleName(); /** Instance of a <code>RoutingManager</code> object. */ private static RoutingManager instance; /** Android context. */ private Context context; /** <code>DatabaseLogger</code> for interacting with the database. */ private DatabaseLogger databaseLogger; /** List of data source message publishers. */ private Publishers publishers; /** * Constructor * * @throws IOException */ private RoutingManager(Context context) throws IOException { Log.d(TAG, "RoutingManager()....constructor()"); this.context = context; databaseLogger = DatabaseLogger.getInstance(context); publishers = new Publishers(); } /** * Returns this instance of this class. * * @throws IOException */ public static RoutingManager getInstance(Context context) throws IOException { if (instance == null) instance = new RoutingManager(context); return instance; } /** * Registers the given data source. * * <p> * If the data source is persistent, the data source gets added to the list of <code>Publisher</code>s * and subscribed to the <code>databaseLogger</code>. * </p> * * @param dataSource Data source to register. * @return A <code>DataSourceClient</code> constructed from the given <code>dataSource</code>. */ public DataSourceClient register(DataSource dataSource) { DataSourceClient dataSourceClient = registerDataSource(dataSource); if (dataSource.isPersistent()) { publishers.addPublisher(dataSourceClient.getDs_id(), databaseLogger); } else { publishers.addPublisher(dataSourceClient.getDs_id()); } return dataSourceClient; } /** * Inserts the given <code>DataType</code> array into the database. * * @param ds_id Data source identifier. * @param dataTypes Array of data to insert. * @return The status after insertion. */ public Status insert(int ds_id, DataType[] dataTypes) { return publishers.receivedData(ds_id, dataTypes, false); } /** * Inserts the given <code>DataType</code> array into the database. * * @param ds_id Data source identifier. * @param dataTypes Array of high frequency data to insert. * @return The status after insertion. */ public Status insertHF(int ds_id, DataTypeDoubleArray[] dataTypes) { return publishers.receivedDataHF(ds_id, dataTypes); } /** * Queries the database for data within the given time frame. * * @param ds_id Data source identifier. * @param starttimestamp Beginning of the time frame. * @param endtimestamp End of the time frame. * @return ArrayList of <code>DataType</code>s that match the query. */ public ArrayList<DataType> query(int ds_id, long starttimestamp, long endtimestamp) { return databaseLogger.query(ds_id, starttimestamp, endtimestamp); } /** * Queries the database for the last n samples. * * @param ds_id Data source identifier. * @param last_n_sample Number of samples to return. * @return ArrayList of <code>DataType</code>s that match the query. */ public ArrayList<DataType> query(int ds_id, int last_n_sample) { return databaseLogger.query(ds_id, last_n_sample); } /** * Returns an arrayList of <code>RowObject</code>s matching the query. * * @param ds_id Data source identifier. * @param limit Maximum number of rows to return. * @return */ public ArrayList<RowObject> queryLastKey(int ds_id, int limit) { return databaseLogger.queryLastKey(ds_id, limit); } /** * Returns the size of the query in number of rows. * * @return The number of rows within the query. */ public DataTypeLong querySize() { return databaseLogger.querySize(); } /** * Unregisters the given data source by removing it from the <code>Publisher</code> array. * * @param ds_id Data source identifier to remove. * @return The status after the given data source has been unregistered. */ public Status unregister(int ds_id) { int statusCode = publishers.remove(ds_id); return new Status(statusCode); } /** * Subscribes the given data source to <code>MessageSubscriber</code>. * * @param ds_id Data source identifier. * @param packageName * @param reply Reference to a message handler. * @return The status after subscription */ public Status subscribe(int ds_id, String packageName, Messenger reply) { int statusCode = publishers.subscribe(ds_id, packageName, reply); Log.d(TAG, "subscribe_status=" + statusCode + " ds_id=" + ds_id + " package_name=" + packageName); return new Status(statusCode); } /** * Unsubscribes the given data source. * * @param ds_id Data source identifier. * @param packageName * @param reply Reference to a message handler. * @return The status after unsubscribing. */ public Status unsubscribe(int ds_id, String packageName, Messenger reply) { int statusCode = publishers.unsubscribe(ds_id, packageName, reply); return new Status(statusCode); } /** * Finds the given data sources within the database. * * @param dataSource <code>DataSource</code> to find. * @return An arrayList of matching <code>DataSourceClients</code> */ public ArrayList<DataSourceClient> find(DataSource dataSource) { ArrayList<DataSourceClient> dataSourceClients = databaseLogger.find(dataSource); if (dataSourceClients.size() > 0) { for (int i = 0; i < dataSourceClients.size(); i++) { if (publishers.isExist(dataSourceClients.get(i).getDs_id())) { int ds_id = dataSourceClients.get(i).getDs_id(); DataSourceClient dataSourceClient = new DataSourceClient(ds_id, dataSourceClients.get(i).getDataSource(), new Status(Status.DATASOURCE_ACTIVE)); dataSourceClients.set(i, dataSourceClient); } } } return dataSourceClients; } /** * Registers the given data source with <code>DatabaseLogger</code>. * * @param dataSource Data source to register. * @return The registered <code>DataSourceClient</code>. */ private DataSourceClient registerDataSource(DataSource dataSource) { DataSourceClient dataSourceClient; if (dataSource == null || dataSource.getType() == null || dataSource.getApplication().getId() == null) dataSourceClient = new DataSourceClient(-1, dataSource, new Status(Status.DATASOURCE_INVALID)); else { ArrayList<DataSourceClient> dataSourceClients = databaseLogger.find(dataSource); if (dataSourceClients.size() == 0) { dataSourceClient = databaseLogger.register(dataSource); } else if (dataSourceClients.size() == 1) { dataSourceClient = new DataSourceClient(dataSourceClients.get(0).getDs_id(), dataSourceClients .get(0).getDataSource(), new Status(Status.DATASOURCE_EXIST)); } else { dataSourceClient = new DataSourceClient(-1, dataSource, new Status(Status.DATASOURCE_MULTIPLE_EXIST)); } } return dataSourceClient; } /** * Closes the <code>RoutingManager</code>, <code>publishers</code>, and <code>databaseLogger</code>. */ public void close() { Log.d(TAG, "RoutingManager()...close()..."); if (instance != null) { publishers.close(); databaseLogger.close(); instance = null; } } /** * Updates the given data source's summary. * * @param dataSource Data source to update. * @param dataType Data type of the summary data. * @return Status after the update. */ public Status updateSummary(DataSource dataSource, DataType dataType) { Status status = null; for(int i = 0; i < 4; i++) { int ds_id = registerSummary(dataSource, i); long updatedTimestamp = getUpdatedTimestamp(dataType.getDateTime(), i); ArrayList<DataType> dataTypeLast = query(ds_id, 1); if(dataTypeLast.size() == 0){ status = publishers.receivedData(ds_id, new DataType[]{createDataType(dataType, null, updatedTimestamp)}, false); }else if(i == 0){ status = publishers.receivedData(ds_id, new DataType[]{createDataType(dataType, dataTypeLast.get(0), updatedTimestamp)}, true); }else if (dataTypeLast.get(0).getDateTime() != updatedTimestamp) { status = publishers.receivedData(ds_id, new DataType[]{createDataType(dataType, null, updatedTimestamp)}, false); } else { status = publishers.receivedData(ds_id, new DataType[]{createDataType(dataType, dataTypeLast.get(0), updatedTimestamp)}, true); } } return status; } /** * Registers a new <code>DataSourceClient</code> summary. * * @param dataSource <code>DataSource</code> to summarize. * @param now Determines what kind of summary is being registered. * @return The <code>DataSource</code> identifier associated with the summary. */ private int registerSummary(DataSource dataSource, int now){ String type = dataSource.getType(); DataSourceBuilder dataSourceBuilder = new DataSourceBuilder(dataSource); switch(now) { case 0: dataSourceBuilder = dataSourceBuilder.setType(type + "_SUMMARY_TOTAL"); break; case 1: dataSourceBuilder = dataSourceBuilder.setType(type + "_SUMMARY_MINUTE"); break; case 2: dataSourceBuilder = dataSourceBuilder.setType(type + "_SUMMARY_HOUR"); break; case 3: dataSourceBuilder = dataSourceBuilder.setType(type + "_SUMMARY_DAY"); break; default: } DataSourceClient dataSourceClient = register(dataSourceBuilder.build()); return dataSourceClient.getDs_id(); } /** * Creates new <code>DataType</code> objects containing the current sample plus the previous sample. * * @param dataType The current sample. * @param dataTypeLast The last sample collected. * @param time Time the sample was collected. * @return The created <code>DataType</code>. */ private DataType createDataType(DataType dataType, DataType dataTypeLast, long time){ if(dataType instanceof DataTypeDouble) { double sampleCur = ((DataTypeDouble) dataType).getSample(); double sampleLast = 0; if(dataTypeLast != null) { sampleLast = ((DataTypeDouble) dataTypeLast).getSample(); } return new DataTypeDouble(time, sampleCur + sampleLast); } if(dataType instanceof DataTypeDoubleArray) { double[] sampleCur = ((DataTypeDoubleArray) dataType).getSample(); double[] sampleFinal = new double[sampleCur.length]; System.arraycopy(sampleCur, 0, sampleFinal, 0, sampleCur.length); if(dataTypeLast != null) { double[] sampleLast = ((DataTypeDoubleArray) dataTypeLast).getSample(); for(int i = 0; i < sampleLast.length; i++) sampleFinal[i] += sampleLast[i]; } return new DataTypeDoubleArray(time, sampleFinal); } if(dataType instanceof DataTypeInt) { int sampleCur = ((DataTypeInt) dataType).getSample(); int sampleLast = 0; if(dataTypeLast != null) { sampleLast = ((DataTypeInt) dataTypeLast).getSample(); } return new DataTypeInt(time, sampleCur + sampleLast); } if(dataType instanceof DataTypeIntArray) { int[] sampleCur = ((DataTypeIntArray) dataType).getSample(); int[] sampleFinal = new int[sampleCur.length]; System.arraycopy(sampleCur, 0, sampleFinal, 0, sampleCur.length); if(dataTypeLast != null) { if(dataTypeLast instanceof DataTypeInt) sampleCur = null; int[] sampleLast = ((DataTypeIntArray) dataTypeLast).getSample(); for(int i = 0; i < sampleLast.length; i++) sampleFinal[i] += sampleLast[i]; } return new DataTypeIntArray(time, sampleFinal); } if(dataType instanceof DataTypeLong) { long sampleCur = ((DataTypeLong) dataType).getSample(); long sampleLast = 0; if(dataTypeLast != null) { sampleLast = ((DataTypeLong) dataTypeLast).getSample(); } return new DataTypeLong(time, sampleLast+sampleCur); } if(dataType instanceof DataTypeLongArray) { long[] sampleCur = ((DataTypeLongArray) dataType).getSample(); long[] sampleFinal = new long[sampleCur.length]; System.arraycopy(sampleCur, 0, sampleFinal, 0, sampleCur.length); if(dataTypeLast != null) { long[] sampleLast = ((DataTypeLongArray) dataTypeLast).getSample(); for(int i = 0; i < sampleLast.length; i++) sampleFinal[i] += sampleLast[i]; } return new DataTypeLongArray(time, sampleFinal); } if(dataType instanceof DataTypeFloat) { float sampleCur = ((DataTypeFloat) dataType).getSample(); float sampleLast = 0; if(dataTypeLast != null) { sampleLast = ((DataTypeFloat) dataTypeLast).getSample(); } return new DataTypeFloat(time, sampleCur + sampleLast); } if(dataType instanceof DataTypeFloatArray) { float[] sampleCur = ((DataTypeFloatArray) dataType).getSample(); float[] sampleFinal = new float[sampleCur.length]; System.arraycopy(sampleCur, 0, sampleFinal, 0, sampleCur.length); if(dataTypeLast!=null) { float[] sampleLast = ((DataTypeFloatArray) dataTypeLast).getSample(); for(int i = 0; i < sampleLast.length; i++) sampleFinal[i] += sampleLast[i]; } return new DataTypeFloatArray(time, sampleFinal); } return null; } /** * Updates the given timestamp to the current time in milliseconds. * * @param curTime Timestamp to update. * @param summaryType Type of timestamp to return. * @return The current timestamp. */ private long getUpdatedTimestamp(long curTime, int summaryType) { Calendar c = Calendar.getInstance(); c.setTimeInMillis(curTime); c.set(Calendar.MILLISECOND, 0); c.set(Calendar.SECOND, 0); switch(summaryType){ case 1: return c.getTimeInMillis(); case 2: c.set(Calendar.MINUTE, 0); return c.getTimeInMillis(); case 3: c.set(Calendar.MINUTE, 0); c.set(Calendar.HOUR_OF_DAY, 0); return c.getTimeInMillis(); default: return curTime; } } }
bsd-2-clause
DragonHawkMedia/KyperJGE
src/dragonhawk/kyperj/core/sound/GameSound.java
1160
package dragonhawk.kyperj.core.sound; import dragonhawk.kyperj.core.load.GameResource; public interface GameSound extends GameResource{ public boolean isPlaying(); public String getRef(); public SoundType getType(); /** * play the current sound * @param loop - whether sound loops */ public void play(boolean loop); /** * stop and reset the current sound */ public void stop(); /** * pause the sound at its current location */ public void pause(); /** * resume the sound at its current location */ public void resume(); /** * reset the current sound to the beginning */ public void reset(); /** * add a callback to the sound * */ public void addCallBack(GameSoundCallback callback); /** * get the sounds unique id * @return - sound id */ public int getID(); /** * get the sounds reference * @return reference */ public String ref(); /** * set the sound volume */ public void setGain(float gain); public boolean isMuted(); public void mute(); public float getGain(); public static enum SoundType{ MUSIC, CLIP; } }
bsd-2-clause
Konstantin8105/GenericSort
sort/src/sort/BinarySort.java
1077
package sort; import search.BinarySearchInMiddleItem; import java.util.ArrayList; import java.util.List; public class BinarySort<T extends Comparable<T>> implements Sort<T> { @Override public List<T> sort(List<T> list) { if (list == null) throw new NullPointerException(); if (list.size() == 0) throw new IndexOutOfBoundsException(); if (list.size() == 1) return new ArrayList<>(list); List<T> output = new ArrayList<>(); output.add(list.get(0)); BinarySearchInMiddleItem<T> binary = new BinarySearchInMiddleItem<>(); for (int i = 1; i < list.size(); i++) { T element = list.get(i); int position = binary.search(output, element); if (position == -1) { output.add(0, element); } else if (position == list.size() || position > output.size() - 1) { output.add(element); } else { output.add(position+1, element); } } return output; } }
bsd-2-clause
scifio/scifio
src/main/java/io/scif/img/cell/loaders/FloatArrayLoader.java
3231
/* * #%L * SCIFIO library for reading and converting scientific file formats. * %% * Copyright (C) 2011 - 2021 SCIFIO developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package io.scif.img.cell.loaders; import io.scif.ImageMetadata; import io.scif.Reader; import io.scif.img.ImageRegion; import io.scif.util.FormatTools; import java.nio.ByteBuffer; import java.nio.ByteOrder; import net.imglib2.img.basictypeaccess.array.FloatArray; import net.imglib2.type.numeric.real.FloatType; /** * {@link SCIFIOArrayLoader} implementation for {@link FloatArray} types. * * @author Mark Hiner */ public class FloatArrayLoader extends AbstractArrayLoader<FloatArray> { public FloatArrayLoader(final Reader reader, final ImageRegion subRegion) { super(reader, subRegion); } @Override public void convertBytes(final FloatArray data, final byte[] bytes, final int planesRead) { final ImageMetadata iMeta = reader().getMetadata().get(0); if (isCompatible()) { final int bpp = getBitsPerElement() / 8; final int offset = planesRead * (bytes.length / bpp); final ByteBuffer bb = ByteBuffer.wrap(bytes); bb.order(iMeta.isLittleEndian() ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN); bb.asFloatBuffer().get(data.getCurrentStorageArray(), offset, bytes.length / bpp); } else { final int pixelType = iMeta.getPixelType(); final int bpp = FormatTools.getBytesPerPixel(pixelType); final int offset = planesRead * (bytes.length / bpp); for (int index = 0; index < bytes.length / bpp; index++) { final float value = (float) utils().decodeWord(bytes, index * bpp, pixelType, iMeta.isLittleEndian()); data.setValue(offset + index, value); } } } @Override public FloatArray emptyArray(final int entities) { return new FloatArray(entities); } @Override public int getBitsPerElement() { return 32; } @Override public Class<?> outputClass() { return FloatType.class; } }
bsd-2-clause
iotoasis/SO
so-util/src/main/java/com/pineone/icbms/so/util/spring/springkafka/producer/AProducerHandler.java
2341
package com.pineone.icbms.so.util.spring.springkafka.producer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.support.SendResult; import org.springframework.util.concurrent.ListenableFuture; import org.springframework.util.concurrent.ListenableFutureCallback; /** * KafkaProducer handler.<BR/> * * Created by uni4love on 2017. 4. 10.. */ abstract public class AProducerHandler<K, V> implements ListenableFutureCallback<SendResult<String, String>> { /** * logger */ protected Logger log = LoggerFactory.getLogger(getClass()); /** * kafka producer template by springkafka. */ @Autowired private KafkaTemplate<K, V> kafkaTemplate; /** * send message to kafka.<BR/> * * @param topic topic * @param key key * @param message value */ public void send(String topic, K key, V message, ListenableFutureCallback<SendResult<K, V>> callback) { ListenableFuture<SendResult<K, V>> future = kafkaTemplate.send(topic, key, message); if (callback != null) future.addCallback(callback); } /** * Called when the {@link ListenableFuture} completes with success. * <p>Note that Exceptions raised by this method are ignored. * * @param result the result */ @Override public void onSuccess(SendResult<String, String> result) { log.info("sent message='{}' with offset={}", result.getProducerRecord(), result.getRecordMetadata().offset()); onCompleted(result); } /** * Called when the {@link ListenableFuture} completes with failure. * <p>Note that Exceptions raised by this method are ignored. * * @param ex the failure */ @Override public void onFailure(Throwable ex) { log.error("unable to send message='{}'", ex); onFailed(ex); } /** * Called after super.onSuccess().<BR/> * * @param result the result */ abstract public void onCompleted(SendResult<String, String> result); /** * Called after super.onFailure.<BR/> * * @param ex exception */ abstract public void onFailed(Throwable ex); }
bsd-2-clause
jupsal/schmies-jTEM
libUnzipped/de/jtem/mfc/field/QuaternionEditorPanel.java
4478
/** This file is part of a jTEM project. All jTEM projects are licensed under the FreeBSD license or 2-clause BSD license (see http://www.opensource.org/licenses/bsd-license.php). Copyright (c) 2002-2009, Technische Universität Berlin, jTEM All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ package de.jtem.mfc.field; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.JPanel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; /** * An instance of this class is used by the QuaternionEditor class to display 4 * MinMaxPanels representing a Quaternion. */ public class QuaternionEditorPanel extends JPanel { static final public String QUATERNION_PROPERTY="quaternion"; MinMaxPanel rScrol, iScrol, jScrol, kScrol; Quaternion value; boolean changing; /** * Constructs a new QuaternionEditorPanel initializing 4 MinMaxPanels titled * r, i, j and k. The MinMaxPanel r represents the real part of a Quaternion, * i, j and k represent the 3 imaginary parts of a Quaternion. */ public QuaternionEditorPanel() { value=new Quaternion(); setLayout(new GridBagLayout()); GridBagConstraints gbc=new GridBagConstraints(); gbc.gridwidth=GridBagConstraints.REMAINDER; gbc.fill=GridBagConstraints.HORIZONTAL; gbc.weightx=1f; gbc.insets.top=10; add(rScrol=new MinMaxPanel("r"), gbc); rScrol.getModel().addChangeListener(new QuaternionChangeListener(0)); gbc.insets.top=0; add(iScrol=new MinMaxPanel("i"), gbc); iScrol.getModel().addChangeListener(new QuaternionChangeListener(1)); add(jScrol=new MinMaxPanel("j"), gbc); jScrol.getModel().addChangeListener(new QuaternionChangeListener(2)); gbc.insets.bottom=10; add(kScrol=new MinMaxPanel("k"), gbc); kScrol.getModel().addChangeListener(new QuaternionChangeListener(3)); } /** * Assigns quat to the Quaternion of this QuaternionEditorPanel. * Fires a PropertyChangeEvent with property name {@link * #QUATERNION_PROPERTY} and null for oldValue and newValue. * Get the updated value by calling one of the getQuaternion methods. */ public void setQuaternion(Quaternion quat) { if(!value.equals(quat)) try { changing=true; value.assign(quat); rScrol.setValue(value.getRe()); iScrol.setValue(value.getX()); jScrol.setValue(value.getY()); kScrol.setValue(value.getZ()); firePropertyChange(QUATERNION_PROPERTY, null, null); }finally { changing=false; } } public Quaternion getQuaternion() { return new Quaternion(value); } public void getQuaternion(Quaternion target) { target.assign(value); } private class QuaternionChangeListener implements ChangeListener { final int index; final double[] quaternion=new double[4]; QuaternionChangeListener(int i) { index=i; } public void stateChanged(ChangeEvent ev) { if(changing) return; final DoubleBoundedRangeModel src=(DoubleBoundedRangeModel)ev.getSource(); value.get(quaternion, 0); quaternion[index]=src.getDoubleValue(); value.assign(quaternion, 0); firePropertyChange(QUATERNION_PROPERTY, null, null); } } }
bsd-2-clause
JohnNPhillips/HistoryCleanerPro
HistoryCleaner/app/src/main/java/com/ayros/historycleaner/cleaning/Cleaner.java
6187
package com.ayros.historycleaner.cleaning; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.Activity; import android.os.Build; import android.support.annotation.Nullable; import android.util.Log; import com.ayros.historycleaner.UIRunner; import com.ayros.historycleaner.helpers.Logger; import com.ayros.historycleaner.helpers.RootHelper; import com.google.common.base.Optional; import com.stericson.RootShell.exceptions.RootDeniedException; import com.stericson.RootTools.RootTools; public class Cleaner { public class CleanResults { private final List<CleanItem> successes = new ArrayList<>(); private final Map<CleanItem, Exception> failures = new HashMap<>(); public void addSuccess(CleanItem item) { Logger.debug("Cleaned Successfully: " + item.getUniqueName()); successes.add(item); } public void addFailure(CleanItem item, Exception e) { Logger.debug("Cleaning failure: " + item.getUniqueName()); failures.put(item, e); } public boolean hasFailures() { return !failures.isEmpty(); } public String getErrorReport() { StringBuilder sb = new StringBuilder(); sb.append("Android Version: " + Build.VERSION.RELEASE + "\n"); sb.append("Build: " + Build.DISPLAY + "\n"); sb.append("Has Busybox: " + RootHelper.hasBusybox() + "\n"); sb.append("Has Toolbox: " + RootHelper.hasToolbox() + "\n"); sb.append("Has sqlite: " + RootHelper.hasSqlite() + "\n"); sb.append("\n"); for (Map.Entry<CleanItem, Exception> entry : failures.entrySet()) { sb.append("Item Name: " + entry.getKey().getUniqueName() + "\n"); sb.append("Stack Trace: " + Log.getStackTraceString(entry.getValue())); sb.append("\n\n"); } return sb.toString(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (failures.size() == 0) { sb.append("Cleaned all " + successes.size() + " items successfully!"); } else { sb.append("Cleaned " + successes.size() + " items successfully\n"); sb.append("Encountered errors with " + failures.size() + " items:"); for (CleanItem failureItem : failures.keySet()) { sb.append("\n" + failureItem.getUniqueName()); } } return sb.toString(); } } public class CleanProgressEvent { public CleanItem item = null; public int itemIndex = 0; public int totalItems = 0; public CleanProgressEvent(CleanItem item, int itemIndex, int totalItems) { this.item = item; this.itemIndex = itemIndex; this.totalItems = totalItems; } } private List<CleanItem> cleanList; public Cleaner(List<CleanItem> itemList) { cleanList = new ArrayList<>(itemList); } /** * Cleans all items asynchronously. If an activity is provided, all cleaning * and events will be ran on its UI thread. Also, if a root shell is * required, it must already be running. * * @param cl * @return */ public void cleanAsync(final Optional<? extends Activity> activity, final Optional<CleanListener> cl) { new Thread() { @Override public void run() { final UIRunner uiRunner = new UIRunner(activity); final CleanResults results = new CleanResults(); if (isRootRequired() && !RootTools.isAccessGiven()) { Logger.errorST("Root shell isn't started, cannot clean items"); for (CleanItem item : cleanList) { results.addFailure(item, new RootDeniedException("Root shell not started")); } } else // If root shell is needed, it is started { for (int i = 0; i < cleanList.size(); i++) { final CleanItem item = cleanList.get(i); Logger.debug("About to clean item: " + item.getUniqueName()); // Send progressChanged message if (cl.isPresent()) { final CleanProgressEvent progressEvent = new CleanProgressEvent(item, i, cleanList.size()); uiRunner.runAndWait(new Runnable() { @Override public void run() { cl.get().progressChanged(progressEvent); } }); } // Clean item running on UI thread if necessary uiRunner.runAndWait(new Runnable() { @Override public void run() { try { item.clean(); results.addSuccess(item); } catch (Exception e) { Logger.errorST("Exception cleaning item " + item.getUniqueName(), e); results.addFailure(item, e); } } }); item.postClean(); } } // Send cleaningComplete event if (cl.isPresent()) { uiRunner.runAndWait(new Runnable() { @Override public void run() { cl.get().cleaningComplete(results); } }); } } }.start(); } /** * Cleans all items and sends all events on the current thread. Assumes * current thread is a UI thread if it is needed for any items. Also, if a * root shell is required, it must already be running. * * @param cl * @return */ public CleanResults cleanNow(Optional<CleanListener> cl) { CleanResults results = new CleanResults(); if (isRootRequired() && !RootTools.isAccessGiven()) { Logger.errorST("Root shell isn't started, cannot clean items"); for (CleanItem item : cleanList) { results.addFailure(item, new RootDeniedException("Root shell not running")); } } else { for (int i = 0; i < cleanList.size(); i++) { CleanItem item = cleanList.get(i); if (cl.isPresent()) { cl.get().progressChanged(new CleanProgressEvent(item, i, cleanList.size())); } try { item.clean(); results.addSuccess(item); } catch (Exception e) { Logger.errorST("Exception cleaning item " + item.getUniqueName(), e); results.addFailure(item, e); } item.postClean(); } } if (cl.isPresent()) { cl.get().cleaningComplete(results); } return results; } public boolean isRootRequired() { for (CleanItem item : cleanList) { if (item.isRootRequired()) { return true; } } return false; } }
bsd-2-clause
decamp/thicket
src/main/java/bits/thicket/RepulsePhaseBarnesHut.java
9209
/* * Copyright (c) 2014. Philip DeCamp * Released under the BSD 2-Clause License * http://opensource.org/licenses/BSD-2-Clause */ package bits.thicket; /** * @author decamp */ public class RepulsePhaseBarnesHut implements SolverPhase { private static final float FORCE_COST_FACTOR = 4.0f; private int mDim; private RepulseFunc mFunc; private Quadtree mTree; private float mApproxThreshSq; private int mDepth; private boolean mDepthTune; private int mDepthTunePos; /** 0 = init, 1 = increased once, 2 = increased twice... **/ private int mDepthBest; /** Best depth tested. **/ private float mCostBest; /** Cost of best depth tested. **/ private int mCostTraversal; private int mCostForceCalc; private float[] mWork = new float[6]; @Override public void init( LayoutParams params, Graph graph ) { mDim = params.mDim; mApproxThreshSq = params.mRepulseApproxThresh * params.mRepulseApproxThresh; mDepth = params.mRepulseApproxMaxTreeDepth; if( mDepth <= 0 ) { mDepth = 9; mDepthTune = true; mDepthTunePos = 0; } else { mDepthTune = false; } RepulseEq eq = params.mRepulseEq; if( eq == null ) { eq = RepulseEq.INV_LINEAR_DIST; } mFunc = RepulseEq.newFunc( eq, params.mDim ); mFunc.init( params, graph ); switch( params.mDim ) { case 2: mTree = new Quadtree2(); break; case 3: mTree = new Quadtree3(); break; default: throw new IllegalArgumentException( "LayoutParams.mDim = " + params.mDim ); } } @Override public void step( LayoutParams params, Graph graph ) { step( params, graph, null ); } public void step( LayoutParams params, Graph graph, float[] optGraphBounds ) { if( optGraphBounds == null ) { mTree.rebuild( graph.mVerts, mDepth, null, 0f ); } else if( mDim == 2 ) { float[] cent = mWork; cent[0] = ( optGraphBounds[2] + optGraphBounds[0] ) * 0.5f; cent[1] = ( optGraphBounds[3] + optGraphBounds[1] ) * 0.5f; float dx = optGraphBounds[2] - optGraphBounds[0]; float dy = optGraphBounds[3] - optGraphBounds[1]; float size = dx >= dy ? dx : dy; mTree.rebuild( graph.mVerts, mDepth, cent, size ); } else { float[] cent = mWork; cent[0] = ( optGraphBounds[3] + optGraphBounds[0] ) * 0.5f; cent[1] = ( optGraphBounds[4] + optGraphBounds[1] ) * 0.5f; cent[2] = ( optGraphBounds[5] + optGraphBounds[2] ) * 0.5f; float dx = optGraphBounds[3] - optGraphBounds[0]; float dy = optGraphBounds[4] - optGraphBounds[1]; float dz = optGraphBounds[5] - optGraphBounds[2]; float size = dx >= dy ? dx : dy; if( dz > size ) { size = dz; } mTree.rebuild( graph.mVerts, mDepth, cent, size ); } final QuadtreeCell root = mTree.root(); if( !mDepthTune ) { if( mDim == 2 ) { for( Vert v = graph.mVerts; v != null; v = v.mGraphNext ) { apply2_r( root, v ); } } else { for( Vert v = graph.mVerts; v != null; v = v.mGraphNext ) { apply3_r( root, v ); } } return; } mCostTraversal = 0; mCostForceCalc = 0; if( mDim == 2 ) { for( Vert v = graph.mVerts; v != null; v = v.mGraphNext ) { applyWithTuning2_r( root, v ); } } else { for( Vert v = graph.mVerts; v != null; v = v.mGraphNext ) { applyWithTuning3_r( root, v ); } } float cost = mCostTraversal + FORCE_COST_FACTOR * mCostForceCalc; if( mDepthTunePos == 0 ) { // First iteration. mCostBest = cost; mDepthBest = mDepth--; mDepthTunePos--; } else if( cost < mCostBest ) { // If cost decreased, keep searching in same direction. mCostBest = cost; mDepthBest = mDepth; if( mDepthTunePos > 0 ) { mDepth++; mDepthTunePos++; } else if( mDepth > 1 ) { mDepth--; mDepthTunePos--; } else { // Nowhere to go. We're done. // This is a weird thing to happen, and probably means that most of the points are // at about the same position. mDepthTune = false; } } else { // Cost has decreased. If this occurred on our first attemp to decrease // depth, switch directions. Otherwise, the search is complete. if( mDepthTunePos == -1 ) { mDepth += 2; mDepthTunePos = 1; } else { mDepth = mDepthBest; mDepthTune = false; } } //if( !mDepthTune && graph.mCoarseLevel == 0 ) { // System.out.println( "#DEPTH: " + mDepthBest + " " + mDepth + "\t" + mCostBest ); //} } @Override public void dispose( LayoutParams params, Graph graph ) {} private void apply2_r( QuadtreeCell cell, Vert v ) { float dx = cell.mX - v.mX; float dy = cell.mY - v.mY; float dist = dx * dx + dy * dy; // Check if cell is far away. if( 4.0f * cell.mHalfSize * cell.mHalfSize < mApproxThreshSq * dist ) { mFunc.applyCellForce( cell, v ); return; } // Check if cell is leaf. if( cell.mVerts != null ) { for( Vert u = cell.mVerts; u != null; u = u.mTempNext ) { if( u != v ) { mFunc.appleVertForce( u, v ); } } return; } for( QuadtreeCell child = cell.mChildList; child != null; child = child.mNextSibling ) { apply2_r( child, v ); } } private void apply3_r( QuadtreeCell cell, Vert v ) { float dx = cell.mX - v.mX; float dy = cell.mY - v.mY; float dz = cell.mZ - v.mZ; float dist = dx * dx + dy * dy + dz * dz; // Check if cell is far away. if( 4.0f * cell.mHalfSize * cell.mHalfSize < mApproxThreshSq * dist ) { mFunc.applyCellForce( cell, v ); return; } // Check if cell is leaf. if( cell.mVerts != null ) { for( Vert u = cell.mVerts; u != null; u = u.mTempNext ) { if( u != v ) { mFunc.appleVertForce( u, v ); } } return; } for( QuadtreeCell child = cell.mChildList; child != null; child = child.mNextSibling ) { apply3_r( child, v ); } } private void applyWithTuning2_r( QuadtreeCell cell, Vert v ) { mCostTraversal++; float dx = cell.mX - v.mX; float dy = cell.mY - v.mY; float dist = dx * dx + dy * dy; // Check if cell is far away. if( 4.0f * cell.mHalfSize * cell.mHalfSize < mApproxThreshSq * dist ) { mCostForceCalc++; mFunc.applyCellForce( cell, v ); return; } // Check if cell is leaf. if( cell.mVerts != null ) { for( Vert u = cell.mVerts; u != null; u = u.mTempNext ) { if( u != v ) { mCostForceCalc++; mFunc.appleVertForce( u, v ); } } return; } for( QuadtreeCell child = cell.mChildList; child != null; child = child.mNextSibling ) { applyWithTuning2_r( child, v ); } } private void applyWithTuning3_r( QuadtreeCell cell, Vert v ) { mCostTraversal++; float dx = cell.mX - v.mX; float dy = cell.mY - v.mY; float dz = cell.mZ - v.mZ; float dist = dx * dx + dy * dy + dz * dz; // Check if cell is far away. if( 4.0f * cell.mHalfSize * cell.mHalfSize < mApproxThreshSq * dist ) { mCostForceCalc++; mFunc.applyCellForce( cell, v ); return; } // Check if cell is leaf. if( cell.mVerts != null ) { for( Vert u = cell.mVerts; u != null; u = u.mTempNext ) { if( u != v ) { mCostForceCalc++; mFunc.appleVertForce( u, v ); } } return; } for( QuadtreeCell child = cell.mChildList; child != null; child = child.mNextSibling ) { applyWithTuning3_r( child, v ); } } }
bsd-2-clause
m312z/Mercs
src/mission/behaviour/MechAttack.java
3321
package mission.behaviour; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import mission.Board; import mission.gameobject.Component; public class MechAttack { List<Volley> shootCycle; Volley currentVolley; float timer; public MechAttack() { shootCycle = new ArrayList<Volley>(); currentVolley = null; } public void tick(float dt, Board board) { // no volleys if(shootCycle.size()==0) return; if(currentVolley == null || !shootCycle.contains(currentVolley)) currentVolley = shootCycle.get(0); timer += dt; // next volley if(timer>currentVolley.fireTime + currentVolley.powerupTime) { int i=(shootCycle.indexOf(currentVolley)+1)%shootCycle.size(); currentVolley = shootCycle.get(i); timer = 0; } } public List<Volley> getShootCycle() { return shootCycle; } public boolean isShooting() { if(currentVolley!=null) return timer > currentVolley.powerupTime; return false; } public boolean isPoweringUp() { if(currentVolley!=null) return (timer > 0 && timer <= currentVolley.powerupTime); return false; } public float getPowerupTime() { if(currentVolley!=null) return currentVolley.powerupTime; return 0; } public float getRemainingPowerupTime() { if(currentVolley!=null) return currentVolley.powerupTime - timer; return 0; } public Set<Component> getCurrentComponents() { if(currentVolley!=null) return currentVolley.components; return new HashSet<Component>(0); } public void addVolley(Volley v) { shootCycle.add(v); } public void removeVolley(Component member) { Iterator<Volley> vit = shootCycle.iterator(); while(vit.hasNext()) { Volley v = vit.next(); if(v.components.contains(member)) vit.remove(); } if(currentVolley!=null && shootCycle.size()>0) currentVolley = shootCycle.get(0); } public void removeComponent(Component c) { Iterator<Volley> vit = shootCycle.iterator(); while(vit.hasNext()) { Volley v = vit.next(); Iterator<Component> cit = v.components.iterator(); while(cit.hasNext()) if(cit.next() == c) cit.remove(); } } public void removeEmptyVolleys() { boolean removed = false; Iterator<Volley> vit = shootCycle.iterator(); while(vit.hasNext()) { Volley v = vit.next(); if(v.components.isEmpty()) { if(v == currentVolley) removed = true; vit.remove(); } } if(currentVolley!=null && removed && shootCycle.size()>0) currentVolley = shootCycle.get(0); } public class Volley { public Set<Component> components; public float powerupTime; public float fireTime; public Volley(List<Component> components, float powerupTime, float time) { this.components = new HashSet<Component>(); this.components.addAll(components); this.powerupTime = powerupTime; this.fireTime = time; } public Volley(Component[] components, float powerupTime, float time) { this.components = new HashSet<Component>(); for(int i=0;i<components.length;i++) this.components.add(components[i]); this.powerupTime = powerupTime; this.fireTime = time; } } }
bsd-2-clause
iotoasis/SI
si-modules/LWM2M_IPE_Server/org/eclipse/leshan/core/node/codec/json/LwM2mNodeJsonEncoder.java
9186
/******************************************************************************* * Copyright (c) 2015 Sierra Wireless and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Eclipse Distribution License v1.0 which accompany this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.html. * * Contributors: * Sierra Wireless - initial API and implementation *******************************************************************************/ package org.eclipse.leshan.core.node.codec.json; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map.Entry; import org.eclipse.leshan.core.model.LwM2mModel; import org.eclipse.leshan.core.model.ResourceModel; import org.eclipse.leshan.core.model.ResourceModel.Type; import org.eclipse.leshan.core.node.LwM2mNode; import org.eclipse.leshan.core.node.LwM2mNodeVisitor; import org.eclipse.leshan.core.node.LwM2mObject; import org.eclipse.leshan.core.node.LwM2mObjectInstance; import org.eclipse.leshan.core.node.LwM2mPath; import org.eclipse.leshan.core.node.LwM2mResource; import org.eclipse.leshan.core.node.TimestampedLwM2mNode; import org.eclipse.leshan.core.node.codec.Lwm2mNodeEncoderUtil; import org.eclipse.leshan.json.JsonArrayEntry; import org.eclipse.leshan.json.JsonRootObject; import org.eclipse.leshan.json.LwM2mJson; import org.eclipse.leshan.util.Base64; import org.eclipse.leshan.util.Validate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LwM2mNodeJsonEncoder { private static final Logger LOG = LoggerFactory.getLogger(LwM2mNodeJsonEncoder.class); public static byte[] encode(LwM2mNode node, LwM2mPath path, LwM2mModel model) { Validate.notNull(node); Validate.notNull(path); Validate.notNull(model); InternalEncoder internalEncoder = new InternalEncoder(); internalEncoder.objectId = path.getObjectId(); internalEncoder.model = model; internalEncoder.requestPath = path; node.accept(internalEncoder); JsonRootObject jsonObject = new JsonRootObject(internalEncoder.resourceList); return LwM2mJson.toJsonLwM2m(jsonObject).getBytes(); } public static byte[] encodeTimestampedData(List<TimestampedLwM2mNode> timestampedNodes, LwM2mPath path, LwM2mModel model) { Validate.notNull(timestampedNodes); Validate.notNull(path); Validate.notNull(model); InternalEncoder internalEncoder = new InternalEncoder(); ArrayList<JsonArrayEntry> entries = new ArrayList<>(); for (TimestampedLwM2mNode timestampedLwM2mNode : timestampedNodes) { internalEncoder.objectId = path.getObjectId(); internalEncoder.model = model; internalEncoder.requestPath = path; internalEncoder.resourceList = null; internalEncoder.timestamp = timestampedLwM2mNode.getTimestamp(); timestampedLwM2mNode.getNode().accept(internalEncoder); entries.addAll(internalEncoder.resourceList); } JsonRootObject jsonObject = new JsonRootObject(entries); return LwM2mJson.toJsonLwM2m(jsonObject).getBytes(); } private static class InternalEncoder implements LwM2mNodeVisitor { // visitor inputs private int objectId; private LwM2mModel model; private LwM2mPath requestPath; private Long timestamp; // visitor output private ArrayList<JsonArrayEntry> resourceList = null; @Override public void visit(LwM2mObject object) { LOG.trace("Encoding Object {} into JSON", object); // Validate request path if (!requestPath.isObject()) { throw new IllegalArgumentException("Invalid request path for JSON object encoding"); } // Create resources resourceList = new ArrayList<>(); for (LwM2mObjectInstance instance : object.getInstances().values()) { for (LwM2mResource resource : instance.getResources().values()) { String prefixPath = Integer.toString(instance.getId()) + "/" + Integer.toString(resource.getId()); resourceList.addAll(lwM2mResourceToJsonArrayEntry(prefixPath, timestamp, resource)); } } } @Override public void visit(LwM2mObjectInstance instance) { LOG.trace("Encoding object instance {} into JSON", instance); resourceList = new ArrayList<>(); for (LwM2mResource resource : instance.getResources().values()) { // Validate request path & compute resource path String prefixPath = null; if (requestPath.isObject()) { prefixPath = instance.getId() + "/" + resource.getId(); } else if (requestPath.isObjectInstance()) { prefixPath = Integer.toString(resource.getId()); } else { throw new IllegalArgumentException("Invalid request path for JSON instance encoding"); } // Create resources resourceList.addAll(lwM2mResourceToJsonArrayEntry(prefixPath, timestamp, resource)); } } @Override public void visit(LwM2mResource resource) { LOG.trace("Encoding resource {} into JSON", resource); if (!requestPath.isResource()) { throw new IllegalArgumentException("Invalid request path for JSON resource encoding"); } resourceList = lwM2mResourceToJsonArrayEntry("", timestamp, resource); } private ArrayList<JsonArrayEntry> lwM2mResourceToJsonArrayEntry(String resourcePath, Long timestamp, LwM2mResource resource) { // get type for this resource ResourceModel rSpec = model.getResourceModel(objectId, resource.getId()); Type expectedType = rSpec != null ? rSpec.type : resource.getType(); ArrayList<JsonArrayEntry> resourcesList = new ArrayList<>(); // create JSON resource element if (resource.isMultiInstances()) { for (Entry<Integer, ?> entry : resource.getValues().entrySet()) { // Create resource element JsonArrayEntry jsonResourceElt = new JsonArrayEntry(); if (resourcePath == null || resourcePath.isEmpty()) { jsonResourceElt.setName(Integer.toString(entry.getKey())); } else { jsonResourceElt.setName(resourcePath + "/" + entry.getKey()); } jsonResourceElt.setTime(timestamp); // Convert value using expected type Object convertedValue = Lwm2mNodeEncoderUtil.convertValue(entry.getValue(), resource.getType(), expectedType); this.setResourceValue(convertedValue, expectedType, jsonResourceElt); // Add it to the List resourcesList.add(jsonResourceElt); } } else { // Create resource element JsonArrayEntry jsonResourceElt = new JsonArrayEntry(); jsonResourceElt.setName(resourcePath); jsonResourceElt.setTime(timestamp); // Convert value using expected type this.setResourceValue( Lwm2mNodeEncoderUtil.convertValue(resource.getValue(), resource.getType(), expectedType), expectedType, jsonResourceElt); // Add it to the List resourcesList.add(jsonResourceElt); } return resourcesList; } private void setResourceValue(Object value, Type type, JsonArrayEntry jsonResource) { LOG.trace("Encoding value {} in JSON", value); // Following table 20 in the Specs switch (type) { case STRING: jsonResource.setStringValue((String) value); break; case INTEGER: case FLOAT: jsonResource.setFloatValue((Number) value); break; case BOOLEAN: jsonResource.setBooleanValue((Boolean) value); break; case TIME: // Specs device object example page 44, rec 13 is Time // represented as float? jsonResource.setFloatValue((((Date) value).getTime() / 1000L)); break; case OPAQUE: jsonResource.setStringValue(Base64.encodeBase64String((byte[]) value)); break; default: throw new IllegalArgumentException("Invalid value type: " + type); } } } }
bsd-2-clause
UCDenver-ccp/datasource
datasource-fileparsers/src/main/java/edu/ucdenver/ccp/datasource/fileparsers/gad/GeneticAssociationDbAllTxtFileData.java
17788
/* * Copyright (C) 2009 Center for Computational Pharmacology, University of Colorado School of Medicine * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ package edu.ucdenver.ccp.datasource.fileparsers.gad; /* * #%L * Colorado Computational Pharmacology's common module * %% * Copyright (C) 2012 - 2015 Regents of the University of Colorado * %% * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the Regents of the University of Colorado nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * #L% */ import org.apache.log4j.Logger; import edu.ucdenver.ccp.common.file.reader.Line; import edu.ucdenver.ccp.datasource.fileparsers.Record; import edu.ucdenver.ccp.datasource.fileparsers.RecordField; import edu.ucdenver.ccp.datasource.fileparsers.SingleLineFileRecord; import edu.ucdenver.ccp.datasource.identifiers.DataSource; import edu.ucdenver.ccp.datasource.identifiers.DataSourceIdentifier; import edu.ucdenver.ccp.datasource.identifiers.NucleotideAccessionResolver; import edu.ucdenver.ccp.datasource.identifiers.impl.bio.GadID; import edu.ucdenver.ccp.datasource.identifiers.impl.bio.GiNumberID; import edu.ucdenver.ccp.datasource.identifiers.impl.bio.HgncGeneSymbolID; import edu.ucdenver.ccp.datasource.identifiers.impl.bio.NcbiGeneId; import edu.ucdenver.ccp.datasource.identifiers.impl.bio.OmimID; import edu.ucdenver.ccp.datasource.identifiers.impl.bio.UniGeneID; import edu.ucdenver.ccp.datasource.identifiers.impl.ice.PubMedID; /** * See http://geneticassociationdb.nih.gov/fieldhelp.html for field definitions * * @author Bill Baumgartner * * ID _________ Association(Y/N) _________ Broad Phenotype Disease Class * _________ Disease Class Code _________ MeSH Disease Terms _________ * Chromosom _________ Chr-Band _________ _________ Gene _________ DNA * Start _________ DNA End P Value Reference _________ Pubmed ID * _________ Allele Author Description _________ Allele Functional * Effects _________ Polymophism Class _________ Gene Name _________ * RefSeq _________ Population _________ MeSH Geolocation _________ * Submitter _________ Locus Number _________ Unigene _________ Narrow * Phenotype _________ Mole. Phenotype Journal Title _________ rs Number * _________ OMIM ID Year _________ Conclusion _________ Study Info * _________ Env. Factor _________ GI Gene A _________ GI Allele of Gene * A _________ GI Gene B _________ GI Allele of Gene B _________ GI Gene * C _________ GI Allele of Gene C _________ GI Association? GI combine * Env. Factor _________ GI relevant to Disease */ @Record(dataSource = DataSource.GAD, schemaVersion = "2", comment = "Schema version is 2 b/c one field was dropped: GAD/CDC", label = "GAD record") public class GeneticAssociationDbAllTxtFileData extends SingleLineFileRecord { private static final Logger logger = Logger.getLogger(GeneticAssociationDbAllTxtFileData.class); @RecordField private final GadID gadID; @RecordField private final String associationStr; @RecordField private final String broadPhenotype; @RecordField private final String diseaseClass; @RecordField private final String diseaseClassCode; @RecordField private final String meshDiseaseTerms; @RecordField private final String chromosome; @RecordField private final String chromosomeBand; @RecordField private final HgncGeneSymbolID geneSymbol; @RecordField private final String dnaStart; @RecordField private final String dnaEnd; @RecordField private final String pValue; @RecordField private final String reference; @RecordField private final PubMedID pubmedID; @RecordField private final String alleleAuthorDescription; @RecordField private final String alleleFunctionalEffects; @RecordField private final String polymorphismClass; @RecordField private final String geneName; @RecordField(comment = "Although the column header for this field is 'RefSeqID' it contains nucleotide identifiers that are not RefSeq IDs such as GenBank IDs.") private final DataSourceIdentifier<?> nucleotideDbId; @RecordField private final String population; @RecordField private final String meshGeolocation; @RecordField private final String submitter; @RecordField private final NcbiGeneId entrezGeneID; @RecordField private final UniGeneID unigeneAccessionID; @RecordField private final String narrowPhenotype; @RecordField private final String molecularPhenotype; @RecordField private final String journal; @RecordField private final String articleTitle; @RecordField private final String rsNumber; @RecordField private final OmimID omimID; @RecordField private final String year; @RecordField private final String conclusion; @RecordField private final String studyInfo; @RecordField private final String envFactor; @RecordField private final String giGeneA; @RecordField private final String giAlleleGeneA; @RecordField private final String giGeneB; @RecordField private final String giAlleleGeneB; @RecordField private final String giGeneC; @RecordField private final String giAlleleGeneC; @RecordField private final String hasGiAssociation; @RecordField private final String giCombineEnvFactor; @RecordField private final String giRelevantToDisease; @RecordField private final String associationStatus; public GeneticAssociationDbAllTxtFileData(GadID gadId, String associationStr, String broadPhenotype, String diseaseClass, String diseaseClassCode, String meshDiseaseTerms, String chromosome, String chromosomeBand, HgncGeneSymbolID geneSymbol, String dnaStart, String dnaEnd, String pValue, String reference, PubMedID pubmedID, String alleleAuthorDescription, String alleleFunctionalEffects, String polymorphismClass, String geneName, DataSourceIdentifier<?> nucleotideDbId, String population, String meshGeolocation, String submitter, NcbiGeneId entrezGeneID, UniGeneID unigeneAccessionID, String narrowPhenotype, String molecularPhenotype, String journal, String articleTitle, String rsNumber, OmimID mimNumber, String year, String conclusion, String studyInfo, String envFactor, String giGeneA, String giAlleleGeneA, String giGeneB, String giAlleleGeneB, String giGeneC, String giAlleleGeneC, String hasGiAssociation, String giCombineEnvFactor, String giRelevantToDisease, long byteOffset, long lineNumber) { super(byteOffset, lineNumber); this.gadID = gadId; this.associationStr = associationStr; this.broadPhenotype = broadPhenotype; this.diseaseClass = diseaseClass; this.diseaseClassCode = diseaseClassCode; this.meshDiseaseTerms = meshDiseaseTerms; this.chromosome = chromosome; this.chromosomeBand = chromosomeBand; this.geneSymbol = geneSymbol; this.dnaStart = dnaStart; this.dnaEnd = dnaEnd; this.pValue = pValue; this.reference = reference; this.pubmedID = pubmedID; this.alleleAuthorDescription = alleleAuthorDescription; this.alleleFunctionalEffects = alleleFunctionalEffects; this.polymorphismClass = polymorphismClass; this.geneName = geneName; this.nucleotideDbId = nucleotideDbId; this.population = population; this.meshGeolocation = meshGeolocation; this.submitter = submitter; this.entrezGeneID = entrezGeneID; this.unigeneAccessionID = unigeneAccessionID; this.narrowPhenotype = narrowPhenotype; this.molecularPhenotype = molecularPhenotype; this.journal = journal; this.articleTitle = articleTitle; this.rsNumber = rsNumber; this.omimID = mimNumber; this.year = year; this.conclusion = conclusion; this.studyInfo = studyInfo; this.envFactor = envFactor; this.giGeneA = giGeneA; this.giAlleleGeneA = giAlleleGeneA; this.giGeneB = giGeneB; this.giAlleleGeneB = giAlleleGeneB; this.giGeneC = giGeneC; this.giAlleleGeneC = giAlleleGeneC; this.hasGiAssociation = hasGiAssociation; this.giCombineEnvFactor = giCombineEnvFactor; this.giRelevantToDisease = giRelevantToDisease; if (associationStr.equalsIgnoreCase("Y")) { this.associationStatus = new String("YES"); } else if (associationStr.equalsIgnoreCase("N")) { this.associationStatus = new String("NO"); } else { this.associationStatus = new String("UNSPECIFIED"); } } public GadID getGadId() { return gadID; } public String getAssociationStr() { return associationStr; } public String getBroadPhenotype() { return broadPhenotype; } public String getDiseaseClass() { return diseaseClass; } public String getDiseaseClassCode() { return diseaseClassCode; } public String getMeshDiseaseTerms() { return meshDiseaseTerms; } public String getChromosome() { return chromosome; } public String getChromosomeBand() { return chromosomeBand; } public HgncGeneSymbolID getGeneSymbol() { return geneSymbol; } public String getDnaStart() { return dnaStart; } public String getDnaEnd() { return dnaEnd; } public String getpValue() { return pValue; } public String getReference() { return reference; } public PubMedID getPubmedID() { return pubmedID; } public String getAlleleAuthorDescription() { return alleleAuthorDescription; } public String getAlleleFunctionalEffects() { return alleleFunctionalEffects; } public String getPolymorphismClass() { return polymorphismClass; } public String getGeneName() { return geneName; } public DataSourceIdentifier<?> getNucleotideID() { return nucleotideDbId; } public String getPopulation() { return population; } public String getMeshGeolocation() { return meshGeolocation; } public String getSubmitter() { return submitter; } public NcbiGeneId getEntrezGeneID() { return entrezGeneID; } public UniGeneID getUnigeneAccessionID() { return unigeneAccessionID; } public String getNarrowPhenotype() { return narrowPhenotype; } public String getMolecularPhenotype() { return molecularPhenotype; } public String getJournal() { return journal; } public String getArticleTitle() { return articleTitle; } public String getRsNumber() { return rsNumber; } public OmimID getOmimID() { return omimID; } public String getYear() { return year; } public String getConclusion() { return conclusion; } public String getStudyInfo() { return studyInfo; } public String getEnvFactor() { return envFactor; } public String getGiGeneA() { return giGeneA; } public String getGiAlleleGeneA() { return giAlleleGeneA; } public String getGiGeneB() { return giGeneB; } public String getGiAlleleGeneB() { return giAlleleGeneB; } public String getGiGeneC() { return giGeneC; } public String getGiAlleleGeneC() { return giAlleleGeneC; } public String getHasGiAssociation() { return hasGiAssociation; } public String getGiCombineEnvFactor() { return giCombineEnvFactor; } public String getGiRelevantToDisease() { return giRelevantToDisease; } public boolean hasAssociation() { return associationStr.equalsIgnoreCase("Y"); } public static GeneticAssociationDbAllTxtFileData parseGeneticAssociationDbAllTxtLine(Line line) { String[] toks = line.getText().split("\\t", -1); if (toks.length < 23) { logger.warn("Invalid line detected (" + line.getLineNumber() + "): " + line.getText()); } GadID gadID = new GadID(toks[0].trim()); String associationStr = toks[1]; String broadPhenotype = new String(toks[2]); String diseaseClass = new String(toks[3]); String diseaseClassCode = toks[4]; String meshDiseaseTerms = toks[5]; String chromosome = toks[6]; String chromosomeBand = toks[7]; HgncGeneSymbolID geneSymbol = new HgncGeneSymbolID(toks[8]); String dnaStart = toks[9]; String dnaEnd = toks[10]; String pValue = toks[11]; String reference = toks[12]; PubMedID pubmedID = null; if (!toks[13].isEmpty()) { try { pubmedID = new PubMedID(toks[13]); } catch (IllegalArgumentException e) { logger.warn(e); pubmedID = null; } } String alleleAuthorDescription = toks[14]; String alleleFunctionalEffects = toks[15]; String polymorphismClass = toks[16]; String geneName = toks[17]; String refseqURL = null; try { refseqURL = toks[18]; } catch (ArrayIndexOutOfBoundsException e) { logger.error("Caught exception. Line: (" + line.getLineNumber() + ") #toks: " + toks.length + " Message: " + e.getMessage() + " LINE: " + line.getText()); } DataSourceIdentifier<?> nucleotideId = null; if (!refseqURL.isEmpty()) { String acc = null; if (refseqURL.contains("=")) { acc = refseqURL.substring(refseqURL.lastIndexOf('=') + 1).trim(); } else { acc = refseqURL.substring(refseqURL.lastIndexOf('/') + 1).trim(); } if (acc.matches("\\d+")) { nucleotideId = new GiNumberID(acc); } else { nucleotideId = NucleotideAccessionResolver.resolveNucleotideAccession(acc, refseqURL); } } String population = toks[19]; String meshGeolocation = toks[20]; String submitter = toks[21]; NcbiGeneId entrezGeneID = null; if (!toks[22].isEmpty()) entrezGeneID = new NcbiGeneId(toks[22]); UniGeneID unigeneAccessionID = null; if (!toks[23].trim().isEmpty()) unigeneAccessionID = new UniGeneID(toks[23]); String narrowPhenotype = null; if (toks.length > 24) narrowPhenotype = toks[24]; String molecularPhenotype = null; if (toks.length > 25) molecularPhenotype = toks[25]; String journal = null; if (toks.length > 26) journal = toks[26]; String articleTitle = null; if (toks.length > 27) articleTitle = toks[27]; String rsNumber = null; if (toks.length > 28) rsNumber = toks[28]; OmimID omimID = null; if (toks.length > 29 && !toks[29].isEmpty()) try { omimID = new OmimID(toks[29]); } catch (IllegalArgumentException e) { logger.warn(e); omimID = null; } String gadCdc = ""; String year = ""; String conclusion = ""; String studyInfo = ""; String envFactor = ""; String giGeneA = ""; String giAlleleGeneA = ""; String giGeneB = ""; String giAlleleGeneB = ""; String giGeneC = ""; String giAlleleGeneC = ""; String hasGiAssociation = ""; String giCombineEnvFactor = ""; String giRelevantToDisease = ""; if (toks.length > 30) { year = toks[30]; } if (toks.length > 31) { conclusion = toks[31]; } if (toks.length > 32) { studyInfo = toks[32]; } if (toks.length > 33) { envFactor = toks[33]; } if (toks.length > 34) { giGeneA = toks[34]; } if (toks.length > 35) { giAlleleGeneA = toks[35]; } if (toks.length > 36) { giGeneB = toks[36]; } if (toks.length > 37) { giAlleleGeneB = toks[37]; } if (toks.length > 38) { giGeneC = toks[38]; } if (toks.length > 39) { giAlleleGeneC = toks[39]; } if (toks.length > 40) { hasGiAssociation = toks[40]; } if (toks.length > 41) { giCombineEnvFactor = toks[41]; } if (toks.length > 42) { giRelevantToDisease = toks[42]; } return new GeneticAssociationDbAllTxtFileData(gadID, associationStr, broadPhenotype, diseaseClass, diseaseClassCode, meshDiseaseTerms, chromosome, chromosomeBand, geneSymbol, dnaStart, dnaEnd, pValue, reference, pubmedID, alleleAuthorDescription, alleleFunctionalEffects, polymorphismClass, geneName, nucleotideId, population, meshGeolocation, submitter, entrezGeneID, unigeneAccessionID, narrowPhenotype, molecularPhenotype, journal, articleTitle, rsNumber, omimID, year, conclusion, studyInfo, envFactor, giGeneA, giAlleleGeneA, giGeneB, giAlleleGeneB, giGeneC, giAlleleGeneC, hasGiAssociation, giCombineEnvFactor, giRelevantToDisease, line.getByteOffset(), line.getLineNumber()); } public String getAssociationStatus() { return associationStatus; } }
bsd-3-clause
vitkin/sfdc-email-to-case-agent
src/main/java/com/sforce/mail/Notification.java
5401
/* * #%L * sfdc-email-to-case-agent * %% * Copyright (C) 2005 salesforce.com, inc. * %% * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided * that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or other materials provided with the distribution. * * 3. Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package com.sforce.mail; /** * Notification * * Abstract representation of a notificatation to a administrator. */ public abstract class Notification { public final static String MAIL_SERVICE_DOWN = "Unable to connect to mail service."; public final static String MAIL_SERVICE_LOGIN_FAILED = "Unable to connect to mail service, authentication failed."; public final static String SFDC_SERVICE_DOWN = "Unable to connect to salesforce.com service."; public final static String SFDC_API_ERROR = "Unable to process mail message."; public final static String UNKNOWN_ERROR = "Unknown error while processing mail message."; public static final String SEVERITY_ERROR = "ERROR"; public static final String SEVERITY_WARNING = "WARNING"; public static final String SEVERITY_INFO = "INFO"; private String severity; /** Notification Subject and description */ private String description; /** Notification Message */ private String messageText; /** Notification Recipients, comma delimited list of valid email addresses*/ private String recipients; /** Notification Sender */ private String from; /** Credentials used to authenticate the notification request */ private LoginCredentials credentials; public Notification (LoginCredentials _oCredentials){ severity = ""; description = ""; messageText = ""; recipients = ""; from = ""; credentials = _oCredentials; } /** * @return Returns the m_oCredentials. */ protected LoginCredentials getCredentials() { return credentials; } /** * @param credentials The m_oCredentials to set. */ protected void setCredentials(LoginCredentials credentials) { this.credentials = credentials; } /* (non-Javadoc) * @see com.sforce.mail.LoginCredentials#getPassword() */ public String getPassword() { return this.credentials.getPassword(); } /* (non-Javadoc) * @see com.sforce.mail.LoginCredentials#getServerName() */ public String getServerName() { return this.credentials.getServerName(); } /* (non-Javadoc) * @see com.sforce.mail.LoginCredentials#getUserName() */ public String getUserName() { return this.credentials.getUserName(); } /** * @return Returns the m_sDescription. */ public String getDescription() { return this.description; } /** * @param description The m_sDescription to set. */ public void setDescription(String description) { this.description = description; } /** * @return Returns the m_sFrom. */ public String getFrom() { return this.from; } /** * @param from The m_sFrom to set. */ public void setFrom(String from) { this.from = from; } /** * @return Returns the m_sMessageText. */ public String getMessageText() { return this.messageText; } /** * @param messageText The m_sMessageText to set. */ public void setMessageText(String messageText) { this.messageText = messageText; } /** * @return Returns the m_sSeverity. */ public String getSeverity() { return this.severity; } /** * @param severity The m_sSeverity to set. */ public void setSeverity(String severity) { this.severity = severity; } /** * @return Returns the m_sTo. */ public String getTo() { return this.recipients; } /** * @param to The m_sTo to set. */ public void setTo(String to) { this.recipients = to; } public abstract void sendNotification(); }
bsd-3-clause
kdkanishka/Virustotal-Public-API-V2.0-Client
src/test/java/systemtests/VirusTotalServiceClientSystemTest.java
8204
package systemtests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.Map; import org.junit.After; import org.junit.Before; import org.junit.Test; import systemtests.config.ApiDetails; import com.kanishka.virustotal.dto.DomainReport; import com.kanishka.virustotal.dto.DomainResolution; import com.kanishka.virustotal.dto.FileScanReport; import com.kanishka.virustotal.dto.Sample; import com.kanishka.virustotal.dto.URL; import com.kanishka.virustotal.dto.VirusScanInfo; import com.kanishka.virustotal.exception.APIKeyNotFoundException; import com.kanishka.virustotal.exception.InvalidArguentsException; import com.kanishka.virustotal.exception.QuotaExceededException; import com.kanishka.virustotal.exception.UnauthorizedAccessException; import com.kanishka.virustotalv2.VirusTotalConfig; import com.kanishka.virustotalv2.VirustotalPublicV2; import com.kanishka.virustotalv2.VirustotalPublicV2Impl; /** * Created with IntelliJ IDEA. * User: kanishka * Date: 8/31/14 * Time: 8:59 PM * To change this template use File | Settings | File Templates. */ public class VirusTotalServiceClientSystemTest { VirustotalPublicV2 virusTotalRef; @Before public final void setUp() throws APIKeyNotFoundException { VirusTotalConfig.getConfigInstance().setVirusTotalAPIKey(ApiDetails.API_KEY); virusTotalRef = new VirustotalPublicV2Impl(); } @After public final void tearDown() { System.gc(); } @Test public void it_should_return_domain_report_for_the_given_domain() throws QuotaExceededException, InvalidArguentsException, UnauthorizedAccessException, IOException { String someMaliciousDomain = "www.ntt62.com"; DomainReport report = virusTotalRef.getDomainReport(someMaliciousDomain); Sample[] communicatingSamples = report.getDetectedCommunicatingSamples(); if (communicatingSamples != null) { System.out.println("Communicating Samples"); for (Sample sample : communicatingSamples) { System.out.println("SHA256 : " + sample.getSha256()); System.out.println("Date : " + sample.getDate()); System.out.println("Positives : " + sample.getPositives()); System.out.println("Total : " + sample.getTotal()); assertNotNull(sample.getSha256()); assertNotNull(sample.getDate()); assertTrue(sample.getPositives() > 0); assertTrue(sample.getTotal() > 0); } } Sample[] detectedDownloadedSamples = report.getDetectedDownloadedSamples(); if (detectedDownloadedSamples != null) { System.out.println("Detected Downloaded Samples"); for (Sample sample : detectedDownloadedSamples) { System.out.println("SHA256 : " + sample.getSha256()); System.out.println("Date : " + sample.getDate()); System.out.println("Positives : " + sample.getPositives()); System.out.println("Total : " + sample.getTotal()); assertNotNull(sample.getSha256()); assertNotNull(sample.getDate()); assertTrue(sample.getPositives() > 0); assertTrue(sample.getTotal() > 0); } } URL[] urls = report.getDetectedUrls(); if (urls != null) { System.out.println("Detected URLs"); for (URL url : urls) { System.out.println("URL : " + url.getUrl()); System.out.println("Positives : " + url.getPositives()); System.out.println("Total : " + url.getTotal()); System.out.println("Scan Date" + url.getScanDate()); assertNotNull(url.getUrl()); assertTrue(url.getPositives() > 0); assertTrue(url.getTotal() > 0); assertNotNull(url.getScanDate()); } } DomainResolution[] resolutions = report.getResolutions(); if (resolutions != null) { System.out.println("Resolutions"); for (DomainResolution resolution : resolutions) { System.out.println("IP Address : " + resolution.getIpAddress()); System.out.println("Last Resolved : " + resolution.getLastResolved()); } } Sample[] unDetectedDownloadedSamples = report.getUndetectedDownloadedSamples(); if (unDetectedDownloadedSamples != null) { System.out.println("Undetected Downloaded Samples"); for (Sample sample : unDetectedDownloadedSamples) { System.out.println("SHA256 : " + sample.getSha256()); System.out.println("Date : " + sample.getDate()); System.out.println("Positives : " + sample.getPositives()); System.out.println("Total : " + sample.getTotal()); assertNotNull(sample.getSha256()); assertNotNull(sample.getDate()); assertTrue(sample.getPositives() >= 0); assertTrue(sample.getTotal() > 0); } } Sample[] unDetectedCommunicatingSamples = report.getUndetectedCommunicatingSamples(); if (unDetectedCommunicatingSamples != null) { System.out.println("Undetected Communicating Samples"); for (Sample sample : unDetectedCommunicatingSamples) { System.out.println("SHA256 : " + sample.getSha256()); System.out.println("Date : " + sample.getDate()); System.out.println("Positives : " + sample.getPositives()); System.out.println("Total : " + sample.getTotal()); } } System.out.println("Response Code : " + report.getResponseCode()); System.out.println("Verbose Message : " + report.getVerboseMessage()); } @Test public void it_should_return_file_scan_report_when_resource_was_given() throws UnauthorizedAccessException, IOException, QuotaExceededException { String resource = "275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f"; FileScanReport report = virusTotalRef.getScanReport(resource); System.out.println("MD5 :\t" + report.getMd5()); System.out.println("Perma link :\t" + report.getPermalink()); System.out.println("Resource :\t" + report.getResource()); System.out.println("Scan Date :\t" + report.getScanDate()); System.out.println("Scan Id :\t" + report.getScanId()); System.out.println("SHA1 :\t" + report.getSha1()); System.out.println("SHA256 :\t" + report.getSha256()); System.out.println("Verbose Msg :\t" + report.getVerboseMessage()); System.out.println("Response Code :\t" + report.getResponseCode()); System.out.println("Positives :\t" + report.getPositives()); System.out.println("Total :\t" + report.getTotal()); assertNotNull(report.getMd5()); assertNotNull(report.getPermalink()); assertNotNull(report.getResource()); assertNotNull(report.getScanDate()); assertNotNull(report.getScanId()); assertNotNull(report.getSha1()); assertNotNull(report.getSha256()); assertNotNull(report.getVerboseMessage()); assertEquals(report.getResponseCode(), new Integer(1)); assertTrue(report.getPositives() > 0); assertTrue(report.getTotal() > 0); Map<String, VirusScanInfo> scans = report.getScans(); for (String key : scans.keySet()) { VirusScanInfo virusInfo = scans.get(key); System.out.println("Scanner : " + key); System.out.println("\t\t Resut : " + virusInfo.getResult()); System.out.println("\t\t Update : " + virusInfo.getUpdate()); System.out.println("\t\t Version :" + virusInfo.getVersion()); assertNotNull(virusInfo); assertNotNull(virusInfo.getUpdate()); assertNotNull(virusInfo.getVersion()); } } }
bsd-3-clause
luttero/Maud
src/it/unitn/ing/wizard/HIPPOWizard/IPRFileReader.java
1877
package it.unitn.ing.wizard.HIPPOWizard; import it.unitn.ing.rista.util.MaudPreferences; import it.unitn.ing.wizard.HIPPOWizard.HIPPOdata; import java.io.*; import java.util.ArrayList; import java.util.StringTokenizer; public class IPRFileReader { private BufferedReader input = null; public IPRFileReader(BufferedReader input) { this.input = input; } public void read(HIPPOdata data) throws IOException { double maxBankToleranceTheta = MaudPreferences.getDouble("hippoWizard.maxDelta2ThetaForBankGrouping", 2.0); String line; int lineCounter = 0; while ((line = input.readLine()) != null) { lineCounter++; if (line.length() > 12 && line.substring(6, 12).equals("BNKPAR")) { StringTokenizer tokenizer = new StringTokenizer(line); if (tokenizer.countTokens() < 4) throw(new IOException("Error while reading instrument file at line " + lineCounter)); if (line.charAt(3) == ' ' || line.charAt(3) == '\t') tokenizer.nextToken(); tokenizer.nextToken(); tokenizer.nextToken(); String theta2string = tokenizer.nextToken(); double theta2 = Double.parseDouble(theta2string); int roundedForName = (int) (theta2 + 0.5); String nameAndTof_theta = "Bank" + roundedForName; boolean found = false; for (int i = 0; i < data.mbank.size(); i++) { if (Math.abs(((HIPPOBank) data.mbank.elementAt(i)).theta2 - theta2) < maxBankToleranceTheta) { ((HIPPOBank) data.mbank.elementAt(i)).available = true; found = true; } } if (!found) { String number = line.substring(3, 6); number = number.trim(); // System.out.println(number); data.mbank.add(new HIPPOBank(nameAndTof_theta, theta2, Integer.parseInt(number), true)); // System.out.println("Number of banks read: " + data.mbank.size() + " " + nameAndTof_theta + " " + number); } } } } }
bsd-3-clause
Civcraft/Mercury
src/vg/civcraft/mc/mercury/venus/VenusHandler.java
1282
package vg.civcraft.mc.mercury.venus; import vg.civcraft.mc.mercury.MercuryPlugin; import vg.civcraft.mc.mercury.ServiceHandler; public class VenusHandler implements ServiceHandler { private VenusService service; private MercuryPlugin plugin = MercuryPlugin.instance; public VenusHandler(){ service = new VenusService(); if (service.connected) { service.start(); } else { service = null; } } // Venus doesn't need to be pinged. @Override public void pingService() {} @Override public void addServerToServerList() {} @Override public void sendMessage(String server, String message, String... pluginChannels) { if (service == null) { return; } for (String channel : pluginChannels) { service.sendMessage(server, message, channel); } } @Override public void sendGlobalMessage(String message, String... pluginChannels) { throw new UnsupportedOperationException(); } // Venus doesn't need channels registered. @Override public void addChannels(String... channels) {} @Override public void addGlobalChannels(String... pluginChannels) { addChannels(pluginChannels); } @Override public void destory() { if (service != null) service.teardown(); } @Override public boolean isEnabled(){ return service != null; } }
bsd-3-clause
DweebsUnited/CodeMonkey
java/CodeMonkey/HEMesh/wblut/hemesh/HET_Texture.java
8745
/* * HE_Mesh Frederik Vanhoutte - www.wblut.com * * https://github.com/wblut/HE_Mesh * A Processing/Java library for for creating and manipulating polygonal meshes. * * Public Domain: http://creativecommons.org/publicdomain/zero/1.0/ */ package wblut.hemesh; import processing.core.PImage; import wblut.geom.WB_Coord; import wblut.geom.WB_Point; import wblut.math.WB_MTRandom; import wblut.processing.WB_Color; import wblut.processing.WB_Render3D; public class HET_Texture { /** * */ public static void cleanUVW(final HE_Mesh mesh) { HE_VertexIterator vItr = mesh.vItr(); while (vItr.hasNext()) { vItr.next().cleanUVW(); } } /** * */ public static void clearUVW(final HE_Mesh mesh) { HE_VertexIterator vItr = mesh.vItr(); while (vItr.hasNext()) { vItr.next().clearUVW(); } HE_HalfedgeIterator heItr = mesh.heItr(); while (heItr.hasNext()) { heItr.next().clearUVW(); } } /** * Set vertex colors according to the vertex normal normal.x: -1 to 1, red * component from 0 to 255 normal.y: -1 to 1, green component from 0 to 255 * normal.z: -1 to 1, blue component from 0 to 255 * * @param mesh */ public static void setVertexColorFromVertexNormal(final HE_Mesh mesh) { final HE_VertexIterator vitr = mesh.vItr(); HE_Vertex v; WB_Coord n; int color; while (vitr.hasNext()) { v = vitr.next(); n = v.getVertexNormal(); color = WB_Color.color((int) (128 * (n.xd() + 1)), (int) (128 * (n.yd() + 1)), (int) (128 * (n.zd() + 1))); v.setColor(color); } } /** * Set vertex colors by vertex.getLabel() from a palette (an array of int) * * @param mesh * @param palette */ public static void setVertexColorFromPalette(final HE_Mesh mesh, final int[] palette) { final HE_VertexIterator vitr = mesh.vItr(); HE_Vertex v; final int size = palette.length; int color; while (vitr.hasNext()) { v = vitr.next(); final int choice = Math.max(0, Math.min(size - 1, v.getUserLabel())); color = palette[choice]; v.setColor(color); } } /** * Set vertex colors randomly chosen from a palette (an array of int) * * @param mesh * @param palette */ public static void setRandomVertexColorFromPalette(final HE_Mesh mesh, final int[] palette) { final HE_VertexIterator vitr = mesh.vItr(); HE_Vertex v; final int size = palette.length; int color; while (vitr.hasNext()) { v = vitr.next(); final int choice = (int) Math.min(size - 1, Math.random() * size); color = palette[choice]; v.setColor(color); } } /** * * * @param mesh * @param palette * @param seed */ public static void setRandomVertexColorFromPalette(final HE_Mesh mesh, final int[] palette, final long seed) { final HE_VertexIterator vitr = mesh.vItr(); HE_Vertex v; final int size = palette.length; int color; final WB_MTRandom random = new WB_MTRandom(seed); while (vitr.hasNext()) { v = vitr.next(); final int choice = (int) Math.min(size - 1, random.nextDouble() * size); ; color = palette[choice]; v.setColor(color); } } /** * Set vertex colors according to the umbrella angle. Angle: 0 (infinite * outward or inward spike) to 2 Pi (flat). * * @param mesh * @param minrange * @param maxrange * @param palette */ public static void setVertexColorFromVertexUmbrella(final HE_Mesh mesh, final double minrange, final double maxrange, final int[] palette) { final HE_VertexIterator vitr = mesh.vItr(); HE_Vertex v; int color; final double idenom = 0.5 * palette.length / Math.PI; while (vitr.hasNext()) { v = vitr.next(); color = (int) (idenom * (v.getUmbrellaAngle() - minrange) / (maxrange - minrange)); color = Math.max(0, Math.min(color, palette.length - 1)); v.setColor(palette[color]); } } /** * Set vertex colors according to the Gaussian curvature. * * @param mesh * @param minrange * @param maxrange * @param palette */ public static void setVertexColorFromVertexCurvature(final HE_Mesh mesh, final double minrange, final double maxrange, final int[] palette) { final HE_VertexIterator vitr = mesh.vItr(); HE_Vertex v; int color; final double idenom = 0.5 * palette.length / Math.PI; while (vitr.hasNext()) { v = vitr.next(); color = (int) (idenom * (v.getGaussCurvature() - minrange) / (maxrange - minrange)); color = Math.max(0, Math.min(color, palette.length - 1)); v.setColor(palette[color]); } } /** * Set face colors according to the face normal normal.x: -1 to 1, red * component from 0 to 255 normal.y: -1 to 1, green component from 0 to 255 * normal.z: -1 to 1, blue component from 0 to 255 * * @param mesh */ public static void setFaceColorFromFaceNormal(final HE_Mesh mesh) { final HE_FaceIterator fitr = mesh.fItr(); HE_Face f; WB_Coord n; int color; while (fitr.hasNext()) { f = fitr.next(); n = f.getFaceNormal(); color = WB_Color.color((int) (128 * (n.xd() + 1)), (int) (128 * (n.yd() + 1)), (int) (128 * (n.zd() + 1))); f.setColor(color); } } /** * Set face colors by face.getLabel() from a palette (an array of int) * * @param mesh * @param palette */ public static void setFaceColorFromPalette(final HE_Mesh mesh, final int[] palette) { final HE_FaceIterator fitr = mesh.fItr(); HE_Face f; final int size = palette.length; int color; while (fitr.hasNext()) { f = fitr.next(); final int choice = Math.max(0, Math.min(size - 1, f.getUserLabel())); color = palette[choice]; f.setColor(color); } } /** * Set face colors randomly chosen from a palette (an array of int). * * @param mesh * @param palette */ public static void setRandomFaceColorFromPalette(final HE_Mesh mesh, final int[] palette) { final HE_FaceIterator fitr = mesh.fItr(); HE_Face f; final int size = palette.length; int color; while (fitr.hasNext()) { f = fitr.next(); final int choice = (int) Math.min(size - 1, Math.random() * size); color = palette[choice]; f.setColor(color); } } /** * * * @param mesh * @param palette * @param seed */ public static void setRandomFaceColorFromPalette(final HE_Mesh mesh, final int[] palette, final long seed) { final HE_FaceIterator fitr = mesh.fItr(); HE_Face f; final int size = palette.length; int color; final WB_MTRandom random = new WB_MTRandom(seed); while (fitr.hasNext()) { f = fitr.next(); final int choice = (int) Math.min(size - 1, random.nextDouble() * size); color = palette[choice]; f.setColor(color); } } /** * * * @param mesh * @param texture */ public static void setFaceColorFromTexture(final HE_Mesh mesh, final PImage texture) { final HE_FaceIterator fitr = mesh.fItr(); HE_Face f; HE_Vertex v; HE_TextureCoordinate uvw; while (fitr.hasNext()) { f = fitr.next(); final HE_FaceVertexCirculator fvc = f.fvCrc(); final WB_Point p = new WB_Point(); int id = 0; while (fvc.hasNext()) { v = fvc.next(); uvw = v.getUVW(f); p.addSelf(uvw.ud(), uvw.vd(), 0); id++; } p.divSelf(id); f.setColor(WB_Render3D.getColorFromPImage(p.xd(), p.yd(), texture)); } } /** * * * @param mesh * @param texture */ public static void setHalfedgeColorFromTexture(final HE_Mesh mesh, final PImage texture) { final HE_FaceIterator fitr = mesh.fItr(); HE_Face f; HE_Halfedge he; HE_TextureCoordinate p; while (fitr.hasNext()) { f = fitr.next(); final HE_FaceHalfedgeInnerCirculator fhec = f.fheiCrc(); while (fhec.hasNext()) { he = fhec.next(); p = he.getVertex().getUVW(f); he.setColor(WB_Render3D.getColorFromPImage(p.ud(), p.vd(), texture)); } } } /** * * * @param mesh * @param texture */ public static void setVertexColorFromTexture(final HE_Mesh mesh, final PImage texture) { final HE_VertexIterator vitr = mesh.vItr(); HE_Vertex v; HE_TextureCoordinate p; while (vitr.hasNext()) { v = vitr.next(); p = v.getVertexUVW(); v.setColor(WB_Render3D.getColorFromPImage(p.ud(), p.vd(), texture)); } } /* * New matplotlib colormaps by Nathaniel J. Smith, Stefan van der Walt, and * (in the case of viridis) Eric Firing. * * This file and the colormaps in it are released under the CC0 license / * public domain dedication. We would appreciate credit if you use or * redistribute these colormaps, but do not impose any legal restrictions. * * To the extent possible under law, the persons who associated CC0 with * mpl-colormaps have waived all copyright and related or neighboring rights * to mpl-colormaps. * * You should have received a copy of the CC0 legalcode along with this * work. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. */ }
bsd-3-clause