repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
juleswhite/coursera-sustainable-apps | TestingLectures/app/src/main/java/testing/magnum/io/testingexample/LoginUtils.java | 1844 | package testing.magnum.io.testingexample;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
/**
* Created by jules on 8/8/16.
*/
public class LoginUtils {
/**
* This method checks if the provided string represents a
* valid email address and returns true if it is.
*
* @param email
* @return
*/
public boolean isValidEmailAddress(String email){
boolean hasAtSign = email.indexOf("@") > -1;
return hasAtSign;
}
/**
* This method returns the length of the local part of an email address,
* which is the part that comes before the "@" in the address.
*
* If you test this method thoroughly, you will see that there are some
* edge cases it doesn't handle well.
*
* @param email
* @return
*/
public int getLocalPartLength(String email){
int start = email.indexOf("@");
String localPart = email.substring(0, start);
return localPart.length();
}
/**
* This method returns the postal code at a given latitude / longitude.
*
* If you test this method thoroughly, you will see that there are some
* edge cases it doesn't handle well.
*
* @param ctx
* @param lat
* @param lng
* @return
*/
public String getCurrentZipCode(Context ctx, double lat, double lng){
try {
Geocoder geocoder = new Geocoder(ctx, Locale.getDefault());
// lat,lng, your current location
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
return addresses.get(0).getPostalCode();
} catch(IOException ex){
throw new RuntimeException(ex);
}
}
}
| apache-2.0 |
terryhtran/macros | java/com/example/supertux/Macros/EntryFragment.java | 3398 | package com.example.supertux.Macros;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class EntryFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState) {
final View view = inflater.inflate(R.layout.entry_item, container, false);
final MainActivity mainActivity = (MainActivity) getActivity();
MyEntry myEntry = mainActivity.databaseH.getEntry(mainActivity.entryName, mainActivity.entryTime);
TextView itemNameTextView = (TextView) view.findViewById(R.id.name_text_view);
itemNameTextView.setText(mainActivity.entryName, TextView.BufferType.EDITABLE);
TextView timeTextView = (TextView) view.findViewById(R.id.entry_time_text_view);
timeTextView.setText(mainActivity.entryTime, TextView.BufferType.EDITABLE);
TextView caloriesTextView = (TextView) view.findViewById(R.id.calories_text_view);
caloriesTextView.setText(caloriesTextView.getText() + myEntry.calories.toString(), TextView.BufferType.EDITABLE);
TextView fatsTextView = (TextView) view.findViewById(R.id.fats_text_view);
fatsTextView.setText(fatsTextView.getText() + myEntry.fats.toString(), TextView.BufferType.EDITABLE);
TextView carbsTextView = (TextView) view.findViewById(R.id.carbs_text_view);
carbsTextView.setText(carbsTextView.getText() + myEntry.carbs.toString(), TextView.BufferType.EDITABLE);
TextView proteinTextView = (TextView) view.findViewById(R.id.protein_text_view);
proteinTextView.setText(proteinTextView.getText() + myEntry.protein.toString(), TextView.BufferType.EDITABLE);
TextView servings = (TextView) view.findViewById(R.id.servings_text_view);
servings.setText(servings.getText() + myEntry.servings.toString(), TextView.BufferType.EDITABLE);
Button deleteEntryButton = (Button) view.findViewById(R.id.delete_entry_button);
deleteEntryButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
new AlertDialog.Builder(mainActivity)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Delete Item")
.setMessage("Are you sure?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mainActivity.databaseH.deleteEntry(mainActivity.entryName, mainActivity.entryTime);
ListAllEntriesFragment listAllEntriesFragment = new ListAllEntriesFragment();
getFragmentManager().beginTransaction().replace(R.id.fragment_container, listAllEntriesFragment).addToBackStack(null).commit();
}
})
.setNegativeButton("No", null)
.show();
}
});
return view;
}
} | apache-2.0 |
Noah-Kennedy/MathAndResearch | NewAck/src/objects/Term.java | 964 | package objects;
public class Term /*implements Comparable<Term>*/{
private int m;
private int n;
private int val;
//private int frequency;
public Term(int m, int n){
this.setM(m);
this.setN(n);
//frequency = 0;
}
public int getM() {
return m;
}
private void setM(int m) {
this.m = m;
}
public int getN() {
return n;
}
private void setN(int n) {
this.n = n;
}
public int getVal() {
//frequency++;
return val;
}
public void setVal(int val) {
this.val = val;
}
/*public int getFrequency(){
return frequency;
}
@Override
public int compareTo(Term o) {
if(frequency > o.getFrequency()) return -1;
else if(frequency < o.getFrequency()) return 1;
else return 0;
}*/
public boolean equals(Object o){
return ((Term) o).getM() == getM() && ((Term) o).getN() == getN();
}
/*public String toString(){
return "" + frequency;
}*/
}
| apache-2.0 |
baldimir/jbpm | jbpm-installer/src/test/java/org/jbpm/persistence/scripts/quartzmockentities/QrtzPausedTriggerGrps.java | 1376 | /*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jbpm.persistence.scripts.quartzmockentities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
@Entity(name = "QRTZ_PAUSED_TRIGGER_GRPS")
@IdClass(QrtzPausedTriggersId.class)
public class QrtzPausedTriggerGrps {
@Id
@Column(name = "SCHED_NAME")
private String schedulerName;
@Id
@Column(name = "TRIGGER_GROUP")
private String triggerGroup;
public QrtzPausedTriggerGrps schedulerName(final String schedulerName) {
this.schedulerName = schedulerName;
return this;
}
public QrtzPausedTriggerGrps triggerGroup(final String triggerGroup) {
this.triggerGroup = triggerGroup;
return this;
}
}
| apache-2.0 |
ethereumproject/etherjar | etherjar-tx/src/main/java/io/emeraldpay/etherjar/tx/Signature.java | 3663 | /*
* Copyright (c) 2021 EmeraldPay Inc, All Rights Reserved.
* Copyright (c) 2016-2019 Igor Artamonov, 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 io.emeraldpay.etherjar.tx;
import io.emeraldpay.etherjar.domain.Address;
import org.bouncycastle.jcajce.provider.digest.Keccak;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Objects;
/**
* Signature of a message (i.e. of a transaction)
*/
public class Signature {
private byte[] message;
private int v;
private BigInteger r;
private BigInteger s;
public Signature() {
}
/**
* Creates existing signature
*
* @param message a signed message, usually a Keccak256 of some data
* @param v v part of signature
* @param r R part of signature
* @param s S part of signature
*/
public Signature(byte[] message, int v, BigInteger r, BigInteger s) {
this.message = message;
this.v = v;
this.r = r;
this.s = s;
}
public byte[] getMessage() {
return message;
}
public void setMessage(byte[] message) {
this.message = message;
}
public SignatureType getType() {
return SignatureType.LEGACY;
}
public int getV() {
return v;
}
public void setV(int v) {
this.v = v;
}
public BigInteger getR() {
return r;
}
public void setR(BigInteger r) {
this.r = r;
}
public BigInteger getS() {
return s;
}
public void setS(BigInteger s) {
this.s = s;
}
/**
* Recovers address that signed the message. Requires signature (v,R,S) and message to be set
*
* @return Address which signed the message, or null if address cannot be extracted
*/
public Address recoverAddress() {
try {
if (message == null || message.length == 0) {
throw new IllegalStateException("Transaction/Message hash are not set");
}
byte[] pubkey = Signer.ecrecover(this);
if (pubkey == null) {
return null;
}
Keccak.Digest256 digest = new Keccak.Digest256();
digest.update(pubkey);
byte[] hash = digest.digest();
byte[] buf = new byte[20];
System.arraycopy(hash, 12, buf, 0, 20);
return Address.from(buf);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public int getRecId() {
return v - 27;
}
public boolean canEqual(Signature signature) {
return v == signature.v
&& Arrays.equals(message, signature.message)
&& Objects.equals(r, signature.r)
&& Objects.equals(s, signature.s);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Signature signature = (Signature) o;
return canEqual(signature);
}
@Override
public int hashCode() {
return Objects.hash(r, s);
}
}
| apache-2.0 |
gbif/parsers | src/test/java/org/gbif/common/parsers/date/ThreeTenNumericalDateParserTest.java | 10688 | /*
* 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.gbif.common.parsers.date;
import org.gbif.common.parsers.core.ParseResult;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.Year;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoField;
import java.time.temporal.TemporalAccessor;
import java.util.function.Function;
import javax.annotation.Nullable;
import org.junit.jupiter.api.Test;
import static org.gbif.common.parsers.utils.CSVBasedAssertions.assertTestFile;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Unit testing for ThreeTenNumericalDateParser.
*/
public class ThreeTenNumericalDateParserTest {
private static final String BADDATE_TEST_FILE = "parse/date/threeten_bad_date_tests.txt";
private static final String LOCALDATE_TEST_FILE = "parse/date/threeten_localdate_tests.txt";
private static final String LOCALDATETIME_TEST_FILE = "parse/date/threeten_localdatetime_tests.txt";
private static final String LOCALDATETIME_TZ_TEST_FILE = "parse/date/local_datetime_tz_tests.txt";
private static final int RAW_VAL_IDX = 0;
private static final int YEAR_VAL_IDX = 1;
private static final int MONTH_VAL_IDX = 2;
private static final int DAY_VAL_IDX = 3;
private static final int HOUR_VAL_IDX = 4;
private static final int MIN_VAL_IDX = 5;
private static final int SEC_VAL_IDX = 6;
private static final int NS_VAL_IDX = 7;
private static final int TZ_VAL_IDX = 8;
private static final TemporalParser PARSER = ThreeTenNumericalDateParser.newInstance();
@Test
public void testLocalDateFromFile() {
assertTestFile(LOCALDATE_TEST_FILE,
new Function<String[], Void>() {
@Nullable
@Override
public Void apply(@Nullable String[] row) {
String raw = row[RAW_VAL_IDX];
try {
int year = Integer.parseInt(row[YEAR_VAL_IDX]);
int month = Integer.parseInt(row[MONTH_VAL_IDX]);
int day = Integer.parseInt(row[DAY_VAL_IDX]);
ParseResult<TemporalAccessor> result = PARSER.parse(raw);
assertNotNull(result.getPayload(), raw + " generated null payload");
assertEquals(LocalDate.of(year, month, day), LocalDate.from(result.getPayload()),
"Test file rawValue: " + raw);
} catch (NumberFormatException nfEx){
fail("Error while parsing the test input file content." + nfEx.getMessage());
}
return null;
}
});
}
@Test
public void testLocalDateTimeFromFile() {
assertTestFile(LOCALDATETIME_TEST_FILE,
new Function<String[], Void>() {
@Nullable
@Override
public Void apply(@Nullable String[] row) {
String raw = row[RAW_VAL_IDX];
try {
int year = Integer.parseInt(row[YEAR_VAL_IDX]);
int month = Integer.parseInt(row[MONTH_VAL_IDX]);
int day = Integer.parseInt(row[DAY_VAL_IDX]);
int hour = Integer.parseInt(row[HOUR_VAL_IDX]);
int minute = Integer.parseInt(row[MIN_VAL_IDX]);
int second = Integer.parseInt(row[SEC_VAL_IDX]);
int nanosecond = Integer.parseInt(row[NS_VAL_IDX]);
ParseResult<TemporalAccessor> result = PARSER.parse(raw);
assertNotNull(result.getPayload(), raw + " generated null payload");
assertEquals(LocalDateTime.of(year, month, day, hour, minute, second, nanosecond), LocalDateTime.from(result.getPayload()),
"Test file rawValue: " + raw);
} catch (NumberFormatException nfEx) {
fail("Error while parsing the test input file content." + nfEx.getMessage());
}
return null;
}
});
}
@Test
public void testLocalDateTimeWithTimezoneFromFile() {
assertTestFile(LOCALDATETIME_TZ_TEST_FILE,
new Function<String[], Void>() {
@Nullable
@Override
public Void apply(@Nullable String[] row) {
String raw = row[RAW_VAL_IDX];
try {
int year = Integer.parseInt(row[YEAR_VAL_IDX]);
int month = Integer.parseInt(row[MONTH_VAL_IDX]);
int day = Integer.parseInt(row[DAY_VAL_IDX]);
int hour = Integer.parseInt(row[HOUR_VAL_IDX]);
int minute = Integer.parseInt(row[MIN_VAL_IDX]);
int second = Integer.parseInt(row[SEC_VAL_IDX]);
int millisecond = Integer.parseInt(row[NS_VAL_IDX]);
String zoneId = row[TZ_VAL_IDX];
ParseResult<TemporalAccessor> result = PARSER.parse(raw);
assertNotNull(result.getPayload(), raw + " generated null payload");
assertEquals(ZonedDateTime.of(year, month, day, hour, minute, second,
0, ZoneId.of(zoneId)).with(ChronoField.MILLI_OF_SECOND, millisecond), ZonedDateTime.from(result.getPayload()),
"Test file rawValue: " + raw);
} catch (NumberFormatException nfEx) {
fail("Error while parsing the test input file content." + nfEx.getMessage());
}
return null;
}
});
}
@Test
public void testBadDateFromFile() {
assertTestFile(BADDATE_TEST_FILE,
new Function<String[], Void>() {
@Nullable
@Override
public Void apply(@Nullable String[] row) {
assertEquals(ParseResult.STATUS.FAIL, PARSER.parse(row[RAW_VAL_IDX]).getStatus(), "Test file rawValue: " + row[RAW_VAL_IDX]);
return null;
}
});
}
@Test
public void testParseAsLocalDateTime() {
ThreeTenNumericalDateParser parser = ThreeTenNumericalDateParser.newInstance(Year.of(1900));
// month first with 2 digits years >_<
assertEquals(LocalDate.of(1978, Month.DECEMBER, 21), LocalDate.from(parser.parse("122178").getPayload()));
assertEquals(LocalDate.of(1978, Month.DECEMBER, 21), LocalDate.from(parser.parse("12/21/78").getPayload()));
assertEquals(LocalDate.of(1978, Month.DECEMBER, 21), LocalDate.from(parser.parse("12\\21\\78").getPayload()));
assertEquals(LocalDate.of(1978, Month.DECEMBER, 21), LocalDate.from(parser.parse("12.21.78").getPayload()));
assertEquals(LocalDate.of(1978, Month.DECEMBER, 21), LocalDate.from(parser.parse("12-21-78").getPayload()));
assertEquals(LocalDate.of(1978, Month.DECEMBER, 21), LocalDate.from(parser.parse("12_21_78").getPayload()));
// month/year alone
assertEquals(YearMonth.of(1978, 12), YearMonth.from(parser.parse("1978-12").getPayload()));
// year alone
assertEquals(Year.of(1978), Year.from(parser.parse("1978").getPayload()));
// assertEquals(Year.of(1978), Year.from(parser.parse("78").getPayload()));
}
@Test
public void testParseAsLocalDateByDateParts() {
assertEquals(LocalDate.of(1978, Month.DECEMBER, 21), LocalDate.from(PARSER.parse("1978", "12", "21").getPayload()));
assertEquals(LocalDate.of(1978, Month.DECEMBER, 21), LocalDate.from(PARSER.parse(1978, 12, 21).getPayload()));
assertEquals(LocalDate.of(1978, Month.DECEMBER, 1), LocalDate.from(PARSER.parse("1978", "12", "1").getPayload()));
assertEquals(YearMonth.of(1978, 12), YearMonth.from(PARSER.parse("1978", "12", null).getPayload()));
assertEquals(YearMonth.of(1978, 12), YearMonth.from(PARSER.parse(1978, 12, null).getPayload()));
assertEquals(Year.of(1978), Year.from(PARSER.parse("1978", "", null).getPayload()));
// providing the day without the month should result in an error
assertEquals(ParseResult.STATUS.FAIL, PARSER.parse("1978", "", "2").getStatus());
assertEquals(ParseResult.STATUS.FAIL, PARSER.parse(1978, null, 2).getStatus());
}
// @Ignore("not implemented yet")
// @Test
// public void testUnsupportedFormat() {
// ParseResult<TemporalAccessor> result = PARSER.parse("16/11/1996 0:00:00");
//
// System.out.println(PARSER.parse("1996-11-16T00:00:00"));
// }
@Test
public void testParsePreserveZoneOffset() {
ZonedDateTime offsetDateTime = ZonedDateTime.of(1978, 12, 21, 0, 0, 0,
0, ZoneOffset.of("+02:00"));
assertEquals(offsetDateTime, PARSER.parse("1978-12-21T00:00:00+02:00").getPayload());
}
@Test
public void testAmbiguousDates() {
ParseResult<TemporalAccessor> result;
// Ambiguous
result = PARSER.parse("1/2/1996");
assertNull(result.getPayload());
assertEquals(2, result.getAlternativePayloads().size());
assertTrue(result.getAlternativePayloads().contains(LocalDate.of(1996, 2, 1)));
assertTrue(result.getAlternativePayloads().contains(LocalDate.of(1996, 1, 2)));
// Not ambiguous
result = PARSER.parse("1/1/1996");
assertEquals(LocalDate.of(1996, 1, 1), result.getPayload());
assertNull(result.getAlternativePayloads());
result = PARSER.parse("31/1/1996");
assertEquals(LocalDate.of(1996, 1, 31), result.getPayload());
assertNull(result.getAlternativePayloads());
// Dots aren't used in America.
result = PARSER.parse("4.5.1996");
assertEquals(LocalDate.of(1996, 5, 4), result.getPayload());
assertNull(result.getAlternativePayloads());
}
@Test
public void testBlankDates() {
assertEquals(ParseResult.STATUS.FAIL, PARSER.parse(" ").getStatus());
assertEquals(ParseResult.STATUS.FAIL, PARSER.parse("").getStatus());
assertEquals(ParseResult.STATUS.FAIL, PARSER.parse(null).getStatus());
}
}
| apache-2.0 |
thescouser89/pnc | mapper/src/main/java/org/jboss/pnc/mapper/api/EntityMapper.java | 1989 | /**
* JBoss, Home of Professional Open Source.
* Copyright 2014-2020 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.pnc.mapper.api;
import org.jboss.pnc.dto.DTOEntity;
import org.jboss.pnc.model.GenericEntity;
import java.io.Serializable;
/**
* Mappers that converts database entity to DTO entities and vice versa.
*
* @author Honza Brázdil <jbrazdil@redhat.com>
* @param <ID> The type of the entity identifier
* @param <DB> The database entity type
* @param <DTO> The full DTO entity type
* @param <REF> The reference DTO entity type
*/
public interface EntityMapper<ID extends Serializable, DB extends GenericEntity<ID>, DTO extends REF, REF extends DTOEntity> {
/**
* Converts DTO entity to database entity. This should be used only when creating new entity.
*
* @param dtoEntity DTO entity to be converted.
* @return Converted database entity.
*/
DB toEntity(DTO dtoEntity);
/**
* Converts database entity to DTO entity.
*
* @param dbEntity database entity to be converted.
* @return Converted DTO entity.
*/
DTO toDTO(DB dbEntity);
/**
* Converts database entity to DTO reference entity.
*
* @param dbEntity database entity to be converted.
* @return Converted DTO reference entity.
*/
REF toRef(DB dbEntity);
IdMapper<ID, String> getIdMapper();
}
| apache-2.0 |
shadyeltobgy/wcm-io-caconfig | compat/src/main/java/io/wcm/config/spi/helpers/AbstractParameterProvider.java | 2448 | /*
* #%L
* wcm.io
* %%
* Copyright (C) 2016 wcm.io
* %%
* 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 io.wcm.config.spi.helpers;
import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Set;
import org.osgi.annotation.versioning.ConsumerType;
import com.google.common.collect.ImmutableSet;
import io.wcm.config.api.Parameter;
import io.wcm.config.spi.ParameterProvider;
/**
* Abstract implementation of {@link ParameterProvider} providing list of parameters either from given
* parameter set, or from reading all public static fields from a given class definition.
*/
@ConsumerType
public abstract class AbstractParameterProvider implements ParameterProvider {
private final Set<Parameter<?>> parameters;
/**
* @param parameters Set of parameters for parameter provider
*/
protected AbstractParameterProvider(Set<Parameter<?>> parameters) {
this.parameters = parameters;
}
/**
* @param type Type containing parameter definitions as public static fields.
*/
protected AbstractParameterProvider(Class<?> type) {
this(getParametersFromPublicFields(type));
}
@Override
public final Set<Parameter<?>> getParameters() {
return parameters;
}
/**
* Get all parameters defined as public static fields in the given type.
* @param type Type
* @return Set of parameters
*/
private static Set<Parameter<?>> getParametersFromPublicFields(Class<?> type) {
Set<Parameter<?>> params = new HashSet<>();
try {
Field[] fields = type.getFields();
for (Field field : fields) {
if (field.getType().isAssignableFrom(Parameter.class)) {
params.add((Parameter<?>)field.get(null));
}
}
}
catch (IllegalArgumentException | IllegalAccessException ex) {
throw new RuntimeException("Unable to access fields of " + type.getName(), ex);
}
return ImmutableSet.copyOf(params);
}
}
| apache-2.0 |
fuliang/leetcode | src/UniquePaths.java | 556 | /**
* Created by fuliang on 2015/4/22.
*/
public class UniquePaths {
public int uniquePaths(int m, int n) {
int[][] nums = new int[m][n];
for (int i = 0; i < nums.length; i++) {
nums[i][0] = 1;
}
for (int j = 0; j < nums[0].length; j++) {
nums[0][j] = 1;
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
nums[i][j] = nums[i-1][j] + nums[i][j-1];
}
}
return nums[m-1][n-1];
}
}
| apache-2.0 |
vjanmey/EpicMudfia | com/planet_ink/coffee_mud/Locales/StdMaze.java | 4718 | package com.planet_ink.coffee_mud.Locales;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2000-2014 Bo Zimmerman
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.
*/
@SuppressWarnings({"unchecked","rawtypes"})
public class StdMaze extends StdGrid
{
@Override public String ID(){return "StdMaze";}
public StdMaze()
{
super();
}
@Override
protected Room getGridRoom(int x, int y)
{
final Room R=super.getGridRoom(x,y);
if((R!=null)&&(!CMath.bset(R.phyStats().sensesMask(),PhyStats.SENSE_ROOMUNEXPLORABLE)))
{
R.basePhyStats().setSensesMask(R.basePhyStats().sensesMask()|PhyStats.SENSE_ROOMUNEXPLORABLE);
R.phyStats().setSensesMask(R.phyStats().sensesMask()|PhyStats.SENSE_ROOMUNEXPLORABLE);
}
return R;
}
@Override
protected Room findCenterRoom(int dirCode)
{
final Room dirRoom=rawDoors()[dirCode];
if(dirRoom!=null)
{
final Room altR=super.findCenterRoom(dirCode);
if(altR!=null)
{
final Exit ox=CMClass.getExit("Open");
linkRoom(altR,dirRoom,dirCode,ox,ox);
return altR;
}
}
return null;
}
protected boolean goodDir(int x, int y, int dirCode)
{
if(dirCode==Directions.UP) return false;
if(dirCode==Directions.DOWN) return false;
if(dirCode>=Directions.GATE) return false;
if((x==0)&&(dirCode==Directions.WEST)) return false;
if((y==0)&&(dirCode==Directions.NORTH)) return false;
if((x>=(subMap.length-1))&&(dirCode==Directions.EAST)) return false;
if((y>=(subMap[0].length-1))&&(dirCode==Directions.SOUTH)) return false;
return true;
}
protected Room roomDir(int x, int y, int dirCode)
{
if(!goodDir(x,y,dirCode)) return null;
return subMap[getX(x,dirCode)][getY(y,dirCode)];
}
protected int getY(int y, int dirCode)
{
switch(dirCode)
{
case Directions.NORTH:
return y-1;
case Directions.SOUTH:
return y+1;
}
return y;
}
protected int getX(int x, int dirCode)
{
switch(dirCode)
{
case Directions.EAST:
return x+1;
case Directions.WEST:
return x-1;
}
return x;
}
protected void mazify(Hashtable visited, int x, int y)
{
if(visited.get(subMap[x][y])!=null) return;
final Room room=subMap[x][y];
visited.put(room,room);
final Exit ox=CMClass.getExit("Open");
boolean okRoom=true;
while(okRoom)
{
okRoom=false;
for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--)
{
if(d==Directions.GATE) continue;
final Room possRoom=roomDir(x,y,d);
if(possRoom!=null)
if(visited.get(possRoom)==null)
{
okRoom=true;
break;
}
}
if(okRoom)
{
Room goRoom=null;
int dirCode=-1;
while(goRoom==null)
{
final int d=CMLib.dice().roll(1,Directions.NUM_DIRECTIONS(),0)-1;
final Room possRoom=roomDir(x,y,d);
if(possRoom!=null)
if(visited.get(possRoom)==null)
{
goRoom=possRoom;
dirCode=d;
}
}
linkRoom(room,goRoom,dirCode,ox,ox);
mazify(visited,getX(x,dirCode),getY(y,dirCode));
}
}
}
protected void buildMaze()
{
final Hashtable visited=new Hashtable();
final int x=xsize/2;
final int y=ysize/2;
mazify(visited,x,y);
}
@Override
public void buildGrid()
{
clearGrid(null);
try
{
subMap=new Room[xsize][ysize];
for(int x=0;x<subMap.length;x++)
for(int y=0;y<subMap[x].length;y++)
{
final Room newRoom=getGridRoom(x,y);
if(newRoom!=null)
subMap[x][y]=newRoom;
}
buildMaze();
buildFinalLinks();
}
catch(final Exception e)
{
clearGrid(null);
}
}
}
| apache-2.0 |
cinchapi/accent4j | src/main/java/com/cinchapi/common/concurrent/ExecutorRaceService.java | 7355 | /*
* Copyright (c) 2013-2019 Cinchapi Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cinchapi.common.concurrent;
import java.util.Arrays;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RunnableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import com.cinchapi.common.base.Array;
import com.google.common.base.Preconditions;
/**
* An {@link ExecutorRaceService} provides a mechanism for submitting multiple
* {@link Callable tasks} to an {@link Executor} and waiting for the first task
* to complete.
* <p>
* This is similar to a {@link ExecutorCompletionService} but the semantics are
* slightly different. Central to this service is the concept of "racing". As
* such, it is possible to give one task an arbitrary
* {@link #raceWithHeadStart(long, TimeUnit, Callable, Callable...) head start}
* so that other tasks do not execute if that task completes first.
* </p>
*
* @author Jeff Nelson
*/
public class ExecutorRaceService<V> {
/**
* The {@link Executor} that executes the tasks.
*/
private final Executor executor;
/**
* Construct a new instance.
*
* @param executor
*/
public ExecutorRaceService(Executor executor) {
this.executor = executor;
}
/**
* Return the {@link Future} for the first of the {@code task} and
* {@code tasks} to complete.
* <p>
* The {@link Future} is guaranteed to be {@link Future#isDone()} when this
* method returns.
* </p>
*
* @param task
* @param tasks
* @return the {@link Future} of the completed task
* @throws InterruptedException
*/
@SuppressWarnings("unchecked")
public Future<V> race(Callable<V> task, Callable<V>... tasks)
throws InterruptedException {
return raceWithHeadStart(0, TimeUnit.MICROSECONDS, task, tasks);
}
/**
* Return the {@link Future} for the first of the {@code task} and
* {@code tasks} to complete.
* <p>
* The {@link Future} is guaranteed to be {@link Future#isDone()} when this
* method returns.
* </p>
*
* @param task
* @param tasks
* @return the {@link Future} of the completed task
* @throws InterruptedException
*/
public Future<V> race(Runnable task, Runnable... tasks)
throws InterruptedException {
return raceWithHeadStart(0, TimeUnit.MICROSECONDS, task, tasks);
}
/**
* Return the {@link Future} for the first of the {@code headStartTask} and
* {@code tasks} to complete; giving the first {@code task}
* {@code headStartTime} {@code headStartTimeUnit} to complete before
* allowing the remaining {@code tasks} to race.
* <p>
* Even if the {@code headStartTask} does not finish within the head start
* period, it may still finish before the other {@code tasks} and returns
* its {@link Future}.
* </p>
* <p>
* The {@link Future} is guaranteed to be {@link Future#isDone()} when this
* method returns.
* </p>
*
* @param headStartTime
* @param headStartTimeUnit
* @param headStartTask
* @param tasks
* @return the {@link Future} of the completed task
* @throws InterruptedException
*/
@SuppressWarnings("unchecked")
public Future<V> raceWithHeadStart(long headStartTime,
TimeUnit headStartTimeUnit, Callable<V> headStartTask,
Callable<V>... tasks) throws InterruptedException {
BlockingQueue<Future<V>> completed = new LinkedBlockingQueue<Future<V>>();
Preconditions.checkNotNull(headStartTask);
Preconditions.checkState(tasks.length > 0);
RunnableFuture<V> headStartFuture = new FutureTask<V>(headStartTask);
executor.execute(new QueueingFuture(headStartFuture, completed));
try {
headStartFuture.get(headStartTime, headStartTimeUnit);
return headStartFuture;
}
catch (ExecutionException | TimeoutException e) {
for (Callable<V> task : tasks) {
RunnableFuture<V> future = new FutureTask<V>(task);
executor.execute(new QueueingFuture(future, completed));
}
return completed.take();
}
}
/**
* Return the {@link Future} for the first of the {@code headStartTask} and
* {@code tasks} to complete; giving the first {@code task}
* {@code headStartTime} {@code headStartTimeUnit} to complete before
* allowing the remaining {@code tasks} to race.
* <p>
* Even if the {@code headStartTask} does not finish within the head start
* period, it may still finish before the other {@code tasks} and returns
* its {@link Future}.
* </p>
* <p>
* The {@link Future} is guaranteed to be {@link Future#isDone()} when this
* method returns.
* </p>
*
* @param headStartTime
* @param headStartTimeUnit
* @param headStartTask
* @param tasks
* @return the {@link Future} of the completed task
* @throws InterruptedException
*/
public Future<V> raceWithHeadStart(long headStartTime,
TimeUnit headStartTimeUnit, Runnable headStartTask,
Runnable... tasks) throws InterruptedException {
return raceWithHeadStart(headStartTime, headStartTimeUnit,
Executors.callable(headStartTask, null),
Arrays.stream(tasks).map(Executors::callable)
.collect(Collectors.toList())
.toArray(Array.containing()));
}
/**
* FutureTask extension to enqueue upon completion
*/
private class QueueingFuture extends FutureTask<Void> {
/**
* The queue of completed tasks where this one should be added when it
* is {@link #done()}.
*/
private final BlockingQueue<Future<V>> completed;
/**
* The future that tracks the task completion.
*/
private final Future<V> task;
/**
* Construct a new instance.
*
* @param task
* @param completed
*/
QueueingFuture(RunnableFuture<V> task,
BlockingQueue<Future<V>> completed) {
super(task, null);
this.task = task;
this.completed = completed;
}
@Override
protected void done() {
completed.add(task);
}
}
}
| apache-2.0 |
hazendaz/assertj-core | src/main/java/org/assertj/core/util/introspection/Introspection.java | 6316 | /*
* 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.
*
* Copyright 2012-2021 the original author or authors.
*/
package org.assertj.core.util.introspection;
import static java.lang.String.format;
import static java.lang.reflect.Modifier.isPublic;
import static java.util.Locale.ENGLISH;
import static java.util.Objects.requireNonNull;
import static org.assertj.core.util.Preconditions.checkNotNullOrEmpty;
import static org.assertj.core.util.Strings.quote;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import org.assertj.core.configuration.ConfigurationProvider;
import org.assertj.core.util.VisibleForTesting;
/**
* Utility methods related to <a
* href="http://java.sun.com/docs/books/tutorial/javabeans/introspection/index.html">JavaBeans Introspection</a>.
*
* @author Alex Ruiz
*/
public final class Introspection {
// We want to cache negative results (i.e. absence of methods) to avoid same overhead on subsequent lookups
// However ConcurrentHashMap does not permit nulls - Optional allows caching of 'missing' values
private static final Map<MethodKey, Optional<Method>> METHOD_CACHE = new ConcurrentHashMap<>();
// set false by default to follow the principle of least surprise as usual property getter are getX() isX(), not x().
private static boolean bareNamePropertyMethods = false;
/**
* Returns the getter {@link Method} for a property matching the given name in the given object.
*
* @param propertyName the given property name.
* @param target the given object.
* @return the getter {@code Method} for a property matching the given name in the given object.
* @throws NullPointerException if the given property name is {@code null}.
* @throws IllegalArgumentException if the given property name is empty.
* @throws NullPointerException if the given object is {@code null}.
* @throws IntrospectionError if the getter for the matching property cannot be found or accessed.
*/
public static Method getPropertyGetter(String propertyName, Object target) {
checkNotNullOrEmpty(propertyName);
requireNonNull(target);
Method getter = findGetter(propertyName, target);
if (getter == null) {
throw new IntrospectionError(propertyNotFoundErrorMessage("No getter for property %s in %s", propertyName, target));
}
if (!isPublic(getter.getModifiers())) {
throw new IntrospectionError(propertyNotFoundErrorMessage("No public getter for property %s in %s", propertyName, target));
}
try {
// force access for static class with public getter
getter.setAccessible(true);
getter.invoke(target);
} catch (Exception t) {
throw new IntrospectionError(propertyNotFoundErrorMessage("Unable to find property %s in %s", propertyName, target), t);
}
return getter;
}
public static void setExtractBareNamePropertyMethods(boolean barenamePropertyMethods) {
ConfigurationProvider.loadRegisteredConfiguration();
bareNamePropertyMethods = barenamePropertyMethods;
}
@VisibleForTesting
public static boolean canExtractBareNamePropertyMethods() {
return bareNamePropertyMethods;
}
private static String propertyNotFoundErrorMessage(String message, String propertyName, Object target) {
String targetTypeName = target.getClass().getName();
String property = quote(propertyName);
return format(message, property, targetTypeName);
}
private static Method findGetter(String propertyName, Object target) {
String capitalized = propertyName.substring(0, 1).toUpperCase(ENGLISH) + propertyName.substring(1);
// try to find getProperty
Method getter = findMethod("get" + capitalized, target);
if (isValidGetter(getter)) return getter;
if (bareNamePropertyMethods) {
// try to find bare name property
getter = findMethod(propertyName, target);
if (isValidGetter(getter)) return getter;
}
// try to find isProperty for boolean properties
Method isAccessor = findMethod("is" + capitalized, target);
return isValidGetter(isAccessor) ? isAccessor : null;
}
private static boolean isValidGetter(Method method) {
return method != null && !Modifier.isStatic(method.getModifiers()) && !Void.TYPE.equals(method.getReturnType());
}
private static Method findMethod(String name, Object target) {
final MethodKey methodKey = new MethodKey(name, target.getClass());
return METHOD_CACHE.computeIfAbsent(methodKey, Introspection::findMethodByKey).orElse(null);
}
private static Optional<Method> findMethodByKey(MethodKey key) {
// try public methods only
Class<?> clazz = key.clazz;
try {
return Optional.of(clazz.getMethod(key.name));
} catch (NoSuchMethodException | SecurityException ignored) {}
// search all methods
while (clazz != null) {
try {
return Optional.of(clazz.getDeclaredMethod(key.name));
} catch (NoSuchMethodException | SecurityException ignored) {}
clazz = clazz.getSuperclass();
}
return Optional.empty();
}
private static final class MethodKey {
private final String name;
private final Class<?> clazz;
private MethodKey(final String name, final Class<?> clazz) {
this.name = name;
this.clazz = clazz;
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final MethodKey methodKey = (MethodKey) o;
return Objects.equals(name, methodKey.name) && Objects.equals(clazz, methodKey.clazz);
}
@Override
public int hashCode() {
return Objects.hash(name, clazz);
}
}
private Introspection() {}
}
| apache-2.0 |
orcchg/RxMusic | app/src/main/java/com/orcchg/dev/maxa/rxmusic/data/injection/local/music/artist/ArtistMigrationModule.java | 142 | package com.orcchg.dev.maxa.rxmusic.data.injection.local.music.artist;
import dagger.Module;
@Module
public class ArtistMigrationModule {
}
| apache-2.0 |
sonatype/maven-demo | maven-compat/src/main/java/org/apache/maven/artifact/resolver/WarningResolutionListener.java | 2441 | package org.apache.maven.artifact.resolver;
/*
* 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 org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.versioning.VersionRange;
import org.codehaus.plexus.logging.Logger;
/**
* Send resolution warning events to the warning log.
*
* @author <a href="mailto:brett@apache.org">Brett Porter</a>
* @version $Id: WarningResolutionListener.java 770390 2009-04-30 18:49:42Z jvanzyl $
*/
public class WarningResolutionListener
implements ResolutionListener
{
private Logger logger;
public WarningResolutionListener( Logger logger )
{
this.logger = logger;
}
public void testArtifact( Artifact node )
{
}
public void startProcessChildren( Artifact artifact )
{
}
public void endProcessChildren( Artifact artifact )
{
}
public void includeArtifact( Artifact artifact )
{
}
public void omitForNearer( Artifact omitted,
Artifact kept )
{
}
public void omitForCycle( Artifact omitted )
{
}
public void updateScopeCurrentPom( Artifact artifact,
String scope )
{
}
public void updateScope( Artifact artifact,
String scope )
{
}
public void manageArtifact( Artifact artifact,
Artifact replacement )
{
}
public void selectVersionFromRange( Artifact artifact )
{
}
public void restrictRange( Artifact artifact,
Artifact replacement,
VersionRange newRange )
{
}
}
| apache-2.0 |
Orange-OpenSource/matos-profiles | matos-android/src/main/java/android/util/SparseArray.java | 2012 | package android.util;
/*
* #%L
* Matos
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2010 - 2014 Orange SA
* %%
* 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%
*/
@com.francetelecom.rd.stubs.annotation.ClassDone(0)
public class SparseArray<E>
implements java.lang.Cloneable
{
// Constructors
public SparseArray(){
}
public SparseArray(int arg1){
}
// Methods
@com.francetelecom.rd.stubs.annotation.FieldGet("content")
public E get(int arg1){
return null;
}
@com.francetelecom.rd.stubs.annotation.Code("return (com.francetelecom.rd.stubs.Generator.booleanValue() ? content : arg2);")
public E get(int arg1, E arg2){
return null;
}
public void put(int arg1, @com.francetelecom.rd.stubs.annotation.FieldSet("content") E arg2){
}
public void append(int arg1, @com.francetelecom.rd.stubs.annotation.FieldSet("content") E arg2){
}
public SparseArray<E> clone(){
return (SparseArray) null;
}
public void clear(){
}
public int size(){
return 0;
}
public void remove(int arg1){
}
public void delete(int arg1){
}
public int keyAt(int arg1){
return 0;
}
@com.francetelecom.rd.stubs.annotation.FieldGet("content")
public E valueAt(int arg1){
return null;
}
public int indexOfKey(int arg1){
return 0;
}
public int indexOfValue(E arg1){
return 0;
}
public void setValueAt(int arg1, @com.francetelecom.rd.stubs.annotation.FieldSet("content") E arg2){
}
public void removeAt(int arg1){
}
}
| apache-2.0 |
maheshraju-Huawei/actn | apps/pcep-api/src/test/java/org/onosproject/pcep/pcepio/protocol/PcepReportMsgTest.java | 76890 | /*
* Copyright 2015-present Open Networking Laboratory
*
* 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.onosproject.pcep.pcepio.protocol;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.junit.Test;
import org.onosproject.pcep.pcepio.exceptions.PcepOutOfBoundMessageException;
import org.onosproject.pcep.pcepio.exceptions.PcepParseException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.core.Is.is;
public class PcepReportMsgTest {
/**
* This test case checks for SRP object, LSP object(Symbolic path name tlv), ERO object
* in PcRpt message.
*/
@Test
public void reportMessageTest1() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, 0x24,
0x21, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x10, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x07, 0x10, 0x00, 0x04}; //ERO Object
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for SRP Object, LSP Object(StatefulIPv4LspIdentidiersTlv,SymbolicPathNameTlv
* StatefulLspErrorCodeTlv) ERO Object, LSPA Object, Metric-list, IRO object
* in PcRpt message.
*/
@Test
public void reportMessageTest2() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0x7c,
0x21, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x2c, 0x00, 0x00, 0x10, 0x03, //LSP Object // LSP Object
0x00, 0x12, 0x00, 0x10, //StatefulIPv4LspIdentidiersTlv
(byte) 0xb6, 0x02, 0x4e, 0x1f, 0x00, 0x01, (byte) 0x80, 0x01,
(byte) 0xb6, 0x02, 0x4e, 0x1f, (byte) 0xb6, 0x02, 0x4e, 0x20,
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x00, 0x14, 0x00, 0x04, 0x00, 0x00, 0x00, 0x08, //StatefulLspErrorCodeTlv
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00, // IPv4SubObjects
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x09, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //LSPA Object
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, //Metric Object
0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x20, //Metric Object
};
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for LSP Object(StatefulIPv4LspIdentidiersTlv,SymbolicPathNameTlv,StatefulLspErrorCodeTlv)
* ERO Object, LSPA Object, Metric-list, IRO object
* in PcRpt message.
*/
@Test
public void reportMessageTest3() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0x70,
0x20, 0x10, 0x00, 0x2c, 0x00, 0x00, 0x10, 0x03, //LSP Object //LSP Object
0x00, 0x12, 0x00, 0x10, //StatefulIPv4LspIdentidiersTlv
(byte) 0xb6, 0x02, 0x4e, 0x1f, 0x00, 0x01, (byte) 0x80, 0x01,
(byte) 0xb6, 0x02, 0x4e, 0x1f, (byte) 0xb6, 0x02, 0x4e, 0x20,
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x00, 0x14, 0x00, 0x04, 0x00, 0x00, 0x00, 0x08, //StatefulLspErrorCodeTlv
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00, //Ipv4SubObjects
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x09, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //LSPA Object
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, //Metric Objects
0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x20, //Metric Object
};
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for LSP Object(StatefulIPv4LspIdentidiersTlv,SymbolicPathNameTlv,StatefulLspErrorCodeTlv)
* ERO Object, LSPA Object, Metric-list
* in PcRpt message.
*/
@Test
public void reportMessageTest4() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0x64,
0x21, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x2c, 0x00, 0x00, 0x10, 0x03, //LSP Object //LSP Object
0x00, 0x12, 0x00, 0x10, //StatefulIPv4LspIdentidiersTlv
(byte) 0xb6, 0x02, 0x4e, 0x1f, 0x00, 0x01, (byte) 0x80, 0x01,
(byte) 0xb6, 0x02, 0x4e, 0x1f, (byte) 0xb6, 0x02, 0x4e, 0x20,
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x00, 0x14, 0x00, 0x04, 0x00, 0x00, 0x00, 0x08, //StatefulLspErrorCodeTlv
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x09, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //LSPA Object
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for SRP Object, LSP Object(StatefulIPv4LspIdentidiersTlv,SymbolicPathNameTlv
* StatefulLspErrorCodeTlv) ERO Object, IRO object
* in PcRpt message.
*/
@Test
public void reportMessageTest5() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0x50,
0x21, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x2c, 0x00, 0x00, 0x10, 0x03, //LSP Object //LSP Object
0x00, 0x12, 0x00, 0x10, //StatefulIPv4LspIdentidiersTlv
(byte) 0xb6, 0x02, 0x4e, 0x1f, 0x00, 0x01, (byte) 0x80, 0x01,
(byte) 0xb6, 0x02, 0x4e, 0x1f, (byte) 0xb6, 0x02, 0x4e, 0x20,
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x00, 0x14, 0x00, 0x04, 0x00, 0x00, 0x00, 0x08, //StatefulLspErrorCodeTlv
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00};
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for SRP Object, LSP Object(StatefulIPv4LspIdentidiersTlv,SymbolicPathNameTlv
* StatefulLspErrorCodeTlv) ERO Object, LSPA Object, Metric-list.
* in PcRpt message.
*/
@Test
public void reportMessageTest6() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0x6c,
0x21, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x2c, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x00, 0x12, 0x00, 0x10, //StatefulIPv4LspIdentidiersTlv
(byte) 0xb6, 0x02, 0x4e, 0x1f, 0x00, 0x01, (byte) 0x80, 0x01,
(byte) 0xb6, 0x02, 0x4e, 0x1f, (byte) 0xb6, 0x02, 0x4e, 0x20,
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x00, 0x14, 0x00, 0x04, 0x00, 0x00, 0x00, 0x08, //StatefulLspErrorCodeTlv
0x07, 0x10, 0x00, 0x04, //ERO Object
0x09, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //LSPA Object
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, //Metric object
0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x20, //Metric Object
};
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for LSP Object, ERO Object, LSPA Object, Metric-list, IRO object
* in PcRpt message.
*/
@Test
public void reportMessageTest7() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0x58,
0x21, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x08, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x09, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, //LSPA Object
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, // Metric objects
0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x20};
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for SRP object, LSP object( StatefulIPv4LspIdentidiersTlv, SymbolicPathNameTlv,
* StatefulLspErrorCodeTlv) ERO object, LSPA object, Metric object
* in PcRpt message.
*/
@Test
public void reportMessageTest8() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0x70,
0x21, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x2c, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x00, 0x12, 0x00, 0x10, //StatefulIPv4LspIdentidiersTlv
(byte) 0xb6, 0x02, 0x4e, 0x1f, 0x00, 0x01, (byte) 0x80, 0x01,
(byte) 0xb6, 0x02, 0x4e, 0x1f, (byte) 0xb6, 0x02, 0x4e, 0x20,
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x00, 0x14, 0x00, 0x04, 0x00, 0x00, 0x00, 0x08, //StatefulLspErrorCodeTlv
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x09, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //LSPA Object
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x20}; //Metric Object
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for LSP Object(Symbolic path tlv, StatefulIPv4LspIdentidiersTlv,
* StatefulLspErrorCodeTlv ),ERO Object
* in PcRpt message.
*/
@Test
public void reportMessageTest9() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0x44,
0x20, 0x10, 0x00, 0x2c, 0x00, 0x00, 0x10, 0x03, //LSP Object //LSP Object
0x00, 0x12, 0x00, 0x10, //StatefulIPv4LspIdentidiersTlv
(byte) 0xb6, 0x02, 0x4e, 0x1f, 0x00, 0x01, (byte) 0x80, 0x01,
(byte) 0xb6, 0x02, 0x4e, 0x1f, (byte) 0xb6, 0x02, 0x4e, 0x20,
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x00, 0x14, 0x00, 0x04, 0x00, 0x00, 0x00, 0x08, //StatefulLspErrorCodeTlv
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00};
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for SRP Object,LSP Object(StatefulIPv4LspIdentidiersTlv)ERO Object,RRO Object
* in PcRpt message.
*/
@Test
public void reportMessageTest10() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0x74,
0x21, 0x10, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x1c, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x00, 0x12, 0x00, 0x10, //StatefulIPv4LspIdentidiersTlv
(byte) 0xb6, 0x02, 0x4e, 0x1f, 0x00, 0x01, (byte) 0x80, 0x01,
(byte) 0xb6, 0x02, 0x4e, 0x1f, (byte) 0xb6, 0x02, 0x4e, 0x20,
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x08, 0x10, 0x00, 0x34, 0x01, 0x08, 0x11, 0x01, //RRO Object
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x11, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x06, 0x06,
0x06, 0x06, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x05, 0x05, 0x05, 0x05, 0x04, 0x00};
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for SRP Object,LSP Object(SymbolicPathNameTlv)ERO Object,RRO Object
* in PcRpt message.
*/
@Test
public void reportMessageTest11() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0x68,
0x21, 0x10, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x10, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x08, 0x10, 0x00, 0x34, 0x01, 0x08, 0x11, 0x01, //RRO Object
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x11, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x06, 0x06,
0x06, 0x06, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x05, 0x05, 0x05, 0x05, 0x04, 0x00};
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for SRP Object,LSP Object, ERO Object,RRO Object
* in PcRpt message.
*/
@Test
public void reportMessageTest12() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0x60,
0x21, 0x10, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x08, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x08, 0x10, 0x00, 0x34, 0x01, 0x08, 0x11, 0x01, //RRO Object
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x11, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x06, 0x06,
0x06, 0x06, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x05, 0x05, 0x05, 0x05, 0x04, 0x00};
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for SRP Object,LSP Object(StatefulLspErrorCodeTlv)ERO Object,RRO Object
* in PcRpt message.
*/
@Test
public void reportMessageTest13() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0x68,
0x21, 0x10, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x10, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x00, 0x14, 0x00, 0x04, 0x00, 0x00, 0x00, 0x08, //StatefulLspErrorCodeTlv
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x08, 0x10, 0x00, 0x34, 0x01, 0x08, 0x11, 0x01, //RRO Object
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x11, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x06, 0x06,
0x06, 0x06, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x05, 0x05, 0x05, 0x05, 0x04, 0x00};
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for SRP Object,LSP Object(StatefulRsvpErrorSpecTlv),ERO Object,RRO Object
* in PcRpt message.
*/
@Test
public void reportMessageTest14() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0x60,
0x21, 0x10, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x08, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x08, 0x10, 0x00, 0x34, 0x01, 0x08, 0x11, 0x01, //RRO Object
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x11, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x06, 0x06,
0x06, 0x06, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x05, 0x05, 0x05, 0x05, 0x04, 0x00};
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for SRP Object,LSP Object(symbolic path tlv),LSPA Object,ERO Object
* in PcRpt message.
*/
@Test
public void reportMessageTest15() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0x7C,
0x21, 0x10, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x10, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x09, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, //LSPA Object
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x08, 0x10, 0x00, 0x34, 0x01, 0x08, 0x11, 0x01, //RRO Object
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x11, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x06, 0x06,
0x06, 0x06, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x05, 0x05, 0x05, 0x05, 0x04, 0x00};
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for SRP Object,LSP Object(symbolic path tlv),BandWidth Object,ERO Object
* in PcRpt message.
*/
@Test
public void reportMessageTest16() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0x70,
0x21, 0x10, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x10, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x05, 0x20, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, //Bandwidth Object
0x08, 0x10, 0x00, 0x34, 0x01, 0x08, 0x11, 0x01, //RRO Object
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x11, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x06, 0x06,
0x06, 0x06, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x05, 0x05, 0x05, 0x05, 0x04, 0x00};
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for SRP Object,LSP Object,ERO Object,LSPA Object,RRO Object
* in PcRpt message.
*/
@Test
public void reportMessageTest17() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0x74,
0x21, 0x10, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x08, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x09, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, //LSPA Object
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x08, 0x10, 0x00, 0x34, 0x01, 0x08, 0x11, 0x01, //RRO Object
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x11, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x06, 0x06,
0x06, 0x06, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x05, 0x05, 0x05, 0x05, 0x04, 0x00};
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for SRP Object,LSP Object,ERO Object,BandWidth Object,RRO Object
* in PcRpt message.
*/
@Test
public void reportMessageTest18() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0x68,
0x21, 0x10, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x08, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x05, 0x20, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, //Bandwidth Object
0x08, 0x10, 0x00, 0x34, 0x01, 0x08, 0x11, 0x01, //RRO Object
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x11, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x06, 0x06,
0x06, 0x06, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x05, 0x05, 0x05, 0x05, 0x04, 0x00};
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for SRP Object,LSP Object,ERO Object,Metric-list,RRO Object
* in PcRpt message.
*/
@Test
public void reportMessageTest19() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0x6C,
0x21, 0x10, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x08, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x20, //Metric Object
0x08, 0x10, 0x00, 0x34, 0x01, 0x08, 0x11, 0x01, //RRO Object
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x11, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x06, 0x06,
0x06, 0x06, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x05, 0x05, 0x05, 0x05, 0x04, 0x00};
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for SRP Object,LSP Object,ERO Object,LSPA Object,BandWidth Object,Metric-list,RRO Object
* in PcRpt message.
*/
@Test
public void reportMessageTest20() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0x88,
0x21, 0x10, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x08, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x09, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x05, 0x20, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, //Bandwidth Object
0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x20, //Metric Object
0x08, 0x10, 0x00, 0x34, 0x01, 0x08, 0x11, 0x01, //RRO Object
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x11, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x06, 0x06,
0x06, 0x06, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x05, 0x05, 0x05, 0x05, 0x04, 0x00};
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for SRP Object,LSP Object(Symbolic path tlv, StatefulIPv4LspIdentidiersTlv,
* StatefulLspErrorCodeTlv ) ERO Object,LSPA Object,BandWidth Object,Metric-list,RRO Object
* in PcRpt message.
*/
@Test
public void reportMessageTest21() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0xac,
0x21, 0x10, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x2c, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x00, 0x12, 0x00, 0x10, //StatefulIPv4LspIdentidiersTlv
(byte) 0xb6, 0x02, 0x4e, 0x1f, 0x00, 0x01, (byte) 0x80, 0x01,
(byte) 0xb6, 0x02, 0x4e, 0x1f, (byte) 0xb6, 0x02, 0x4e, 0x20,
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x00, 0x14, 0x00, 0x04, 0x00, 0x00, 0x00, 0x08, //StatefulLspErrorCodeTlv
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x09, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x05, 0x20, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, //Bandwidth Object
0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x20, //Metric Object
0x08, 0x10, 0x00, 0x34, 0x01, 0x08, 0x11, 0x01, //RRO Object
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x11, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x06, 0x06,
0x06, 0x06, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x05, 0x05, 0x05, 0x05, 0x04, 0x00};
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for LSP Object(Symbolic path tlv, StatefulIPv4LspIdentidiersTlv,StatefulLspErrorCodeTlv )
* ERO Object,LSPA Object,BandWidth Object,Metric-list,RRO Object
* in PcRpt message.
*/
@Test
public void reportMessageTest22() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0xA0,
0x20, 0x10, 0x00, 0x2c, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x00, 0x12, 0x00, 0x10, //StatefulIPv4LspIdentidiersTlv
(byte) 0xb6, 0x02, 0x4e, 0x1f, 0x00, 0x01, (byte) 0x80, 0x01,
(byte) 0xb6, 0x02, 0x4e, 0x1f, (byte) 0xb6, 0x02, 0x4e, 0x20,
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x00, 0x14, 0x00, 0x04, 0x00, 0x00, 0x00, 0x08, //StatefulLspErrorCodeTlv
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x09, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x05, 0x20, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, //Bandwidth Object
0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x20, //Metric Object
0x08, 0x10, 0x00, 0x34, 0x01, 0x08, 0x11, 0x01, //RRO Object
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x11, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x06, 0x06,
0x06, 0x06, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x05, 0x05, 0x05, 0x05, 0x04, 0x00};
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for LSP Object(Symbolic path tlv, StatefulIPv4LspIdentidiersTlv,StatefulLspErrorCodeTlv )
* ERO Object,BandWidth Object,Metric-list,RRO Object
* in PcRpt message.
*/
@Test
public void reportMessageTest23() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0x8c,
0x20, 0x10, 0x00, 0x2c, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x00, 0x12, 0x00, 0x10, //StatefulIPv4LspIdentidiersTlv
(byte) 0xb6, 0x02, 0x4e, 0x1f, 0x00, 0x01, (byte) 0x80, 0x01,
(byte) 0xb6, 0x02, 0x4e, 0x1f, (byte) 0xb6, 0x02, 0x4e, 0x20,
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x00, 0x14, 0x00, 0x04, 0x00, 0x00, 0x00, 0x08, //StatefulLspErrorCodeTlv
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x05, 0x20, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, //Bandwidth Object
0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x20, //Metric Object
0x08, 0x10, 0x00, 0x34, 0x01, 0x08, 0x11, 0x01, //RRO Object
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x11, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x06, 0x06,
0x06, 0x06, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x05, 0x05, 0x05, 0x05, 0x04, 0x00};
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for LSP Object(Symbolic path tlv, StatefulIPv4LspIdentidiersTlv,StatefulLspErrorCodeTlv )
* ERO Object,Metric-list,RRO Object
* in PcRpt message.
*/
@Test
public void reportMessageTest24() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0x84,
0x20, 0x10, 0x00, 0x2c, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x00, 0x12, 0x00, 0x10, //StatefulIPv4LspIdentidiersTlv
(byte) 0xb6, 0x02, 0x4e, 0x1f, 0x00, 0x01, (byte) 0x80, 0x01,
(byte) 0xb6, 0x02, 0x4e, 0x1f, (byte) 0xb6, 0x02, 0x4e, 0x20,
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x00, 0x14, 0x00, 0x04, 0x00, 0x00, 0x00, 0x08, //StatefulLspErrorCodeTlv
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x20, //Metric Object
0x08, 0x10, 0x00, 0x34, 0x01, 0x08, 0x11, 0x01, //RRO Object
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x11, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x06, 0x06,
0x06, 0x06, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x05, 0x05, 0x05, 0x05, 0x04, 0x00};
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for LSP Object(Symbolic path tlv, StatefulIPv4LspIdentidiersTlv,StatefulLspErrorCodeTlv )
* ERO Object,LSPA Object,RRO Object
* in PcRpt message.
*/
@Test
public void reportMessageTest25() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0x8c,
0x20, 0x10, 0x00, 0x2c, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x00, 0x12, 0x00, 0x10, //StatefulIPv4LspIdentidiersTlv
(byte) 0xb6, 0x02, 0x4e, 0x1f, 0x00, 0x01, (byte) 0x80, 0x01,
(byte) 0xb6, 0x02, 0x4e, 0x1f, (byte) 0xb6, 0x02, 0x4e, 0x20,
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x00, 0x14, 0x00, 0x04, 0x00, 0x00, 0x00, 0x08, //StatefulLspErrorCodeTlv
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x09, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, //LSPA Object
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x08, 0x10, 0x00, 0x34, 0x01, 0x08, 0x11, 0x01, //RRO Object
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x11, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x06, 0x06,
0x06, 0x06, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x05, 0x05, 0x05, 0x05, 0x04, 0x00};
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for LSP Object(Symbolic path tlv, StatefulIPv4LspIdentidiersTlv,StatefulLspErrorCodeTlv )
* ERO Object,LSPA Object
* in PcRpt message.
*/
@Test
public void reportMessageTest26() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0x58,
0x20, 0x10, 0x00, 0x2c, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x00, 0x12, 0x00, 0x10, //StatefulIPv4LspIdentidiersTlv
(byte) 0xb6, 0x02, 0x4e, 0x1f, 0x00, 0x01, (byte) 0x80, 0x01,
(byte) 0xb6, 0x02, 0x4e, 0x1f, (byte) 0xb6, 0x02, 0x4e, 0x20,
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x00, 0x14, 0x00, 0x04, 0x00, 0x00, 0x00, 0x08, //StatefulLspErrorCodeTlv
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x09, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, //LSPA Object
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for LSP Object(Symbolic path tlv, StatefulIPv4LspIdentidiersTlv,StatefulLspErrorCodeTlv)
* ERO Object
* in PcRpt message.
*/
@Test
public void reportMessageTest27() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0x44,
0x20, 0x10, 0x00, 0x2c, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x00, 0x12, 0x00, 0x10, //StatefulIPv4LspIdentidiersTlv
(byte) 0xb6, 0x02, 0x4e, 0x1f, 0x00, 0x01, (byte) 0x80, 0x01,
(byte) 0xb6, 0x02, 0x4e, 0x1f, (byte) 0xb6, 0x02, 0x4e, 0x20,
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x00, 0x14, 0x00, 0x04, 0x00, 0x00, 0x00, 0x08, //StatefulLspErrorCodeTlv
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00};
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for LSP Object(Symbolic path tlv, StatefulIPv4LspIdentidiersTlv,StatefulLspErrorCodeTlv )
* LSPA Object,BandWidth Object,Metric-list,ERO Object
* in PcRpt message.
*/
@Test
public void reportMessageTest28() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0x6c,
0x20, 0x10, 0x00, 0x2c, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x00, 0x12, 0x00, 0x10, //StatefulIPv4LspIdentidiersTlv
(byte) 0xb6, 0x02, 0x4e, 0x1f, 0x00, 0x01, (byte) 0x80, 0x01,
(byte) 0xb6, 0x02, 0x4e, 0x1f, (byte) 0xb6, 0x02, 0x4e, 0x20,
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x00, 0x14, 0x00, 0x04, 0x00, 0x00, 0x00, 0x08, //StatefulLspErrorCodeTlv
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x09, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x05, 0x20, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, //Bandwidth Object
0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x20};
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for SRP Object,LSP Object(symbolic path tlv),ERO Object,Metric-list,RRO Object
* in PcRpt message.
*/
@Test
public void reportMessageTest29() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0x74,
0x21, 0x10, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x10, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x20, //Metric Object
0x08, 0x10, 0x00, 0x34, 0x01, 0x08, 0x11, 0x01, //RRO Object
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x11, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x06, 0x06,
0x06, 0x06, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x05, 0x05, 0x05, 0x05, 0x04, 0x00};
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for SRP Object,LSP Object(symbolic path tlv),ERO Object,Metric-list,RRO Object
* SRP Object,LSP Object(symbolic path tlv),ERO Object,Metric-list,RRO Object
* in PcRpt message.
*/
@Test
public void reportMessageTest30() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0xE4,
0x21, 0x10, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x10, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x20, //Metric Object
0x08, 0x10, 0x00, 0x34, 0x01, 0x08, 0x11, 0x01, //RRO Object
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x11, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x06, 0x06,
0x06, 0x06, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x05, 0x05, 0x05, 0x05, 0x04, 0x00,
0x21, 0x10, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x10, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x20, //Metric Object
0x08, 0x10, 0x00, 0x34, 0x01, 0x08, 0x11, 0x01, //RRO Object
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x11, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x06, 0x06,
0x06, 0x06, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x05, 0x05, 0x05, 0x05, 0x04, 0x00};
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for SRP Object,LSP Object(symbolic path tlv),ERO Object,LSPA Object
* BandWidth Object,Metric-list,RRO Object,SRP Object,LSP Object(symbolic path tlv)
* ERO Object,Metric-list,RRO Object
* in PcRpt message.
*/
@Test
public void reportMessageTest31() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x01, 0x00,
0x21, 0x10, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x10, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x09, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, //LSPA Object
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x05, 0x20, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, //Bandwidth Object
0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x20, //Metric Object
0x08, 0x10, 0x00, 0x34, 0x01, 0x08, 0x11, 0x01, //RRO Object
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x11, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x06, 0x06,
0x06, 0x06, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x05, 0x05, 0x05, 0x05, 0x04, 0x00,
0x21, 0x10, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x10, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x20, //Metric Object
0x08, 0x10, 0x00, 0x34, 0x01, 0x08, 0x11, 0x01, //RRO Object
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x11, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x06, 0x06,
0x06, 0x06, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x05, 0x05, 0x05, 0x05, 0x04, 0x00};
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for SRP Object,LSP Object(symbolic path tlv),ERO Object,LSPA Object
* BandWidth Object,Metric-list,RRO Object,SRP Object,LSP Object(symbolic path tlv)
* ERO Object,LSPA Object,Metric-list,RRO Object
* in PcRpt message.
*/
@Test
public void reportMessageTest32() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x01, (byte) 0x14,
0x21, 0x10, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x10, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x09, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, //LSPA Object
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x05, 0x20, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, //Bandwidth Object
0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x20, //Metric Object
0x08, 0x10, 0x00, 0x34, 0x01, 0x08, 0x11, 0x01, //RRO Object
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x11, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x06, 0x06,
0x06, 0x06, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x05, 0x05, 0x05, 0x05, 0x04, 0x00,
0x21, 0x10, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x10, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x09, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, //LSPA Object
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x20, //Metric Object
0x08, 0x10, 0x00, 0x34, 0x01, 0x08, 0x11, 0x01, //RRO Object
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x11, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x06, 0x06,
0x06, 0x06, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x05, 0x05, 0x05, 0x05, 0x04, 0x00};
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for SRP Object,LSP Object(symbolic path tlv),ERO Object,LSPA Object
* BandWidth Object,Metric-list,RRO Object,SRP Object,LSP Object(symbolic path tlv)
* ERO Object,LSPA Object,BandWidth Object,Metric-list,RRO Object
* in PcRpt message.
*/
@Test
public void reportMessageTest33() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x01, (byte) 0x1c,
0x21, 0x10, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x10, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x09, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, //LSPA Object
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x05, 0x20, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, //Bandwidth Object
0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x20, //Metric Object
0x08, 0x10, 0x00, 0x34, 0x01, 0x08, 0x11, 0x01, //RRO Object
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x11, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x06, 0x06,
0x06, 0x06, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x05, 0x05, 0x05, 0x05, 0x04, 0x00,
0x21, 0x10, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x10, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x09, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x05, 0x20, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, //Bandwidth Object
0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x20, //Metric Object
0x08, 0x10, 0x00, 0x34, 0x01, 0x08, 0x11, 0x01, //RRO Object
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x11, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x06, 0x06,
0x06, 0x06, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x02, 0x04, 0x00, 0x01, 0x08, 0x12, 0x01,
0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x05, 0x05, 0x05, 0x05, 0x04, 0x00};
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for SRP Object,LSP Object(symbolic path Tlv),ERO Object,LSPA Object
* BandWidth Object,Metric-list,SRP Object,LSP Object(symbolic path tlv)
* ERO Object,LSPA Object,BandWidth Object,Metric-list
* in PcRpt message.
*/
@Test
public void reportMessageTest34() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0xB4,
0x21, 0x10, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x10, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x09, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, //LSPA Object
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x05, 0x20, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, //Bandwidth Object
0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x20, //Metric Object
0x21, 0x10, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x10, 0x00, 0x00, 0x10, 0x04, //LSP Object
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x09, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, //LSPA Object
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x05, 0x20, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, //Bandwidth Object
0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x20}; //Metric Object
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
/**
* This test case checks for SRP Object,LSP Object)Symbolic path tlv),ERO Object,SRP Object
* LSP Object(symbolic path tlv) ERO Object,LSPA Object, BandWidth Object,Metric-list
* in PcRpt message.
*/
@Test
public void reportMessageTest35() throws PcepParseException, PcepOutOfBoundMessageException {
byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0x8C,
0x21, 0x10, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x10, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x21, 0x10, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
0x20, 0x10, 0x00, 0x10, 0x00, 0x00, 0x10, 0x03, //LSP Object
0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
0x07, 0x10, 0x00, 0x14, //ERO Object
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00,
0x09, 0x10, 0x00, 0x14, //LSPA Object
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x05, 0x20, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, //Bandwidth Object
0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x20}; //Metric Object
byte[] testReportMsg = {0};
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(reportMsg);
PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
PcepMessage message = null;
message = reader.readFrom(buffer);
assertThat(message, instanceOf(PcepReportMsg.class));
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
message.writeTo(buf);
int readLen = buf.writerIndex();
testReportMsg = new byte[readLen];
buf.readBytes(testReportMsg, 0, readLen);
assertThat(testReportMsg, is(reportMsg));
}
}
| apache-2.0 |
equella/Equella | Source/Plugins/Core/com.equella.serverbase/src/com/tle/hibernate/dialect/LongNStringType.java | 1324 | /*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* The Apereo Foundation licenses this file to you under the Apache License,
* Version 2.0, (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tle.hibernate.dialect;
import org.hibernate.type.AbstractSingleColumnStandardBasicType;
import org.hibernate.type.descriptor.java.StringTypeDescriptor;
@SuppressWarnings("nls")
public class LongNStringType extends AbstractSingleColumnStandardBasicType<String> {
private static final long serialVersionUID = 1L;
public LongNStringType() {
super(LongNVarcharTypeDescriptor.INSTANCE, StringTypeDescriptor.INSTANCE);
}
@Override
public String getName() {
return "materialized_clob";
}
}
| apache-2.0 |
hanahmily/sky-walking | apm-collector/apm-collector-core/src/main/java/org/apache/skywalking/apm/collector/core/data/Operation.java | 1257 | /*
* 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.skywalking.apm.collector.core.data;
/**
* @author peng-yongsheng
*/
public interface Operation {
String operate(String newValue, String oldValue);
Long operate(Long newValue, Long oldValue);
Double operate(Double newValue, Double oldValue);
Integer operate(Integer newValue, Integer oldValue);
Boolean operate(Boolean newValue, Boolean oldValue);
byte[] operate(byte[] newValue, byte[] oldValue);
}
| apache-2.0 |
kikoso/Event-Bus-Architecture | app/src/main/java/com/enrique/eventbusarchitecture/secondfragment/SecondFragment.java | 601 | package com.enrique.eventbusarchitecture.secondfragment;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.enrique.eventbusarchitecture.R;
import butterknife.ButterKnife;
public class SecondFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.second_fragment, container, false);
ButterKnife.inject(this, view);
return view;
}
}
| apache-2.0 |
leafclick/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/ui/actions/GoToHashOrRefAction.java | 2623 | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.vcs.log.ui.actions;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.vcs.log.VcsLog;
import com.intellij.vcs.log.VcsLogDataKeys;
import com.intellij.vcs.log.impl.VcsGoToRefComparator;
import com.intellij.vcs.log.impl.VcsLogManager;
import com.intellij.vcs.log.statistics.VcsLogUsageTriggerCollector;
import com.intellij.vcs.log.ui.VcsLogInternalDataKeys;
import com.intellij.vcs.log.ui.VcsLogUiEx;
import com.intellij.vcs.log.util.VcsLogUtil;
import org.jetbrains.annotations.NotNull;
import java.util.Set;
public class GoToHashOrRefAction extends DumbAwareAction {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
VcsLogUsageTriggerCollector.triggerUsage(e, this);
Project project = e.getRequiredData(CommonDataKeys.PROJECT);
VcsLog log = e.getRequiredData(VcsLogDataKeys.VCS_LOG);
VcsLogUiEx logUi = e.getRequiredData(VcsLogInternalDataKeys.LOG_UI_EX);
VcsLogManager logManager = e.getRequiredData(VcsLogInternalDataKeys.LOG_MANAGER);
Set<VirtualFile> visibleRoots = VcsLogUtil.getVisibleRoots(logUi);
GoToHashOrRefPopup popup =
new GoToHashOrRefPopup(project, logUi.getDataPack().getRefs(), visibleRoots, log::jumpToReference,
vcsRef -> logUi.jumpToCommit(vcsRef.getCommitHash(), vcsRef.getRoot()),
logManager.getColorManager(),
new VcsGoToRefComparator(logUi.getDataPack().getLogProviders()));
popup.show(logUi.getTable());
}
@Override
public void update(@NotNull AnActionEvent e) {
VcsLog log = e.getData(VcsLogDataKeys.VCS_LOG);
VcsLogUiEx logUi = e.getData(VcsLogInternalDataKeys.LOG_UI_EX);
e.getPresentation().setEnabledAndVisible(e.getProject() != null && log != null && logUi != null);
}
}
| apache-2.0 |
vzagnitko/BluetoothMusicServer | src/main/java/ua/com/lsd25/config/FacebookConfig.java | 650 | package ua.com.lsd25.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.social.facebook.api.Facebook;
import org.springframework.social.facebook.api.impl.FacebookTemplate;
/**
* @author vzagnitko
*/
@Configuration
public class FacebookConfig {
@Value("${spring.social.facebook.access.token}")
private String facebookAccessToken;
public FacebookConfig() {
}
@Bean
public Facebook getFacebook() {
return new FacebookTemplate(facebookAccessToken);
}
}
| apache-2.0 |
dprguiuc/Cassandra-Wasef | src/java/org/apache/cassandra/hadoop/pig/AbstractCassandraStorage.java | 31146 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.hadoop.pig;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.util.*;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.exceptions.SyntaxException;
import org.apache.cassandra.auth.IAuthenticator;
import org.apache.cassandra.db.Column;
import org.apache.cassandra.db.IColumn;
import org.apache.cassandra.db.marshal.*;
import org.apache.cassandra.db.marshal.AbstractCompositeType.CompositeComponent;
import org.apache.cassandra.hadoop.*;
import org.apache.cassandra.thrift.*;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.Hex;
import org.apache.cassandra.utils.UUIDGen;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.*;
import org.apache.pig.*;
import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.data.*;
import org.apache.pig.impl.util.UDFContext;
import org.apache.thrift.TDeserializer;
import org.apache.thrift.TException;
import org.apache.thrift.TSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A LoadStoreFunc for retrieving data from and storing data to Cassandra
*/
public abstract class AbstractCassandraStorage extends LoadFunc implements StoreFuncInterface, LoadMetadata
{
protected enum MarshallerType { COMPARATOR, DEFAULT_VALIDATOR, KEY_VALIDATOR, SUBCOMPARATOR };
// system environment variables that can be set to configure connection info:
// alternatively, Hadoop JobConf variables can be set using keys from ConfigHelper
public final static String PIG_INPUT_RPC_PORT = "PIG_INPUT_RPC_PORT";
public final static String PIG_INPUT_INITIAL_ADDRESS = "PIG_INPUT_INITIAL_ADDRESS";
public final static String PIG_INPUT_PARTITIONER = "PIG_INPUT_PARTITIONER";
public final static String PIG_OUTPUT_RPC_PORT = "PIG_OUTPUT_RPC_PORT";
public final static String PIG_OUTPUT_INITIAL_ADDRESS = "PIG_OUTPUT_INITIAL_ADDRESS";
public final static String PIG_OUTPUT_PARTITIONER = "PIG_OUTPUT_PARTITIONER";
public final static String PIG_RPC_PORT = "PIG_RPC_PORT";
public final static String PIG_INITIAL_ADDRESS = "PIG_INITIAL_ADDRESS";
public final static String PIG_PARTITIONER = "PIG_PARTITIONER";
public final static String PIG_INPUT_FORMAT = "PIG_INPUT_FORMAT";
public final static String PIG_OUTPUT_FORMAT = "PIG_OUTPUT_FORMAT";
public final static String PIG_INPUT_SPLIT_SIZE = "PIG_INPUT_SPLIT_SIZE";
protected String DEFAULT_INPUT_FORMAT;
protected String DEFAULT_OUTPUT_FORMAT;
public final static String PARTITION_FILTER_SIGNATURE = "cassandra.partition.filter";
protected static final Logger logger = LoggerFactory.getLogger(AbstractCassandraStorage.class);
protected String username;
protected String password;
protected String keyspace;
protected String column_family;
protected String loadSignature;
protected String storeSignature;
protected Configuration conf;
protected String inputFormatClass;
protected String outputFormatClass;
protected int splitSize = 64 * 1024;
protected String partitionerClass;
protected boolean usePartitionFilter = false;
public AbstractCassandraStorage()
{
super();
}
/** Deconstructs a composite type to a Tuple. */
protected Tuple composeComposite(AbstractCompositeType comparator, ByteBuffer name) throws IOException
{
List<CompositeComponent> result = comparator.deconstruct(name);
Tuple t = TupleFactory.getInstance().newTuple(result.size());
for (int i=0; i<result.size(); i++)
setTupleValue(t, i, result.get(i).comparator.compose(result.get(i).value));
return t;
}
/** convert a column to a tuple */
protected Tuple columnToTuple(IColumn col, CfDef cfDef, AbstractType comparator) throws IOException
{
Tuple pair = TupleFactory.getInstance().newTuple(2);
// name
if(comparator instanceof AbstractCompositeType)
setTupleValue(pair, 0, composeComposite((AbstractCompositeType)comparator,col.name()));
else
setTupleValue(pair, 0, comparator.compose(col.name()));
// value
if (col instanceof Column)
{
// standard
Map<ByteBuffer,AbstractType> validators = getValidatorMap(cfDef);
if (validators.get(col.name()) == null)
{
Map<MarshallerType, AbstractType> marshallers = getDefaultMarshallers(cfDef);
setTupleValue(pair, 1, marshallers.get(MarshallerType.DEFAULT_VALIDATOR).compose(col.value()));
}
else
setTupleValue(pair, 1, validators.get(col.name()).compose(col.value()));
return pair;
}
else
{
// super
ArrayList<Tuple> subcols = new ArrayList<Tuple>();
for (IColumn subcol : col.getSubColumns())
subcols.add(columnToTuple(subcol, cfDef, parseType(cfDef.getSubcomparator_type())));
pair.set(1, new DefaultDataBag(subcols));
}
return pair;
}
/** set the value to the position of the tuple */
protected void setTupleValue(Tuple pair, int position, Object value) throws ExecException
{
if (value instanceof BigInteger)
pair.set(position, ((BigInteger) value).intValue());
else if (value instanceof ByteBuffer)
pair.set(position, new DataByteArray(ByteBufferUtil.getArray((ByteBuffer) value)));
else if (value instanceof UUID)
pair.set(position, new DataByteArray(UUIDGen.decompose((java.util.UUID) value)));
else if (value instanceof Date)
pair.set(position, DateType.instance.decompose((Date) value).getLong());
else
pair.set(position, value);
}
/** get the columnfamily definition for the signature */
protected CfDef getCfDef(String signature)
{
UDFContext context = UDFContext.getUDFContext();
Properties property = context.getUDFProperties(AbstractCassandraStorage.class);
return cfdefFromString(property.getProperty(signature));
}
/** construct a map to store the mashaller type to cassandra data type mapping */
protected Map<MarshallerType, AbstractType> getDefaultMarshallers(CfDef cfDef) throws IOException
{
Map<MarshallerType, AbstractType> marshallers = new EnumMap<MarshallerType, AbstractType>(MarshallerType.class);
AbstractType comparator;
AbstractType subcomparator;
AbstractType default_validator;
AbstractType key_validator;
comparator = parseType(cfDef.getComparator_type());
subcomparator = parseType(cfDef.getSubcomparator_type());
default_validator = parseType(cfDef.getDefault_validation_class());
key_validator = parseType(cfDef.getKey_validation_class());
marshallers.put(MarshallerType.COMPARATOR, comparator);
marshallers.put(MarshallerType.DEFAULT_VALIDATOR, default_validator);
marshallers.put(MarshallerType.KEY_VALIDATOR, key_validator);
marshallers.put(MarshallerType.SUBCOMPARATOR, subcomparator);
return marshallers;
}
/** get the validators */
protected Map<ByteBuffer, AbstractType> getValidatorMap(CfDef cfDef) throws IOException
{
Map<ByteBuffer, AbstractType> validators = new HashMap<ByteBuffer, AbstractType>();
for (ColumnDef cd : cfDef.getColumn_metadata())
{
if (cd.getValidation_class() != null && !cd.getValidation_class().isEmpty())
{
AbstractType validator = null;
try
{
validator = TypeParser.parse(cd.getValidation_class());
validators.put(cd.name, validator);
}
catch (ConfigurationException e)
{
throw new IOException(e);
}
catch (SyntaxException e)
{
throw new IOException(e);
}
}
}
return validators;
}
/** parse the string to a cassandra data type */
protected AbstractType parseType(String type) throws IOException
{
try
{
// always treat counters like longs, specifically CCT.compose is not what we need
if (type != null && type.equals("org.apache.cassandra.db.marshal.CounterColumnType"))
return LongType.instance;
return TypeParser.parse(type);
}
catch (ConfigurationException e)
{
throw new IOException(e);
}
catch (SyntaxException e)
{
throw new IOException(e);
}
}
@Override
public InputFormat getInputFormat()
{
try
{
return FBUtilities.construct(inputFormatClass, "inputformat");
}
catch (ConfigurationException e)
{
throw new RuntimeException(e);
}
}
/** decompose the query to store the parameters in a map */
public static Map<String, String> getQueryMap(String query) throws UnsupportedEncodingException
{
String[] params = query.split("&");
Map<String, String> map = new HashMap<String, String>();
for (String param : params)
{
String[] keyValue = param.split("=");
map.put(keyValue[0], URLDecoder.decode(keyValue[1],"UTF-8"));
}
return map;
}
/** set hadoop cassandra connection settings */
protected void setConnectionInformation() throws IOException
{
if (System.getenv(PIG_RPC_PORT) != null)
{
ConfigHelper.setInputRpcPort(conf, System.getenv(PIG_RPC_PORT));
ConfigHelper.setOutputRpcPort(conf, System.getenv(PIG_RPC_PORT));
}
if (System.getenv(PIG_INPUT_RPC_PORT) != null)
ConfigHelper.setInputRpcPort(conf, System.getenv(PIG_INPUT_RPC_PORT));
if (System.getenv(PIG_OUTPUT_RPC_PORT) != null)
ConfigHelper.setOutputRpcPort(conf, System.getenv(PIG_OUTPUT_RPC_PORT));
if (System.getenv(PIG_INITIAL_ADDRESS) != null)
{
ConfigHelper.setInputInitialAddress(conf, System.getenv(PIG_INITIAL_ADDRESS));
ConfigHelper.setOutputInitialAddress(conf, System.getenv(PIG_INITIAL_ADDRESS));
}
if (System.getenv(PIG_INPUT_INITIAL_ADDRESS) != null)
ConfigHelper.setInputInitialAddress(conf, System.getenv(PIG_INPUT_INITIAL_ADDRESS));
if (System.getenv(PIG_OUTPUT_INITIAL_ADDRESS) != null)
ConfigHelper.setOutputInitialAddress(conf, System.getenv(PIG_OUTPUT_INITIAL_ADDRESS));
if (System.getenv(PIG_PARTITIONER) != null)
{
ConfigHelper.setInputPartitioner(conf, System.getenv(PIG_PARTITIONER));
ConfigHelper.setOutputPartitioner(conf, System.getenv(PIG_PARTITIONER));
}
if(System.getenv(PIG_INPUT_PARTITIONER) != null)
ConfigHelper.setInputPartitioner(conf, System.getenv(PIG_INPUT_PARTITIONER));
if(System.getenv(PIG_OUTPUT_PARTITIONER) != null)
ConfigHelper.setOutputPartitioner(conf, System.getenv(PIG_OUTPUT_PARTITIONER));
if (System.getenv(PIG_INPUT_FORMAT) != null)
inputFormatClass = getFullyQualifiedClassName(System.getenv(PIG_INPUT_FORMAT));
else
inputFormatClass = DEFAULT_INPUT_FORMAT;
if (System.getenv(PIG_OUTPUT_FORMAT) != null)
outputFormatClass = getFullyQualifiedClassName(System.getenv(PIG_OUTPUT_FORMAT));
else
outputFormatClass = DEFAULT_OUTPUT_FORMAT;
}
/** get the full class name */
protected String getFullyQualifiedClassName(String classname)
{
return classname.contains(".") ? classname : "org.apache.cassandra.hadoop." + classname;
}
/** get pig type for the cassandra data type*/
protected byte getPigType(AbstractType type)
{
if (type instanceof LongType || type instanceof DateType) // DateType is bad and it should feel bad
return DataType.LONG;
else if (type instanceof IntegerType || type instanceof Int32Type) // IntegerType will overflow at 2**31, but is kept for compatibility until pig has a BigInteger
return DataType.INTEGER;
else if (type instanceof AsciiType)
return DataType.CHARARRAY;
else if (type instanceof UTF8Type)
return DataType.CHARARRAY;
else if (type instanceof FloatType)
return DataType.FLOAT;
else if (type instanceof DoubleType)
return DataType.DOUBLE;
else if (type instanceof AbstractCompositeType )
return DataType.TUPLE;
return DataType.BYTEARRAY;
}
public ResourceStatistics getStatistics(String location, Job job)
{
return null;
}
@Override
public String relativeToAbsolutePath(String location, Path curDir) throws IOException
{
return location;
}
@Override
public void setUDFContextSignature(String signature)
{
this.loadSignature = signature;
}
/** StoreFunc methods */
public void setStoreFuncUDFContextSignature(String signature)
{
this.storeSignature = signature;
}
public String relToAbsPathForStoreLocation(String location, Path curDir) throws IOException
{
return relativeToAbsolutePath(location, curDir);
}
/** output format */
public OutputFormat getOutputFormat()
{
try
{
return FBUtilities.construct(outputFormatClass, "outputformat");
}
catch (ConfigurationException e)
{
throw new RuntimeException(e);
}
}
public void checkSchema(ResourceSchema schema) throws IOException
{
// we don't care about types, they all get casted to ByteBuffers
}
/** convert object to ByteBuffer */
protected ByteBuffer objToBB(Object o)
{
if (o == null)
return (ByteBuffer)o;
if (o instanceof java.lang.String)
return ByteBuffer.wrap(new DataByteArray((String)o).get());
if (o instanceof Integer)
return Int32Type.instance.decompose((Integer)o);
if (o instanceof Long)
return LongType.instance.decompose((Long)o);
if (o instanceof Float)
return FloatType.instance.decompose((Float)o);
if (o instanceof Double)
return DoubleType.instance.decompose((Double)o);
if (o instanceof UUID)
return ByteBuffer.wrap(UUIDGen.decompose((UUID) o));
if(o instanceof Tuple) {
List<Object> objects = ((Tuple)o).getAll();
List<ByteBuffer> serialized = new ArrayList<ByteBuffer>(objects.size());
int totalLength = 0;
for(Object sub : objects)
{
ByteBuffer buffer = objToBB(sub);
serialized.add(buffer);
totalLength += 2 + buffer.remaining() + 1;
}
ByteBuffer out = ByteBuffer.allocate(totalLength);
for (ByteBuffer bb : serialized)
{
int length = bb.remaining();
out.put((byte) ((length >> 8) & 0xFF));
out.put((byte) (length & 0xFF));
out.put(bb);
out.put((byte) 0);
}
out.flip();
return out;
}
return ByteBuffer.wrap(((DataByteArray) o).get());
}
public void cleanupOnFailure(String failure, Job job)
{
}
/** Methods to get the column family schema from Cassandra */
protected void initSchema(String signature)
{
Properties properties = UDFContext.getUDFContext().getUDFProperties(AbstractCassandraStorage.class);
// Only get the schema if we haven't already gotten it
if (!properties.containsKey(signature))
{
try
{
Cassandra.Client client = ConfigHelper.getClientFromInputAddressList(conf);
client.set_keyspace(keyspace);
if (username != null && password != null)
{
Map<String, String> credentials = new HashMap<String, String>(2);
credentials.put(IAuthenticator.USERNAME_KEY, username);
credentials.put(IAuthenticator.PASSWORD_KEY, password);
try
{
client.login(new AuthenticationRequest(credentials));
}
catch (AuthenticationException e)
{
logger.error("Authentication exception: invalid username and/or password");
throw new RuntimeException(e);
}
catch (AuthorizationException e)
{
throw new AssertionError(e); // never actually throws AuthorizationException.
}
}
// compose the CfDef for the columfamily
CfDef cfDef = getCfDef(client);
if (cfDef != null)
properties.setProperty(signature, cfdefToString(cfDef));
else
throw new RuntimeException(String.format("Column family '%s' not found in keyspace '%s'",
column_family,
keyspace));
}
catch (TException e)
{
throw new RuntimeException(e);
}
catch (InvalidRequestException e)
{
throw new RuntimeException(e);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
catch (UnavailableException e)
{
throw new RuntimeException(e);
}
catch (TimedOutException e)
{
throw new RuntimeException(e);
}
catch (SchemaDisagreementException e)
{
throw new RuntimeException(e);
}
}
}
/** convert CfDef to string */
protected static String cfdefToString(CfDef cfDef)
{
assert cfDef != null;
// this is so awful it's kind of cool!
TSerializer serializer = new TSerializer(new TBinaryProtocol.Factory());
try
{
return Hex.bytesToHex(serializer.serialize(cfDef));
}
catch (TException e)
{
throw new RuntimeException(e);
}
}
/** convert string back to CfDef */
protected static CfDef cfdefFromString(String st)
{
assert st != null;
TDeserializer deserializer = new TDeserializer(new TBinaryProtocol.Factory());
CfDef cfDef = new CfDef();
try
{
deserializer.deserialize(cfDef, Hex.hexToBytes(st));
}
catch (TException e)
{
throw new RuntimeException(e);
}
return cfDef;
}
/** return the CfDef for the column family */
protected CfDef getCfDef(Cassandra.Client client)
throws InvalidRequestException,
UnavailableException,
TimedOutException,
SchemaDisagreementException,
TException,
CharacterCodingException
{
// get CF meta data
String query = "SELECT type, " +
" comparator," +
" subcomparator," +
" default_validator, " +
" key_validator," +
" key_aliases " +
"FROM system.schema_columnfamilies " +
"WHERE keyspace_name = '%s' " +
" AND columnfamily_name = '%s' ";
CqlResult result = client.execute_cql3_query(
ByteBufferUtil.bytes(String.format(query, keyspace, column_family)),
Compression.NONE,
ConsistencyLevel.ONE);
if (result == null || result.rows == null || result.rows.isEmpty())
return null;
Iterator<CqlRow> iteraRow = result.rows.iterator();
CfDef cfDef = new CfDef();
cfDef.keyspace = keyspace;
cfDef.name = column_family;
boolean cql3Table = false;
if (iteraRow.hasNext())
{
CqlRow cqlRow = iteraRow.next();
cfDef.column_type = ByteBufferUtil.string(cqlRow.columns.get(0).value);
cfDef.comparator_type = ByteBufferUtil.string(cqlRow.columns.get(1).value);
ByteBuffer subComparator = cqlRow.columns.get(2).value;
if (subComparator != null)
cfDef.subcomparator_type = ByteBufferUtil.string(subComparator);
cfDef.default_validation_class = ByteBufferUtil.string(cqlRow.columns.get(3).value);
cfDef.key_validation_class = ByteBufferUtil.string(cqlRow.columns.get(4).value);
List<String> keys = null;
if (cqlRow.columns.get(5).value != null)
{
String keyAliases = ByteBufferUtil.string(cqlRow.columns.get(5).value);
keys = FBUtilities.fromJsonList(keyAliases);
}
// get column meta data
if (keys != null && keys.size() > 0)
cql3Table = true;
}
cfDef.column_metadata = getColumnMetadata(client, cql3Table);
return cfDef;
}
/** get a list of columns */
protected abstract List<ColumnDef> getColumnMetadata(Cassandra.Client client, boolean cql3Table)
throws InvalidRequestException,
UnavailableException,
TimedOutException,
SchemaDisagreementException,
TException,
CharacterCodingException;
/** get column meta data */
protected List<ColumnDef> getColumnMeta(Cassandra.Client client)
throws InvalidRequestException,
UnavailableException,
TimedOutException,
SchemaDisagreementException,
TException,
CharacterCodingException
{
String query = "SELECT column_name, " +
" validator, " +
" index_type " +
"FROM system.schema_columns " +
"WHERE keyspace_name = '%s' " +
" AND columnfamily_name = '%s'";
CqlResult result = client.execute_cql3_query(
ByteBufferUtil.bytes(String.format(query, keyspace, column_family)),
Compression.NONE,
ConsistencyLevel.ONE);
List<CqlRow> rows = result.rows;
List<ColumnDef> columnDefs = new ArrayList<ColumnDef>();
if (rows == null || rows.isEmpty())
return columnDefs;
Iterator<CqlRow> iterator = rows.iterator();
while (iterator.hasNext())
{
CqlRow row = iterator.next();
ColumnDef cDef = new ColumnDef();
cDef.setName(ByteBufferUtil.clone(row.getColumns().get(0).value));
cDef.validation_class = ByteBufferUtil.string(row.getColumns().get(1).value);
ByteBuffer indexType = row.getColumns().get(2).value;
if (indexType != null)
cDef.index_type = getIndexType(ByteBufferUtil.string(indexType));
columnDefs.add(cDef);
}
return columnDefs;
}
/** get keys meta data */
protected List<ColumnDef> getKeysMeta(Cassandra.Client client)
throws InvalidRequestException,
UnavailableException,
TimedOutException,
SchemaDisagreementException,
TException,
IOException
{
String query = "SELECT key_aliases, " +
" column_aliases, " +
" key_validator, " +
" comparator, " +
" keyspace_name, " +
" value_alias, " +
" default_validator " +
"FROM system.schema_columnfamilies " +
"WHERE keyspace_name = '%s'" +
" AND columnfamily_name = '%s' ";
CqlResult result = client.execute_cql3_query(
ByteBufferUtil.bytes(String.format(query, keyspace, column_family)),
Compression.NONE,
ConsistencyLevel.ONE);
if (result == null || result.rows == null || result.rows.isEmpty())
return null;
List<CqlRow> rows = result.rows;
Iterator<CqlRow> iteraRow = rows.iterator();
List<ColumnDef> keys = new ArrayList<ColumnDef>();
if (iteraRow.hasNext())
{
CqlRow cqlRow = iteraRow.next();
String name = ByteBufferUtil.string(cqlRow.columns.get(4).value);
logger.debug("Found ksDef name: {}", name);
String keyString = ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.columns.get(0).getValue()));
logger.debug("partition keys: {}", keyString);
List<String> keyNames = FBUtilities.fromJsonList(keyString);
Iterator<String> iterator = keyNames.iterator();
while (iterator.hasNext())
{
ColumnDef cDef = new ColumnDef();
cDef.name = ByteBufferUtil.bytes(iterator.next());
keys.add(cDef);
}
keyString = ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.columns.get(1).getValue()));
logger.debug("cluster keys: {}", keyString);
keyNames = FBUtilities.fromJsonList(keyString);
iterator = keyNames.iterator();
while (iterator.hasNext())
{
ColumnDef cDef = new ColumnDef();
cDef.name = ByteBufferUtil.bytes(iterator.next());
keys.add(cDef);
}
String validator = ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.columns.get(2).getValue()));
logger.debug("row key validator: {}", validator);
AbstractType<?> keyValidator = parseType(validator);
Iterator<ColumnDef> keyItera = keys.iterator();
if (keyValidator instanceof CompositeType)
{
Iterator<AbstractType<?>> typeItera = ((CompositeType) keyValidator).types.iterator();
while (typeItera.hasNext())
keyItera.next().validation_class = typeItera.next().toString();
}
else
keyItera.next().validation_class = keyValidator.toString();
validator = ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.columns.get(3).getValue()));
logger.debug("cluster key validator: {}", validator);
if (keyItera.hasNext() && validator != null && !validator.isEmpty())
{
AbstractType<?> clusterKeyValidator = parseType(validator);
if (clusterKeyValidator instanceof CompositeType)
{
Iterator<AbstractType<?>> typeItera = ((CompositeType) clusterKeyValidator).types.iterator();
while (keyItera.hasNext())
keyItera.next().validation_class = typeItera.next().toString();
}
else
keyItera.next().validation_class = clusterKeyValidator.toString();
}
// compact value_alias column
if (cqlRow.columns.get(5).value != null)
{
try
{
String compactValidator = ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.columns.get(6).getValue()));
logger.debug("default validator: {}", compactValidator);
AbstractType<?> defaultValidator = parseType(compactValidator);
ColumnDef cDef = new ColumnDef();
cDef.name = cqlRow.columns.get(5).value;
cDef.validation_class = defaultValidator.toString();
keys.add(cDef);
}
catch (Exception e)
{
// no compact column at value_alias
}
}
}
return keys;
}
/** get index type from string */
protected IndexType getIndexType(String type)
{
type = type.toLowerCase();
if ("keys".equals(type))
return IndexType.KEYS;
else if("custom".equals(type))
return IndexType.CUSTOM;
else if("composites".equals(type))
return IndexType.COMPOSITES;
else
return null;
}
/** return partition keys */
public String[] getPartitionKeys(String location, Job job)
{
if (!usePartitionFilter)
return null;
List<ColumnDef> indexes = getIndexes();
String[] partitionKeys = new String[indexes.size()];
for (int i = 0; i < indexes.size(); i++)
{
partitionKeys[i] = new String(indexes.get(i).getName());
}
return partitionKeys;
}
/** get a list of columns with defined index*/
protected List<ColumnDef> getIndexes()
{
CfDef cfdef = getCfDef(loadSignature);
List<ColumnDef> indexes = new ArrayList<ColumnDef>();
for (ColumnDef cdef : cfdef.column_metadata)
{
if (cdef.index_type != null)
indexes.add(cdef);
}
return indexes;
}
}
| apache-2.0 |
ZHANGLONG678/springmvc | src/main/java/com/cetc/TokenInterceptor.java | 5596 | package com.cetc;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.cetc.model.RespDataVo;
import com.cetc.utils.Base64;
import com.cetc.utils.DateUtil;
import com.cetc.utils.JsonUtils;
import com.cetc.utils.ValueTool;
import net.sf.json.JSONObject;
/**
*
* @author hp
*
*/
public class TokenInterceptor implements HandlerInterceptor {
private static Logger logger = LoggerFactory.getLogger(TokenInterceptor.class);
private NamedThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<>("StopWatch-StartTime");
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
long beginTime = System.currentTimeMillis();// 1、开始时间
startTimeThreadLocal.set(beginTime);// 线程绑定变量(该数据只有当前请求的线程可见)
String reqJson = "";
String getReqParm = "";
//增加跨域请求
if(request.getHeader("Origin")!=null&&
(request.getHeader("Origin").equals("http://localhost:8000")||
request.getHeader("Origin").equals("http://10.111.10.42:8000"))
){
logger.debug("需要跨域请求{}", request.getRequestURI());
response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));
};
if (request.getRequestURI().contains("user/login")) {
JSONObject obj = new JSONObject();
obj.put("userName", request.getParameter("userName"));
obj.put("userPwd", request.getParameter("userPwd"));
logger.info("*****【" + request.getMethod() + "】请求url地址:" + request.getRequestURL() + " \n 请求参数: "
+ obj.toString());
return true;
} else {
RespDataVo root = new RespDataVo();
String token = null;
if (StringUtils.equals("get", request.getMethod().toLowerCase())) {
token = request.getParameter("token");
getReqParm = request.getQueryString();
} else if (StringUtils.equals("post", request.getMethod().toLowerCase())) {
InputStream inputStream = request.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
String tempStr = "";
while ((tempStr = reader.readLine()) != null) {
reqJson += tempStr;
}
reader.close();
inputStream.close();
JSONObject reqBody = JSONObject.fromObject(reqJson);
token = reqBody.getString("token");
}
logger.info("*****【" + request.getMethod() + "】请求url地址:" + request.getRequestURL() + " \n 请求参数: "
+ getReqParm + "" + reqJson);
if (token != null) {
String tokenStr = new String(Base64.decode(token));
if (!tokenStr.contains("_") || tokenStr.split("_").length < 3) { // token
// 不包含"_"
// 或者包含但是格式不正确
String code = "1012";
root.setCode(code);
response.setCharacterEncoding("utf-8");
root.setMsg(ValueTool.getValue().get(code));
response.getWriter().write(JsonUtils.parseBeanToJson(root));
return false;
} else {
String tokenCode = tokenStr.split("_")[1];
if (StringUtils.equals("A123456a", tokenStr.split("_")[2])) {// 校验token是否修改
if (DateUtil.dayDiff(new Date(), tokenCode) - 30 > 0) {// 限制30分钟内可以访问
String code = "1011";
root.setCode(code);
response.setCharacterEncoding("utf-8");
root.setMsg(ValueTool.getValue().get(code));
response.getWriter().write(JsonUtils.parseBeanToJson(root));
return false;
} else {
request.setAttribute("userId", tokenStr.split("_")[0]);
request.setAttribute("param", reqJson);
return true;
}
} else {
String code = "1012";
root.setCode(code);
response.setCharacterEncoding("utf-8");
root.setMsg(ValueTool.getValue().get(code));
response.getWriter().write(JsonUtils.parseBeanToJson(root));
return false;
}
}
}
String code = "1010";
root.setCode(code);
response.setCharacterEncoding("utf-8");
root.setMsg(ValueTool.getValue().get(code));
response.getWriter().write(JsonUtils.parseBeanToJson(root));
return false;
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
long endTime = System.currentTimeMillis();// 2、结束时间
long beginTime = startTimeThreadLocal.get();// 得到线程绑定的局部变量(开始时间)
long consumeTime = endTime - beginTime;// 3、消耗的时间
if (consumeTime > 500) {// 此处认为处理时间超过500毫秒的请求为慢请求
// TODO 记录到日志文件
System.out.println(String.format("%s consume %d millis", request.getRequestURI(), consumeTime));
logger.info("************end***********" + request.getRequestURL() + " 执行时长:" + consumeTime);
}
}
} | apache-2.0 |
simtse/CatholicJourney | app/src/main/java/org/sfx/catholicjourney/core/utils/TextUtility.java | 901 | package org.sfx.catholicjourney.core.utils;
import android.content.res.ColorStateList;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
/**
* Created by simonadmin on 2015-03-18.
*/
public class TextUtility {
/**
* Set the TextView text. If text is null/empty, hide textview.
*
* @param tv TextView to set text in
* @param text
* @throws Exception
*/
public static void setText(TextView tv, CharSequence text) {
if (tv != null) {
if (TextUtils.isEmpty(text)) {
tv.setVisibility(View.GONE);
} else {
tv.setVisibility(View.VISIBLE);
tv.setText(text);
}
}
}
public static void setTextColor(TextView tv, int color) {
if (tv != null) {
tv.setTextColor(color);
}
}
public static void setTextColor(TextView tv, ColorStateList colorStateList) {
if (tv != null) {
tv.setTextColor(colorStateList);
}
}
}
| apache-2.0 |
pokyno/Webtechnologie | Webtechnologie_Opdracht1/src/nl/pietervanberkel/util/ServletListener.java | 504 | package nl.pietervanberkel.util;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import nl.pietervanberkel.model.Model;
@WebListener
public class ServletListener implements ServletContextListener{
@Override
public void contextDestroyed(ServletContextEvent arg0) {
}
@Override
public void contextInitialized(ServletContextEvent sce) {
sce.getServletContext().setAttribute("Model", new Model());
}
}
| apache-2.0 |
misterflud/aoleynikov | chapter_001/src/main/java/ru/job4j/loops/Factorial.java | 343 | package ru.job4j.loops;
/**Counting factorial.
*@author Anton Oleynikov
*@version 1
*/
public class Factorial {
/**
*@param max max
*@return count count
*/
public int fac(int max) {
int count = 1;
for (int i = 2; i <= max; i++) {
count = count * i;
}
return count;
}
} | apache-2.0 |
dbflute-test/dbflute-test-dbms-postgresql | src/main/java/org/docksidestage/postgresql/dbflute/cbean/cq/bs/BsProductStatusCQ.java | 13406 | package org.docksidestage.postgresql.dbflute.cbean.cq.bs;
import java.util.Map;
import org.dbflute.cbean.*;
import org.dbflute.cbean.chelper.*;
import org.dbflute.cbean.coption.*;
import org.dbflute.cbean.cvalue.ConditionValue;
import org.dbflute.cbean.sqlclause.SqlClause;
import org.dbflute.exception.IllegalConditionBeanOperationException;
import org.docksidestage.postgresql.dbflute.cbean.cq.ciq.*;
import org.docksidestage.postgresql.dbflute.cbean.*;
import org.docksidestage.postgresql.dbflute.cbean.cq.*;
/**
* The base condition-query of product_status.
* @author DBFlute(AutoGenerator)
*/
public class BsProductStatusCQ extends AbstractBsProductStatusCQ {
// ===================================================================================
// Attribute
// =========
protected ProductStatusCIQ _inlineQuery;
// ===================================================================================
// Constructor
// ===========
public BsProductStatusCQ(ConditionQuery referrerQuery, SqlClause sqlClause, String aliasName, int nestLevel) {
super(referrerQuery, sqlClause, aliasName, nestLevel);
}
// ===================================================================================
// InlineView/OrClause
// ===================
/**
* Prepare InlineView query. <br>
* {select ... from ... left outer join (select * from product_status) where FOO = [value] ...}
* <pre>
* cb.query().queryMemberStatus().<span style="color: #CC4747">inline()</span>.setFoo...;
* </pre>
* @return The condition-query for InlineView query. (NotNull)
*/
public ProductStatusCIQ inline() {
if (_inlineQuery == null) { _inlineQuery = xcreateCIQ(); }
_inlineQuery.xsetOnClause(false); return _inlineQuery;
}
protected ProductStatusCIQ xcreateCIQ() {
ProductStatusCIQ ciq = xnewCIQ();
ciq.xsetBaseCB(_baseCB);
return ciq;
}
protected ProductStatusCIQ xnewCIQ() {
return new ProductStatusCIQ(xgetReferrerQuery(), xgetSqlClause(), xgetAliasName(), xgetNestLevel(), this);
}
/**
* Prepare OnClause query. <br>
* {select ... from ... left outer join product_status on ... and FOO = [value] ...}
* <pre>
* cb.query().queryMemberStatus().<span style="color: #CC4747">on()</span>.setFoo...;
* </pre>
* @return The condition-query for OnClause query. (NotNull)
* @throws IllegalConditionBeanOperationException When this condition-query is base query.
*/
public ProductStatusCIQ on() {
if (isBaseQuery()) { throw new IllegalConditionBeanOperationException("OnClause for local table is unavailable!"); }
ProductStatusCIQ inlineQuery = inline(); inlineQuery.xsetOnClause(true); return inlineQuery;
}
// ===================================================================================
// Query
// =====
protected ConditionValue _productStatusCode;
public ConditionValue xdfgetProductStatusCode()
{ if (_productStatusCode == null) { _productStatusCode = nCV(); }
return _productStatusCode; }
protected ConditionValue xgetCValueProductStatusCode() { return xdfgetProductStatusCode(); }
public Map<String, ProductCQ> xdfgetProductStatusCode_ExistsReferrer_ProductList() { return xgetSQueMap("productStatusCode_ExistsReferrer_ProductList"); }
public String keepProductStatusCode_ExistsReferrer_ProductList(ProductCQ sq) { return xkeepSQue("productStatusCode_ExistsReferrer_ProductList", sq); }
public Map<String, ProductCQ> xdfgetProductStatusCode_NotExistsReferrer_ProductList() { return xgetSQueMap("productStatusCode_NotExistsReferrer_ProductList"); }
public String keepProductStatusCode_NotExistsReferrer_ProductList(ProductCQ sq) { return xkeepSQue("productStatusCode_NotExistsReferrer_ProductList", sq); }
public Map<String, ProductCQ> xdfgetProductStatusCode_SpecifyDerivedReferrer_ProductList() { return xgetSQueMap("productStatusCode_SpecifyDerivedReferrer_ProductList"); }
public String keepProductStatusCode_SpecifyDerivedReferrer_ProductList(ProductCQ sq) { return xkeepSQue("productStatusCode_SpecifyDerivedReferrer_ProductList", sq); }
public Map<String, ProductCQ> xdfgetProductStatusCode_QueryDerivedReferrer_ProductList() { return xgetSQueMap("productStatusCode_QueryDerivedReferrer_ProductList"); }
public String keepProductStatusCode_QueryDerivedReferrer_ProductList(ProductCQ sq) { return xkeepSQue("productStatusCode_QueryDerivedReferrer_ProductList", sq); }
public Map<String, Object> xdfgetProductStatusCode_QueryDerivedReferrer_ProductListParameter() { return xgetSQuePmMap("productStatusCode_QueryDerivedReferrer_ProductList"); }
public String keepProductStatusCode_QueryDerivedReferrer_ProductListParameter(Object pm) { return xkeepSQuePm("productStatusCode_QueryDerivedReferrer_ProductList", pm); }
/**
* Add order-by as ascend. <br>
* (商品ステータスコード)product_status_code: {PK, NotNull, bpchar(3)}
* @return this. (NotNull)
*/
public BsProductStatusCQ addOrderBy_ProductStatusCode_Asc() { regOBA("product_status_code"); return this; }
/**
* Add order-by as descend. <br>
* (商品ステータスコード)product_status_code: {PK, NotNull, bpchar(3)}
* @return this. (NotNull)
*/
public BsProductStatusCQ addOrderBy_ProductStatusCode_Desc() { regOBD("product_status_code"); return this; }
protected ConditionValue _productStatusName;
public ConditionValue xdfgetProductStatusName()
{ if (_productStatusName == null) { _productStatusName = nCV(); }
return _productStatusName; }
protected ConditionValue xgetCValueProductStatusName() { return xdfgetProductStatusName(); }
/**
* Add order-by as ascend. <br>
* product_status_name: {NotNull, varchar(50)}
* @return this. (NotNull)
*/
public BsProductStatusCQ addOrderBy_ProductStatusName_Asc() { regOBA("product_status_name"); return this; }
/**
* Add order-by as descend. <br>
* product_status_name: {NotNull, varchar(50)}
* @return this. (NotNull)
*/
public BsProductStatusCQ addOrderBy_ProductStatusName_Desc() { regOBD("product_status_name"); return this; }
protected ConditionValue _displayOrder;
public ConditionValue xdfgetDisplayOrder()
{ if (_displayOrder == null) { _displayOrder = nCV(); }
return _displayOrder; }
protected ConditionValue xgetCValueDisplayOrder() { return xdfgetDisplayOrder(); }
/**
* Add order-by as ascend. <br>
* display_order: {UQ, NotNull, int4(10)}
* @return this. (NotNull)
*/
public BsProductStatusCQ addOrderBy_DisplayOrder_Asc() { regOBA("display_order"); return this; }
/**
* Add order-by as descend. <br>
* display_order: {UQ, NotNull, int4(10)}
* @return this. (NotNull)
*/
public BsProductStatusCQ addOrderBy_DisplayOrder_Desc() { regOBD("display_order"); return this; }
// ===================================================================================
// SpecifiedDerivedOrderBy
// =======================
/**
* Add order-by for specified derived column as ascend.
* <pre>
* cb.specify().derivedPurchaseList().max(new SubQuery<PurchaseCB>() {
* public void query(PurchaseCB subCB) {
* subCB.specify().columnPurchaseDatetime();
* }
* }, <span style="color: #CC4747">aliasName</span>);
* <span style="color: #3F7E5E">// order by [alias-name] asc</span>
* cb.<span style="color: #CC4747">addSpecifiedDerivedOrderBy_Asc</span>(<span style="color: #CC4747">aliasName</span>);
* </pre>
* @param aliasName The alias name specified at (Specify)DerivedReferrer. (NotNull)
* @return this. (NotNull)
*/
public BsProductStatusCQ addSpecifiedDerivedOrderBy_Asc(String aliasName) { registerSpecifiedDerivedOrderBy_Asc(aliasName); return this; }
/**
* Add order-by for specified derived column as descend.
* <pre>
* cb.specify().derivedPurchaseList().max(new SubQuery<PurchaseCB>() {
* public void query(PurchaseCB subCB) {
* subCB.specify().columnPurchaseDatetime();
* }
* }, <span style="color: #CC4747">aliasName</span>);
* <span style="color: #3F7E5E">// order by [alias-name] desc</span>
* cb.<span style="color: #CC4747">addSpecifiedDerivedOrderBy_Desc</span>(<span style="color: #CC4747">aliasName</span>);
* </pre>
* @param aliasName The alias name specified at (Specify)DerivedReferrer. (NotNull)
* @return this. (NotNull)
*/
public BsProductStatusCQ addSpecifiedDerivedOrderBy_Desc(String aliasName) { registerSpecifiedDerivedOrderBy_Desc(aliasName); return this; }
// ===================================================================================
// Union Query
// ===========
public void reflectRelationOnUnionQuery(ConditionQuery bqs, ConditionQuery uqs) {
}
// ===================================================================================
// Foreign Query
// =============
protected Map<String, Object> xfindFixedConditionDynamicParameterMap(String property) {
return null;
}
// ===================================================================================
// ScalarCondition
// ===============
public Map<String, ProductStatusCQ> xdfgetScalarCondition() { return xgetSQueMap("scalarCondition"); }
public String keepScalarCondition(ProductStatusCQ sq) { return xkeepSQue("scalarCondition", sq); }
// ===================================================================================
// MyselfDerived
// =============
public Map<String, ProductStatusCQ> xdfgetSpecifyMyselfDerived() { return xgetSQueMap("specifyMyselfDerived"); }
public String keepSpecifyMyselfDerived(ProductStatusCQ sq) { return xkeepSQue("specifyMyselfDerived", sq); }
public Map<String, ProductStatusCQ> xdfgetQueryMyselfDerived() { return xgetSQueMap("queryMyselfDerived"); }
public String keepQueryMyselfDerived(ProductStatusCQ sq) { return xkeepSQue("queryMyselfDerived", sq); }
public Map<String, Object> xdfgetQueryMyselfDerivedParameter() { return xgetSQuePmMap("queryMyselfDerived"); }
public String keepQueryMyselfDerivedParameter(Object pm) { return xkeepSQuePm("queryMyselfDerived", pm); }
// ===================================================================================
// MyselfExists
// ============
protected Map<String, ProductStatusCQ> _myselfExistsMap;
public Map<String, ProductStatusCQ> xdfgetMyselfExists() { return xgetSQueMap("myselfExists"); }
public String keepMyselfExists(ProductStatusCQ sq) { return xkeepSQue("myselfExists", sq); }
// ===================================================================================
// MyselfInScope
// =============
public Map<String, ProductStatusCQ> xdfgetMyselfInScope() { return xgetSQueMap("myselfInScope"); }
public String keepMyselfInScope(ProductStatusCQ sq) { return xkeepSQue("myselfInScope", sq); }
// ===================================================================================
// Very Internal
// =============
// very internal (for suppressing warn about 'Not Use Import')
protected String xCB() { return ProductStatusCB.class.getName(); }
protected String xCQ() { return ProductStatusCQ.class.getName(); }
protected String xCHp() { return HpQDRFunction.class.getName(); }
protected String xCOp() { return ConditionOption.class.getName(); }
protected String xMap() { return Map.class.getName(); }
}
| apache-2.0 |
nafae/developer | modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201306/CreativeSetError.java | 4339 | /**
* CreativeSetError.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.axis.v201306;
/**
* Errors relating to creative sets & subclasses.
*/
public class CreativeSetError extends com.google.api.ads.dfp.axis.v201306.ApiError implements java.io.Serializable {
/* The error reason represented by an enum. */
private com.google.api.ads.dfp.axis.v201306.CreativeSetErrorReason reason;
public CreativeSetError() {
}
public CreativeSetError(
java.lang.String fieldPath,
java.lang.String trigger,
java.lang.String errorString,
java.lang.String apiErrorType,
com.google.api.ads.dfp.axis.v201306.CreativeSetErrorReason reason) {
super(
fieldPath,
trigger,
errorString,
apiErrorType);
this.reason = reason;
}
/**
* Gets the reason value for this CreativeSetError.
*
* @return reason * The error reason represented by an enum.
*/
public com.google.api.ads.dfp.axis.v201306.CreativeSetErrorReason getReason() {
return reason;
}
/**
* Sets the reason value for this CreativeSetError.
*
* @param reason * The error reason represented by an enum.
*/
public void setReason(com.google.api.ads.dfp.axis.v201306.CreativeSetErrorReason reason) {
this.reason = reason;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof CreativeSetError)) return false;
CreativeSetError other = (CreativeSetError) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = super.equals(obj) &&
((this.reason==null && other.getReason()==null) ||
(this.reason!=null &&
this.reason.equals(other.getReason())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = super.hashCode();
if (getReason() != null) {
_hashCode += getReason().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(CreativeSetError.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201306", "CreativeSetError"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("reason");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201306", "reason"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201306", "CreativeSetError.Reason"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| apache-2.0 |
BUPTAnderson/apache-hive-2.1.1-src | service/src/java/org/apache/hive/service/cli/operation/SQLOperation.java | 27525 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hive.service.cli.operation;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.PrivilegedExceptionAction;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.CharEncoding;
import org.apache.hadoop.hive.common.metrics.common.Metrics;
import org.apache.hadoop.hive.common.metrics.common.MetricsConstant;
import org.apache.hadoop.hive.common.metrics.common.MetricsFactory;
import org.apache.hadoop.hive.common.metrics.common.MetricsScope;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.Schema;
import org.apache.hadoop.hive.ql.CommandNeedRetryException;
import org.apache.hadoop.hive.ql.Driver;
import org.apache.hadoop.hive.ql.QueryDisplay;
import org.apache.hadoop.hive.ql.QueryState;
import org.apache.hadoop.hive.ql.exec.ExplainTask;
import org.apache.hadoop.hive.ql.exec.FetchTask;
import org.apache.hadoop.hive.ql.exec.Task;
import org.apache.hadoop.hive.ql.log.PerfLogger;
import org.apache.hadoop.hive.ql.metadata.Hive;
import org.apache.hadoop.hive.ql.processors.CommandProcessorResponse;
import org.apache.hadoop.hive.ql.session.OperationLog;
import org.apache.hadoop.hive.ql.session.SessionState;
import org.apache.hadoop.hive.serde.serdeConstants;
import org.apache.hadoop.hive.serde2.SerDe;
import org.apache.hadoop.hive.serde2.SerDeException;
import org.apache.hadoop.hive.serde2.SerDeUtils;
import org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.StructField;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.thrift.ThriftJDBCBinarySerDe;
import org.apache.hadoop.hive.shims.Utils;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hive.service.cli.FetchOrientation;
import org.apache.hive.service.cli.HiveSQLException;
import org.apache.hive.service.cli.OperationState;
import org.apache.hive.service.cli.RowSet;
import org.apache.hive.service.cli.RowSetFactory;
import org.apache.hive.service.cli.TableSchema;
import org.apache.hive.service.cli.session.HiveSession;
import org.apache.hive.service.server.ThreadWithGarbageCleanup;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
/**
* SQLOperation.
*
*/
@SuppressWarnings("deprecation")
public class SQLOperation extends ExecuteStatementOperation {
private Driver driver = null;
private CommandProcessorResponse response;
private TableSchema resultSchema = null;
private Schema mResultSchema = null;
private SerDe serde = null;
private boolean fetchStarted = false;
private volatile MetricsScope currentSQLStateScope;
// Display for WebUI.
private SQLOperationDisplay sqlOpDisplay;
private long queryTimeout;
private ScheduledExecutorService timeoutExecutor;
private final boolean runAsync;
/**
* A map to track query count running by each user
*/
private static Map<String, AtomicInteger> userQueries = new HashMap<String, AtomicInteger>();
private static final String ACTIVE_SQL_USER = MetricsConstant.SQL_OPERATION_PREFIX + "active_user";
public SQLOperation(HiveSession parentSession, String statement, Map<String, String> confOverlay,
boolean runInBackground, long queryTimeout) {
// TODO: call setRemoteUser in ExecuteStatementOperation or higher.
// 调用父类ExecuteStatementOperation的构造方法
super(parentSession, statement, confOverlay, runInBackground);
// beeline调用的时候runAsync是true
this.runAsync = runInBackground;
// queryTimeout默认是0
this.queryTimeout = queryTimeout;
setupSessionIO(parentSession.getSessionState());
try {
sqlOpDisplay = new SQLOperationDisplay(this);
} catch (HiveSQLException e) {
LOG.warn("Error calcluating SQL Operation Display for webui", e);
}
}
@Override
public boolean shouldRunAsync() {
return runAsync;
}
private void setupSessionIO(SessionState sessionState) {
try {
sessionState.in = null; // hive server's session input stream is not used
sessionState.out = new PrintStream(System.out, true, CharEncoding.UTF_8);
sessionState.info = new PrintStream(System.err, true, CharEncoding.UTF_8);
sessionState.err = new PrintStream(System.err, true, CharEncoding.UTF_8);
} catch (UnsupportedEncodingException e) {
LOG.error("Error creating PrintStream", e);
e.printStackTrace();
sessionState.out = null;
sessionState.info = null;
sessionState.err = null;
}
}
/**
* Compile the query and extract metadata
* @param queryState
* @throws HiveSQLException
*/
public void prepare(QueryState queryState) throws HiveSQLException {
// 调用父类的setState方法设置状态
setState(OperationState.RUNNING);
try {
// 实例化driver
driver = new Driver(queryState, getParentSession().getUserName());
// Start the timer thread for cancelling the query when query timeout is reached
// queryTimeout == 0 means no timeout
// 当达到查询超时时启动定时器线程取消查询, 如果queryTimeout为0, 则表示不存在超时
LOG.info("-----******>>> queryTimeout:" + queryTimeout);
if (queryTimeout > 0) {
timeoutExecutor = new ScheduledThreadPoolExecutor(1);
Runnable timeoutTask = new Runnable() {
@Override
public void run() {
try {
LOG.info("Query timed out after: " + queryTimeout
+ " seconds. Cancelling the execution now.");
SQLOperation.this.cancel(OperationState.TIMEDOUT);
} catch (HiveSQLException e) {
LOG.error("Error cancelling the query after timeout: " + queryTimeout + " seconds", e);
} finally {
// Stop
timeoutExecutor.shutdown();
}
}
};
timeoutExecutor.schedule(timeoutTask, queryTimeout, TimeUnit.SECONDS);
}
sqlOpDisplay.setQueryDisplay(driver.getQueryDisplay());
// set the operation handle information in Driver, so that thrift API users
// can use the operation handle they receive, to lookup query information in
// Yarn ATS
// 设置OperationId, 比如: KtahFvbXQYGKzFUH40h5fA
String guid64 = Base64.encodeBase64URLSafeString(getHandle().getHandleIdentifier()
.toTHandleIdentifier().getGuid()).trim();
LOG.info("++++++++>> operationId:" + guid64);
driver.setOperationId(guid64);
// In Hive server mode, we are not able to retry in the FetchTask
// case, when calling fetch queries since execute() has returned.
// For now, we disable the test attempts.
driver.setTryCount(Integer.MAX_VALUE);
// 编译statement, 生成执行计划, 权限校验, 核心的地方
response = driver.compileAndRespond(statement);
if (0 != response.getResponseCode()) {
throw toSQLException("Error while compiling statement", response);
}
// 上面在执行driver的compileAndRespond方法的过程中会设置schema
mResultSchema = driver.getSchema();
// hasResultSet should be true only if the query has a FetchTask
// "explain" is an exception for now
if(driver.getPlan().getFetchTask() != null) {
LOG.info("+++++-----++++> getFetchTask() != null");
//Schema has to be set
if (mResultSchema == null || !mResultSchema.isSetFieldSchemas()) {
throw new HiveSQLException("Error compiling query: Schema and FieldSchema " +
"should be set when query plan has a FetchTask");
}
resultSchema = new TableSchema(mResultSchema);
// 设置hasResultSet为true, 同时设置OperationHandle的hasResultSet为true, OperationHandle这个值是客户端用来判断是否有result的标识位
setHasResultSet(true);
} else {
setHasResultSet(false);
}
// Set hasResultSet true if the plan has ExplainTask
// TODO explain should use a FetchTask for reading
// 判断是不是ExplainTask, 如果是的话将是否含有ResultSet设为true
for (Task<? extends Serializable> task: driver.getPlan().getRootTasks()) {
if (task.getClass() == ExplainTask.class) {
LOG.info("------>>> mResultSchema:" + mResultSchema);
resultSchema = new TableSchema(mResultSchema);
setHasResultSet(true);
break;
}
}
} catch (HiveSQLException e) {
setState(OperationState.ERROR);
throw e;
} catch (Throwable e) {
setState(OperationState.ERROR);
throw new HiveSQLException("Error running query: " + e.toString(), e);
}
}
private void runQuery() throws HiveSQLException {
try {
OperationState opState = getStatus().getState();
// Operation may have been cancelled by another thread
if (opState.isTerminal()) {
LOG.info("Not running the query. Operation is already in terminal state: " + opState
+ ", perhaps cancelled due to query timeout or by another thread.");
return;
}
// In Hive server mode, we are not able to retry in the FetchTask
// case, when calling fetch queries since execute() has returned.
// For now, we disable the test attempts.
driver.setTryCount(Integer.MAX_VALUE);
// 调用Driver的run方法来执行mapreduce Task
response = driver.run();
if (0 != response.getResponseCode()) {
throw toSQLException("Error while processing statement", response);
}
} catch (HiveSQLException e) {
/**
* If the operation was cancelled by another thread, or the execution timed out, Driver#run
* may return a non-zero response code. We will simply return if the operation state is
* CANCELED, TIMEDOUT or CLOSED, otherwise throw an exception
*/
if ((getStatus().getState() == OperationState.CANCELED)
|| (getStatus().getState() == OperationState.TIMEDOUT)
|| (getStatus().getState() == OperationState.CLOSED)) {
return;
} else {
setState(OperationState.ERROR);
throw e;
}
} catch (Throwable e) {
setState(OperationState.ERROR);
throw new HiveSQLException("Error running query: " + e.toString(), e);
}
// 更新状态为finished
setState(OperationState.FINISHED);
}
@Override
public void runInternal() throws HiveSQLException {
// 调用父类方法更新状态
setState(OperationState.PENDING);
// runAsync通过beeline调用的话是true
boolean runAsync = shouldRunAsync();
// runAsync按true处理, hive.server2.async.exec.async.compile默认是false, 所以asyncPrepare是false
final boolean asyncPrepare = runAsync
&& HiveConf.getBoolVar(queryState.getConf(),
HiveConf.ConfVars.HIVE_SERVER2_ASYNC_EXEC_ASYNC_COMPILE);
LOG.info("++++>>>+++>>> runAsync:" + runAsync + ", asyncPrePare:" + asyncPrepare);
// asyncPrepare是false, 所以执行prepare方法, 会对hql进行编译生成执行计划
if (!asyncPrepare) {
prepare(queryState);
}
LOG.info("+++++++ prepare finished!");
// runAsync是true执行else中的逻辑, 即异步执行查询计划
if (!runAsync) {
runQuery();
} else {
// We'll pass ThreadLocals in the background thread from the foreground (handler) thread.
// 1) ThreadLocal Hive object needs to be set in background thread
// 2) The metastore client in Hive is associated with right user.
// 3) Current UGI will get used by metastore when metastore is in embedded mode
Runnable work = new BackgroundWork(getCurrentUGI(), parentSession.getSessionHive(),
SessionState.getPerfLogger(), SessionState.get(), asyncPrepare);
try {
// This submit blocks if no background threads are available to run this operation
// 调用HiveSessionImpl的submitBackgroundOperation方法
Future<?> backgroundHandle = getParentSession().submitBackgroundOperation(work);
// 调用setBackgroundHandle方法将上面的backgroundHandle设置给SQLOperation的backgroundHandle
setBackgroundHandle(backgroundHandle);
} catch (RejectedExecutionException rejected) {
setState(OperationState.ERROR);
throw new HiveSQLException("The background threadpool cannot accept" +
" new task for execution, please retry the operation", rejected);
}
}
}
private final class BackgroundWork implements Runnable {
private final UserGroupInformation currentUGI;
private final Hive parentHive;
private final PerfLogger parentPerfLogger;
private final SessionState parentSessionState;
private final boolean asyncPrepare;
private BackgroundWork(UserGroupInformation currentUGI,
Hive parentHive, PerfLogger parentPerfLogger,
SessionState parentSessionState, boolean asyncPrepare) {
this.currentUGI = currentUGI;
this.parentHive = parentHive;
this.parentPerfLogger = parentPerfLogger;
this.parentSessionState = parentSessionState;
this.asyncPrepare = asyncPrepare;
}
@Override
public void run() {
PrivilegedExceptionAction<Object> doAsAction = new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws HiveSQLException {
Hive.set(parentHive);
// TODO: can this result in cross-thread reuse of session state?
SessionState.setCurrentSessionState(parentSessionState);
PerfLogger.setPerfLogger(parentPerfLogger);
// Set current OperationLog in this async thread for keeping on saving query log.
// 将SQLOperation的OperationLog设置给当前线程
registerCurrentOperationLog();
// 注册当前线程的Context
registerLoggingContext();
try {
// 通过beeline调用时, asyncPrepare是false
if (asyncPrepare) {
prepare(queryState);
}
// 最核心的地方, 调用SQLOperation的runQuery方法
runQuery();
} catch (HiveSQLException e) {
// 调用父类方法设置异常信息
setOperationException(e);
LOG.error("Error running hive query: ", e);
} finally {
// 移除设置的Context信息
unregisterLoggingContext();
// 移除注册在当前线程的OperationLog
unregisterOperationLog();
}
return null;
}
};
try {
currentUGI.doAs(doAsAction);
} catch (Exception e) {
// 调用父类的方法设置异常信息
setOperationException(new HiveSQLException(e));
LOG.error("Error running hive query as user : " + currentUGI.getShortUserName(), e);
}
finally {
/**
* We'll cache the ThreadLocal RawStore object for this background thread for an orderly cleanup
* when this thread is garbage collected later.
* @see org.apache.hive.service.server.ThreadWithGarbageCleanup#finalize()
*/
if (ThreadWithGarbageCleanup.currentThread() instanceof ThreadWithGarbageCleanup) {
ThreadWithGarbageCleanup currentThread =
(ThreadWithGarbageCleanup) ThreadWithGarbageCleanup.currentThread();
currentThread.cacheThreadLocalRawStore();
}
}
}
}
/**
* Returns the current UGI on the stack
* @param opConfig
* @return UserGroupInformation
* @throws HiveSQLException
*/
private UserGroupInformation getCurrentUGI() throws HiveSQLException {
try {
return Utils.getUGI();
} catch (Exception e) {
throw new HiveSQLException("Unable to get current user", e);
}
}
private void registerCurrentOperationLog() {
if (isOperationLogEnabled) {
if (operationLog == null) {
LOG.warn("Failed to get current OperationLog object of Operation: " +
getHandle().getHandleIdentifier());
isOperationLogEnabled = false;
return;
}
OperationLog.setCurrentOperationLog(operationLog);
}
}
private synchronized void cleanup(OperationState state) throws HiveSQLException {
setState(state);
if (shouldRunAsync()) {
Future<?> backgroundHandle = getBackgroundHandle();
if (backgroundHandle != null) {
boolean success = backgroundHandle.cancel(true);
if (success) {
LOG.info("The running operation has been successfully interrupted.");
}
}
}
if (driver != null) {
driver.close();
driver.destroy();
}
driver = null;
SessionState ss = SessionState.get();
if (ss == null) {
LOG.warn("Operation seems to be in invalid state, SessionState is null");
} else {
ss.deleteTmpOutputFile();
ss.deleteTmpErrOutputFile();
}
// Shutdown the timeout thread if any, while closing this operation
if ((timeoutExecutor != null) && (state != OperationState.TIMEDOUT) && (state.isTerminal())) {
timeoutExecutor.shutdownNow();
}
}
@Override
public void cancel(OperationState stateAfterCancel) throws HiveSQLException {
cleanup(stateAfterCancel);
cleanupOperationLog();
}
@Override
public void close() throws HiveSQLException {
cleanup(OperationState.CLOSED);
cleanupOperationLog();
}
@Override
public TableSchema getResultSetSchema() throws HiveSQLException {
// Since compilation is always a blocking RPC call, and schema is ready after compilation,
// we can return when are in the RUNNING state.
assertState(new ArrayList<OperationState>(Arrays.asList(OperationState.RUNNING,
OperationState.FINISHED)));
if (resultSchema == null) {
resultSchema = new TableSchema(driver.getSchema());
}
return resultSchema;
}
private transient final List<Object> convey = new ArrayList<Object>();
@Override
public RowSet getNextRowSet(FetchOrientation orientation, long maxRows)
throws HiveSQLException {
validateDefaultFetchOrientation(orientation);
assertState(new ArrayList<OperationState>(Arrays.asList(OperationState.FINISHED)));
FetchTask fetchTask = driver.getFetchTask();
boolean isBlobBased = false;
if (fetchTask != null && fetchTask.getWork().isUsingThriftJDBCBinarySerDe()) {
// Just fetch one blob if we've serialized thrift objects in final tasks
maxRows = 1;
isBlobBased = true;
}
driver.setMaxRows((int) maxRows);
RowSet rowSet = RowSetFactory.create(resultSchema, getProtocolVersion(), isBlobBased);
try {
/* if client is requesting fetch-from-start and its not the first time reading from this operation
* then reset the fetch position to beginning
*/
if (orientation.equals(FetchOrientation.FETCH_FIRST) && fetchStarted) {
driver.resetFetch();
}
fetchStarted = true;
driver.setMaxRows((int) maxRows);
if (driver.getResults(convey)) {
return decode(convey, rowSet);
}
return rowSet;
} catch (IOException e) {
throw new HiveSQLException(e);
} catch (CommandNeedRetryException e) {
throw new HiveSQLException(e);
} catch (Exception e) {
throw new HiveSQLException(e);
} finally {
convey.clear();
}
}
@Override
public String getTaskStatus() throws HiveSQLException {
if (driver != null) {
List<QueryDisplay.TaskDisplay> statuses = driver.getQueryDisplay().getTaskDisplays();
if (statuses != null) {
ByteArrayOutputStream out = null;
try {
ObjectMapper mapper = new ObjectMapper();
out = new ByteArrayOutputStream();
mapper.writeValue(out, statuses);
return out.toString("UTF-8");
} catch (JsonGenerationException e) {
throw new HiveSQLException(e);
} catch (JsonMappingException e) {
throw new HiveSQLException(e);
} catch (IOException e) {
throw new HiveSQLException(e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
throw new HiveSQLException(e);
}
}
}
}
}
// Driver not initialized
return null;
}
private RowSet decode(List<Object> rows, RowSet rowSet) throws Exception {
if (driver.isFetchingTable()) {
return prepareFromRow(rows, rowSet);
}
return decodeFromString(rows, rowSet);
}
// already encoded to thrift-able object in ThriftFormatter
private RowSet prepareFromRow(List<Object> rows, RowSet rowSet) throws Exception {
for (Object row : rows) {
rowSet.addRow((Object[]) row);
}
return rowSet;
}
private RowSet decodeFromString(List<Object> rows, RowSet rowSet)
throws SQLException, SerDeException {
getSerDe();
StructObjectInspector soi = (StructObjectInspector) serde.getObjectInspector();
List<? extends StructField> fieldRefs = soi.getAllStructFieldRefs();
Object[] deserializedFields = new Object[fieldRefs.size()];
Object rowObj;
ObjectInspector fieldOI;
int protocol = getProtocolVersion().getValue();
for (Object rowString : rows) {
try {
rowObj = serde.deserialize(new BytesWritable(((String)rowString).getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) {
throw new SerDeException(e);
}
for (int i = 0; i < fieldRefs.size(); i++) {
StructField fieldRef = fieldRefs.get(i);
fieldOI = fieldRef.getFieldObjectInspector();
Object fieldData = soi.getStructFieldData(rowObj, fieldRef);
deserializedFields[i] = SerDeUtils.toThriftPayload(fieldData, fieldOI, protocol);
}
rowSet.addRow(deserializedFields);
}
return rowSet;
}
private SerDe getSerDe() throws SQLException {
if (serde != null) {
return serde;
}
try {
List<FieldSchema> fieldSchemas = mResultSchema.getFieldSchemas();
StringBuilder namesSb = new StringBuilder();
StringBuilder typesSb = new StringBuilder();
if (fieldSchemas != null && !fieldSchemas.isEmpty()) {
for (int pos = 0; pos < fieldSchemas.size(); pos++) {
if (pos != 0) {
namesSb.append(",");
typesSb.append(",");
}
namesSb.append(fieldSchemas.get(pos).getName());
typesSb.append(fieldSchemas.get(pos).getType());
}
}
String names = namesSb.toString();
String types = typesSb.toString();
serde = new LazySimpleSerDe();
Properties props = new Properties();
if (names.length() > 0) {
LOG.debug("Column names: " + names);
props.setProperty(serdeConstants.LIST_COLUMNS, names);
}
if (types.length() > 0) {
LOG.debug("Column types: " + types);
props.setProperty(serdeConstants.LIST_COLUMN_TYPES, types);
}
SerDeUtils.initializeSerDe(serde, new HiveConf(), props, null);
} catch (Exception ex) {
ex.printStackTrace();
throw new SQLException("Could not create ResultSet: " + ex.getMessage(), ex);
}
return serde;
}
/**
* Get summary information of this SQLOperation for display in WebUI.
*/
public SQLOperationDisplay getSQLOperationDisplay() {
return sqlOpDisplay;
}
@Override
protected void onNewState(OperationState state, OperationState prevState) {
super.onNewState(state, prevState);
currentSQLStateScope = setMetrics(currentSQLStateScope, MetricsConstant.SQL_OPERATION_PREFIX,
MetricsConstant.COMPLETED_SQL_OPERATION_PREFIX, state);
Metrics metrics = MetricsFactory.getInstance();
if (metrics != null) {
try {
// New state is changed to running from something else (user is active)
if (state == OperationState.RUNNING && prevState != state) {
incrementUserQueries(metrics);
}
// New state is not running (user not active) any more
if (prevState == OperationState.RUNNING && prevState != state) {
decrementUserQueries(metrics);
}
} catch (IOException e) {
LOG.warn("Error metrics", e);
}
}
if (state == OperationState.FINISHED || state == OperationState.CANCELED || state == OperationState.ERROR) {
//update runtime
sqlOpDisplay.setRuntime(getOperationComplete() - getOperationStart());
}
if (state == OperationState.CLOSED) {
sqlOpDisplay.closed();
} else {
//CLOSED state not interesting, state before (FINISHED, ERROR) is.
sqlOpDisplay.updateState(state);
}
}
private void incrementUserQueries(Metrics metrics) throws IOException {
String username = parentSession.getUserName();
if (username != null) {
synchronized (userQueries) {
AtomicInteger count = userQueries.get(username);
if (count == null) {
count = new AtomicInteger(0);
AtomicInteger prev = userQueries.put(username, count);
if (prev == null) {
metrics.incrementCounter(ACTIVE_SQL_USER);
} else {
count = prev;
}
}
count.incrementAndGet();
}
}
}
private void decrementUserQueries(Metrics metrics) throws IOException {
String username = parentSession.getUserName();
if (username != null) {
synchronized (userQueries) {
AtomicInteger count = userQueries.get(username);
if (count != null && count.decrementAndGet() <= 0) {
metrics.decrementCounter(ACTIVE_SQL_USER);
userQueries.remove(username);
}
}
}
}
public String getExecutionEngine() {
return queryState.getConf().getVar(HiveConf.ConfVars.HIVE_EXECUTION_ENGINE);
}
}
| apache-2.0 |
Buble1981/MyDroolsFork | drools-compiler/src/main/java/org/drools/compiler/reteoo/compiled/ObjectTypeNodeCompiler.java | 7672 | package org.drools.compiler.reteoo.compiled;
import org.drools.core.base.ClassObjectType;
import org.drools.core.base.ValueType;
import org.drools.compiler.compiler.PackageBuilder;
import org.drools.compiler.compiler.PackageRegistry;
import org.drools.compiler.lang.descr.PackageDescr;
import org.drools.core.reteoo.ObjectTypeNode;
import org.drools.core.reteoo.compiled.AssertHandler;
import org.drools.core.reteoo.compiled.CompiledNetwork;
import org.drools.core.reteoo.compiled.DeclarationsHandler;
import org.drools.core.reteoo.compiled.HashedAlphasDeclaration;
import org.drools.core.reteoo.compiled.ObjectTypeNodeParser;
import org.drools.core.reteoo.compiled.SetNodeReferenceHandler;
import org.drools.compiler.rule.builder.dialect.java.JavaDialect;
import java.util.Collection;
/**
* todo: document
*/
public class ObjectTypeNodeCompiler {
private static final String NEWLINE = "\n";
private static final String PACKAGE_NAME = "org.drools.core.reteoo.compiled";
private static final String BINARY_PACKAGE_NAME = PACKAGE_NAME.replace('.', '/');
/**
* This field hold the fully qualified class name that the {@link ObjectTypeNode} is representing.
*/
private String className;
/**
* This field will hold the "simple" name of the generated class
*/
private String generatedClassSimpleName;
/**
* OTN we are creating a compiled network for
*/
private ObjectTypeNode objectTypeNode;
private StringBuilder builder = new StringBuilder();
private ObjectTypeNodeCompiler(ObjectTypeNode objectTypeNode) {
this.objectTypeNode = objectTypeNode;
ClassObjectType classObjectType = (ClassObjectType) objectTypeNode.getObjectType();
this.className = classObjectType.getClassName();
generatedClassSimpleName = "Compiled" + classObjectType.getClassName().replace('.', '_') + "Network";
}
private String generateSource() {
createClassDeclaration();
ObjectTypeNodeParser parser = new ObjectTypeNodeParser(objectTypeNode);
// create declarations
DeclarationsHandler declarations = new DeclarationsHandler(builder);
parser.accept(declarations);
// we need the hashed declarations when creating the constructor
Collection<HashedAlphasDeclaration> hashedAlphaDeclarations = declarations.getHashedAlphaDeclarations();
createConstructor(hashedAlphaDeclarations);
// create set node method
SetNodeReferenceHandler setNode = new SetNodeReferenceHandler(builder);
parser.accept(setNode);
// create assert method
AssertHandler assertHandler = new AssertHandler(builder, className, hashedAlphaDeclarations.size() > 0);
parser.accept(assertHandler);
// end of class
builder.append("}").append(NEWLINE);
return builder.toString();
}
/**
* This method will output the package statement, followed by the opening of the class declaration
*/
private void createClassDeclaration() {
builder.append("package ").append(PACKAGE_NAME).append(";").append(NEWLINE);
builder.append("public class ").append(generatedClassSimpleName).append(" extends ").
append(CompiledNetwork.class.getName()).append("{ ").append(NEWLINE);
}
/**
* Creates the constructor for the generated class. If the hashedAlphaDeclarations is empty, it will just
* output a empty default constructor; if it is not, the constructor will contain code to fill the hash
* alpha maps with the values and node ids.
*
* @param hashedAlphaDeclarations declarations used for creating statements to populate the hashed alpha
* maps for the generate class
*/
private void createConstructor(Collection<HashedAlphasDeclaration> hashedAlphaDeclarations) {
builder.append("public ").append(generatedClassSimpleName).append("() {").append(NEWLINE);
// for each hashed alpha, we need to fill in the map member variable with the hashed values to node Ids
for (HashedAlphasDeclaration declaration : hashedAlphaDeclarations) {
String mapVariableName = declaration.getVariableName();
for (Object hashedValue : declaration.getHashedValues()) {
Object value = hashedValue;
// need to quote value if it is a string
if (declaration.getValueType() == ValueType.STRING_TYPE) {
value = "\"" + value + "\"";
}
String nodeId = declaration.getNodeId(hashedValue);
// generate the map.put(hashedValue, nodeId) call
builder.append(mapVariableName).append(".put(").append(value).append(", ").append(nodeId).append(");");
builder.append(NEWLINE);
}
}
builder.append("}").append(NEWLINE);
}
/**
* Returns the fully qualified name of the generated subclass of {@link CompiledNetwork}
*
* @return name of generated class
*/
private String getName() {
return getPackageName() + "." + generatedClassSimpleName;
}
/**
* Returns the fully qualified binary name of the generated subclass of {@link CompiledNetwork}
*
* @return binary name of generated class
*/
private String getBinaryName() {
return BINARY_PACKAGE_NAME + "." + generatedClassSimpleName + ".class";
}
private String getPackageName() {
return PACKAGE_NAME;
}
/**
* Creates a {@link CompiledNetwork} for the specified {@link ObjectTypeNode}. The {@link PackageBuilder} is used
* to compile the generated source and load the class.
*
* @param pkgBuilder builder used to compile and load class
* @param objectTypeNode OTN we are generating a compiled network for
* @return CompiledNetwork
*/
public static CompiledNetwork compile(PackageBuilder pkgBuilder, ObjectTypeNode objectTypeNode) {
if (objectTypeNode == null) {
throw new IllegalArgumentException("ObjectTypeNode cannot be null!");
}
if (pkgBuilder == null) {
throw new IllegalArgumentException("PackageBuilder cannot be null!");
}
ObjectTypeNodeCompiler compiler = new ObjectTypeNodeCompiler(objectTypeNode);
String packageName = compiler.getPackageName();
PackageRegistry pkgReg = pkgBuilder.getPackageRegistry(packageName);
if (pkgReg == null) {
pkgBuilder.addPackage(new PackageDescr(packageName));
pkgReg = pkgBuilder.getPackageRegistry(packageName);
}
String source = compiler.generateSource();
String generatedSourceName = compiler.getName();
JavaDialect dialect = (JavaDialect) pkgReg.getDialectCompiletimeRegistry().getDialect("java");
dialect.addSrc(compiler.getBinaryName(), source.getBytes());
pkgBuilder.compileAll();
pkgBuilder.updateResults();
CompiledNetwork network;
try {
network = (CompiledNetwork) Class.forName(generatedSourceName, true, pkgBuilder.getRootClassLoader()).newInstance();
} catch (ClassNotFoundException e) {
throw new RuntimeException("This is a bug. Please contact the development team", e);
} catch (IllegalAccessException e) {
throw new RuntimeException("This is a bug. Please contact the development team", e);
} catch (InstantiationException e) {
throw new RuntimeException("This is a bug. Please contact the development team", e);
}
return network;
}
}
| apache-2.0 |
cloudfoundry/cf-java-client | cloudfoundry-client/src/test/java/org/cloudfoundry/client/v2/routemappings/GetRouteMappingRequestTest.java | 1059 | /*
* Copyright 2013-2021 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.cloudfoundry.client.v2.routemappings;
import org.junit.Test;
public final class GetRouteMappingRequestTest {
@Test(expected = IllegalStateException.class)
public void noRouteMappingId() {
GetRouteMappingRequest.builder()
.build();
}
@Test
public void valid() {
GetRouteMappingRequest.builder()
.routeMappingId("route-mapping-id")
.build();
}
}
| apache-2.0 |
hwxiasn/archetypes | ygb/ygb-web/src/main/java/com/qingbo/ginkgo/ygb/web/pojo/BrokerAdd.java | 954 | package com.qingbo.ginkgo.ygb.web.pojo;
import java.io.Serializable;
public class BrokerAdd implements Serializable{
private static final long serialVersionUID = -6153623054869466896L;
//营销机构userId
private Long marketingUserId;
private String customerNum;
private String userName;
private String realName;
public Long getMarketingUserId() {
return marketingUserId;
}
public void setMarketingUserId(Long marketingUserId) {
this.marketingUserId = marketingUserId;
}
public String getCustomerNum() {
return customerNum;
}
public void setCustomerNum(String customerNum) {
this.customerNum = customerNum;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
}
| apache-2.0 |
Praveen2112/presto | core/trino-main/src/test/java/io/trino/operator/scalar/BenchmarkArrayFilter.java | 10904 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.operator.scalar;
import com.google.common.collect.ImmutableList;
import io.trino.jmh.Benchmarks;
import io.trino.metadata.FunctionArgumentDefinition;
import io.trino.metadata.FunctionBinding;
import io.trino.metadata.FunctionListBuilder;
import io.trino.metadata.FunctionMetadata;
import io.trino.metadata.ResolvedFunction;
import io.trino.metadata.Signature;
import io.trino.metadata.SqlScalarFunction;
import io.trino.metadata.TestingFunctionResolution;
import io.trino.operator.DriverYieldSignal;
import io.trino.operator.project.PageProcessor;
import io.trino.spi.Page;
import io.trino.spi.block.Block;
import io.trino.spi.block.BlockBuilder;
import io.trino.spi.type.ArrayType;
import io.trino.spi.type.Type;
import io.trino.spi.type.TypeSignature;
import io.trino.sql.gen.ExpressionCompiler;
import io.trino.sql.relational.CallExpression;
import io.trino.sql.relational.LambdaDefinitionExpression;
import io.trino.sql.relational.RowExpression;
import io.trino.sql.relational.VariableReferenceExpression;
import io.trino.sql.tree.QualifiedName;
import io.trino.type.FunctionType;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OperationsPerInvocation;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import java.lang.invoke.MethodHandle;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import static com.google.common.base.Throwables.throwIfUnchecked;
import static com.google.common.base.Verify.verify;
import static io.trino.memory.context.AggregatedMemoryContext.newSimpleAggregatedMemoryContext;
import static io.trino.metadata.FunctionKind.SCALAR;
import static io.trino.metadata.Signature.typeVariable;
import static io.trino.operator.scalar.BenchmarkArrayFilter.ExactArrayFilterFunction.EXACT_ARRAY_FILTER_FUNCTION;
import static io.trino.spi.function.InvocationConvention.InvocationArgumentConvention.NEVER_NULL;
import static io.trino.spi.function.InvocationConvention.InvocationReturnConvention.FAIL_ON_NULL;
import static io.trino.spi.function.OperatorType.LESS_THAN;
import static io.trino.spi.type.BigintType.BIGINT;
import static io.trino.spi.type.BooleanType.BOOLEAN;
import static io.trino.spi.type.TypeSignature.arrayType;
import static io.trino.spi.type.TypeSignature.functionType;
import static io.trino.spi.type.TypeUtils.readNativeValue;
import static io.trino.sql.analyzer.TypeSignatureProvider.fromTypes;
import static io.trino.sql.relational.Expressions.constant;
import static io.trino.sql.relational.Expressions.field;
import static io.trino.testing.TestingConnectorSession.SESSION;
import static io.trino.util.Reflection.methodHandle;
import static java.lang.Boolean.TRUE;
@SuppressWarnings("MethodMayBeStatic")
@State(Scope.Thread)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(2)
@Warmup(iterations = 10, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 10, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@BenchmarkMode(Mode.AverageTime)
public class BenchmarkArrayFilter
{
private static final int POSITIONS = 100_000;
private static final int ARRAY_SIZE = 4;
private static final int NUM_TYPES = 1;
private static final List<Type> TYPES = ImmutableList.of(BIGINT);
static {
verify(NUM_TYPES == TYPES.size());
}
@Benchmark
@OperationsPerInvocation(POSITIONS * ARRAY_SIZE * NUM_TYPES)
public List<Optional<Page>> benchmark(BenchmarkData data)
{
return ImmutableList.copyOf(
data.getPageProcessor().process(
SESSION,
new DriverYieldSignal(),
newSimpleAggregatedMemoryContext().newLocalMemoryContext(PageProcessor.class.getSimpleName()),
data.getPage()));
}
@SuppressWarnings("FieldMayBeFinal")
@State(Scope.Thread)
public static class BenchmarkData
{
@Param({"filter", "exact_filter"})
private String name = "filter";
private Page page;
private PageProcessor pageProcessor;
@Setup
public void setup()
{
TestingFunctionResolution functionResolution = new TestingFunctionResolution()
.addFunctions(new FunctionListBuilder().function(EXACT_ARRAY_FILTER_FUNCTION).getFunctions());
ExpressionCompiler compiler = functionResolution.getExpressionCompiler();
ImmutableList.Builder<RowExpression> projectionsBuilder = ImmutableList.builder();
Block[] blocks = new Block[TYPES.size()];
for (int i = 0; i < TYPES.size(); i++) {
Type elementType = TYPES.get(i);
ArrayType arrayType = new ArrayType(elementType);
ResolvedFunction resolvedFunction = functionResolution.resolveFunction(
QualifiedName.of(name),
fromTypes(arrayType, new FunctionType(ImmutableList.of(BIGINT), BOOLEAN)));
ResolvedFunction lessThan = functionResolution.resolveOperator(LESS_THAN, ImmutableList.of(BIGINT, BIGINT));
projectionsBuilder.add(new CallExpression(resolvedFunction, ImmutableList.of(
field(0, arrayType),
new LambdaDefinitionExpression(
ImmutableList.of(BIGINT),
ImmutableList.of("x"),
new CallExpression(lessThan, ImmutableList.of(constant(0L, BIGINT), new VariableReferenceExpression("x", BIGINT)))))));
blocks[i] = createChannel(POSITIONS, ARRAY_SIZE, arrayType);
}
ImmutableList<RowExpression> projections = projectionsBuilder.build();
pageProcessor = compiler.compilePageProcessor(Optional.empty(), projections).get();
page = new Page(blocks);
}
private static Block createChannel(int positionCount, int arraySize, ArrayType arrayType)
{
BlockBuilder blockBuilder = arrayType.createBlockBuilder(null, positionCount);
for (int position = 0; position < positionCount; position++) {
BlockBuilder entryBuilder = blockBuilder.beginBlockEntry();
for (int i = 0; i < arraySize; i++) {
if (arrayType.getElementType().getJavaType() == long.class) {
arrayType.getElementType().writeLong(entryBuilder, ThreadLocalRandom.current().nextLong());
}
else {
throw new UnsupportedOperationException();
}
}
blockBuilder.closeEntry();
}
return blockBuilder.build();
}
public PageProcessor getPageProcessor()
{
return pageProcessor;
}
public Page getPage()
{
return page;
}
}
public static void main(String[] args)
throws Exception
{
// assure the benchmarks are valid before running
BenchmarkData data = new BenchmarkData();
data.setup();
new BenchmarkArrayFilter().benchmark(data);
Benchmarks.benchmark(BenchmarkArrayFilter.class).run();
}
public static final class ExactArrayFilterFunction
extends SqlScalarFunction
{
public static final ExactArrayFilterFunction EXACT_ARRAY_FILTER_FUNCTION = new ExactArrayFilterFunction();
private static final MethodHandle METHOD_HANDLE = methodHandle(ExactArrayFilterFunction.class, "filter", Type.class, Block.class, MethodHandle.class);
private ExactArrayFilterFunction()
{
super(new FunctionMetadata(
new Signature(
"exact_filter",
ImmutableList.of(typeVariable("T")),
ImmutableList.of(),
arrayType(new TypeSignature("T")),
ImmutableList.of(
arrayType(new TypeSignature("T")),
functionType(new TypeSignature("T"), BOOLEAN.getTypeSignature())),
false),
false,
ImmutableList.of(
new FunctionArgumentDefinition(false),
new FunctionArgumentDefinition(false)),
false,
false,
"return array containing elements that match the given predicate",
SCALAR));
}
@Override
protected ScalarFunctionImplementation specialize(FunctionBinding functionBinding)
{
Type type = functionBinding.getTypeVariable("T");
return new ChoicesScalarFunctionImplementation(
functionBinding,
FAIL_ON_NULL,
ImmutableList.of(NEVER_NULL, NEVER_NULL),
METHOD_HANDLE.bindTo(type));
}
public static Block filter(Type type, Block block, MethodHandle function)
{
int positionCount = block.getPositionCount();
BlockBuilder resultBuilder = type.createBlockBuilder(null, positionCount);
for (int position = 0; position < positionCount; position++) {
Long input = (Long) readNativeValue(type, block, position);
Boolean keep;
try {
keep = (Boolean) function.invokeExact(input);
}
catch (Throwable t) {
throwIfUnchecked(t);
throw new RuntimeException(t);
}
if (TRUE.equals(keep)) {
block.writePositionTo(position, resultBuilder);
}
}
return resultBuilder.build();
}
}
}
| apache-2.0 |
Daniel-Dos/Java-Design-Patterns | src/StructuralPatterns/ProxyPatterns/ProxyClasses/Proxy.java | 448 | package StructuralPatterns.ProxyPatterns.ProxyClasses;
import StructuralPatterns.ProxyPatterns.OriginalClasses.ConcreteSubject;
import StructuralPatterns.ProxyPatterns.OriginalClasses.Subject;
public class Proxy extends Subject {
ConcreteSubject cs;
@Override
public void doSomeWork() {
System.out.println("Proxy call happening now");
// Lazy initizalization
if(cs == null) {
cs = new ConcreteSubject();
}
cs.doSomeWork();
}
}
| apache-2.0 |
alexcaisenchuan/FunWeibo | src/com/alex/common/model/GeoPos.java | 1134 | package com.alex.common.model;
import com.baidu.platform.comapi.basestruct.GeoPoint;
/**
* 地理位置的重新封装
* @author caisenchuan
*/
public class GeoPos extends GeoPoint{
/*--------------------------
* 常量
*-------------------------*/
/*--------------------------
* 自定义类型
*-------------------------*/
/*--------------------------
* 成员变量
*-------------------------*/
/*--------------------------
* public方法
*-------------------------*/
/**
* 直接使用double型的经纬度进行构造
* @param lat
* @param lon
*/
public GeoPos(double lat, double lon) {
super((int)(lat * 1E6), (int)(lon * 1E6));
}
/*--------------------------
* protected、packet方法
*-------------------------*/
/*--------------------------
* private方法
*-------------------------*/
/**
* 使用int型的经纬度进行构造,单位是微度 (度 * 1E6)
* @param arg0
* @param arg1
*/
private GeoPos(int lat, int lon) {
super(lat, lon);
}
}
| apache-2.0 |
lesaint/experimenting-annotation-processing | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation2/Class_039.java | 145 | package fr.javatronic.blog.massive.annotation2;
import fr.javatronic.blog.processor.Annotation_002;
@Annotation_002
public class Class_039 {
}
| apache-2.0 |
rfellows/pentaho-kettle | engine/src/org/pentaho/di/trans/steps/userdefinedjavaclass/TransformClassBase.java | 20128 | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.trans.steps.userdefinedjavaclass;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.pentaho.di.core.BlockingRowSet;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.ResultFile;
import org.pentaho.di.core.RowSet;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleRowException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.row.RowDataUtil;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.row.value.ValueMetaFactory;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepData.StepExecutionStatus;
import org.pentaho.di.trans.step.RowListener;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepIOMeta;
import org.pentaho.di.trans.step.StepIOMetaInterface;
import org.pentaho.di.trans.step.StepListener;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.pentaho.di.trans.step.errorhandling.Stream;
import org.pentaho.di.trans.step.errorhandling.StreamIcon;
import org.pentaho.di.trans.step.errorhandling.StreamInterface.StreamType;
import org.pentaho.di.trans.steps.userdefinedjavaclass.UserDefinedJavaClassMeta.FieldInfo;
import org.pentaho.di.www.SocketRepository;
public abstract class TransformClassBase {
private static Class<?> PKG = UserDefinedJavaClassMeta.class; // for i18n purposes, needed by Translator2!!
protected boolean first = true;
protected boolean updateRowMeta = true;
protected UserDefinedJavaClass parent;
protected UserDefinedJavaClassMeta meta;
protected UserDefinedJavaClassData data;
public TransformClassBase( UserDefinedJavaClass parent, UserDefinedJavaClassMeta meta,
UserDefinedJavaClassData data ) throws KettleStepException {
this.parent = parent;
this.meta = meta;
this.data = data;
try {
data.inputRowMeta = getTransMeta().getPrevStepFields( getStepMeta() ).clone();
data.outputRowMeta = getTransMeta().getThisStepFields( getStepMeta(), null, data.inputRowMeta.clone() );
data.parameterMap = new HashMap<String, String>();
for ( UsageParameter par : meta.getUsageParameters() ) {
if ( par.tag != null && par.value != null ) {
data.parameterMap.put( par.tag, par.value );
}
}
data.infoMap = new HashMap<String, String>();
for ( StepDefinition stepDefinition : meta.getInfoStepDefinitions() ) {
if ( stepDefinition.tag != null
&& stepDefinition.stepMeta != null && stepDefinition.stepMeta.getName() != null ) {
data.infoMap.put( stepDefinition.tag, stepDefinition.stepMeta.getName() );
}
}
data.targetMap = new HashMap<String, String>();
for ( StepDefinition stepDefinition : meta.getTargetStepDefinitions() ) {
if ( stepDefinition.tag != null
&& stepDefinition.stepMeta != null && stepDefinition.stepMeta.getName() != null ) {
data.targetMap.put( stepDefinition.tag, stepDefinition.stepMeta.getName() );
}
}
} catch ( KettleStepException e ) {
e.printStackTrace();
throw e;
}
}
public void addResultFile( ResultFile resultFile ) {
parent.addResultFileImpl( resultFile );
}
public void addRowListener( RowListener rowListener ) {
parent.addRowListenerImpl( rowListener );
}
public void addStepListener( StepListener stepListener ) {
parent.addStepListenerImpl( stepListener );
}
public boolean checkFeedback( long lines ) {
return parent.checkFeedbackImpl( lines );
}
public void cleanup() {
parent.cleanupImpl();
}
public long decrementLinesRead() {
return parent.decrementLinesReadImpl();
}
public long decrementLinesWritten() {
return parent.decrementLinesWrittenImpl();
}
public void dispose( StepMetaInterface smi, StepDataInterface sdi ) {
parent.disposeImpl( smi, sdi );
}
public RowSet findInputRowSet( String sourceStep ) throws KettleStepException {
return parent.findInputRowSetImpl( sourceStep );
}
public RowSet findInputRowSet( String from, int fromcopy, String to, int tocopy ) {
return parent.findInputRowSetImpl( from, fromcopy, to, tocopy );
}
public RowSet findOutputRowSet( String targetStep ) throws KettleStepException {
return parent.findOutputRowSetImpl( targetStep );
}
public RowSet findOutputRowSet( String from, int fromcopy, String to, int tocopy ) {
return parent.findOutputRowSetImpl( from, fromcopy, to, tocopy );
}
public int getClusterSize() {
return parent.getClusterSizeImpl();
}
public int getCopy() {
return parent.getCopyImpl();
}
public RowMetaInterface getErrorRowMeta() {
return parent.getErrorRowMetaImpl();
}
public long getErrors() {
return parent.getErrorsImpl();
}
public RowMetaInterface getInputRowMeta() {
return parent.getInputRowMetaImpl();
}
public List<RowSet> getInputRowSets() {
return parent.getInputRowSetsImpl();
}
public long getLinesInput() {
return parent.getLinesInputImpl();
}
public long getLinesOutput() {
return parent.getLinesOutputImpl();
}
public long getLinesRead() {
return parent.getLinesReadImpl();
}
public long getLinesRejected() {
return parent.getLinesRejectedImpl();
}
public long getLinesSkipped() {
return parent.getLinesSkippedImpl();
}
public long getLinesUpdated() {
return parent.getLinesUpdatedImpl();
}
public long getLinesWritten() {
return parent.getLinesWrittenImpl();
}
public List<RowSet> getOutputRowSets() {
return parent.getOutputRowSetsImpl();
}
public String getPartitionID() {
return parent.getPartitionIDImpl();
}
public Map<String, BlockingRowSet> getPartitionTargets() {
return parent.getPartitionTargetsImpl();
}
public long getProcessed() {
return parent.getProcessedImpl();
}
public int getRepartitioning() {
return parent.getRepartitioningImpl();
}
public Map<String, ResultFile> getResultFiles() {
return parent.getResultFilesImpl();
}
public Object[] getRow() throws KettleException {
Object[] row = parent.getRowImpl();
if ( updateRowMeta ) {
// Update data.inputRowMeta and data.outputRowMeta
RowMetaInterface inputRowMeta = parent.getInputRowMeta();
data.inputRowMeta = inputRowMeta;
data.outputRowMeta =
inputRowMeta == null ? null : getTransMeta().getThisStepFields(
getStepMeta(), null, inputRowMeta.clone() );
updateRowMeta = false;
}
return row;
}
public Object[] getRowFrom( RowSet rowSet ) throws KettleStepException {
return parent.getRowFromImpl( rowSet );
}
public List<RowListener> getRowListeners() {
return parent.getRowListenersImpl();
}
public long getRuntime() {
return parent.getRuntimeImpl();
}
public int getSlaveNr() {
return parent.getSlaveNrImpl();
}
public SocketRepository getSocketRepository() {
return parent.getSocketRepositoryImpl();
}
public StepExecutionStatus getStatus() {
return parent.getStatusImpl();
}
public String getStatusDescription() {
return parent.getStatusDescriptionImpl();
}
public StepDataInterface getStepDataInterface() {
return parent.getStepDataInterfaceImpl();
}
public String getStepID() {
return parent.getStepIDImpl();
}
public List<StepListener> getStepListeners() {
return parent.getStepListenersImpl();
}
public StepMeta getStepMeta() {
return parent.getStepMetaImpl();
}
public String getStepname() {
return parent.getStepnameImpl();
}
public Trans getTrans() {
return parent.getTransImpl();
}
public TransMeta getTransMeta() {
return parent.getTransMetaImpl();
}
public String getTypeId() {
return parent.getTypeIdImpl();
}
public int getUniqueStepCountAcrossSlaves() {
return parent.getUniqueStepCountAcrossSlavesImpl();
}
public int getUniqueStepNrAcrossSlaves() {
return parent.getUniqueStepNrAcrossSlavesImpl();
}
public String getVariable( String variableName ) {
return parent.getVariableImpl( variableName );
}
public String getVariable( String variableName, String defaultValue ) {
return parent.getVariableImpl( variableName, defaultValue );
}
public long incrementLinesInput() {
return parent.incrementLinesInputImpl();
}
public long incrementLinesOutput() {
return parent.incrementLinesOutputImpl();
}
public long incrementLinesRead() {
return parent.incrementLinesReadImpl();
}
public long incrementLinesRejected() {
return parent.incrementLinesRejectedImpl();
}
public long incrementLinesSkipped() {
return parent.incrementLinesSkippedImpl();
}
public long incrementLinesUpdated() {
return parent.incrementLinesUpdatedImpl();
}
public long incrementLinesWritten() {
return parent.incrementLinesWrittenImpl();
}
public boolean init( StepMetaInterface stepMetaInterface, StepDataInterface stepDataInterface ) {
return parent.initImpl( stepMetaInterface, stepDataInterface );
}
public void initBeforeStart() throws KettleStepException {
parent.initBeforeStartImpl();
}
public boolean isDistributed() {
return parent.isDistributedImpl();
}
public boolean isInitialising() {
return parent.isInitialisingImpl();
}
public boolean isPartitioned() {
return parent.isPartitionedImpl();
}
public boolean isSafeModeEnabled() {
return parent.isSafeModeEnabledImpl();
}
public boolean isStopped() {
return parent.isStoppedImpl();
}
public boolean isUsingThreadPriorityManagment() {
return parent.isUsingThreadPriorityManagmentImpl();
}
public void logBasic( String s ) {
parent.logBasicImpl( s );
}
public void logDebug( String s ) {
parent.logDebugImpl( s );
}
public void logDetailed( String s ) {
parent.logDetailedImpl( s );
}
public void logError( String s ) {
parent.logErrorImpl( s );
}
public void logError( String s, Throwable e ) {
parent.logErrorImpl( s, e );
}
public void logMinimal( String s ) {
parent.logMinimalImpl( s );
}
public void logRowlevel( String s ) {
parent.logRowlevelImpl( s );
}
public void logSummary() {
parent.logSummaryImpl();
}
public void markStart() {
parent.markStartImpl();
}
public void markStop() {
parent.markStopImpl();
}
public void openRemoteInputStepSocketsOnce() throws KettleStepException {
parent.openRemoteInputStepSocketsOnceImpl();
}
public void openRemoteOutputStepSocketsOnce() throws KettleStepException {
parent.openRemoteOutputStepSocketsOnceImpl();
}
public boolean outputIsDone() {
return parent.outputIsDoneImpl();
}
public abstract boolean processRow( StepMetaInterface smi, StepDataInterface sdi ) throws KettleException;
public void putError( RowMetaInterface rowMeta, Object[] row, long nrErrors, String errorDescriptions,
String fieldNames, String errorCodes ) throws KettleStepException {
parent.putErrorImpl( rowMeta, row, nrErrors, errorDescriptions, fieldNames, errorCodes );
}
public void putRow( RowMetaInterface row, Object[] data ) throws KettleStepException {
parent.putRowImpl( row, data );
}
public void putRowTo( RowMetaInterface rowMeta, Object[] row, RowSet rowSet ) throws KettleStepException {
parent.putRowToImpl( rowMeta, row, rowSet );
}
public void removeRowListener( RowListener rowListener ) {
parent.removeRowListenerImpl( rowListener );
}
public int rowsetInputSize() {
return parent.rowsetInputSizeImpl();
}
public int rowsetOutputSize() {
return parent.rowsetOutputSizeImpl();
}
public void safeModeChecking( RowMetaInterface row ) throws KettleRowException {
parent.safeModeCheckingImpl( row );
}
public void setErrors( long errors ) {
parent.setErrorsImpl( errors );
}
public void setInputRowMeta( RowMetaInterface rowMeta ) {
parent.setInputRowMetaImpl( rowMeta );
}
public void setInputRowSets( List<RowSet> inputRowSets ) {
parent.setInputRowSetsImpl( inputRowSets );
}
public void setLinesInput( long newLinesInputValue ) {
parent.setLinesInputImpl( newLinesInputValue );
}
public void setLinesOutput( long newLinesOutputValue ) {
parent.setLinesOutputImpl( newLinesOutputValue );
}
public void setLinesRead( long newLinesReadValue ) {
parent.setLinesReadImpl( newLinesReadValue );
}
public void setLinesRejected( long linesRejected ) {
parent.setLinesRejectedImpl( linesRejected );
}
public void setLinesSkipped( long newLinesSkippedValue ) {
parent.setLinesSkippedImpl( newLinesSkippedValue );
}
public void setLinesUpdated( long newLinesUpdatedValue ) {
parent.setLinesUpdatedImpl( newLinesUpdatedValue );
}
public void setLinesWritten( long newLinesWrittenValue ) {
parent.setLinesWrittenImpl( newLinesWrittenValue );
}
public void setOutputDone() {
parent.setOutputDoneImpl();
}
public void setOutputRowSets( List<RowSet> outputRowSets ) {
parent.setOutputRowSetsImpl( outputRowSets );
}
public void setStepListeners( List<StepListener> stepListeners ) {
parent.setStepListenersImpl( stepListeners );
}
public void setVariable( String variableName, String variableValue ) {
parent.setVariableImpl( variableName, variableValue );
}
public void stopAll() {
parent.stopAllImpl();
}
public void stopRunning( StepMetaInterface stepMetaInterface, StepDataInterface stepDataInterface )
throws KettleException {
parent.stopRunningImpl( stepMetaInterface, stepDataInterface );
}
public String toString() {
return parent.toStringImpl();
}
public static String[] getInfoSteps() {
return null;
}
@SuppressWarnings( "unchecked" )
public static void getFields( boolean clearResultFields, RowMetaInterface row, String originStepname,
RowMetaInterface[] info, StepMeta nextStep, VariableSpace space, List<?> fields ) throws KettleStepException {
if ( clearResultFields ) {
row.clear();
}
for ( FieldInfo fi : (List<FieldInfo>) fields ) {
try {
ValueMetaInterface v = ValueMetaFactory.createValueMeta( fi.name, fi.type );
v.setLength( fi.length );
v.setPrecision( fi.precision );
v.setOrigin( originStepname );
row.addValueMeta( v );
} catch ( Exception e ) {
throw new KettleStepException( e );
}
}
}
public static StepIOMetaInterface getStepIOMeta( UserDefinedJavaClassMeta meta ) {
StepIOMetaInterface ioMeta = new StepIOMeta( true, true, true, false, true, true );
for ( StepDefinition stepDefinition : meta.getInfoStepDefinitions() ) {
ioMeta.addStream( new Stream(
StreamType.INFO, stepDefinition.stepMeta, stepDefinition.description, StreamIcon.INFO, null ) );
}
for ( StepDefinition stepDefinition : meta.getTargetStepDefinitions() ) {
ioMeta.addStream( new Stream(
StreamType.TARGET, stepDefinition.stepMeta, stepDefinition.description, StreamIcon.TARGET, null ) );
}
return ioMeta;
}
public String getParameter( String tag ) {
if ( tag == null ) {
return null;
}
return parent.environmentSubstitute( data.parameterMap.get( tag ) );
}
public RowSet findInfoRowSet( String tag ) throws KettleException {
if ( tag == null ) {
return null;
}
String stepname = data.infoMap.get( tag );
if ( Const.isEmpty( stepname ) ) {
throw new KettleException( BaseMessages.getString(
PKG, "TransformClassBase.Exception.UnableToFindInfoStepNameForTag", tag ) );
}
RowSet rowSet = findInputRowSet( stepname );
if ( rowSet == null ) {
throw new KettleException( BaseMessages.getString(
PKG, "TransformClassBase.Exception.UnableToFindInfoRowSetForStep", stepname ) );
}
return rowSet;
}
public RowSet findTargetRowSet( String tag ) throws KettleException {
if ( tag == null ) {
return null;
}
String stepname = data.targetMap.get( tag );
if ( Const.isEmpty( stepname ) ) {
throw new KettleException( BaseMessages.getString(
PKG, "TransformClassBase.Exception.UnableToFindTargetStepNameForTag", tag ) );
}
RowSet rowSet = findOutputRowSet( stepname );
if ( rowSet == null ) {
throw new KettleException( BaseMessages.getString(
PKG, "TransformClassBase.Exception.UnableToFindTargetRowSetForStep", stepname ) );
}
return rowSet;
}
private final Map<String, FieldHelper> inFieldHelpers = new HashMap<String, FieldHelper>();
private final Map<String, FieldHelper> infoFieldHelpers = new HashMap<String, FieldHelper>();
private final Map<String, FieldHelper> outFieldHelpers = new HashMap<String, FieldHelper>();
public enum Fields {
In, Out, Info;
}
public FieldHelper get( Fields type, String name ) throws KettleStepException {
FieldHelper fh;
switch ( type ) {
case In:
fh = inFieldHelpers.get( name );
if ( fh == null ) {
try {
fh = new FieldHelper( data.inputRowMeta, name );
} catch ( IllegalArgumentException e ) {
throw new KettleStepException( BaseMessages.getString(
PKG, "TransformClassBase.Exception.UnableToFindFieldHelper", type.name(), name ) );
}
inFieldHelpers.put( name, fh );
}
break;
case Out:
fh = outFieldHelpers.get( name );
if ( fh == null ) {
try {
fh = new FieldHelper( data.outputRowMeta, name );
} catch ( IllegalArgumentException e ) {
throw new KettleStepException( BaseMessages.getString(
PKG, "TransformClassBase.Exception.UnableToFindFieldHelper", type.name(), name ) );
}
outFieldHelpers.put( name, fh );
}
break;
case Info:
fh = infoFieldHelpers.get( name );
if ( fh == null ) {
RowMetaInterface rmi = getTransMeta().getPrevInfoFields( getStepname() );
try {
fh = new FieldHelper( rmi, name );
} catch ( IllegalArgumentException e ) {
throw new KettleStepException( BaseMessages.getString(
PKG, "TransformClassBase.Exception.UnableToFindFieldHelper", type.name(), name ) );
}
infoFieldHelpers.put( name, fh );
}
break;
default:
throw new KettleStepException( BaseMessages.getString(
PKG, "TransformClassBase.Exception.InvalidFieldsType", type.name(), name ) );
}
return fh;
}
public Object[] createOutputRow( Object[] inputRow, int outputRowSize ) {
if ( meta.isClearingResultFields() ) {
return RowDataUtil.allocateRowData( outputRowSize );
} else {
return RowDataUtil.createResizedCopy( inputRow, outputRowSize );
}
}
}
| apache-2.0 |
onyxbits/raccoon4 | src/main/java/de/onyxbits/raccoon/appmgr/MyAppsViewBuilder.java | 7560 | /*
* Copyright 2015 Patrick Ahlbrecht
*
* 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 de.onyxbits.raccoon.appmgr;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URI;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import de.onyxbits.raccoon.db.DatabaseManager;
import de.onyxbits.raccoon.db.DatasetEvent;
import de.onyxbits.raccoon.db.DatasetListener;
import de.onyxbits.raccoon.db.DatasetListenerProxy;
import de.onyxbits.raccoon.gui.ButtonBarBuilder;
import de.onyxbits.raccoon.gui.TitleStrip;
import de.onyxbits.raccoon.net.ServerManager;
import de.onyxbits.raccoon.qr.CopyContentAction;
import de.onyxbits.raccoon.qr.QrPanel;
import de.onyxbits.raccoon.repo.AndroidApp;
import de.onyxbits.raccoon.repo.AndroidAppDao;
import de.onyxbits.raccoon.repo.AppGroup;
import de.onyxbits.raccoon.repo.AppGroupDao;
import de.onyxbits.weave.LifecycleManager;
import de.onyxbits.weave.swing.AbstractPanelBuilder;
import de.onyxbits.weave.swing.ActionLocalizer;
import de.onyxbits.weave.swing.WindowToggleAction;
/**
* A browser for listing all the apps in local storage.
*
* @author patrick
*
*/
public class MyAppsViewBuilder extends AbstractPanelBuilder implements
CaretListener, ActionListener, DatasetListener {
public static final String ID = MyAppsViewBuilder.class.getSimpleName();
private JComboBox<AppGroup> groupFilter;
private JTextField nameFilter;
private String lastFilter;
private QrPanel transfer;
private ListViewBuilder listView;
private ListWorker listWorker;
private JButton install;
@Override
protected JPanel assemble() {
listView = new ListViewBuilder();
JScrollPane listScroll = new JScrollPane(listView.build(globals));
listScroll.setPreferredSize(new Dimension(400, 500));
listScroll.getVerticalScrollBar().setUnitIncrement(20);
TitleStrip titleStrip = new TitleStrip(Messages.getString(ID + ".title"),
Messages.getString(ID + ".subTitle"), new ImageIcon(getClass()
.getResource("/icons/appicon.png")));
nameFilter = new JTextField(10);
nameFilter.setMargin(new Insets(2, 2, 2, 2));
nameFilter.addCaretListener(this);
nameFilter.requestFocusInWindow();
groupFilter = new JComboBox<AppGroup>();
groupFilter.addActionListener(this);
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.WEST;
JPanel filterPanel = new JPanel();
filterPanel.setLayout(new GridBagLayout());
gbc.gridx = 0;
gbc.gridy = 0;
filterPanel.add(new JLabel(Messages.getString(ID + ".byname")), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
filterPanel.add(nameFilter, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
filterPanel.add(new JLabel(Messages.getString(ID + ".bygroup")), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
filterPanel.add(groupFilter, gbc);
filterPanel.setBorder(BorderFactory.createTitledBorder(Messages
.getString(ID + ".filter")));
ActionLocalizer al = Messages.getLocalizer();
Action toggle = al.localize(new InvertAction(listView), "invertselection");
Action editGroups = al.localize(
new WindowToggleAction(globals.get(LifecycleManager.class),
GroupEditorBuilder.ID), "editgroups");
install = new JButton(listView.installAction);
install.addActionListener(this);
JPanel actionPanel = new ButtonBarBuilder()
.withVerticalAlignment()
.addButton(editGroups)
.addButton(toggle)
.add(install)
.addButton(listView.exportAction)
.addButton(listView.deleteAction)
.withBorder(
BorderFactory.createTitledBorder(Messages
.getString(ID + ".actions"))).build(globals);
JPanel ret = new JPanel();
ret.setLayout(new GridBagLayout());
transfer = new QrPanel(200);
transfer.withActions(new CopyContentAction(globals, transfer));
String location = globals.get(ServerManager.class)
.serve(new ArrayList<AndroidApp>()).toString();
transfer.setContentString(location);
transfer.setBorder(BorderFactory.createTitledBorder(Messages.getString(ID
+ ".transfer")));
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
gbc.gridwidth = 2;
gbc.insets.bottom = 10;
gbc.anchor = GridBagConstraints.NORTHWEST;
ret.add(titleStrip, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 0;
gbc.weighty = 0;
gbc.gridwidth = 1;
gbc.insets.right = 10;
gbc.insets.left = 5;
ret.add(filterPanel, gbc);
gbc.gridx = 0;
gbc.gridy = 2;
ret.add(actionPanel, gbc);
gbc.gridx = 0;
gbc.gridy = 3;
ret.add(transfer, gbc);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridheight = 3;
gbc.weighty = 1;
gbc.weightx = 1;
gbc.insets.right = 5;
gbc.insets.left = 0;
ret.add(listScroll, gbc);
reloadGroups();
reloadList();
globals.get(DatabaseManager.class).get(AndroidAppDao.class)
.addDataSetListener(new DatasetListenerProxy(this));
globals.get(DatabaseManager.class).get(AppGroupDao.class)
.addDataSetListener(new DatasetListenerProxy(this));
return ret;
}
private void reloadGroups() {
try {
Vector<AppGroup> groups = globals.get(DatabaseManager.class)
.get(AppGroupDao.class).list();
groupFilter.setModel(new DefaultComboBoxModel<AppGroup>(groups));
groupFilter.insertItemAt(null, 0);
groupFilter.setSelectedIndex(0);
}
catch (SQLException e) {
e.printStackTrace();
}
}
protected void reloadList() {
if (listWorker != null) {
listWorker.cancel(true);
}
if (listView != null) {
// Entirely possible that this method gets called without the window being
// assembled -> Silently ignore the request.
listView.clear();
listWorker = new ListWorker(listView, transfer, globals);
listWorker.execute();
}
}
@Override
public void caretUpdate(CaretEvent e) {
String tmp = nameFilter.getText();
if (!tmp.equals(lastFilter)) {
lastFilter = tmp;
URI uri = listView.filter(tmp, (AppGroup) groupFilter.getSelectedItem());
transfer.setContentString(uri.toString());
}
}
@Override
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
if (src == groupFilter) {
URI uri = listView.filter(lastFilter,
(AppGroup) groupFilter.getSelectedItem());
transfer.setContentString(uri.toString());
}
}
@Override
public void onDataSetChange(DatasetEvent event) {
reloadList();
reloadGroups();
}
}
| apache-2.0 |
dx-pbuckley/vavr | vavr/src/test/java/io/vavr/collection/euler/Euler36Test.java | 1790 | /* __ __ __ __ __ ___
* \ \ / / \ \ / / __/
* \ \/ / /\ \ \/ / /
* \____/__/ \__\____/__/.ɪᴏ
* ᶜᵒᵖʸʳᶦᵍʰᵗ ᵇʸ ᵛᵃᵛʳ ⁻ ˡᶦᶜᵉⁿˢᵉᵈ ᵘⁿᵈᵉʳ ᵗʰᵉ ᵃᵖᵃᶜʰᵉ ˡᶦᶜᵉⁿˢᵉ ᵛᵉʳˢᶦᵒⁿ ᵗʷᵒ ᵈᵒᵗ ᶻᵉʳᵒ
*/
package io.vavr.collection.euler;
import io.vavr.collection.CharSeq;
import io.vavr.collection.Stream;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* <strong>Problem 36: Double-base palindromes</strong>
* <p>The decimal number, 585 = 1001001001<sub>2</sub> (binary), is palindromic in both bases.</p>
* <p>Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.</p>
* <p class="info">(Please note that the palindromic number, in either base, may not include leading zeros.)</p>
* See also <a href="https://projecteuler.net/problem=36">projecteuler.net problem 36</a>.
*/
public class Euler36Test {
@Test
public void shouldSolveProblem36() {
assertThat(solve(1000000)).isEqualTo(872187);
}
private static int solve(int n) {
return Stream.range(1, n)
.filter(Euler36Test::isDoubleBasePalindrome)
.sum().intValue();
}
private static boolean isPalindrome(CharSeq seq) {
return seq.dropWhile(c -> c == '0').equals(seq.reverse().dropWhile(c -> c == '0'));
}
private static boolean isDoubleBasePalindrome(int x) {
final CharSeq seq = CharSeq.of(Integer.toString(x));
final CharSeq rev = CharSeq.of(Integer.toBinaryString(x));
return isPalindrome(seq) && isPalindrome(rev);
}
}
| apache-2.0 |
pjworkspace/wscs | wscs-service-provider/src/main/java/com/xxx/market/service/provider/PromotionServiceImpl.java | 13513 | package com.xxx.market.service.provider;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xxx.market.model.Product;
import com.xxx.market.model.ProductSpecItem;
import com.xxx.market.model.Promotion;
import com.xxx.market.model.PromotionSet;
import com.xxx.market.service.api.product.ProductPromotionResultDto;
import com.xxx.market.service.api.ump.PromotionParamDto;
import com.xxx.market.service.api.ump.PromotionResultDto;
import com.xxx.market.service.api.ump.PromotionService;
import com.xxx.market.service.api.ump.PromotionSetResultDto;
import com.xxx.market.service.api.ump.UmpException;
import com.xxx.market.service.base.AbstractServiceImpl;
import com.xxx.market.service.utils.DateTimeUtil;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
@Service("promotionService")
public class PromotionServiceImpl extends AbstractServiceImpl implements PromotionService{
@Override
@Transactional(rollbackFor = UmpException.class)
public void save(Promotion promotion, Long sellerId, String promotionSetItems) throws UmpException {
if(promotion == null || StrKit.isBlank(promotionSetItems) || sellerId == null)
throw new UmpException("保存限时折扣出错:参数不全");
if(promotion.getId() == null){
promotion.setSellerId(sellerId);
promotion.setActive(true);
promotion.save();
}else{
promotion.update();
}
JSONArray jarr = null;
try {
jarr = JSONArray.parseArray(promotionSetItems);
} catch (Exception e) {
throw new UmpException(e.getMessage());
}
if(jarr == null || jarr.size() <=0) throw new UmpException("未设置活动折扣信息");
//需要添加的折扣设置项
List<PromotionSet> promotionAddSets = new ArrayList<PromotionSet>();
//需要更新的折扣设置项
List<PromotionSet> promotionUpdateSets = new ArrayList<PromotionSet>();
//需要删除的折扣设置项
List<PromotionSet> promotionDelSets = new ArrayList<PromotionSet>();
for(int i=0;i<jarr.size();i++){
JSONObject jsonObj = jarr.getJSONObject(i);
if(jsonObj == null
|| jsonObj.getLong("productId") == null
|| jsonObj.getFloat("jianjia") == null
|| jsonObj.getFloat("zhekou") == null
|| jsonObj.getInteger("ptype") == null
|| jsonObj.getFloat("promotion") == null
|| (!"del".equals(jsonObj.getString("opt")) && jsonObj.getFloat("promotion") <=0)) //新增或修改的时候,打折或减价后商品价格必须大于0
throw new UmpException("保存折扣活动,折扣设置项值有误,请检查,打折后的价格必须大于0");
Long promotionSetId = jsonObj.getLong("psetId");
PromotionSet promotionSet = null;
if(promotionSetId == null){
promotionSet = new PromotionSet();
promotionSet.setProductId(jsonObj.getLong("productId"));
promotionSet.setPromotionId(promotion.getId());
promotionSet.setCreated(new Date());
promotionSet.setActive(true);
promotionSet.setPromotionSetJianjia(jsonObj.getFloat("jianjia"));
promotionSet.setPromotionSetZhekou(jsonObj.getFloat("zhekou"));
promotionSet.setPromotionType(jsonObj.getInteger("ptype"));
promotionSet.setPromotionValue(jsonObj.getFloat("promotion"));
promotionSet.setUpdated(new Date());
promotionAddSets.add(promotionSet);
}else{
promotionSet = PromotionSet.dao.findById(promotionSetId);
if(promotionSet == null) throw new UmpException("折扣设置记录不存在");
if("del".equals(jsonObj.getString("opt"))){
promotionDelSets.add(promotionSet);
try {
promotionSet.delete();
} catch (Exception e) {
throw new UmpException(e.getMessage());
}
}
if("updated".equals(jsonObj.getString("opt"))){
promotionSet.setPromotionSetJianjia(jsonObj.getFloat("jianjia"));
promotionSet.setPromotionSetZhekou(jsonObj.getFloat("zhekou"));
promotionSet.setPromotionType(jsonObj.getInteger("ptype"));
promotionSet.setPromotionValue(jsonObj.getFloat("promotion"));
promotionSet.setUpdated(new Date());
promotionUpdateSets.add(promotionSet);
}
}
}
if(promotionDelSets.size()<=0 && promotionAddSets.size() <=0 && promotionUpdateSets.size()<=0)
throw new UmpException("没有设置折扣项数据");
try {
if(promotionAddSets.size() > 0){
Db.batchSave(promotionAddSets, promotionAddSets.size());
}
if(promotionUpdateSets.size() > 0){
Db.batchUpdate(promotionUpdateSets, promotionUpdateSets.size());
}
} catch (Exception e) {
throw new UmpException(e.getMessage());
}
}
@Override
public PromotionResultDto getPromotionInfo(Long id) throws UmpException {
if(id == null) throw new UmpException("获取折扣信息参数错误");
Promotion promotion = Promotion.dao.findById(id);
if(promotion == null) throw new UmpException("折扣信息不存在");
return getPromotionInfo(promotion);
}
@Override
public PromotionResultDto getPromotionInfo(Promotion promotion) throws UmpException {
PromotionResultDto promotionDto = new PromotionResultDto();
promotionDto.setPromotionId(promotion.getId());
promotionDto.setPromotionName(promotion.getPromotionName());
promotionDto.setPromotionTag(promotion.getPromotionTag());
promotionDto.setStartDate(promotion.getStartDate());
promotionDto.setEndDate(promotion.getEndDate());
List<Record> promotionSets = Db.find("select ps.*, p.id as product_id, p.name, p.image, p.price from " + PromotionSet.table + " ps "
+ " left join " + Product.table + " p on ps.product_id=p.id "
+ " where promotion_id=? ", promotion.getId());
List<PromotionSetResultDto> setResultDtos = new ArrayList<PromotionSetResultDto>();
for(Record record : promotionSets){
PromotionSetResultDto psrDto = new PromotionSetResultDto();
psrDto.setId(record.getLong("id"));
psrDto.setProductId(record.getLong("product_id"));
psrDto.setPromotinId(promotion.getId());
psrDto.setProductName(record.getStr("name"));
psrDto.setProductImg(getImageDomain() + record.getStr("image"));
psrDto.setProductPrice(record.getStr("price"));
psrDto.setType(record.getInt("promotion_type"));
psrDto.setJianjia(new BigDecimal(record.getFloat("promotion_set_jianjia")).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue());
psrDto.setZhekou(new BigDecimal(record.getFloat("promotion_set_zhekou")).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue());
psrDto.setPromotionValue(new BigDecimal(record.getFloat("promotion_value")).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue());
setResultDtos.add(psrDto);
}
promotionDto.setPromotionSets(setResultDtos);
return promotionDto;
}
@Override
public Page<PromotionResultDto> list(PromotionParamDto promotionParam) throws UmpException{
if(promotionParam == null || promotionParam.getSellerId() == null)
throw new UmpException("获取限时打折列表数据参数错误");
Page<Promotion> pages = Promotion.dao.paginate(promotionParam.getPageNo(), promotionParam.getPageSize(),
"select * ",
" from " + Promotion.table + " where seller_id=? ", promotionParam.getSellerId());
List<PromotionResultDto> promotionDtos = new ArrayList<PromotionResultDto>();
for(Promotion promotion : pages.getList()){
PromotionResultDto promotionDto = new PromotionResultDto();
promotionDto.setPromotionId(promotion.getId());
promotionDto.setPromotionName(promotion.getPromotionName());
promotionDto.setPromotionTag(promotion.getPromotionTag());
promotionDto.setStartDate(promotion.getStartDate());
promotionDto.setEndDate(promotion.getEndDate());
promotionDtos.add(promotionDto);
}
return new Page<PromotionResultDto> (promotionDtos, promotionParam.getPageNo(), promotionParam.getPageSize(), pages.getTotalPage(), pages.getTotalRow());
}
@Override
public ProductPromotionResultDto getProductPromotion(Product product) throws UmpException {
//查询卖家有效时间范围内的促销活动
List<Promotion> promotions = Promotion.dao.find(
"select * from " + Promotion.table + " where seller_id=? and start_date<=? and end_date>=? ",
product.getSellerId(), new Date(), new Date());
for(Promotion promo : promotions){
PromotionResultDto promotionResultDto=getPromotionInfo(promo);
List<PromotionSetResultDto> promotionSets = promotionResultDto.getPromotionSets();
for(PromotionSetResultDto psrDto : promotionSets){
if(psrDto.getProductId() == product.getId()){
//获取该商品对应的打折数据
ProductPromotionResultDto prodprom = new ProductPromotionResultDto();
prodprom.setPromotionTag(promo.getPromotionTag()); //活动标签
prodprom.setPromotionPrice(psrDto.getPromotionValue().toString());//打折后的价格
if(psrDto.getType() == 1){
prodprom.setPromotionInfo(psrDto.getZhekou() + "折 ");
}else{
prodprom.setPromotionInfo("减¥" + new BigDecimal(psrDto.getJianjia()).setScale(2, BigDecimal.ROUND_HALF_UP));
}
if(promo.getStartDate().after(new Date())){
prodprom.setPromotionTime("还差" + DateTimeUtil.compareDay(promo.getStartDate(), new Date()) + "天开始");
}else {
prodprom.setPromotionTime("剩余" + DateTimeUtil.compareDay(promo.getEndDate(), new Date()) + "天结束");
}
//如果商品是多规格的话,折扣价也是一个范围
String promotionPrice = getProductPromotionPriceSection(product, psrDto);
if(StrKit.notBlank(promotionPrice)) prodprom.setPromotionPrice(promotionPrice);
return prodprom;
}
}
}
return null;
}
@Override
public String getProductPromotionPriceSection(Product product, PromotionSetResultDto promotionSetParam) throws UmpException {
List<ProductSpecItem> productSpecItems = ProductSpecItem.dao.find(" select * from "
+ ProductSpecItem.table + " where product_id=? ", product.getId());
ProductSpecItem prodSpecFirst = null;
if(productSpecItems !=null && productSpecItems.size()>0){
prodSpecFirst = productSpecItems.get(0);
BigDecimal min, max; min = max = prodSpecFirst.getPrice();
for(ProductSpecItem productSpecItem : productSpecItems){
BigDecimal bprice = productSpecItem.getPrice();
if(bprice.compareTo(max)==1){
max= bprice;
}
if(bprice.compareTo(min)==-1){
min= bprice;
}
}
BigDecimal minProm, maxProm; String promotionPrice = "";
if(max.compareTo(min)==0) {
if(promotionSetParam.getType() == 1) {
//打折 保留两位小数,四舍五入
minProm = min.multiply(new BigDecimal(promotionSetParam.getZhekou()/10)).setScale(2, BigDecimal.ROUND_HALF_UP);
}else {
//减价
minProm = min.subtract(new BigDecimal(promotionSetParam.getJianjia())).setScale(2, BigDecimal.ROUND_HALF_UP);
}
promotionPrice = minProm.toString();
}else {
if(promotionSetParam.getType() ==1) {
//打折
minProm = min.multiply(new BigDecimal(promotionSetParam.getZhekou()/10)).setScale(2, BigDecimal.ROUND_HALF_UP);
maxProm = max.multiply(new BigDecimal(promotionSetParam.getZhekou()/10)).setScale(2, BigDecimal.ROUND_HALF_UP);
}else {
//减价
minProm = min.subtract(new BigDecimal(promotionSetParam.getJianjia())).setScale(2, BigDecimal.ROUND_HALF_UP);
maxProm = max.subtract(new BigDecimal(promotionSetParam.getJianjia())).setScale(2, BigDecimal.ROUND_HALF_UP);
}
promotionPrice = minProm.toString() + " ~ " + maxProm.toString();
}
return promotionPrice;
}
return null;
}
@Override
public PromotionSet getProductPromotionSet(Product product) throws UmpException {
List<Promotion> promotions = Promotion.dao.find(
"select * from " + Promotion.table + " where seller_id=? and start_date<=? and end_date>=? ",
product.getSellerId(), new Date(), new Date());
for(Promotion promo : promotions){
List<PromotionSet> promotionSets = PromotionSet.dao.find("select * from " + PromotionSet.table + " where promotion_id=? ", promo.getId());
for(PromotionSet ps : promotionSets){
if(ps.getProductId() == product.getId())
return ps;
}
}
return null;
}
@Override
public String getProductPromotionPrice(Product product, ProductSpecItem specItem) throws UmpException {
PromotionSet promotionSet = getProductPromotionSet(product);
if(promotionSet !=null){
BigDecimal promoPrice = null;
BigDecimal oldPrice = (specItem != null) ? specItem.getPrice() : new BigDecimal(product.getPrice());
if(promotionSet.getPromotionType() == 1){//打折
promoPrice = oldPrice.multiply(new BigDecimal(promotionSet.getPromotionSetZhekou()/10));
}else{
//减价
promoPrice = oldPrice.subtract(new BigDecimal(promotionSet.getPromotionSetJianjia()));
}
if(promoPrice != null) {
promoPrice = promoPrice.setScale(2, BigDecimal.ROUND_HALF_UP);
return promoPrice.toString();
}
}
return null;
}
@Override
public String getProductPromotionPrice(Product product) throws UmpException {
return getProductPromotionPrice(product, null);
}
}
| apache-2.0 |
mapr/hbase | hbase-server/src/main/java/org/apache/hadoop/hbase/procedure/ProcedureMember.java | 9277 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.procedure;
import java.io.Closeable;
import java.io.IOException;
import java.util.Collection;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.hbase.DaemonThreadFactory;
import org.apache.hadoop.hbase.errorhandling.ForeignException;
import com.google.common.collect.MapMaker;
/**
* Process to kick off and manage a running {@link Subprocedure} on a member. This is the
* specialized part of a {@link Procedure} that actually does procedure type-specific work
* and reports back to the coordinator as it completes each phase.
* <p>
* If there is a connection error ({@link #controllerConnectionFailure(String, IOException)}), all
* currently running subprocedures are notify to failed since there is no longer a way to reach any
* other members or coordinators since the rpcs are down.
*/
@InterfaceAudience.Private
public class ProcedureMember implements Closeable {
private static final Log LOG = LogFactory.getLog(ProcedureMember.class);
final static long KEEP_ALIVE_MILLIS_DEFAULT = 5000;
private final SubprocedureFactory builder;
private final ProcedureMemberRpcs rpcs;
private final ConcurrentMap<String,Subprocedure> subprocs =
new MapMaker().concurrencyLevel(4).weakValues().makeMap();
private final ExecutorService pool;
/**
* Instantiate a new ProcedureMember. This is a slave that executes subprocedures.
*
* @param rpcs controller used to send notifications to the procedure coordinator
* @param pool thread pool to submit subprocedures
* @param factory class that creates instances of a subprocedure.
*/
public ProcedureMember(ProcedureMemberRpcs rpcs, ThreadPoolExecutor pool,
SubprocedureFactory factory) {
this.pool = pool;
this.rpcs = rpcs;
this.builder = factory;
}
/**
* Default thread pool for the procedure
*
* @param memberName
* @param procThreads the maximum number of threads to allow in the pool
*/
public static ThreadPoolExecutor defaultPool(String memberName, int procThreads) {
return defaultPool(memberName, procThreads, KEEP_ALIVE_MILLIS_DEFAULT);
}
/**
* Default thread pool for the procedure
*
* @param memberName
* @param procThreads the maximum number of threads to allow in the pool
* @param keepAliveMillis the maximum time (ms) that excess idle threads will wait for new tasks
*/
public static ThreadPoolExecutor defaultPool(String memberName, int procThreads,
long keepAliveMillis) {
return new ThreadPoolExecutor(1, procThreads, keepAliveMillis, TimeUnit.MILLISECONDS,
new SynchronousQueue<Runnable>(),
new DaemonThreadFactory("member: '" + memberName + "' subprocedure-pool"));
}
/**
* Package exposed. Not for public use.
*
* @return reference to the Procedure member's rpcs object
*/
ProcedureMemberRpcs getRpcs() {
return rpcs;
}
/**
* This is separated from execution so that we can detect and handle the case where the
* subprocedure is invalid and inactionable due to bad info (like DISABLED snapshot type being
* sent here)
* @param opName
* @param data
* @return subprocedure
*/
public Subprocedure createSubprocedure(String opName, byte[] data) {
return builder.buildSubprocedure(opName, data);
}
/**
* Submit an subprocedure for execution. This starts the local acquire phase.
* @param subproc the subprocedure to execute.
* @return <tt>true</tt> if the subprocedure was started correctly, <tt>false</tt> if it
* could not be started. In the latter case, the subprocedure holds a reference to
* the exception that caused the failure.
*/
public boolean submitSubprocedure(Subprocedure subproc) {
// if the submitted subprocedure was null, bail.
if (subproc == null) {
LOG.warn("Submitted null subprocedure, nothing to run here.");
return false;
}
String procName = subproc.getName();
if (procName == null || procName.length() == 0) {
LOG.error("Subproc name cannot be null or the empty string");
return false;
}
// make sure we aren't already running an subprocedure of that name
Subprocedure rsub = subprocs.get(procName);
if (rsub != null) {
if (!rsub.isComplete()) {
LOG.error("Subproc '" + procName + "' is already running. Bailing out");
return false;
}
LOG.warn("A completed old subproc " + procName + " is still present, removing");
if (!subprocs.remove(procName, rsub)) {
LOG.error("Another thread has replaced existing subproc '" + procName + "'. Bailing out");
return false;
}
}
LOG.debug("Submitting new Subprocedure:" + procName);
// kick off the subprocedure
try {
if (subprocs.putIfAbsent(procName, subproc) == null) {
this.pool.submit(subproc);
return true;
} else {
LOG.error("Another thread has submitted subproc '" + procName + "'. Bailing out");
return false;
}
} catch (RejectedExecutionException e) {
subprocs.remove(procName, subproc);
// the thread pool is full and we can't run the subprocedure
String msg = "Subprocedure pool is full!";
subproc.cancel(msg, e.getCause());
}
LOG.error("Failed to start subprocedure '" + procName + "'");
return false;
}
/**
* Notification that procedure coordinator has reached the global barrier
* @param procName name of the subprocedure that should start running the in-barrier phase
*/
public void receivedReachedGlobalBarrier(String procName) {
Subprocedure subproc = subprocs.get(procName);
if (subproc == null) {
LOG.warn("Unexpected reached glabal barrier message for Sub-Procedure '" + procName + "'");
return;
}
subproc.receiveReachedGlobalBarrier();
}
/**
* Best effort attempt to close the threadpool via Thread.interrupt.
*/
@Override
public void close() throws IOException {
// have to use shutdown now to break any latch waiting
pool.shutdownNow();
}
/**
* Shutdown the threadpool, and wait for upto timeoutMs millis before bailing
* @param timeoutMs timeout limit in millis
* @return true if successfully, false if bailed due to timeout.
* @throws InterruptedException
*/
boolean closeAndWait(long timeoutMs) throws InterruptedException {
pool.shutdown();
return pool.awaitTermination(timeoutMs, TimeUnit.MILLISECONDS);
}
/**
* The connection to the rest of the procedure group (member and coordinator) has been
* broken/lost/failed. This should fail any interested subprocedure, but not attempt to notify
* other members since we cannot reach them anymore.
* @param message description of the error
* @param cause the actual cause of the failure
*
* TODO i'm tempted to just remove this code completely and treat it like any other abort.
* Implementation wise, if this happens it is a ZK failure which means the RS will abort.
*/
public void controllerConnectionFailure(final String message, final IOException cause) {
Collection<Subprocedure> toNotify = subprocs.values();
LOG.error(message, cause);
for (Subprocedure sub : toNotify) {
// TODO notify the elements, if they aren't null
sub.cancel(message, cause);
}
}
/**
* Send abort to the specified procedure
* @param procName name of the procedure to about
* @param ee exception information about the abort
*/
public void receiveAbortProcedure(String procName, ForeignException ee) {
LOG.debug("Request received to abort procedure " + procName, ee);
// if we know about the procedure, notify it
Subprocedure sub = subprocs.get(procName);
if (sub == null) {
LOG.info("Received abort on procedure with no local subprocedure " + procName +
", ignoring it.", ee);
return; // Procedure has already completed
}
String msg = "Propagating foreign exception to subprocedure " + sub.getName();
LOG.error(msg, ee);
sub.cancel(msg, ee);
}
}
| apache-2.0 |
strengthandwill/collage-lwp | src/pohkahkong/livewallpaper/collage/StartDialog.java | 2776 | package pohkahkong.livewallpaper.collage;
import android.app.Activity;
import android.app.WallpaperManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.Toast;
/**
*
* @author Poh Kah Kong
*
*/
public class StartDialog extends Activity implements OnClickListener {
private final String androidRateUri = "https://play.google.com/store/apps/details?id=pohkahkong.livewallpaper.collage&feature=search_result#?t=W251bGwsMSwxLDEsInBvaGthaGtvbmcubGl2ZXdhbGxwYXBlci5jb2xsYWdlIl0.";
private final String facebookLikeUri = "https://www.facebook.com/CollageLiveWallpaper";
private final String rainbowUri = "https://play.google.com/store/apps/details?id=pohkahkong.game.rainbow&feature=more_from_developer#?t=W251bGwsMSwxLDEwMiwicG9oa2Foa29uZy5nYW1lLnJhaW5ib3ciXQ..";
private LinearLayout applicationLL;
private LinearLayout androidRateLL;
private LinearLayout facebookLikeLL;
private LinearLayout rainbowLL;
private LinearLayout closeLL;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog);
applicationLL = (LinearLayout) findViewById(R.id.applicationLL);
androidRateLL = (LinearLayout) findViewById(R.id.androidRateLL);
facebookLikeLL = (LinearLayout) findViewById(R.id.facebookLikeLL);
rainbowLL = (LinearLayout) findViewById(R.id.rainbowLL);
closeLL = (LinearLayout) findViewById(R.id.closeLL);
applicationLL.setOnClickListener(this);
androidRateLL.setOnClickListener(this);
facebookLikeLL.setOnClickListener(this);
rainbowLL.setOnClickListener(this);
closeLL.setOnClickListener(this);
Toast msg = Toast.makeText(this, "Double tap on the screen to\ndrag or zoom the wallpaper!", Toast.LENGTH_LONG);
msg.show();
}
public void onClick(View view) {
// TODO Auto-generated method stub
if (view.getId()==R.id.applicationLL) {
Intent intent = new Intent();
intent.setAction(WallpaperManager.ACTION_LIVE_WALLPAPER_CHOOSER);
finish();
startActivity(intent);
} else if (view.getId()==R.id.androidRateLL)
goWebSite(androidRateUri);
else if (view.getId()==R.id.facebookLikeLL)
goWebSite(facebookLikeUri);
else if (view.getId()==R.id.rainbowLL)
goWebSite(rainbowUri);
else if (view.getId()==R.id.closeLL)
finish();
}
private void goWebSite(String uriStr) {
Uri uri = Uri.parse(uriStr);
finish();
startActivity( new Intent( Intent.ACTION_VIEW, uri ) );
}
} | apache-2.0 |
liuyb02/async-http-client | client/src/test/java/org/asynchttpclient/NonAsciiContentLengthTest.java | 3574 | /*
* Copyright (c) 2010-2012 Sonatype, Inc. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package org.asynchttpclient;
import static java.nio.charset.StandardCharsets.*;
import static org.asynchttpclient.test.TestUtils.findFreePort;
import static org.asynchttpclient.test.TestUtils.newJettyHttpServer;
import static org.testng.Assert.assertEquals;
import org.asynchttpclient.AsyncHttpClient;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
public class NonAsciiContentLengthTest extends AbstractBasicTest {
@BeforeClass(alwaysRun = true)
public void setUpGlobal() throws Exception {
port1 = findFreePort();
server = newJettyHttpServer(port1);
server.setHandler(new AbstractHandler() {
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
int MAX_BODY_SIZE = 1024; // Can only handle bodies of up to 1024 bytes.
byte[] b = new byte[MAX_BODY_SIZE];
int offset = 0;
int numBytesRead;
try (ServletInputStream is = request.getInputStream()) {
while ((numBytesRead = is.read(b, offset, MAX_BODY_SIZE - offset)) != -1) {
offset += numBytesRead;
}
}
assertEquals(request.getContentLength(), offset);
response.setStatus(200);
response.setCharacterEncoding(request.getCharacterEncoding());
response.setContentLength(request.getContentLength());
try (ServletOutputStream os = response.getOutputStream()) {
os.write(b, 0, offset);
}
}
});
server.start();
}
@Test(groups = { "standalone", "default_provider" })
public void testNonAsciiContentLength() throws Exception {
execute("test");
execute("\u4E00"); // Unicode CJK ideograph for one
}
protected void execute(String body) throws IOException, InterruptedException, ExecutionException {
try (AsyncHttpClient client = new DefaultAsyncHttpClient()) {
BoundRequestBuilder r = client.preparePost(getTargetUrl()).setBody(body).setBodyCharset(UTF_8);
Future<Response> f = r.execute();
Response resp = f.get();
assertEquals(resp.getStatusCode(), 200);
assertEquals(body, resp.getResponseBody(UTF_8));
}
}
}
| apache-2.0 |
RcExtract/Minecord | src/main/java/com/rcextract/minecord/event/server/ServerSetPermanentEvent.java | 671 | package com.rcextract.minecord.event.server;
import org.bukkit.event.HandlerList;
import com.rcextract.minecord.Server;
public class ServerSetPermanentEvent extends ServerEvent {
private static final HandlerList handlers = new HandlerList();
public static HandlerList getHandlerList() {
return handlers;
}
private boolean permanent;
public ServerSetPermanentEvent(Server server, boolean permanent) {
super(server);
this.permanent = permanent;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public boolean isPermanent() {
return permanent;
}
public void setPermanent(boolean permanent) {
this.permanent = permanent;
}
}
| apache-2.0 |
gzsombor/ranger | security-admin/src/main/java/org/apache/ranger/patch/PatchMigration_J10002.java | 18542 | /*
* 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.ranger.patch;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.ranger.biz.RangerBizUtil;
import org.apache.ranger.biz.ServiceDBStore;
import org.apache.ranger.common.AppConstants;
import org.apache.ranger.common.JSONUtil;
import org.apache.ranger.common.RangerCommonEnums;
import org.apache.ranger.common.SearchCriteria;
import org.apache.ranger.common.ServiceUtil;
import org.apache.ranger.common.StringUtil;
import org.apache.ranger.db.RangerDaoManager;
import org.apache.ranger.entity.XXAsset;
import org.apache.ranger.entity.XXAuditMap;
import org.apache.ranger.entity.XXGroup;
import org.apache.ranger.entity.XXPolicy;
import org.apache.ranger.entity.XXPolicyConditionDef;
import org.apache.ranger.entity.XXPortalUser;
import org.apache.ranger.entity.XXResource;
import org.apache.ranger.entity.XXServiceConfigDef;
import org.apache.ranger.entity.XXServiceDef;
import org.apache.ranger.entity.XXUser;
import org.apache.ranger.plugin.model.RangerPolicy;
import org.apache.ranger.plugin.model.RangerService;
import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem;
import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemAccess;
import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource;
import org.apache.ranger.plugin.store.EmbeddedServiceDefsUtil;
import org.apache.ranger.service.RangerPolicyService;
import org.apache.ranger.service.XPermMapService;
import org.apache.ranger.service.XPolicyService;
import org.apache.ranger.util.CLIUtil;
import org.apache.ranger.view.VXPermMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class PatchMigration_J10002 extends BaseLoader {
private static final Logger logger = Logger.getLogger(PatchMigration_J10002.class);
@Autowired
RangerDaoManager daoMgr;
@Autowired
ServiceDBStore svcDBStore;
@Autowired
JSONUtil jsonUtil;
@Autowired
RangerPolicyService policyService;
@Autowired
StringUtil stringUtil;
@Autowired
XPolicyService xPolService;
@Autowired
XPermMapService xPermMapService;
@Autowired
RangerBizUtil bizUtil;
private static int policyCounter = 0;
private static int serviceCounter = 0;
static Set<String> unsupportedLegacyPermTypes = new HashSet<String>();
static {
unsupportedLegacyPermTypes.add("Unknown");
unsupportedLegacyPermTypes.add("Reset");
unsupportedLegacyPermTypes.add("Obfuscate");
unsupportedLegacyPermTypes.add("Mask");
}
public static void main(String[] args) {
logger.info("main()");
try {
PatchMigration_J10002 loader = (PatchMigration_J10002) CLIUtil.getBean(PatchMigration_J10002.class);
loader.init();
while (loader.isMoreToProcess()) {
loader.load();
}
logger.info("Load complete. Exiting!!!");
System.exit(0);
} catch (Exception e) {
logger.error("Error loading", e);
System.exit(1);
}
}
@Override
public void init() throws Exception {
// Do Nothing
}
@Override
public void execLoad() {
logger.info("==> MigrationPatch.execLoad()");
try {
migrateServicesToNewSchema();
migratePoliciesToNewSchema();
updateSequences();
} catch (Exception e) {
logger.error("Error whille migrating data.", e);
}
logger.info("<== MigrationPatch.execLoad()");
}
@Override
public void printStats() {
logger.info("Total Number of migrated repositories/services: " + serviceCounter);
logger.info("Total Number of migrated resources/policies: " + policyCounter);
}
public void migrateServicesToNewSchema() throws Exception {
logger.info("==> MigrationPatch.migrateServicesToNewSchema()");
try {
List<XXAsset> repoList = daoMgr.getXXAsset().getAll();
if (repoList.isEmpty()) {
return;
}
if (!repoList.isEmpty()) {
EmbeddedServiceDefsUtil.instance().init(svcDBStore);
}
svcDBStore.setPopulateExistingBaseFields(true);
for (XXAsset xAsset : repoList) {
if (xAsset.getActiveStatus() == AppConstants.STATUS_DELETED) {
continue;
}
RangerService existing = svcDBStore.getServiceByName(xAsset.getName());
if (existing != null) {
logger.info("Repository/Service already exists. Ignoring migration of repo: " + xAsset.getName());
continue;
}
RangerService service = new RangerService();
service = mapXAssetToService(service, xAsset);
service = svcDBStore.createService(service);
serviceCounter++;
logger.info("New Service created. ServiceName: " + service.getName());
}
svcDBStore.setPopulateExistingBaseFields(false);
} catch (Exception e) {
throw new Exception("Error while migrating data to new Plugin Schema.", e);
}
logger.info("<== MigrationPatch.migrateServicesToNewSchema()");
}
public void migratePoliciesToNewSchema() throws Exception {
logger.info("==> MigrationPatch.migratePoliciesToNewSchema()");
try {
List<XXResource> resList = daoMgr.getXXResource().getAll();
if (resList.isEmpty()) {
return;
}
svcDBStore.setPopulateExistingBaseFields(true);
for (XXResource xRes : resList) {
if (xRes.getResourceStatus() == AppConstants.STATUS_DELETED) {
continue;
}
XXAsset xAsset = daoMgr.getXXAsset().getById(xRes.getAssetId());
if (xAsset == null) {
logger.error("No Repository found for policyName: " + xRes.getPolicyName());
continue;
}
RangerService service = svcDBStore.getServiceByName(xAsset.getName());
if (service == null) {
logger.error("No Service found for policy. Ignoring migration of such policy, policyName: "
+ xRes.getPolicyName());
continue;
}
XXPolicy existing = daoMgr.getXXPolicy().findByNameAndServiceId(xRes.getPolicyName(), service.getId());
if (existing != null) {
logger.info("Policy already exists. Ignoring migration of policy: " + existing.getName());
continue;
}
RangerPolicy policy = new RangerPolicy();
policy = mapXResourceToPolicy(policy, xRes, service);
if(policy != null) {
policy = svcDBStore.createPolicy(policy);
policyCounter++;
logger.info("New policy created. policyName: " + policy.getName());
}
}
svcDBStore.setPopulateExistingBaseFields(false);
} catch (Exception e) {
throw new Exception("Error while migrating data to new Plugin Schema.", e);
}
logger.info("<== MigrationPatch.migratePoliciesToNewSchema()");
}
private RangerService mapXAssetToService(RangerService service, XXAsset xAsset) throws Exception {
String type = "";
String name = xAsset.getName();
String description = xAsset.getDescription();
Map<String, String> configs = null;
int typeInt = xAsset.getAssetType();
XXServiceDef serviceDef = daoMgr.getXXServiceDef().findByName(AppConstants.getLabelFor_AssetType(typeInt).toLowerCase());
if (serviceDef == null) {
throw new Exception("No ServiceDefinition found for repository: " + name);
}
type = serviceDef.getName();
configs = jsonUtil.jsonToMap(xAsset.getConfig());
List<XXServiceConfigDef> mandatoryConfigs = daoMgr.getXXServiceConfigDef().findByServiceDefName(type);
for (XXServiceConfigDef serviceConf : mandatoryConfigs) {
if (serviceConf.getIsMandatory()) {
if (!stringUtil.isEmpty(configs.get(serviceConf.getName()))) {
continue;
}
String dataType = serviceConf.getType();
String defaultValue = serviceConf.getDefaultvalue();
if (stringUtil.isEmpty(defaultValue)) {
defaultValue = getDefaultValueForDataType(dataType);
}
configs.put(serviceConf.getName(), defaultValue);
}
}
service.setType(type);
service.setName(name);
service.setDescription(description);
service.setConfigs(configs);
service.setCreateTime(xAsset.getCreateTime());
service.setUpdateTime(xAsset.getUpdateTime());
XXPortalUser createdByUser = daoMgr.getXXPortalUser().getById(xAsset.getAddedByUserId());
XXPortalUser updByUser = daoMgr.getXXPortalUser().getById(xAsset.getUpdatedByUserId());
if (createdByUser != null) {
service.setCreatedBy(createdByUser.getLoginId());
}
if (updByUser != null) {
service.setUpdatedBy(updByUser.getLoginId());
}
service.setId(xAsset.getId());
return service;
}
private String getDefaultValueForDataType(String dataType) {
String defaultValue = "";
switch (dataType) {
case "int":
defaultValue = "0";
break;
case "string":
defaultValue = "unknown";
break;
case "bool":
defaultValue = "false";
break;
case "enum":
defaultValue = "0";
break;
case "password":
defaultValue = "password";
break;
default:
break;
}
return defaultValue;
}
private RangerPolicy mapXResourceToPolicy(RangerPolicy policy, XXResource xRes, RangerService service) {
String serviceName = service.getName();
String serviceType = service.getType();
String name = xRes.getPolicyName();
String description = xRes.getDescription();
Boolean isAuditEnabled = true;
Boolean isEnabled = true;
Map<String, RangerPolicyResource> resources = new HashMap<String, RangerPolicyResource>();
List<RangerPolicyItem> policyItems = new ArrayList<RangerPolicyItem>();
XXServiceDef svcDef = daoMgr.getXXServiceDef().findByName(serviceType);
if(svcDef == null) {
logger.error(serviceType + ": service-def not found. Skipping policy '" + name + "'");
return null;
}
List<XXAuditMap> auditMapList = daoMgr.getXXAuditMap().findByResourceId(xRes.getId());
if (stringUtil.isEmpty(auditMapList)) {
isAuditEnabled = false;
}
if (xRes.getResourceStatus() == AppConstants.STATUS_DISABLED) {
isEnabled = false;
}
Boolean isPathRecursive = xRes.getIsRecursive() == RangerCommonEnums.BOOL_TRUE;
Boolean isTableExcludes = xRes.getTableType() == RangerCommonEnums.POLICY_EXCLUSION;
Boolean isColumnExcludes = xRes.getColumnType() == RangerCommonEnums.POLICY_EXCLUSION;
if (StringUtils.equalsIgnoreCase(serviceType, "hdfs")) {
toRangerResourceList(xRes.getName(), "path", Boolean.FALSE, isPathRecursive, resources);
} else if (StringUtils.equalsIgnoreCase(serviceType, "hbase")) {
toRangerResourceList(xRes.getTables(), "table", isTableExcludes, Boolean.FALSE, resources);
toRangerResourceList(xRes.getColumnFamilies(), "column-family", Boolean.FALSE, Boolean.FALSE, resources);
toRangerResourceList(xRes.getColumns(), "column", isColumnExcludes, Boolean.FALSE, resources);
} else if (StringUtils.equalsIgnoreCase(serviceType, "hive")) {
toRangerResourceList(xRes.getDatabases(), "database", Boolean.FALSE, Boolean.FALSE, resources);
toRangerResourceList(xRes.getTables(), "table", isTableExcludes, Boolean.FALSE, resources);
toRangerResourceList(xRes.getColumns(), "column", isColumnExcludes, Boolean.FALSE, resources);
toRangerResourceList(xRes.getUdfs(), "udf", Boolean.FALSE, Boolean.FALSE, resources);
} else if (StringUtils.equalsIgnoreCase(serviceType, "knox")) {
toRangerResourceList(xRes.getTopologies(), "topology", Boolean.FALSE, Boolean.FALSE, resources);
toRangerResourceList(xRes.getServices(), "service", Boolean.FALSE, Boolean.FALSE, resources);
} else if (StringUtils.equalsIgnoreCase(serviceType, "storm")) {
toRangerResourceList(xRes.getTopologies(), "topology", Boolean.FALSE, Boolean.FALSE, resources);
}
policyItems = getPolicyItemListForRes(xRes, svcDef);
policy.setService(serviceName);
policy.setName(name);
policy.setDescription(description);
policy.setIsAuditEnabled(isAuditEnabled);
policy.setIsEnabled(isEnabled);
policy.setResources(resources);
policy.setPolicyItems(policyItems);
policy.setCreateTime(xRes.getCreateTime());
policy.setUpdateTime(xRes.getUpdateTime());
XXPortalUser createdByUser = daoMgr.getXXPortalUser().getById(xRes.getAddedByUserId());
XXPortalUser updByUser = daoMgr.getXXPortalUser().getById(xRes.getUpdatedByUserId());
if (createdByUser != null) {
policy.setCreatedBy(createdByUser.getLoginId());
}
if (updByUser != null) {
policy.setUpdatedBy(updByUser.getLoginId());
}
policy.setId(xRes.getId());
return policy;
}
private Map<String, RangerPolicy.RangerPolicyResource> toRangerResourceList(String resourceString, String resourceType, Boolean isExcludes, Boolean isRecursive, Map<String, RangerPolicy.RangerPolicyResource> resources) {
Map<String, RangerPolicy.RangerPolicyResource> ret = resources == null ? new HashMap<String, RangerPolicy.RangerPolicyResource>() : resources;
if(StringUtils.isNotBlank(resourceString)) {
RangerPolicy.RangerPolicyResource resource = ret.get(resourceType);
if(resource == null) {
resource = new RangerPolicy.RangerPolicyResource();
resource.setIsExcludes(isExcludes);
resource.setIsRecursive(isRecursive);
ret.put(resourceType, resource);
}
Collections.addAll(resource.getValues(), resourceString.split(","));
}
return ret;
}
private List<RangerPolicyItem> getPolicyItemListForRes(XXResource xRes, XXServiceDef svcDef) {
List<RangerPolicyItem> policyItems = new ArrayList<RangerPolicyItem>();
SearchCriteria sc = new SearchCriteria();
sc.addParam("resourceId", xRes.getId());
List<VXPermMap> permMapList = xPermMapService.searchXPermMaps(sc).getVXPermMaps();
HashMap<String, List<VXPermMap>> sortedPermMap = new HashMap<String, List<VXPermMap>>();
// re-group the list with permGroup as the key
if (permMapList != null) {
for(VXPermMap permMap : permMapList) {
String permGrp = permMap.getPermGroup();
List<VXPermMap> sortedList = sortedPermMap.get(permGrp);
if(sortedList == null) {
sortedList = new ArrayList<VXPermMap>();
sortedPermMap.put(permGrp, sortedList);
}
sortedList.add(permMap);
}
}
for (Entry<String, List<VXPermMap>> entry : sortedPermMap.entrySet()) {
List<String> userList = new ArrayList<String>();
List<String> groupList = new ArrayList<String>();
List<RangerPolicyItemAccess> accessList = new ArrayList<RangerPolicyItemAccess>();
String ipAddress = null;
RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
for(VXPermMap permMap : entry.getValue()) {
if(permMap.getPermFor() == AppConstants.XA_PERM_FOR_USER) {
String userName = getUserName(permMap);
if (! userList.contains(userName)) {
userList.add(userName);
}
} else if(permMap.getPermFor() == AppConstants.XA_PERM_FOR_GROUP) {
String groupName = getGroupName(permMap);
if (! groupList.contains(groupName)) {
groupList.add(groupName);
}
}
String accessType = ServiceUtil.toAccessType(permMap.getPermType());
if(StringUtils.isBlank(accessType) || unsupportedLegacyPermTypes.contains(accessType)) {
logger.info(accessType + ": is not a valid access-type, ignoring accesstype for policy: " + xRes.getPolicyName());
continue;
}
if(StringUtils.equalsIgnoreCase(accessType, "Admin")) {
policyItem.setDelegateAdmin(Boolean.TRUE);
if ( svcDef.getId() == EmbeddedServiceDefsUtil.instance().getHBaseServiceDefId()) {
addAccessType(accessType, accessList);
}
} else {
addAccessType(accessType, accessList);
}
ipAddress = permMap.getIpAddress();
}
if(CollectionUtils.isEmpty(accessList)) {
logger.info("no access specified. ignoring policyItem for policy: " + xRes.getPolicyName());
continue;
}
if(CollectionUtils.isEmpty(userList) && CollectionUtils.isEmpty(groupList)) {
logger.info("no user or group specified. ignoring policyItem for policy: " + xRes.getPolicyName());
continue;
}
policyItem.setUsers(userList);
policyItem.setGroups(groupList);
policyItem.setAccesses(accessList);
if(ipAddress != null && !ipAddress.isEmpty()) {
XXPolicyConditionDef policyCond = daoMgr.getXXPolicyConditionDef().findByServiceDefIdAndName(svcDef.getId(), "ip-range");
if(policyCond != null) {
RangerPolicy.RangerPolicyItemCondition ipCondition = new RangerPolicy.RangerPolicyItemCondition("ip-range", Collections.singletonList(ipAddress));
policyItem.getConditions().add(ipCondition);
}
}
policyItems.add(policyItem);
}
return policyItems;
}
private void addAccessType(String accessType, List<RangerPolicyItemAccess> accessList) {
boolean alreadyExists = false;
for(RangerPolicyItemAccess access : accessList) {
if(StringUtils.equalsIgnoreCase(accessType, access.getType())) {
alreadyExists = true;
break;
}
}
if(!alreadyExists) {
accessList.add(new RangerPolicyItemAccess(accessType));
}
}
private void updateSequences() {
daoMgr.getXXServiceDef().updateSequence();
daoMgr.getXXService().updateSequence();
daoMgr.getXXPolicy().updateSequence();
}
private String getUserName(VXPermMap permMap) {
String userName = permMap.getUserName();
if(userName == null || userName.isEmpty()) {
Long userId = permMap.getUserId();
if(userId != null) {
XXUser xxUser = daoMgr.getXXUser().getById(userId);
if(xxUser != null) {
userName = xxUser.getName();
}
}
}
return userName;
}
private String getGroupName(VXPermMap permMap) {
String groupName = permMap.getGroupName();
if(groupName == null || groupName.isEmpty()) {
Long groupId = permMap.getGroupId();
if(groupId != null) {
XXGroup xxGroup = daoMgr.getXXGroup().getById(groupId);
if(xxGroup != null) {
groupName = xxGroup.getName();
}
}
}
return groupName;
}
}
| apache-2.0 |
matobet/moVirt | moVirt/src/main/java/org/ovirt/mobile/movirt/ui/mvp/FinishableView.java | 114 | package org.ovirt.mobile.movirt.ui.mvp;
public interface FinishableView extends BaseView {
void finish();
}
| apache-2.0 |
bernhardhuber/netbeansplugins | nb-policy-support/src/org/netbeans/modules/policysupport/PolicyEditorKit.java | 1443 | /*
* PolicyEditorKit.java
*
* Created on October 20, 2005, 5:14 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package org.netbeans.modules.policysupport;
import javax.swing.text.Document;
import org.netbeans.editor.Syntax;
import org.netbeans.modules.editor.NbEditorKit;
import org.openide.ErrorManager;
/**
*
* @author HuberB1
*/
public class PolicyEditorKit extends NbEditorKit {
protected final static long serialVersionUID = 20060730114300L;
private static final ErrorManager LOGGER = ErrorManager.getDefault().getInstance("org.netbeans.modules.policysupport.PolicyEditorKit");
private static final boolean LOG = LOGGER.isLoggable(ErrorManager.INFORMATIONAL);
public static final String MIME_TYPE = "text/x-java-policy"; // NOI18N
/**
*
* Creates a new instance of PolicyEditorKit
*/
public PolicyEditorKit() {
}
/**
* Create a syntax object suitable for highlighting Policy file syntax
*/
public Syntax createSyntax(Document doc) {
if (LOG) {
LOGGER.log(ErrorManager.INFORMATIONAL, "createSyntax"); // NOI18N
}
return new PolicySyntax();
}
/**
* Retrieves the content type for this editor kit
*/
public String getContentType() {
return MIME_TYPE;
}
} | apache-2.0 |
mdanielwork/intellij-community | platform/lang-impl/src/com/intellij/codeInspection/ui/actions/ExportHTMLAction.java | 12805 | // 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.codeInspection.ui.actions;
import com.intellij.application.options.CodeStyle;
import com.intellij.codeEditor.printing.ExportToHTMLSettings;
import com.intellij.codeInspection.InspectionApplication;
import com.intellij.codeInspection.InspectionsBundle;
import com.intellij.codeInspection.ex.*;
import com.intellij.codeInspection.export.ExportToHTMLDialog;
import com.intellij.codeInspection.export.InspectionTreeHtmlWriter;
import com.intellij.codeInspection.ui.*;
import com.intellij.configurationStore.JbXmlOutputter;
import com.intellij.icons.AllIcons;
import com.intellij.ide.BrowserUtil;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.ui.popup.ListPopup;
import com.intellij.openapi.ui.popup.PopupStep;
import com.intellij.openapi.ui.popup.util.BaseListPopupStep;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.util.ui.tree.TreeUtil;
import gnu.trove.THashSet;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.io.*;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ExportHTMLAction extends AnAction implements DumbAware {
private static final Logger LOG = Logger.getInstance(ExportHTMLAction.class);
private final InspectionResultsView myView;
@NonNls private static final String ROOT = "root";
@NonNls private static final String AGGREGATE = "_aggregate";
@NonNls private static final String HTML = "HTML";
@NonNls private static final String XML = "XML";
public ExportHTMLAction(final InspectionResultsView view) {
super(InspectionsBundle.message("inspection.action.export.html"), null, AllIcons.ToolbarDecorator.Export);
myView = view;
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
final ListPopup popup = JBPopupFactory.getInstance().createListPopup(
new BaseListPopupStep<String>(InspectionsBundle.message("inspection.action.export.popup.title"), HTML, XML) {
@Override
public PopupStep onChosen(final String selectedValue, final boolean finalChoice) {
return doFinalStep(() -> exportHTML(Comparing.strEqual(selectedValue, HTML)));
}
});
InspectionResultsView.showPopup(e, popup);
}
private void exportHTML(final boolean exportToHTML) {
ExportToHTMLDialog exportToHTMLDialog = new ExportToHTMLDialog(myView.getProject(), exportToHTML);
final ExportToHTMLSettings exportToHTMLSettings = ExportToHTMLSettings.getInstance(myView.getProject());
if (exportToHTMLSettings.OUTPUT_DIRECTORY == null) {
exportToHTMLSettings.OUTPUT_DIRECTORY = PathManager.getHomePath() + File.separator + "inspections";
}
exportToHTMLDialog.reset();
if (!exportToHTMLDialog.showAndGet()) {
return;
}
exportToHTMLDialog.apply();
final String outputDirectoryName = exportToHTMLSettings.OUTPUT_DIRECTORY;
ApplicationManager.getApplication().invokeLater(() -> {
final Runnable exportRunnable = () -> ApplicationManager.getApplication().runReadAction(() -> {
if (!exportToHTML) {
dump2xml(outputDirectoryName);
}
else {
try {
new InspectionTreeHtmlWriter(myView, outputDirectoryName);
}
catch (ProcessCanceledException e) {
// Do nothing here.
}
}
});
if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(exportRunnable,
InspectionsBundle.message(exportToHTML
? "inspection.generating.html.progress.title"
: "inspection.generating.xml.progress.title"), true,
myView.getProject())) {
return;
}
if (exportToHTML && exportToHTMLSettings.OPEN_IN_BROWSER) {
BrowserUtil.browse(new File(exportToHTMLSettings.OUTPUT_DIRECTORY, "index.html"));
}
});
}
private void dump2xml(final String outputDirectoryName) {
try {
final File outputDir = new File(outputDirectoryName);
if (!outputDir.exists() && !outputDir.mkdirs()) {
throw new IOException("Cannot create \'" + outputDir + "\'");
}
final InspectionTreeNode root = myView.getTree().getRoot();
final Exception[] ex = new Exception[1];
final Set<String> visitedTools = new THashSet<>();
Format format = JDOMUtil.createFormat("\n");
XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
TreeUtil.treeNodeTraverser(root).traverse().processEach(node -> {
if (node instanceof InspectionNode) {
InspectionNode toolNode = (InspectionNode)node;
if (toolNode.isExcluded()) return true;
InspectionToolWrapper toolWrapper = toolNode.getToolWrapper();
if (!visitedTools.add(toolNode.getToolWrapper().getShortName())) return true;
String name = toolWrapper.getShortName();
try (XmlWriterWrapper reportWriter = new XmlWriterWrapper(myView.getProject(), outputDirectoryName, name,
xmlOutputFactory, format, GlobalInspectionContextBase.PROBLEMS_TAG_NAME);
XmlWriterWrapper aggregateWriter = new XmlWriterWrapper(myView.getProject(), outputDirectoryName, name + AGGREGATE,
xmlOutputFactory, format, ROOT)) {
reportWriter.checkOpen();
for (InspectionToolPresentation presentation : getPresentationsFromAllScopes(toolNode)) {
presentation.exportResults(reportWriter::writeElement, presentation::isExcluded, presentation::isExcluded);
if (presentation instanceof AggregateResultsExporter) {
((AggregateResultsExporter)presentation).exportAggregateResults(aggregateWriter::writeElement);
}
}
}
catch (XmlWriterWrapperException e) {
Throwable cause = e.getCause();
ex[0] = cause instanceof Exception ? (Exception)cause : e;
}
}
return true;
});
if (ex[0] != null) {
throw ex[0];
}
final Element element = new Element(InspectionApplication.INSPECTIONS_NODE);
final String profileName = myView.getCurrentProfileName();
if (profileName != null) {
element.setAttribute(InspectionApplication.PROFILE, profileName);
}
JDOMUtil.write(element,
new File(outputDirectoryName, InspectionApplication.DESCRIPTIONS + InspectionApplication.XML_EXTENSION),
CodeStyle.getDefaultSettings().getLineSeparator());
}
catch (Exception e) {
LOG.error(e);
ApplicationManager.getApplication().invokeLater(() -> Messages.showErrorDialog(myView, e.getMessage()));
}
}
@NotNull
public static BufferedWriter getWriter(String outputDirectoryName, String name) throws FileNotFoundException {
File file = getInspectionResultFile(outputDirectoryName, name);
FileUtil.createParentDirs(file);
return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), CharsetToolkit.UTF8_CHARSET));
}
@NotNull
public static File getInspectionResultFile(String outputDirectoryName, String name) {
return new File(outputDirectoryName, name + InspectionApplication.XML_EXTENSION);
}
@NotNull
private Collection<InspectionToolPresentation> getPresentationsFromAllScopes(@NotNull InspectionNode node) {
final InspectionToolWrapper wrapper = node.getToolWrapper();
Stream<InspectionToolWrapper> wrappers;
if (myView.getCurrentProfileName() == null){
wrappers = Stream.of(wrapper);
} else {
final String shortName = wrapper.getShortName();
final GlobalInspectionContextImpl context = myView.getGlobalInspectionContext();
final Tools tools = context.getTools().get(shortName);
if (tools != null) { //dummy entry points tool
wrappers = tools.getTools().stream().map(ScopeToolState::getTool);
} else {
wrappers = Stream.empty();
}
}
return wrappers.map(w -> myView.getGlobalInspectionContext().getPresentation(w)).collect(Collectors.toList());
}
private static class XmlWriterWrapper implements Closeable {
private final Project myProject;
private final String myOutputDirectoryName;
private final String myName;
private final XMLOutputFactory myFactory;
private final Format myFormat;
private final String myRootTagName;
private XMLStreamWriter myXmlWriter;
private Writer myFileWriter;
XmlWriterWrapper(@NotNull Project project,
@NotNull String outputDirectoryName,
@NotNull String name,
@NotNull XMLOutputFactory factory,
@NotNull Format format,
@NotNull String rootTagName) {
myProject = project;
myOutputDirectoryName = outputDirectoryName;
myName = name;
myFactory = factory;
myFormat = format;
myRootTagName = rootTagName;
}
void writeElement(@NotNull Element element) {
try {
checkOpen();
myXmlWriter.writeCharacters(myFormat.getLineSeparator() + myFormat.getIndent());
myXmlWriter.flush();
JbXmlOutputter.collapseMacrosAndWrite(element, myProject, myFileWriter);
myFileWriter.flush();
}
catch (XMLStreamException | IOException e) {
throw new XmlWriterWrapperException(e);
}
}
void checkOpen() {
if (myXmlWriter == null) {
myFileWriter = openFile(myOutputDirectoryName, myName);
myXmlWriter = startWritingXml(myFileWriter);
}
}
@Override
public void close() {
if (myXmlWriter != null) {
try {
endWritingXml(myXmlWriter);
}
finally {
myXmlWriter = null;
try {
closeFile(myFileWriter);
}
finally {
myFileWriter = null;
}
}
}
}
@NotNull
private static Writer openFile(@NotNull String outputDirectoryName, @NotNull String name) {
try {
return getWriter(outputDirectoryName, name);
}
catch (FileNotFoundException e) {
throw new XmlWriterWrapperException(e);
}
}
private static void closeFile(@NotNull Writer fileWriter) {
try {
fileWriter.close();
}
catch (IOException e) {
throw new XmlWriterWrapperException(e);
}
}
@NotNull
private XMLStreamWriter startWritingXml(@NotNull Writer fileWriter) {
try {
XMLStreamWriter xmlWriter = myFactory.createXMLStreamWriter(fileWriter);
xmlWriter.writeStartElement(myRootTagName);
return xmlWriter;
}
catch (XMLStreamException e) {
throw new XmlWriterWrapperException(e);
}
}
private void endWritingXml(@NotNull XMLStreamWriter xmlWriter) {
try {
try {
xmlWriter.writeCharacters(myFormat.getLineSeparator());
xmlWriter.writeEndElement();
xmlWriter.flush();
}
finally {
xmlWriter.close();
}
}
catch (XMLStreamException e) {
throw new XmlWriterWrapperException(e);
}
}
}
private static class XmlWriterWrapperException extends RuntimeException {
private XmlWriterWrapperException(Throwable cause) {
super(cause.getMessage(), cause);
}
}
}
| apache-2.0 |
SkyCrawl/pikater-vaadin | src/org/pikater/web/PikaterWebLogger.java | 857 | package org.pikater.web;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.pikater.shared.logging.GeneralPikaterLogger;
import org.pikater.shared.logging.IPikaterLogger;
/**
* Special logger wrapper to be used by the web application.
*
* @author SkyCrawl
*/
public class PikaterWebLogger extends GeneralPikaterLogger
{
private static final IPikaterLogger innerLogger = createPikaterLogger(Logger.getLogger("log4j"));
public static IPikaterLogger getLogger()
{
return innerLogger;
}
public static void logThrowable(String message, Throwable t)
{
getLogger().logThrowable(message, t);
}
public static void log(Level logLevel, String message)
{
getLogger().log(logLevel, message);
}
public static void log(Level logLevel, String source, String message)
{
getLogger().log(logLevel, source, message);
}
} | apache-2.0 |
littlezhou/hadoop | hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/scm/pipeline/TestPipelineClose.java | 8956 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
*/
package org.apache.hadoop.hdds.scm.pipeline;
import org.apache.hadoop.hdds.HddsConfigKeys;
import org.apache.hadoop.hdds.conf.OzoneConfiguration;
import org.apache.hadoop.hdds.protocol.DatanodeDetails;
import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
import org.apache.hadoop.hdds.protocol.proto.StorageContainerDatanodeProtocolProtos.PipelineReport;
import org.apache.hadoop.hdds.scm.ScmConfigKeys;
import org.apache.hadoop.hdds.scm.TestUtils;
import org.apache.hadoop.hdds.scm.container.ContainerID;
import org.apache.hadoop.hdds.scm.container.ContainerInfo;
import org.apache.hadoop.hdds.scm.container.ContainerManager;
import org.apache.hadoop.hdds.scm.container.common.helpers.ContainerWithPipeline;
import org.apache.hadoop.hdds.scm.server.SCMDatanodeHeartbeatDispatcher.PipelineReportFromDatanode;
import org.apache.hadoop.hdds.scm.server.SCMDatanodeHeartbeatDispatcher.PipelineActionsFromDatanode;
import org.apache.hadoop.hdds.scm.server.StorageContainerManager;
import org.apache.hadoop.hdds.server.events.EventQueue;
import org.apache.hadoop.ozone.MiniOzoneCluster;
import org.apache.hadoop.ozone.container.ozoneimpl.OzoneContainer;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.apache.hadoop.hdds.protocol.proto.HddsProtos.ReplicationFactor.THREE;
import static org.apache.hadoop.hdds.protocol.proto.HddsProtos.ReplicationType.RATIS;
/**
* Tests for Pipeline Closing.
*/
public class TestPipelineClose {
private MiniOzoneCluster cluster;
private OzoneConfiguration conf;
private StorageContainerManager scm;
private ContainerWithPipeline ratisContainer;
private ContainerManager containerManager;
private PipelineManager pipelineManager;
private long pipelineDestroyTimeoutInMillis;
/**
* Create a MiniDFSCluster for testing.
*
* @throws IOException
*/
@Before
public void init() throws Exception {
conf = new OzoneConfiguration();
cluster = MiniOzoneCluster.newBuilder(conf).setNumDatanodes(3).build();
conf.setTimeDuration(HddsConfigKeys.HDDS_HEARTBEAT_INTERVAL, 1000,
TimeUnit.MILLISECONDS);
pipelineDestroyTimeoutInMillis = 5000;
conf.setTimeDuration(ScmConfigKeys.OZONE_SCM_PIPELINE_DESTROY_TIMEOUT,
pipelineDestroyTimeoutInMillis, TimeUnit.MILLISECONDS);
cluster.waitForClusterToBeReady();
scm = cluster.getStorageContainerManager();
containerManager = scm.getContainerManager();
pipelineManager = scm.getPipelineManager();
ContainerInfo containerInfo = containerManager
.allocateContainer(RATIS, THREE, "testOwner");
ratisContainer = new ContainerWithPipeline(containerInfo,
pipelineManager.getPipeline(containerInfo.getPipelineID()));
pipelineManager = scm.getPipelineManager();
// At this stage, there should be 2 pipeline one with 1 open container each.
// Try closing the both the pipelines, one with a closed container and
// the other with an open container.
}
/**
* Shutdown MiniDFSCluster.
*/
@After
public void shutdown() {
if (cluster != null) {
cluster.shutdown();
}
}
@Test
public void testPipelineCloseWithClosedContainer() throws IOException {
Set<ContainerID> set = pipelineManager
.getContainersInPipeline(ratisContainer.getPipeline().getId());
ContainerID cId = ratisContainer.getContainerInfo().containerID();
Assert.assertEquals(1, set.size());
set.forEach(containerID -> Assert.assertEquals(containerID, cId));
// Now close the container and it should not show up while fetching
// containers by pipeline
containerManager
.updateContainerState(cId, HddsProtos.LifeCycleEvent.FINALIZE);
containerManager
.updateContainerState(cId, HddsProtos.LifeCycleEvent.CLOSE);
Set<ContainerID> setClosed = pipelineManager
.getContainersInPipeline(ratisContainer.getPipeline().getId());
Assert.assertEquals(0, setClosed.size());
pipelineManager.finalizePipeline(ratisContainer.getPipeline().getId());
Pipeline pipeline1 = pipelineManager
.getPipeline(ratisContainer.getPipeline().getId());
Assert.assertEquals(Pipeline.PipelineState.CLOSED,
pipeline1.getPipelineState());
pipelineManager.removePipeline(pipeline1.getId());
for (DatanodeDetails dn : ratisContainer.getPipeline().getNodes()) {
// Assert that the pipeline has been removed from Node2PipelineMap as well
Assert.assertEquals(scm.getScmNodeManager().getPipelines(
dn).size(), 0);
}
}
@Test
public void testPipelineCloseWithOpenContainer() throws IOException,
TimeoutException, InterruptedException {
Set<ContainerID> setOpen = pipelineManager.getContainersInPipeline(
ratisContainer.getPipeline().getId());
Assert.assertEquals(1, setOpen.size());
ContainerID cId2 = ratisContainer.getContainerInfo().containerID();
pipelineManager.finalizePipeline(ratisContainer.getPipeline().getId());
Assert.assertEquals(Pipeline.PipelineState.CLOSED,
pipelineManager.getPipeline(
ratisContainer.getPipeline().getId()).getPipelineState());
Pipeline pipeline2 = pipelineManager
.getPipeline(ratisContainer.getPipeline().getId());
Assert.assertEquals(Pipeline.PipelineState.CLOSED,
pipeline2.getPipelineState());
}
@Test
public void testPipelineCloseWithPipelineAction() throws Exception {
List<DatanodeDetails> dns = ratisContainer.getPipeline().getNodes();
PipelineActionsFromDatanode
pipelineActionsFromDatanode = TestUtils
.getPipelineActionFromDatanode(dns.get(0),
ratisContainer.getPipeline().getId());
// send closing action for pipeline
PipelineActionHandler pipelineActionHandler =
new PipelineActionHandler(pipelineManager, conf);
pipelineActionHandler
.onMessage(pipelineActionsFromDatanode, new EventQueue());
Thread.sleep((int) (pipelineDestroyTimeoutInMillis * 1.2));
OzoneContainer ozoneContainer =
cluster.getHddsDatanodes().get(0).getDatanodeStateMachine()
.getContainer();
List<PipelineReport> pipelineReports =
ozoneContainer.getPipelineReport().getPipelineReportList();
for (PipelineReport pipelineReport : pipelineReports) {
// ensure the pipeline is not reported by any dn
Assert.assertNotEquals(
PipelineID.getFromProtobuf(pipelineReport.getPipelineID()),
ratisContainer.getPipeline().getId());
}
try {
pipelineManager.getPipeline(ratisContainer.getPipeline().getId());
Assert.fail("Pipeline should not exist in SCM");
} catch (PipelineNotFoundException e) {
}
}
@Test
public void testPipelineCloseWithPipelineReport() throws IOException {
Pipeline pipeline = ratisContainer.getPipeline();
pipelineManager.finalizePipeline(pipeline.getId());
// remove pipeline from SCM
pipelineManager.removePipeline(pipeline.getId());
for (DatanodeDetails dn : pipeline.getNodes()) {
PipelineReportFromDatanode pipelineReport =
TestUtils.getPipelineReportFromDatanode(dn, pipeline.getId());
PipelineReportHandler pipelineReportHandler =
new PipelineReportHandler(pipelineManager, conf);
// on receiving pipeline report for the pipeline, pipeline report handler
// should destroy the pipeline for the dn
pipelineReportHandler.onMessage(pipelineReport, new EventQueue());
}
OzoneContainer ozoneContainer =
cluster.getHddsDatanodes().get(0).getDatanodeStateMachine()
.getContainer();
List<PipelineReport> pipelineReports =
ozoneContainer.getPipelineReport().getPipelineReportList();
for (PipelineReport pipelineReport : pipelineReports) {
// pipeline should not be reported by any dn
Assert.assertNotEquals(
PipelineID.getFromProtobuf(pipelineReport.getPipelineID()),
ratisContainer.getPipeline().getId());
}
}
} | apache-2.0 |
vjanmey/EpicMudfia | com/planet_ink/coffee_mud/WebMacros/QuestMaker.java | 32575 | package com.planet_ink.coffee_mud.WebMacros;
import com.planet_ink.miniweb.interfaces.*;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.core.exceptions.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
import java.util.regex.Pattern;
/*
Copyright 2000-2014 Bo Zimmerman
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.
*/
@SuppressWarnings({"unchecked","rawtypes"})
public class QuestMaker extends StdWebMacro
{
@Override public String name() {return "QuestMaker";}
@Override public boolean isAdminMacro() {return true;}
private static final Pattern keyPattern=Pattern.compile("^AT_(.+)");
public DVector getPage(MOB mob, HTTPRequest httpReq, String template, String page, String fileToGet)
{
DVector pageList=(DVector)httpReq.getRequestObjects().get("QM_PAGE_LIST");
DVector filePages=(DVector)httpReq.getRequestObjects().get("QM_FILE_PAGES");
if(template.length()==0)
{
httpReq.removeUrlParameter("QM_FILE_PAGES");
filePages=null;
if(pageList!=null) return pageList;
pageList=CMLib.quests().getQuestTemplate(mob, fileToGet);
httpReq.getRequestObjects().put("QM_PAGE_LIST",pageList);
return pageList;
}
final int pageNumber=CMath.s_int(page)-1;
if(filePages==null)
{
filePages=CMLib.quests().getQuestTemplate(mob, template);
httpReq.getRequestObjects().put("QM_FILE_PAGES",filePages);
}
final List<DVector> qPages=(List<DVector>)filePages.elementAt(0,4);
if(pageNumber<=0) return qPages.get(0);
if(pageNumber>=qPages.size()) return qPages.get(qPages.size()-1);
return qPages.get(pageNumber);
}
private String itemList(List<Item> itemList, Item oldItem, String oldValue)
{
final StringBuffer list=new StringBuffer("");
if(oldItem==null) oldItem=RoomData.getItemFromCatalog(oldValue);
for (final Item I : itemList)
{
list.append("<OPTION VALUE=\""+RoomData.getItemCode(itemList, I)+"\" ");
if((oldItem!=null)&&(oldItem.sameAs(I)))
list.append("SELECTED");
list.append(">");
list.append(I.Name()+RoomData.getObjIDSuffix(I));
}
list.append("<OPTION VALUE=\"\">------ CATALOGED -------");
final String[] names=CMLib.catalog().getCatalogItemNames();
for (final String name : names)
{
list.append("<OPTION VALUE=\"CATALOG-"+name+"\"");
if((oldItem!=null)
&&(CMLib.flags().isCataloged(oldItem))
&&(oldItem.Name().equalsIgnoreCase(name)))
list.append(" SELECTED");
list.append(">"+name);
}
return list.toString();
}
public List<MOB> getCatalogMobsForList(Physical[] fromList)
{
final List<MOB> toList=new Vector<MOB>();
for(Physical P : fromList)
{
P=(Physical)P.copyOf();
CMLib.catalog().changeCatalogUsage(P,true);
if(P instanceof MOB)
toList.add((MOB)P);
}
return toList;
}
public List<Item> getCatalogItemsForList(Physical[] fromList)
{
final List<Item> toList=new Vector<Item>();
for(Physical P : fromList)
{
P=(Physical)P.copyOf();
CMLib.catalog().changeCatalogUsage(P,true);
if(P instanceof Item)
toList.add((Item)P);
}
return toList;
}
private String mobList(List<MOB> mobList, MOB oldMob, String oldValue)
{
final StringBuffer list=new StringBuffer("");
if(oldMob==null) oldMob=RoomData.getMOBFromCatalog(oldValue);
for (final MOB M2 : mobList)
{
list.append("<OPTION VALUE=\""+RoomData.getMOBCode(mobList, M2)+"\" ");
if((oldMob!=null)&&(oldMob.sameAs(M2)))
list.append("SELECTED");
list.append(">");
list.append(M2.Name()+RoomData.getObjIDSuffix(M2));
}
list.append("<OPTION VALUE=\"\">------ CATALOGED -------");
final String[] names=CMLib.catalog().getCatalogMobNames();
for (final String name : names)
{
list.append("<OPTION VALUE=\"CATALOG-"+name+"\"");
if((oldMob!=null)
&&(CMLib.flags().isCataloged(oldMob))
&&(oldMob.Name().equalsIgnoreCase(name)))
list.append(" SELECTED");
list.append(">"+name);
}
return list.toString();
}
@Override
public String runMacro(HTTPRequest httpReq, String parm)
{
final java.util.Map<String,String> parms=parseParms(parm);
if((parms==null)||(parms.size()==0)) return "";
final MOB M = Authenticate.getAuthenticatedMob(httpReq);
if(M==null) return "[error -- no authenticated mob!]";
String qFileToGet=null;
if(parms.containsKey("QMFILETOGET"))
qFileToGet=parms.get("QMFILETOGET");
String qTemplate=httpReq.getUrlParameter("QMTEMPLATE");
if((qTemplate==null)||(qTemplate.length()==0)) qTemplate="";
String qPageStr=httpReq.getUrlParameter("QMPAGE");
if((qPageStr==null)||(qPageStr.length()==0)) qPageStr="";
String qPageErrors=httpReq.getUrlParameter("QMPAGEERRORS");
if((qPageErrors==null)||(qPageErrors.length()==0)) qPageErrors="";
if(parms.containsKey("QMPAGETITLE"))
{
final DVector pageData=getPage(M,httpReq,qTemplate,qPageStr,null);
if(pageData==null) return "[error -- no page selected!]";
return (String)pageData.elementAt(0,2);
}
else
if(parms.containsKey("QMPAGEINSTR"))
{
final DVector pageData=getPage(M,httpReq,qTemplate,qPageStr,null);
if(pageData==null) return "[error -- no page selected!]";
return (String)pageData.elementAt(0,3);
}
else
if(parms.containsKey("QMPAGEFIELDS"))
{
final DVector pageData=getPage(M,httpReq,qTemplate,qPageStr,qFileToGet);
if(pageData==null) return "[error - no page data?!]";
String labelColor=parms.get("LABELCOLOR");
if(labelColor==null) labelColor="<FONT COLOR=YELLOW><B>";
String descColor=parms.get("DESCCOLOR");
if(descColor==null) descColor="<FONT COLOR=WHITE><I>";
final StringBuffer list=new StringBuffer("");
if(qTemplate.length()==0)
{
String oldTemplate=httpReq.getUrlParameter("QMOLDTEMPLATE");
if((oldTemplate==null)||(oldTemplate.length()==0)) oldTemplate="";
for(int d=0;d<pageData.size();d++)
{
list.append("<TR><TD VALIGN=TOP><INPUT TYPE=RADIO NAME=QMTEMPLATE VALUE=\""+htmlOutgoingFilter((String)pageData.elementAt(d,3))+"\"");
if(pageData.elementAt(d,3).equals(oldTemplate))
list.append(" CHECKED");
list.append("> "+labelColor+(String)pageData.elementAt(d,1)+"</B></FONT></I></TD>");
list.append("<TD>"+descColor+(String)pageData.elementAt(d,2)+"</B></FONT></I></TD></TR>");
list.append("<TR><TD><BR></TD><TD><BR></TD></TR>");
}
return list.toString();
}
final List<String> V=new XVector<String>();
for(final String str : httpReq.getUrlParameters() )
if(keyPattern.matcher(str.toUpperCase().subSequence(0, str.length())).matches())
V.add(str.toUpperCase());
list.append("<TR><TD COLSPAN=2>");
for(int v=0;v<V.size();v++)
{
final String key=V.get(v);
if((!key.startsWith("AT_")))
continue;
boolean thisPage=false;
for(int step=1;step<pageData.size();step++)
{
final String keyName=(String)pageData.elementAt(step,2);
if(keyName.startsWith("$")
&&(key.substring(3).toUpperCase().equals(keyName.substring(1))
||(key.substring(3).toUpperCase().startsWith(keyName.substring(1)+"_")
&&CMath.isNumber(key.substring(3+keyName.length())))))
{ thisPage=true; break;}
}
if(thisPage) continue;
String oldVal=httpReq.getUrlParameter(key);
if(oldVal==null) oldVal="";
list.append("<INPUT TYPE=HIDDEN NAME="+key+" VALUE=\""+htmlOutgoingFilter(oldVal)+"\">\n\r");
}
list.append("</TD></TR>\n\r");
String lastLabel=null;
for(int step=1;step<pageData.size();step++)
{
final Integer stepType=(Integer)pageData.elementAt(step,1);
final String keyName=(String)pageData.elementAt(step,2);
final String defValue=(String)pageData.elementAt(step,3);
String httpKeyName=keyName;
if(httpKeyName.startsWith("$")) httpKeyName=httpKeyName.substring(1);
final String keyNameFixed=CMStrings.capitalizeAndLower(httpKeyName.replace('_',' '));
httpKeyName="AT_"+httpKeyName;
final boolean optionalEntry=CMath.bset(stepType.intValue(),QuestManager.QM_COMMAND_OPTIONAL);
final int inputCode=stepType.intValue()&QuestManager.QM_COMMAND_MASK;
String oldValue=httpReq.getUrlParameter(httpKeyName);
switch(inputCode)
{
case QuestManager.QM_COMMAND_$TITLE: break;
case QuestManager.QM_COMMAND_$LABEL: lastLabel=defValue; break;
case QuestManager.QM_COMMAND_$EXPRESSION:
case QuestManager.QM_COMMAND_$TIMEEXPRESSION:
case QuestManager.QM_COMMAND_$UNIQUE_QUEST_NAME:
{
if(oldValue==null) oldValue=defValue;
list.append("<TR><TD COLSPAN=2><BR></TD></TR>\n\r");
list.append("<TR><TD COLSPAN=2>"+descColor+lastLabel+"</B></FONT></I></TD></TR>\n\r");
list.append("<TR><TD>"+labelColor+keyNameFixed+"</B></FONT></I></TD>");
list.append("<TD><INPUT TYPE=TEXT SIZE=20 NAME="+httpKeyName+" ");
list.append(" VALUE=\""+htmlOutgoingFilter(oldValue)+"\"></TD></TR>");
break;
}
case QuestManager.QM_COMMAND_$LONG_STRING:
{
if(oldValue==null) oldValue=defValue;
list.append("<TR><TD COLSPAN=2><BR></TD></TR>\n\r");
list.append("<TR><TD COLSPAN=2>"+descColor+lastLabel+"</B></FONT></I></TD></TR>\n\r");
list.append("<TR><TD>"+labelColor+keyNameFixed+"</B></FONT></I></TD>");
list.append("<TD><TEXTAREA ROWS=3 COLS=40 NAME="+httpKeyName+">");
list.append(oldValue+"</TEXTAREA></TD></TR>");
break;
}
case QuestManager.QM_COMMAND_$ZAPPERMASK:
{
if(oldValue==null) oldValue=defValue;
list.append("<TR><TD COLSPAN=2><BR></TD></TR>\n\r");
list.append("<TR><TD COLSPAN=2>"+descColor+lastLabel+"</B></FONT></I></TD></TR>\n\r");
list.append("<TR><TD>"+labelColor+keyNameFixed+"</B></FONT></I></TD>");
list.append("<TD><TEXTAREA COLS=40 ROWS=2 NAME="+httpKeyName+">");
list.append(oldValue+"</TEXTAREA></TD></TR>");
break;
}
case QuestManager.QM_COMMAND_$STRING:
case QuestManager.QM_COMMAND_$ROOMID:
case QuestManager.QM_COMMAND_$NAME:
case QuestManager.QM_COMMAND_$AREA:
{
if(oldValue==null) oldValue=defValue;
list.append("<TR><TD COLSPAN=2><BR></TD></TR>\n\r");
list.append("<TR><TD COLSPAN=2>"+descColor+lastLabel+"</B></FONT></I></TD></TR>\n\r");
list.append("<TR><TD>"+labelColor+keyNameFixed+"</B></FONT></I></TD>");
list.append("<TD><INPUT TYPE=TEXT SIZE=40 NAME="+httpKeyName+" ");
list.append(" VALUE=\""+htmlOutgoingFilter(oldValue)+"\"></TD></TR>");
break;
}
case QuestManager.QM_COMMAND_$HIDDEN:
break;
case QuestManager.QM_COMMAND_$ABILITY:
{
if(oldValue==null) oldValue=defValue;
if(oldValue==null) oldValue="";
list.append("<TR><TD COLSPAN=2><BR></TD></TR>\n\r");
list.append("<TR><TD COLSPAN=2>"+descColor+lastLabel+"</B></FONT></I></TD></TR>\n\r");
list.append("<TR><TD>"+labelColor+keyNameFixed+"</B></FONT></I></TD>");
list.append("<TD><SELECT NAME="+httpKeyName+">");
if(optionalEntry) list.append("<OPTION VALUE=\"\" "+((oldValue.length()==0)?"SELECTED":"")+">");
Ability A=null;
for(final Enumeration<Ability> e=CMClass.abilities();e.hasMoreElements();)
{
A=e.nextElement();
if(((A.classificationCode()&Ability.ALL_DOMAINS)==Ability.DOMAIN_ARCHON)&&(!CMSecurity.isASysOp(M)))
continue;
list.append("<OPTION VALUE=\""+A.ID()+"\" ");
if(oldValue.equals(A.ID())) list.append("SELECTED");
list.append(">");
list.append(A.ID());
}
list.append("</SELECT>");
list.append("</TD></TR>");
break;
}
case QuestManager.QM_COMMAND_$EXISTING_QUEST_NAME:
{
if(oldValue==null) oldValue=defValue;
if(oldValue==null) oldValue="";
list.append("<TR><TD COLSPAN=2><BR></TD></TR>\n\r");
list.append("<TR><TD COLSPAN=2>"+descColor+lastLabel+"</B></FONT></I></TD></TR>\n\r");
list.append("<TR><TD>"+labelColor+keyNameFixed+"</B></FONT></I></TD>");
list.append("<TD><SELECT NAME="+httpKeyName+">");
if(optionalEntry) list.append("<OPTION VALUE=\"\" "+((oldValue.length()==0)?"SELECTED":"")+">");
for(int q=0;q<CMLib.quests().numQuests();q++)
{
final Quest Q2=CMLib.quests().fetchQuest(q);
list.append("<OPTION VALUE=\""+Q2.name()+"\" ");
if(oldValue.equals(Q2.name())) list.append("SELECTED");
list.append(">");
list.append(Q2.name());
}
list.append("</SELECT>");
list.append("</TD></TR>");
break;
}
case QuestManager.QM_COMMAND_$CHOOSE:
{
list.append("<TR><TD COLSPAN=2><BR></TD></TR>\n\r");
list.append("<TR><TD COLSPAN=2>"+descColor+lastLabel+"</B></FONT></I></TD></TR>\n\r");
list.append("<TR><TD>"+labelColor+keyNameFixed+"</B></FONT></I></TD>");
list.append("<TD><SELECT NAME="+httpKeyName+">");
final List<String> options=CMParms.parseCommas(defValue.toUpperCase(),true);
if(optionalEntry) options.add(0,"");
for(int o=0;o<options.size();o++)
{
final String val=options.get(o);
list.append("<OPTION VALUE=\""+val+"\" ");
if(val.equalsIgnoreCase(oldValue)) list.append("SELECTED");
list.append(">");
list.append(val);
}
list.append("</SELECT></TD></TR>");
break;
}
case QuestManager.QM_COMMAND_$ITEMXML:
{
if(oldValue==null) oldValue=defValue;
if(oldValue==null) oldValue="";
List<Item> itemList=new Vector();
itemList=RoomData.contributeItems(itemList);
final Item oldItem=RoomData.getItemFromAnywhere(itemList,oldValue);
list.append("<TR><TD COLSPAN=2><BR></TD></TR>\n\r");
list.append("<TR><TD COLSPAN=2>"+descColor+lastLabel+"</B></FONT></I></TD></TR>\n\r");
list.append("<TR><TD>"+labelColor+keyNameFixed+"</B></FONT></I></TD>");
list.append("<TD><SELECT NAME="+httpKeyName+">");
if(optionalEntry) list.append("<OPTION VALUE=\"\" "+((oldValue.length()==0)?"SELECTED":"")+">");
list.append(itemList(itemList,oldItem,oldValue));
list.append("</SELECT>");
list.append("<INPUT TYPE=BUTTON NAME=BUTT_"+httpKeyName+" VALUE=\"NEW\" ONCLICK=\"AddNewItem();\">");
list.append("</TD></TR>");
break;
}
case QuestManager.QM_COMMAND_$ITEMXML_ONEORMORE:
{
if(oldValue==null) oldValue=defValue;
List<Item> itemList=new Vector();
itemList=RoomData.contributeItems(itemList);
final Vector oldValues=new Vector();
int which=1;
oldValue=httpReq.getUrlParameter(httpKeyName+"_"+which);
while(oldValue!=null)
{
if((!oldValue.equalsIgnoreCase("DELETE"))&&(oldValue.length()>0))
oldValues.addElement(oldValue);
which++;
oldValue=httpReq.getUrlParameter(httpKeyName+"_"+which);
}
oldValues.addElement("");
for(int i=0;i<oldValues.size();i++)
{
oldValue=(String)oldValues.elementAt(i);
final Item oldItem=(oldValue.length()>0)?RoomData.getItemFromAnywhere(itemList,oldValue):null;
if(i==0)
{
list.append("<TR><TD COLSPAN=2><BR></TD></TR>\n\r");
list.append("<TR><TD COLSPAN=2>"+descColor+lastLabel+"</B></FONT></I></TD></TR>\n\r");
}
list.append("<TR><TD>"+labelColor+keyNameFixed+"</B></FONT></I></TD>");
list.append("<TD><SELECT NAME="+httpKeyName+"_"+(i+1)+" ONCHANGE=\"Refresh();\">");
if(i<oldValues.size()-1) list.append("<OPTION VALUE=\"DELETE\">Delete!");
if(oldValue.length()==0) list.append("<OPTION VALUE=\"\" "+((oldValue.length()==0)?"SELECTED":"")+">");
list.append(itemList(itemList,oldItem,oldValue));
list.append("</SELECT>");
if(i==oldValues.size()-1)
list.append("<INPUT TYPE=BUTTON NAME=BUTT_"+httpKeyName+" VALUE=\"NEW\" ONCLICK=\"AddNewItem();\">");
list.append("</TD></TR>");
}
break;
}
case QuestManager.QM_COMMAND_$MOBXML:
{
if(oldValue==null) oldValue=defValue;
if(oldValue != null)
{
List<MOB> mobList=new Vector();
mobList=RoomData.contributeMOBs(mobList);
final MOB oldMob=RoomData.getMOBFromCode(mobList,oldValue);
list.append("<TR><TD COLSPAN=2><BR></TD></TR>\n\r");
list.append("<TR><TD COLSPAN=2>"+descColor+lastLabel+"</B></FONT></I></TD></TR>\n\r");
list.append("<TR><TD>"+labelColor+keyNameFixed+"</B></FONT></I></TD>");
list.append("<TD><SELECT NAME="+httpKeyName+">");
if(optionalEntry) list.append("<OPTION VALUE=\"\" "+((oldValue.length()==0)?"SELECTED":"")+">");
list.append(mobList(mobList,oldMob,oldValue));
list.append("</SELECT>");
list.append("<INPUT TYPE=BUTTON NAME=BUTT_"+httpKeyName+" VALUE=\"NEW\" ONCLICK=\"AddNewMob();\">");
list.append("</TD></TR>");
}
break;
}
case QuestManager.QM_COMMAND_$MOBXML_ONEORMORE:
{
if(oldValue==null) oldValue=defValue;
final List<MOB>mobList=RoomData.contributeMOBs(new Vector<MOB>());
final Vector oldValues=new Vector();
int which=1;
oldValue=httpReq.getUrlParameter(httpKeyName+"_"+which);
while(oldValue!=null)
{
if((!oldValue.equalsIgnoreCase("DELETE"))&&(oldValue.length()>0))
oldValues.addElement(oldValue);
which++;
oldValue=httpReq.getUrlParameter(httpKeyName+"_"+which);
}
oldValues.addElement("");
for(int i=0;i<oldValues.size();i++)
{
oldValue=(String)oldValues.elementAt(i);
final MOB oldMob=(oldValue.length()>0)?RoomData.getMOBFromCode(mobList,oldValue):null;
if(i==0)
{
list.append("<TR><TD COLSPAN=2><BR></TD></TR>\n\r");
list.append("<TR><TD COLSPAN=2>"+descColor+lastLabel+"</B></FONT></I></TD></TR>\n\r");
}
list.append("<TR><TD>"+labelColor+keyNameFixed+"</B></FONT></I></TD>");
list.append("<TD><SELECT NAME="+httpKeyName+"_"+(i+1)+" ONCHANGE=\"Refresh();\">");
if(i<oldValues.size()-1) list.append("<OPTION VALUE=\"DELETE\">Delete!");
if(oldValue.length()==0) list.append("<OPTION VALUE=\"\" "+((oldValue.length()==0)?"SELECTED":"")+">");
list.append(mobList(mobList,oldMob,oldValue));
list.append("</SELECT>");
if(i==oldValues.size()-1)
list.append("<INPUT TYPE=BUTTON NAME=BUTT_"+httpKeyName+" VALUE=\"NEW\" ONCLICK=\"AddNewMob();\">");
list.append("</TD></TR>");
}
break;
}
case QuestManager.QM_COMMAND_$FACTION:
{
if(oldValue==null) oldValue=defValue;
if(oldValue==null) oldValue="";
list.append("<TR><TD COLSPAN=2><BR></TD></TR>\n\r");
list.append("<TR><TD COLSPAN=2>"+descColor+lastLabel+"</B></FONT></I></TD></TR>\n\r");
list.append("<TR><TD>"+labelColor+keyNameFixed+"</B></FONT></I></TD>");
list.append("<TD><SELECT NAME="+httpKeyName+">");
if(optionalEntry) list.append("<OPTION VALUE=\"\" "+((oldValue.length()==0)?"SELECTED":"")+">");
for(final Enumeration f=CMLib.factions().factions();f.hasMoreElements();)
{
final Faction F=(Faction)f.nextElement();
final String fkey=F.factionID().toUpperCase().trim();
list.append("<OPTION VALUE=\""+fkey+"\" ");
if(oldValue.equals(fkey)) list.append("SELECTED");
list.append(">");
list.append(F.name());
}
list.append("</SELECT>");
list.append("</TD></TR>");
break;
}
}
}
return list.toString();
}
else
if(parms.containsKey("QMLASTPAGE"))
{
final DVector pageData=getPage(M,httpReq,qTemplate,qPageStr,null);
if(pageData==null) return "false";
final DVector filePages=(DVector)httpReq.getRequestObjects().get("QM_FILE_PAGES");
if(filePages==null) return "false";
return(((Vector)filePages.elementAt(0,4)).lastElement()==pageData)?"true":"false";
}
else
if(parms.containsKey("QMPAGEERRORS")) return qPageErrors;
else
if(parms.containsKey("QMERRORS")) return qPageErrors;
else
if(parms.containsKey("QMTEMPLATE")) return qTemplate;
else
if(parms.containsKey("QMPAGE")) return qPageStr;
else
if(parms.containsKey("NEXT")||parms.containsKey("FINISH"))
{
if((qTemplate.length()>0)&&(CMath.s_int(qPageStr)<=0))
{
httpReq.addFakeUrlParameter("QMPAGE","1");
httpReq.addFakeUrlParameter("QMERRORS","");
httpReq.addFakeUrlParameter("QMPAGEERRORS","");
return "";
}
if(qTemplate.length()==0) return "[error - no template chosen?!]";
final DVector pageData=getPage(M,httpReq,qTemplate,qPageStr,null);
if(pageData==null) return "[error - no page data?!]";
final StringBuffer errors=new StringBuffer("");
for(int step=1;step<pageData.size();step++)
{
final Integer stepType=(Integer)pageData.elementAt(step,1);
final String keyName=(String)pageData.elementAt(step,2);
final String defValue=(String)pageData.elementAt(step,3);
String httpKeyName=keyName;
if(httpKeyName.startsWith("$")) httpKeyName=httpKeyName.substring(1);
final String keyNameFixed=CMStrings.capitalizeAndLower(httpKeyName.replace('_',' '));
httpKeyName="AT_"+httpKeyName;
final boolean optionalEntry=CMath.bset(stepType.intValue(),QuestManager.QM_COMMAND_OPTIONAL);
final int inputCode=stepType.intValue()&QuestManager.QM_COMMAND_MASK;
String oldValue=httpReq.getUrlParameter(httpKeyName);
final GenericEditor.CMEval eval= QuestManager.QM_COMMAND_TESTS[inputCode];
try
{
switch(inputCode)
{
case QuestManager.QM_COMMAND_$TITLE: break;
case QuestManager.QM_COMMAND_$LABEL: break;
case QuestManager.QM_COMMAND_$HIDDEN:
httpReq.addFakeUrlParameter(httpKeyName,defValue);
break;
case QuestManager.QM_COMMAND_$ITEMXML_ONEORMORE:
{
final List<Item> rawitemlist=RoomData.contributeItems(new Vector<Item>());
rawitemlist.addAll(getCatalogItemsForList(CMLib.catalog().getCatalogItems()));
final Vector oldValues=new Vector();
int which=1;
oldValue=httpReq.getUrlParameter(httpKeyName+"_"+which);
while(oldValue!=null)
{
if((!oldValue.equalsIgnoreCase("DELETE"))&&(oldValue.length()>0))
oldValues.addElement(oldValue);
which++;
oldValue=httpReq.getUrlParameter(httpKeyName+"_"+which);
}
if(oldValues.size()==0) oldValues.addElement("");
String newVal="";
for(int i=0;i<oldValues.size();i++)
{
oldValue=(String)oldValues.elementAt(i);
Item I2=oldValue.length()>0?RoomData.getItemFromAnywhere(rawitemlist,oldValue):null;
if(I2==null)
I2=oldValue.length()>0?RoomData.getItemFromCatalog(oldValue):null;
if(I2!=null)
{
if(CMLib.flags().isCataloged(I2))
oldValue=CMLib.english().getContextSameName(rawitemlist,I2);
else
oldValue=CMLib.english().getContextName(rawitemlist,I2);
}
final Object[] choices=rawitemlist.toArray();
final String thisVal=(String)eval.eval(oldValue,choices,optionalEntry);
if(thisVal.length()>0)
{
final Item I3=(Item)CMLib.english().fetchEnvironmental(rawitemlist, thisVal, false);
if(I3!=null)
{
if(CMLib.flags().isCataloged(I3))
newVal+="CATALOG-"+I3.Name()+";";
else
newVal+=RoomData.getItemCode(rawitemlist, I3)+";";
}
}
}
httpReq.addFakeUrlParameter(httpKeyName,newVal);
break;
}
case QuestManager.QM_COMMAND_$ITEMXML:
{
final List<Item> rawitemlist=RoomData.contributeItems(new Vector<Item>());
rawitemlist.addAll(getCatalogItemsForList(CMLib.catalog().getCatalogItems()));
if(oldValue==null) oldValue="";
Item I2=oldValue.length()>0?RoomData.getItemFromAnywhere(rawitemlist,oldValue):null;
if(I2==null)
I2=oldValue.length()>0?RoomData.getItemFromCatalog(oldValue):null;
if(I2!=null)
{
if(CMLib.flags().isCataloged(I2))
oldValue=CMLib.english().getContextSameName(rawitemlist,I2);
else
oldValue=CMLib.english().getContextName(rawitemlist,I2);
}
final Object[] choices=rawitemlist.toArray();
String newVal=(String)eval.eval(oldValue,choices,optionalEntry);
if(newVal.length()>0)
{
final Item I3=(Item)CMLib.english().fetchEnvironmental(rawitemlist, newVal, false);
if(I3!=null)
{
if(CMLib.flags().isCataloged(I3))
newVal="CATALOG-"+I3.Name()+";";
else
newVal=RoomData.getItemCode(rawitemlist, I3)+";";
}
}
httpReq.addFakeUrlParameter(httpKeyName,newVal);
break;
}
case QuestManager.QM_COMMAND_$MOBXML_ONEORMORE:
{
final List<MOB> rawmoblist=RoomData.contributeMOBs(new Vector<MOB>());
rawmoblist.addAll(getCatalogMobsForList(CMLib.catalog().getCatalogMobs()));
final Vector oldValues=new Vector();
int which=1;
oldValue=httpReq.getUrlParameter(httpKeyName+"_"+which);
while(oldValue!=null)
{
if((!oldValue.equalsIgnoreCase("DELETE"))&&(oldValue.length()>0))
oldValues.addElement(oldValue);
which++;
oldValue=httpReq.getUrlParameter(httpKeyName+"_"+which);
}
if(oldValues.size()==0) oldValues.addElement("");
String newVal="";
for(int i=0;i<oldValues.size();i++)
{
oldValue=(String)oldValues.elementAt(i);
MOB M2=oldValue.length()>0?RoomData.getMOBFromCode(rawmoblist,oldValue):null;
if(M2==null)
M2=oldValue.length()>0?RoomData.getMOBFromCatalog(oldValue):null;
if(M2!=null)
{
if(CMLib.flags().isCataloged(M2))
oldValue=CMLib.english().getContextSameName(rawmoblist,M2);
else
oldValue=CMLib.english().getContextName(rawmoblist,M2);
}
final Object[] choices=rawmoblist.toArray();
final String thisVal=(String)eval.eval(oldValue,choices,optionalEntry);
if(thisVal.length()>0)
{
final MOB M3=(MOB)CMLib.english().fetchEnvironmental(rawmoblist, thisVal, false);
if(M3!=null)
{
if(CMLib.flags().isCataloged(M3))
newVal+="CATALOG-"+M3.Name()+";";
else
newVal+=RoomData.getMOBCode(rawmoblist, M3)+";";
}
}
}
httpReq.addFakeUrlParameter(httpKeyName,newVal);
break;
}
case QuestManager.QM_COMMAND_$MOBXML:
{
final List<MOB> rawmoblist=RoomData.contributeMOBs(new Vector<MOB>());
rawmoblist.addAll(getCatalogMobsForList(CMLib.catalog().getCatalogMobs()));
if(oldValue==null) oldValue="";
MOB M2=oldValue.length()>0?RoomData.getMOBFromCode(rawmoblist,oldValue):null;
if(M2==null)
M2=oldValue.length()>0?RoomData.getMOBFromCatalog(oldValue):null;
if(M2!=null)
{
if(CMLib.flags().isCataloged(M2))
oldValue=CMLib.english().getContextSameName(rawmoblist,M2);
else
oldValue=CMLib.english().getContextName(rawmoblist,M2);
}
final Object[] choices=rawmoblist.toArray();
String newVal=(String)eval.eval(oldValue,choices,optionalEntry);
if(newVal.length()>0)
{
final MOB M3=(MOB)CMLib.english().fetchEnvironmental(rawmoblist, newVal, false);
if(M3!=null)
{
if(CMLib.flags().isCataloged(M3))
newVal="CATALOG-"+M3.Name()+";";
else
newVal=RoomData.getMOBCode(rawmoblist, M3)+";";
}
}
httpReq.addFakeUrlParameter(httpKeyName,newVal);
break;
}
case QuestManager.QM_COMMAND_$CHOOSE:
{
if(oldValue==null) oldValue="";
final Object[] choices=CMParms.parseCommas(defValue.toUpperCase(),true).toArray();
final String newVal=(String)eval.eval(oldValue,choices,optionalEntry);
httpReq.addFakeUrlParameter(httpKeyName,newVal);
break;
}
default:
{
if(oldValue==null) oldValue="";
final String newVal=(String)eval.eval(oldValue,null,optionalEntry);
httpReq.addFakeUrlParameter(httpKeyName,newVal);
break;
}
}
}
catch(final CMException e)
{
errors.append("Error in field '"+keyNameFixed+"': "+e.getMessage()+"<BR>");
}
}
httpReq.addFakeUrlParameter("QMPAGEERRORS",errors.toString());
if(errors.toString().length()>0) return "";
if(parms.containsKey("FINISH"))
{
String name="";
final DVector filePages=(DVector)httpReq.getRequestObjects().get("QM_FILE_PAGES");
String script=((StringBuffer)filePages.elementAt(0,5)).toString();
String var=null;
String val=null;
final List<DVector> qPages=(List<DVector>)filePages.elementAt(0,4);
for(int page=0;page<qPages.size();page++)
{
final DVector pageDV=qPages.get(page);
for(int v=0;v<pageDV.size();v++)
{
var=(String)pageDV.elementAt(v,2);
String httpKeyName=var;
if(httpKeyName.startsWith("$"))
httpKeyName=httpKeyName.substring(1);
else
continue;
httpKeyName="AT_"+httpKeyName;
val=httpReq.getUrlParameter(httpKeyName);
if(val==null) val="";
switch(((Integer)pageDV.elementAt(v,1)).intValue()&QuestManager.QM_COMMAND_MASK)
{
case QuestManager.QM_COMMAND_$UNIQUE_QUEST_NAME:
name=val;
break;
case QuestManager.QM_COMMAND_$ITEMXML:
case QuestManager.QM_COMMAND_$ITEMXML_ONEORMORE:
{
final List<String> V=CMParms.parseSemicolons(val,true);
val="";
for(int v1=0;v1<V.size();v1++)
{
Item I=RoomData.getItemFromCode(RoomData.getItemCache(),V.get(v1));
if(I==null)
I=RoomData.getItemFromAnywhere(RoomData.getItemCache(),V.get(v1));
if(I==null)
I=RoomData.getItemFromCatalog(V.get(v1));
if(I!=null)
val+=CMLib.coffeeMaker().getItemXML(I).toString();
}
break;
}
case QuestManager.QM_COMMAND_$MOBXML:
case QuestManager.QM_COMMAND_$MOBXML_ONEORMORE:
{
final List<String> V=CMParms.parseSemicolons(val,true);
val="";
for(int v1=0;v1<V.size();v1++)
{
MOB M2=RoomData.getMOBFromCode(RoomData.getMOBCache(),V.get(v1));
if(M2==null) M2=RoomData.getMOBFromCatalog(V.get(v1));
if(M2!=null)
val+=CMLib.coffeeMaker().getMobXML(M2).toString();
}
break;
}
}
script=CMStrings.replaceAll(script,var,val);
}
}
script=CMStrings.replaceAll(script,"$#AUTHOR",M.Name());
final Quest Q=(Quest)CMClass.getCommon("DefaultQuest");
final CMFile newQF=new CMFile(Resources.makeFileResourceName("quests/"+name+".quest"),M,CMFile.FLAG_LOGERRORS);
if(!newQF.saveText(script))
{
httpReq.addFakeUrlParameter("QMPAGEERRORS","Unable to save your quest. Please consult the log.");
return "";
}
Q.setScript("LOAD=quests/"+name+".quest",true);
if((Q.name().trim().length()==0)||(Q.duration()<0))
{
httpReq.addFakeUrlParameter("QMPAGEERRORS","Unable to create your quest. Please consult the log.");
return "";
}
final Quest badQ=CMLib.quests().fetchQuest(name);
if(badQ!=null)
{
httpReq.addFakeUrlParameter("QMPAGEERRORS","Unable to create your quest. One of that name already exists!");
return "";
}
Log.sysOut("QuestMgr",M.Name()+" created quest '"+Q.name()+"'");
CMLib.quests().addQuest(Q);
CMLib.quests().save();
}
httpReq.addFakeUrlParameter("QMPAGE",""+(CMath.s_int(qPageStr)+1));
return "";
}
else
if(parms.containsKey("BACK"))
{
final int pageNumber=CMath.s_int(qPageStr);
if(pageNumber>1)
httpReq.addFakeUrlParameter("QMPAGE",""+(CMath.s_int(qPageStr)-1));
else
{
httpReq.addFakeUrlParameter("QMTEMPLATE","");
httpReq.addFakeUrlParameter("QMPAGE","");
}
}
return "";
}
}
| apache-2.0 |
openknowledge/jaxrs-versioning | jaxrs-versioning/src/main/java/de/openknowledge/jaxrs/versioning/conversion/Version.java | 1612 | /*
* Copyright (C) open knowledge GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package de.openknowledge.jaxrs.versioning.conversion;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.ext.InterceptorContext;
/**
* @author Arne Limburg - open knowledge GmbH
*/
public class Version {
private static final String VERSION_PROPERTY_NAME = Version.class.getName().toLowerCase();
private static final ThreadLocal<String> VERSION = new ThreadLocal<String>();
public static String get(InterceptorContext context) {
return VERSION.get();
// return (String)context.getProperty(VERSION_PROPERTY_NAME);
}
public static String get(ContainerRequestContext context) {
return VERSION.get();
// return (String)context.getProperty(VERSION_PROPERTY_NAME);
}
public static void set(ContainerRequestContext context, String version) {
VERSION.set(version);
// context.setProperty(VERSION_PROPERTY_NAME, version);
}
public static void unset(InterceptorContext context) {
VERSION.remove();
// context.removeProperty(VERSION_PROPERTY_NAME);
}
}
| apache-2.0 |
ohac/sha1coinj | core/src/main/java/com/google/sha1coin/core/AbstractWalletEventListener.java | 1767 | /**
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.sha1coin.core;
import com.google.sha1coin.script.Script;
import com.google.sha1coin.wallet.AbstractKeyChainEventListener;
import java.util.List;
/**
* Convenience implementation of {@link WalletEventListener}.
*/
public abstract class AbstractWalletEventListener extends AbstractKeyChainEventListener implements WalletEventListener {
@Override
public void onCoinsReceived(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) {
onChange();
}
@Override
public void onCoinsSent(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) {
onChange();
}
@Override
public void onReorganize(Wallet wallet) {
onChange();
}
@Override
public void onTransactionConfidenceChanged(Wallet wallet, Transaction tx) {
onChange();
}
@Override
public void onKeysAdded(List<ECKey> keys) {
onChange();
}
@Override
public void onScriptsAdded(Wallet wallet, List<Script> scripts) {
onChange();
}
@Override
public void onWalletChanged(Wallet wallet) {
onChange();
}
public void onChange() {
}
}
| apache-2.0 |
OkieOth/othCache | memcachedCacheImpl/src/main/java/de/othsoft/cache/memcached/CacheImpl.java | 18579 | /*
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.othsoft.cache.memcached;
import de.othsoft.cache.base.ICache;
import de.othsoft.cache.base.error.CacheException;
import de.othsoft.cache.base.util.CacheValue;
import de.othsoft.helper.base.Identifier;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeoutException;
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.XMemcachedClient;
import net.rubyeye.xmemcached.exception.MemcachedException;
import net.rubyeye.xmemcached.transcoders.IntegerTranscoder;
import net.rubyeye.xmemcached.transcoders.LongTranscoder;
import net.rubyeye.xmemcached.transcoders.StringTranscoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author eiko
*/
public class CacheImpl implements ICache {
private final static int MAX_EXPIRES=7*24*60*60; // one week - no better idea
MemcachedClient client = null;
String serverAddr = null;
int serverPort = 0;
long timeout=5000;
private static long appCount;
private static long userCount;
private final static long KEY_BASE = new Date().getTime();
private static final StringTranscoder STRING_TRANSCODER = new StringTranscoder("UTF-8");
private static final IntegerTranscoder INT_TRANSCODER = new IntegerTranscoder();
private static final LongTranscoder LONG_TRANSCODER = new LongTranscoder();
/**
*
* @param address address of memcached server, something like 127.0.0.1:12000
*/
public void setServer(String address,int port) {
try {
this.serverAddr=address;
if (client!=null) {
client = null;
}
client=new XMemcachedClient(address,port);
}
catch(IOException e) {
logger.error("<<{}>> error while create memcached client for address {}: [{}] {}",
Identifier.getInst().getName(),address,e.getClass().getName(),e.getMessage());
client = null;
this.serverAddr = null;
}
}
public void closeServerCon() {
if (client instanceof XMemcachedClient) {
logger.info("<<{}>> remove server with addr {}",
Identifier.getInst().getName(),serverAddr);
try {
((XMemcachedClient)client).shutdown();
}
catch(IOException io) {
logger.error("<<{}>> error while close memcached client for address {}: [{}] {}",
Identifier.getInst().getName(),serverAddr,io.getClass().getName(),io.getMessage());
}
}
client = null;
}
private void checkInitAndIfWrongThrowException() throws CacheException {
if (client==null) {
throw new CacheException("memcached client not initialized");
}
}
private String getMemcachedKey(String appKey,String userKey,String entryKey) {
return appKey+"_"+userKey+"_"+entryKey;
}
@Override
public synchronized String createUniqueUserKey(String base) throws CacheException{
userCount++;
return String.format("%d-%s-%d", KEY_BASE,base,userCount);
}
@Override
public synchronized String createUniqueAppKey(String base) throws CacheException{
appCount++;
return String.format("%d-%s-%d", KEY_BASE,base,appCount);
}
@Override
public void setStrValue(String appKey,String userKey,String entryKey, String value,int expireSeconds) throws CacheException {
if (value==null) throw new CacheException("setStrValue - null values are not allowed");
checkInitAndIfWrongThrowException();
String memcachedKey=getMemcachedKey(appKey, userKey, entryKey);
try {
client.set(memcachedKey,expireSeconds,value);
}
catch(TimeoutException | InterruptedException | MemcachedException e) {
throw new CacheException(e,String.format("error while setStrValue - app: %s, user: %s, key: %s",
appKey,userKey,entryKey));
}
}
@Override
public void setStrValue(String appKey,String userKey,String entryKey,String value) throws CacheException {
if (value==null) throw new CacheException("setStrValue - null values are not allowed");
checkInitAndIfWrongThrowException();
String memcachedKey=getMemcachedKey(appKey, userKey,entryKey);
try {
client.set(memcachedKey,MAX_EXPIRES,value);
}
catch(TimeoutException | InterruptedException | MemcachedException e) {
throw new CacheException(e,String.format("error while setStrValue - app: %s, user: %s, key: %s",
appKey,userKey,entryKey));
}
}
@Override
public void setBoolValue(String appKey,String userKey,String entryKey,Boolean value,int expireSeconds) throws CacheException {
checkInitAndIfWrongThrowException();
String memcachedKey=getMemcachedKey(appKey, userKey,entryKey);
try {
if (value==null)
client.delete(memcachedKey);
else {
int iValue = value ? 1 : 0;
client.set(memcachedKey,expireSeconds,iValue);
}
}
catch(TimeoutException | InterruptedException | MemcachedException e) {
throw new CacheException(e,String.format("error while setBoolValue - app: %s, user: %s, key: %s",
appKey,userKey,entryKey));
}
}
@Override
public void setBoolValue(String appKey,String userKey,String entryKey,Boolean value) throws CacheException {
checkInitAndIfWrongThrowException();
String memcachedKey=getMemcachedKey(appKey, userKey,entryKey);
try {
if (value==null)
client.delete(memcachedKey);
else {
int iValue = value ? 1 : 0;
client.set(memcachedKey,MAX_EXPIRES,iValue);
}
}
catch(TimeoutException | InterruptedException | MemcachedException e) {
throw new CacheException(e,String.format("error while setBoolValue - app: %s, user: %s, key: %s",
appKey,userKey,entryKey));
}
}
@Override
public void setIntValue(String appKey,String userKey,String entryKey,Integer value,int expireSeconds) throws CacheException {
checkInitAndIfWrongThrowException();
String memcachedKey=getMemcachedKey(appKey, userKey,entryKey);
try {
if (value==null)
client.delete(memcachedKey);
else
client.set(memcachedKey,expireSeconds,value);
}
catch(TimeoutException | InterruptedException | MemcachedException e) {
throw new CacheException(e,String.format("error while setIntValue - app: %s, user: %s, key: %s",
appKey,userKey,entryKey));
}
}
@Override
public void setIntValue(String appKey,String userKey,String entryKey,Integer value) throws CacheException {
checkInitAndIfWrongThrowException();
String memcachedKey=getMemcachedKey(appKey, userKey,entryKey);
try {
if (value==null)
client.delete(memcachedKey);
else
client.set(memcachedKey,MAX_EXPIRES,value);
}
catch(TimeoutException | InterruptedException | MemcachedException e) {
throw new CacheException(e,String.format("error while setIntValue - app: %s, user: %s, key: %s",
appKey,userKey,entryKey));
}
}
@Override
public void setLongValue(String appKey,String userKey,String entryKey,Long value,int expireSeconds) throws CacheException {
checkInitAndIfWrongThrowException();
String memcachedKey=getMemcachedKey(appKey, userKey,entryKey);
try {
if (value==null)
client.delete(memcachedKey);
else
client.set(memcachedKey,expireSeconds,value);
}
catch(TimeoutException | InterruptedException | MemcachedException e) {
throw new CacheException(e,String.format("error while setLongValue - app: %s, user: %s, key: %s",
appKey,userKey,entryKey));
}
}
@Override
public void setLongValue(String appKey,String userKey,String entryKey,Long value) throws CacheException {
checkInitAndIfWrongThrowException();
String memcachedKey=getMemcachedKey(appKey, userKey,entryKey);
try {
if (value==null)
client.delete(memcachedKey);
else
client.set(memcachedKey,MAX_EXPIRES,value);
}
catch(TimeoutException | InterruptedException | MemcachedException e) {
throw new CacheException(e,String.format("error while setLongValue - app: %s, user: %s, key: %s",
appKey,userKey,entryKey));
}
}
@Override
public void setValues(String appKey,String userKey,List<CacheValue> cacheValueArray) throws CacheException {
checkInitAndIfWrongThrowException();
try {
for (CacheValue cacheValue:cacheValueArray) {
String memcachedKey=getMemcachedKey(appKey, userKey,cacheValue.getKey());
if (cacheValue.getType()==String.class) {
String v = (String) cacheValue.getValue();
if (v==null)
client.delete(memcachedKey);
else
client.set(memcachedKey,cacheValue.getExpireSeconds(),v);
}
else if (cacheValue.getType()==Integer.class) {
Integer v = (Integer) cacheValue.getValue();
if (v==null)
client.delete(memcachedKey);
else
client.set(memcachedKey,cacheValue.getExpireSeconds(),v);
}
else if (cacheValue.getType()==Long.class) {
Long v = (Long) cacheValue.getValue();
if (v==null)
client.delete(memcachedKey);
else
client.set(memcachedKey,cacheValue.getExpireSeconds(),v);
}
else if (cacheValue.getType()==Boolean.class) {
Boolean b = (Boolean)cacheValue.getValue();
if (b==null)
client.delete(memcachedKey);
else if (b==true)
client.set(memcachedKey,cacheValue.getExpireSeconds(),1);
else
client.set(memcachedKey,cacheValue.getExpireSeconds(),0);
}
}
}
catch(TimeoutException | InterruptedException | MemcachedException e) {
throw new CacheException(e,String.format("error while setValues - app: %s, user: %s",appKey,userKey));
}
}
@Override
public void touchValues(String appKey,String userKey,List<String> keyArray,int expireSeconds) throws CacheException {
checkInitAndIfWrongThrowException();
try {
for (String entryKey:keyArray) {
String memcachedKey=getMemcachedKey(appKey, userKey,entryKey);
client.touch(memcachedKey,expireSeconds);
}
}
catch(TimeoutException | InterruptedException | MemcachedException e) {
throw new CacheException(e,String.format("error while touchValues - app: %s, user: %s",appKey,userKey));
}
}
@Override
public void touchValue(String appKey,String userKey,String entryKey,int expireSeconds) throws CacheException {
checkInitAndIfWrongThrowException();
String memcachedKey=getMemcachedKey(appKey, userKey,entryKey);
try {
client.touch(memcachedKey,expireSeconds);
}
catch(TimeoutException | InterruptedException | MemcachedException e) {
throw new CacheException(e,String.format("error while touchValue - app: %s, user: %s, key: %s",
appKey,userKey,entryKey));
}
}
@Override
public void removeValues(String appKey,String userKey,List<String> keyArray) throws CacheException {
checkInitAndIfWrongThrowException();
try {
for (String entryKey:keyArray) {
String memcachedKey=getMemcachedKey(appKey, userKey,entryKey);
client.delete(memcachedKey);
}
}
catch(TimeoutException | InterruptedException | MemcachedException e) {
throw new CacheException(e,String.format("error while removeValues - app: %s, user: %s",
appKey,userKey));
}
}
@Override
public void removeValue(String appKey,String userKey,String entryKey) throws CacheException {
checkInitAndIfWrongThrowException();
String memcachedKey=getMemcachedKey(appKey, userKey,entryKey);
try {
client.delete(memcachedKey);
}
catch(TimeoutException | InterruptedException | MemcachedException e) {
throw new CacheException(e,String.format("error while removeValue - app: %s, user: %s, key: %s",
appKey,userKey,entryKey));
}
}
@Override
public String getStrValue(String appKey,String userKey,String entryKey) throws CacheException {
checkInitAndIfWrongThrowException();
String memcachedKey=getMemcachedKey(appKey, userKey,entryKey);
try {
return client.get(memcachedKey,timeout,STRING_TRANSCODER);
}
catch(TimeoutException | InterruptedException | MemcachedException e) {
throw new CacheException(e,String.format("error while getStrValue - app: %s, user: %s, key: %s",
appKey,userKey,entryKey));
}
}
@Override
public Boolean getBoolValue(String appKey,String userKey,String entryKey) throws CacheException {
checkInitAndIfWrongThrowException();
String memcachedKey=getMemcachedKey(appKey, userKey,entryKey);
try {
Integer i = client.get(memcachedKey,timeout,INT_TRANSCODER);
if (i==null) return null;
return i==1;
}
catch(TimeoutException | InterruptedException | MemcachedException e) {
throw new CacheException(e,String.format("error while getBoolValue - app: %s, user: %s, key: %s",
appKey,userKey,entryKey));
}
}
@Override
public Integer getIntValue(String appKey,String userKey,String entryKey) throws CacheException {
checkInitAndIfWrongThrowException();
String memcachedKey=getMemcachedKey(appKey, userKey,entryKey);
try {
return client.get(memcachedKey,timeout,INT_TRANSCODER);
}
catch(TimeoutException | InterruptedException | MemcachedException e) {
throw new CacheException(e,String.format("error while getIntValue - app: %s, user: %s, key: %s",
appKey,userKey,entryKey));
}
}
@Override
public Long getLongValue(String appKey,String userKey,String entryKey) throws CacheException {
checkInitAndIfWrongThrowException();
String memcachedKey=getMemcachedKey(appKey, userKey,entryKey);
try {
return client.get(memcachedKey,timeout,LONG_TRANSCODER);
}
catch(TimeoutException | InterruptedException | MemcachedException e) {
throw new CacheException(e,String.format("error while getLongValue - app: %s, user: %s, key: %s",
appKey,userKey,entryKey));
}
}
@Override
public void getValues(String appKey,String userKey,List<CacheValue> cacheValueArray) throws CacheException {
checkInitAndIfWrongThrowException();
try {
for (CacheValue cacheValue:cacheValueArray) {
String memcachedKey=getMemcachedKey(appKey, userKey,cacheValue.getKey());
if (cacheValue.getType()==String.class) {
cacheValue.setValue(client.get(memcachedKey,timeout,STRING_TRANSCODER));
}
else if (cacheValue.getType()==Integer.class) {
cacheValue.setValue(client.get(memcachedKey,timeout,INT_TRANSCODER));
}
else if (cacheValue.getType()==Long.class) {
cacheValue.setValue(client.get(memcachedKey,timeout,LONG_TRANSCODER));
}
else if (cacheValue.getType()==Boolean.class) {
Integer i = client.get(memcachedKey,timeout,INT_TRANSCODER);
if (i==null)
cacheValue.setValue(null);
else if (i==1)
cacheValue.setValue(true);
else
cacheValue.setValue(false);
}
}
}
catch(TimeoutException | InterruptedException | MemcachedException e) {
throw new CacheException(e,String.format("error while setValues - app: %s, user: %s",appKey,userKey));
}
}
private static Logger logger = LoggerFactory.getLogger(CacheImpl.class);
}
| apache-2.0 |
mbezjak/vhdllab | vhdllab-common/src/main/java/hr/fer/zemris/vhdllab/entity/ClientLog.java | 2807 | /*******************************************************************************
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership.
*
* 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 hr.fer.zemris.vhdllab.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.hibernate.validator.Length;
import org.hibernate.validator.NotNull;
@Entity
@Table(name = "client_logs", uniqueConstraints = { @UniqueConstraint(columnNames = {
"user_id", "created_on" }) })
public class ClientLog extends OwnedEntity {
private static final long serialVersionUID = 2460564318284652078L;
@NotNull
@Length(max = 16000000) // ~ 16MB
private String data;
@NotNull
@Column(name = "created_on", updatable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date createdOn;
public ClientLog() {
super();
}
public ClientLog(String data) {
this(null, data);
}
public ClientLog(String userId, String data) {
super(userId, null);
setData(data);
Date timestamp = new Date();
setCreatedOn(timestamp);
setName(timestamp.toString());
}
public ClientLog(ClientLog clone) {
super(clone);
setData(clone.data);
setCreatedOn(clone.createdOn);
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
@Override
public String toString() {
return new ToStringBuilder(this)
.appendSuper(super.toString())
.append("createdOn", createdOn)
.append("dataLength", StringUtils.length(data))
.toString();
}
}
| apache-2.0 |
kartaa/AsyncJobProcessor | src/main/java/org/ajp/server/job/Job.java | 506 | package org.ajp.server.job;
import java.util.concurrent.Callable;
import org.ajp.server.job.JobResult.JobResultStatus;
import org.ajp.server.model.JobRequest;
public class Job implements Callable<JobResult> {
private JobRequest jobRequest = null;
public Job(final JobRequest jreq) {
this.jobRequest = jreq;
}
@Override
public JobResult call() throws Exception {
JobResult jres = new JobResult();
jobRequest.getId();
jres.setStatus(JobResultStatus.SUCCESS);
return jres;
}
}
| apache-2.0 |
ajordens/clouddriver | clouddriver-cloudfoundry/src/main/java/com/netflix/spinnaker/clouddriver/cloudfoundry/client/Routes.java | 8900 | /*
* Copyright 2018 Pivotal, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.clouddriver.cloudfoundry.client;
import static com.netflix.spinnaker.clouddriver.cloudfoundry.client.CloudFoundryClientUtils.collectPageResources;
import static com.netflix.spinnaker.clouddriver.cloudfoundry.client.CloudFoundryClientUtils.safelyCall;
import static java.util.Collections.emptySet;
import static java.util.Collections.singletonList;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.netflix.spinnaker.clouddriver.cloudfoundry.client.api.RouteService;
import com.netflix.spinnaker.clouddriver.cloudfoundry.client.model.RouteId;
import com.netflix.spinnaker.clouddriver.cloudfoundry.client.model.v2.Resource;
import com.netflix.spinnaker.clouddriver.cloudfoundry.client.model.v2.Route;
import com.netflix.spinnaker.clouddriver.cloudfoundry.client.model.v2.RouteMapping;
import com.netflix.spinnaker.clouddriver.cloudfoundry.model.CloudFoundryDomain;
import com.netflix.spinnaker.clouddriver.cloudfoundry.model.CloudFoundryLoadBalancer;
import com.netflix.spinnaker.clouddriver.cloudfoundry.model.CloudFoundryServerGroup;
import com.netflix.spinnaker.clouddriver.cloudfoundry.model.CloudFoundrySpace;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class Routes {
private static final Pattern VALID_ROUTE_REGEX =
Pattern.compile("^([a-zA-Z0-9_-]+)\\.([a-zA-Z0-9_.-]+)(:[0-9]+)?([/a-zA-Z0-9_.-]+)?$");
private final String account;
private final RouteService api;
private final Applications applications;
private final Domains domains;
private final Spaces spaces;
private final Integer resultsPerPage;
private final ForkJoinPool forkJoinPool;
private LoadingCache<String, List<RouteMapping>> routeMappings;
public Routes(
String account,
RouteService api,
Applications applications,
Domains domains,
Spaces spaces,
Integer resultsPerPage,
ForkJoinPool forkJoinPool) {
this.account = account;
this.api = api;
this.applications = applications;
this.domains = domains;
this.spaces = spaces;
this.resultsPerPage = resultsPerPage;
this.forkJoinPool = forkJoinPool;
this.routeMappings =
CacheBuilder.newBuilder()
.expireAfterWrite(3, TimeUnit.MINUTES)
.build(
new CacheLoader<String, List<RouteMapping>>() {
@Override
public List<RouteMapping> load(@Nonnull String guid)
throws CloudFoundryApiException, ResourceNotFoundException {
return collectPageResources("route mappings", pg -> api.routeMappings(guid, pg))
.stream()
.map(Resource::getEntity)
.collect(Collectors.toList());
}
});
}
private CloudFoundryLoadBalancer map(Resource<Route> res) throws CloudFoundryApiException {
Route route = res.getEntity();
Set<CloudFoundryServerGroup> mappedApps = emptySet();
try {
mappedApps =
routeMappings.get(res.getMetadata().getGuid()).stream()
.map(rm -> applications.findById(rm.getAppGuid()))
.collect(Collectors.toSet());
} catch (ExecutionException e) {
if (!(e.getCause() instanceof ResourceNotFoundException))
throw new CloudFoundryApiException(e.getCause(), "Unable to find route mappings by id");
}
return CloudFoundryLoadBalancer.builder()
.account(account)
.id(res.getMetadata().getGuid())
.host(route.getHost())
.path(route.getPath())
.port(route.getPort())
.space(spaces.findById(route.getSpaceGuid()))
.domain(domains.findById(route.getDomainGuid()))
.mappedApps(mappedApps)
.build();
}
@Nullable
public CloudFoundryLoadBalancer find(RouteId routeId, String spaceId)
throws CloudFoundryApiException {
CloudFoundrySpace id = spaces.findById(spaceId);
String orgId = id.getOrganization().getId();
List<String> queryParams = new ArrayList<>();
queryParams.add("host:" + routeId.getHost());
queryParams.add("organization_guid:" + orgId);
queryParams.add("domain_guid:" + routeId.getDomainGuid());
if (routeId.getPath() != null) queryParams.add("path:" + routeId.getPath());
if (routeId.getPort() != null) queryParams.add("port:" + routeId.getPort().toString());
return collectPageResources("route mappings", pg -> api.all(pg, 1, queryParams)).stream()
.filter(
routeResource ->
(routeId.getPath() != null || routeResource.getEntity().getPath().isEmpty())
&& (routeId.getPort() != null || routeResource.getEntity().getPort() == null))
.findFirst()
.map(this::map)
.orElse(null);
}
@Nullable
public RouteId toRouteId(String uri) throws CloudFoundryApiException {
Matcher matcher = VALID_ROUTE_REGEX.matcher(uri);
if (matcher.find()) {
CloudFoundryDomain domain = domains.findByName(matcher.group(2)).orElse(null);
if (domain == null) {
return null;
}
RouteId routeId = new RouteId();
routeId.setHost(matcher.group(1));
routeId.setDomainGuid(domain.getId());
routeId.setPort(
matcher.group(3) == null ? null : Integer.parseInt(matcher.group(3).substring(1)));
routeId.setPath(matcher.group(4));
return routeId;
} else {
return null;
}
}
public List<CloudFoundryLoadBalancer> all(List<CloudFoundrySpace> spaces)
throws CloudFoundryApiException {
try {
if (!spaces.isEmpty()) {
List<String> spaceGuids = spaces.stream().map(s -> s.getId()).collect(Collectors.toList());
String orgFilter =
"organization_guid IN "
+ spaces.stream()
.map(s -> s.getOrganization().getId())
.collect(Collectors.joining(","));
return forkJoinPool
.submit(
() ->
collectPageResources(
"routes", pg -> api.all(pg, resultsPerPage, singletonList(orgFilter)))
.parallelStream()
.map(this::map)
.filter(lb -> spaceGuids.contains(lb.getSpace().getId()))
.collect(Collectors.toList()))
.get();
} else {
return forkJoinPool
.submit(
() ->
collectPageResources("routes", pg -> api.all(pg, resultsPerPage, null))
.parallelStream()
.map(this::map)
.collect(Collectors.toList()))
.get();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public CloudFoundryLoadBalancer createRoute(RouteId routeId, String spaceId)
throws CloudFoundryApiException {
Route route = new Route(routeId, spaceId);
try {
Resource<Route> newRoute =
safelyCall(() -> api.createRoute(route))
.orElseThrow(
() ->
new CloudFoundryApiException(
"Cloud Foundry signaled that route creation succeeded but failed to provide a response."));
return map(newRoute);
} catch (CloudFoundryApiException e) {
if (e.getErrorCode() == null) throw e;
switch (e.getErrorCode()) {
case ROUTE_HOST_TAKEN:
case ROUTE_PATH_TAKEN:
case ROUTE_PORT_TAKEN:
return this.find(routeId, spaceId);
default:
throw e;
}
}
}
public void deleteRoute(String loadBalancerGuid) throws CloudFoundryApiException {
safelyCall(() -> api.deleteRoute(loadBalancerGuid));
}
public static boolean isValidRouteFormat(String route) {
return VALID_ROUTE_REGEX.matcher(route).find();
}
}
| apache-2.0 |
googleapis/java-datalabeling | proto-google-cloud-datalabeling-v1beta1/src/main/java/com/google/cloud/datalabeling/v1beta1/ImageSegmentationAnnotationOrBuilder.java | 3972 | /*
* 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/datalabeling/v1beta1/annotation.proto
package com.google.cloud.datalabeling.v1beta1;
public interface ImageSegmentationAnnotationOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.datalabeling.v1beta1.ImageSegmentationAnnotation)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* The mapping between rgb color and annotation spec. The key is the rgb
* color represented in format of rgb(0, 0, 0). The value is the
* AnnotationSpec.
* </pre>
*
* <code>
* map<string, .google.cloud.datalabeling.v1beta1.AnnotationSpec> annotation_colors = 1;
* </code>
*/
int getAnnotationColorsCount();
/**
*
*
* <pre>
* The mapping between rgb color and annotation spec. The key is the rgb
* color represented in format of rgb(0, 0, 0). The value is the
* AnnotationSpec.
* </pre>
*
* <code>
* map<string, .google.cloud.datalabeling.v1beta1.AnnotationSpec> annotation_colors = 1;
* </code>
*/
boolean containsAnnotationColors(java.lang.String key);
/** Use {@link #getAnnotationColorsMap()} instead. */
@java.lang.Deprecated
java.util.Map<java.lang.String, com.google.cloud.datalabeling.v1beta1.AnnotationSpec>
getAnnotationColors();
/**
*
*
* <pre>
* The mapping between rgb color and annotation spec. The key is the rgb
* color represented in format of rgb(0, 0, 0). The value is the
* AnnotationSpec.
* </pre>
*
* <code>
* map<string, .google.cloud.datalabeling.v1beta1.AnnotationSpec> annotation_colors = 1;
* </code>
*/
java.util.Map<java.lang.String, com.google.cloud.datalabeling.v1beta1.AnnotationSpec>
getAnnotationColorsMap();
/**
*
*
* <pre>
* The mapping between rgb color and annotation spec. The key is the rgb
* color represented in format of rgb(0, 0, 0). The value is the
* AnnotationSpec.
* </pre>
*
* <code>
* map<string, .google.cloud.datalabeling.v1beta1.AnnotationSpec> annotation_colors = 1;
* </code>
*/
com.google.cloud.datalabeling.v1beta1.AnnotationSpec getAnnotationColorsOrDefault(
java.lang.String key, com.google.cloud.datalabeling.v1beta1.AnnotationSpec defaultValue);
/**
*
*
* <pre>
* The mapping between rgb color and annotation spec. The key is the rgb
* color represented in format of rgb(0, 0, 0). The value is the
* AnnotationSpec.
* </pre>
*
* <code>
* map<string, .google.cloud.datalabeling.v1beta1.AnnotationSpec> annotation_colors = 1;
* </code>
*/
com.google.cloud.datalabeling.v1beta1.AnnotationSpec getAnnotationColorsOrThrow(
java.lang.String key);
/**
*
*
* <pre>
* Image format.
* </pre>
*
* <code>string mime_type = 2;</code>
*
* @return The mimeType.
*/
java.lang.String getMimeType();
/**
*
*
* <pre>
* Image format.
* </pre>
*
* <code>string mime_type = 2;</code>
*
* @return The bytes for mimeType.
*/
com.google.protobuf.ByteString getMimeTypeBytes();
/**
*
*
* <pre>
* A byte string of a full image's color map.
* </pre>
*
* <code>bytes image_bytes = 3;</code>
*
* @return The imageBytes.
*/
com.google.protobuf.ByteString getImageBytes();
}
| apache-2.0 |
toby1984/j2048 | src/main/java/de/codesourcery/j2048/IInputProvider.java | 1279 | /**
* Copyright 2015 Tobias Gierke <tobias.gierke@code-sourcery.de>
*
* 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 de.codesourcery.j2048;
import java.awt.Component;
/**
* Abstraction for receiving either input from either the user or the AI,
*
* @author tobias.gierke@code-sourcery.de
*/
public interface IInputProvider
{
/**
* Possible actions.
*
* @author tobias.gierke@code-sourcery.de
*/
public static enum Action
{
NONE,TILT_DOWN,TILT_UP,TILT_LEFT,TILT_RIGHT,RESTART;
}
/**
* Returns the current action for a given board state.
*
* @param state
* @return
*/
public Action getAction(BoardState state);
/**
* Attaches this input provider to its UI peer.
* @param peer
*/
public void attach(Component peer);
} | apache-2.0 |
yardstick-benchmarks/yardstick-spark | src/main/java/org/yardstickframework/spark/model/Person.java | 4426 | /*
* 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.yardstickframework.spark.model;
import java.io.*;
/**
* Person record used for query test.
*/
public class Person implements Externalizable {
/** Person ID. */
private int id;
/** Person ID. */
private int orgId;
/** First name (not-indexed). */
private String firstName;
/** Last name (not indexed). */
private String lastName;
/** Salary. */
private double salary;
/**
* Constructs empty person.
*/
public Person() {
// No-op.
}
/**
* Constructs person record that is not linked to any organization.
*
* @param id Person ID.
* @param firstName First name.
* @param lastName Last name.
* @param salary Salary.
*/
public Person(int id, String firstName, String lastName, double salary) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.salary = salary;
}
/**
* Constructs person record that is not linked to any organization.
*
* @param id Person ID.
* @param orgId Organization ID.
* @param firstName First name.
* @param lastName Last name.
* @param salary Salary.
*/
public Person(int id, int orgId, String firstName, String lastName, double salary) {
this.id = id;
this.orgId = orgId;
this.firstName = firstName;
this.lastName = lastName;
this.salary = salary;
}
/**
* @return Person id.
*/
public int getId() {
return id;
}
/**
* @param id Person id.
*/
public void setId(int id) {
this.id = id;
}
/**
* @return Person first name.
*/
public String getFirstName() {
return firstName;
}
/**
* @param firstName Person first name.
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* @return Person last name.
*/
public String getLastName() {
return lastName;
}
/**
* @param lastName Person last name.
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* @return Salary.
*/
public double getSalary() {
return salary;
}
/**
* @param salary Salary.
*/
public void setSalary(double salary) {
this.salary = salary;
}
/**
* @return Organization ID.
*/
public int getOrgId() {
return orgId;
}
/**
* @param orgId Organization ID.
*/
public void setOrgId(int orgId) {
this.orgId = orgId;
}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(id);
out.writeUTF(firstName);
out.writeUTF(lastName);
out.writeDouble(salary);
}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
id = in.readInt();
firstName = in.readUTF();
lastName = in.readUTF();
salary = in.readDouble();
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {
return this == o || (o instanceof Person) && id == ((Person)o).id;
}
/** {@inheritDoc} */
@Override public int hashCode() {
return id;
}
/** {@inheritDoc} */
@Override public String toString() {
return "Person [firstName=" + firstName +
", id=" + id +
", lastName=" + lastName +
", salary=" + salary +
']';
}
}
| apache-2.0 |
gdefias/StudyJava | InitJava/base/src/main/java/Thread/Concurrent/TestCopyOnWriteArraySet.java | 234 | package Thread.Concurrent;
/**
* Created by Defias on 2017/8/27.
*
* CopyOnWriteArraySet
*
* 基于CopyOnWriteArrayList 的实现
*
*/
import java.util.concurrent.CopyOnWriteArraySet;
public class TestCopyOnWriteArraySet {
}
| apache-2.0 |
JacobASeverson/pac4j | pac4j-cas/src/test/java/org/pac4j/cas/client/CasProxyReceptorTests.java | 2771 | package org.pac4j.cas.client;
import org.junit.Test;
import org.pac4j.core.context.MockWebContext;
import org.pac4j.core.exception.HttpAction;
import org.pac4j.core.util.TestsConstants;
import org.pac4j.core.util.TestsHelper;
import static org.junit.Assert.*;
/**
* This class tests the {@link CasProxyReceptor} class.
*
* @author Jerome Leleu
* @since 1.4.0
*/
public final class CasProxyReceptorTests implements TestsConstants {
@Test
public void testMissingCallbackUrl() {
final CasProxyReceptor client = new CasProxyReceptor();
TestsHelper.initShouldFail(client, "callbackUrl cannot be blank");
}
@Test
public void testMissingStorage() {
final CasProxyReceptor client = new CasProxyReceptor();
client.setCallbackUrl(CALLBACK_URL);
client.setStore(null);
TestsHelper.initShouldFail(client, "store cannot be null");
}
@Test
public void testMissingPgt() {
final CasProxyReceptor client = new CasProxyReceptor();
client.setCallbackUrl(CALLBACK_URL);
final MockWebContext context = MockWebContext.create();
try {
client.getCredentials(context.addRequestParameter(CasProxyReceptor.PARAM_PROXY_GRANTING_TICKET, VALUE));
} catch (final HttpAction e) {
assertEquals(200, context.getResponseStatus());
assertEquals("", context.getResponseContent());
assertEquals("Missing proxyGrantingTicket or proxyGrantingTicketIou", e.getMessage());
}
}
@Test
public void testMissingPgtiou() {
final CasProxyReceptor client = new CasProxyReceptor();
client.setCallbackUrl(CALLBACK_URL);
final MockWebContext context = MockWebContext.create();
TestsHelper.expectException(() -> client.getCredentials(context.addRequestParameter(CasProxyReceptor.PARAM_PROXY_GRANTING_TICKET_IOU, VALUE)), HttpAction.class,
"Missing proxyGrantingTicket or proxyGrantingTicketIou");
assertEquals(200, context.getResponseStatus());
assertEquals("", context.getResponseContent());
}
@Test
public void testOk() {
final CasProxyReceptor client = new CasProxyReceptor();
client.setCallbackUrl(CALLBACK_URL);
final MockWebContext context = MockWebContext.create()
.addRequestParameter(CasProxyReceptor.PARAM_PROXY_GRANTING_TICKET, VALUE)
.addRequestParameter(CasProxyReceptor.PARAM_PROXY_GRANTING_TICKET_IOU, VALUE);
TestsHelper.expectException(() -> client.getCredentials(context), HttpAction.class, "No credential for CAS proxy receptor -> returns ok");
assertEquals(200, context.getResponseStatus());
assertTrue(context.getResponseContent().length() > 0);
}
}
| apache-2.0 |
jesg/selenium-grid-demo | src/test/java/jesg/SeleniumGridTest.java | 1717 | package jesg;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.HasCapabilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class SeleniumGridTest {
private WebDriver driver;
private Capabilities capabilities;
private Map<String, Capabilities> browserConfig = new HashMap<String, Capabilities>();
@BeforeTest
public void init(){
browserConfig.put("firefox", DesiredCapabilities.firefox());
browserConfig.put("chrome", DesiredCapabilities.chrome());
browserConfig.put("phantomjs", DesiredCapabilities.phantomjs());
}
@Parameters({ "browser" })
@BeforeMethod
public void setUp(@Optional("firefox") String browser) throws Exception {
RemoteWebDriver remoteDriver = new RemoteWebDriver(browserConfig.get(browser));
driver = remoteDriver;
capabilities = ((HasCapabilities) remoteDriver).getCapabilities();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
@AfterMethod
public void tearDown() throws Exception {
driver.quit();
}
@Test()
public void verifyLinks() {
driver.get("https://www.google.com/");
System.out.println("Browser: " + capabilities.getBrowserName()
+ " version: " + capabilities.getVersion() + " platform: "
+ capabilities.getPlatform() + " title: " + driver.getTitle());
}
}
| apache-2.0 |
binarytemple/mybatis-all-syncing-test | src/main/java/org/apache/ibatis/builder/MapperBuilderAssistant.java | 18210 | /*
* Copyright 2009-2012 The MyBatis Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ibatis.builder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import org.apache.ibatis.cache.Cache;
import org.apache.ibatis.cache.decorators.LruCache;
import org.apache.ibatis.cache.impl.PerpetualCache;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.executor.keygen.KeyGenerator;
import org.apache.ibatis.mapping.CacheBuilder;
import org.apache.ibatis.mapping.Discriminator;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMap;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
import org.apache.ibatis.mapping.ResultFlag;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.mapping.ResultMapping;
import org.apache.ibatis.mapping.ResultSetType;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.mapping.StatementType;
import org.apache.ibatis.reflection.MetaClass;
import org.apache.ibatis.scripting.LanguageDriver;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
public class MapperBuilderAssistant extends BaseBuilder {
private String currentNamespace;
private String resource;
private Cache currentCache;
public MapperBuilderAssistant(Configuration configuration, String resource) {
super(configuration);
ErrorContext.instance().resource(resource);
this.resource = resource;
}
public String getCurrentNamespace() {
return currentNamespace;
}
public void setCurrentNamespace(String currentNamespace) {
if (currentNamespace == null) {
throw new BuilderException("The mapper element requires a namespace attribute to be specified.");
}
if (this.currentNamespace != null && !this.currentNamespace.equals(currentNamespace)) {
throw new BuilderException("Wrong namespace. Expected '"
+ this.currentNamespace + "' but found '" + currentNamespace + "'.");
}
this.currentNamespace = currentNamespace;
}
public String applyCurrentNamespace(String base, boolean isReference) {
if (base == null) return null;
if (isReference) {
// is it qualified with any namespace yet?
if (base.contains(".")) return base;
} else {
// is it qualified with this namespace yet?
if (base.startsWith(currentNamespace + ".")) return base;
if (base.contains(".")) throw new BuilderException("Dots are not allowed in element names, please remove it from " + base);
}
return currentNamespace + "." + base;
}
public Cache useCacheRef(String namespace) {
if (namespace == null) {
throw new BuilderException("cache-ref element requires a namespace attribute.");
}
try {
Cache cache = configuration.getCache(namespace);
if (cache == null) {
throw new IncompleteElementException("No cache for namespace '" + namespace + "' could be found.");
}
currentCache = cache;
return cache;
} catch (IllegalArgumentException e) {
throw new IncompleteElementException("No cache for namespace '" + namespace + "' could be found.", e);
}
}
public Cache useNewCache(Class<? extends Cache> typeClass,
Class<? extends Cache> evictionClass,
Long flushInterval,
Integer size,
boolean readWrite,
Properties props) {
typeClass = valueOrDefault(typeClass, PerpetualCache.class);
evictionClass = valueOrDefault(evictionClass, LruCache.class);
Cache cache = new CacheBuilder(currentNamespace)
.implementation(typeClass)
.addDecorator(evictionClass)
.clearInterval(flushInterval)
.size(size)
.readWrite(readWrite)
.properties(props)
.build();
configuration.addCache(cache);
currentCache = cache;
return cache;
}
public ParameterMap addParameterMap(String id, Class<?> parameterClass, List<ParameterMapping> parameterMappings) {
id = applyCurrentNamespace(id, false);
ParameterMap.Builder parameterMapBuilder = new ParameterMap.Builder(configuration, id, parameterClass, parameterMappings);
ParameterMap parameterMap = parameterMapBuilder.build();
configuration.addParameterMap(parameterMap);
return parameterMap;
}
public ParameterMapping buildParameterMapping(
Class<?> parameterType,
String property,
Class<?> javaType,
JdbcType jdbcType,
String resultMap,
ParameterMode parameterMode,
Class<? extends TypeHandler<?>> typeHandler,
Integer numericScale) {
resultMap = applyCurrentNamespace(resultMap, true);
// Class parameterType = parameterMapBuilder.type();
Class<?> javaTypeClass = resolveParameterJavaType(parameterType, property, javaType, jdbcType);
TypeHandler<?> typeHandlerInstance = resolveTypeHandler(javaTypeClass, typeHandler);
ParameterMapping.Builder builder = new ParameterMapping.Builder(configuration, property, javaTypeClass);
builder.jdbcType(jdbcType);
builder.resultMapId(resultMap);
builder.mode(parameterMode);
builder.numericScale(numericScale);
builder.typeHandler(typeHandlerInstance);
return builder.build();
}
public ResultMap addResultMap(
String id,
Class<?> type,
String extend,
Discriminator discriminator,
List<ResultMapping> resultMappings,
Boolean autoMapping) {
id = applyCurrentNamespace(id, false);
extend = applyCurrentNamespace(extend, true);
ResultMap.Builder resultMapBuilder = new ResultMap.Builder(configuration, id, type, resultMappings, autoMapping);
if (extend != null) {
if (!configuration.hasResultMap(extend)) {
throw new IncompleteElementException("Could not find a parent resultmap with id '" + extend + "'");
}
ResultMap resultMap = configuration.getResultMap(extend);
List<ResultMapping> extendedResultMappings = new ArrayList<ResultMapping>(resultMap.getResultMappings());
extendedResultMappings.removeAll(resultMappings);
// Remove parent constructor if this resultMap declares a constructor.
boolean declaresConstructor = false;
for (ResultMapping resultMapping : resultMappings) {
if (resultMapping.getFlags().contains(ResultFlag.CONSTRUCTOR)) {
declaresConstructor = true;
break;
}
}
if (declaresConstructor) {
Iterator<ResultMapping> extendedResultMappingsIter = extendedResultMappings.iterator();
while (extendedResultMappingsIter.hasNext()) {
if (extendedResultMappingsIter.next().getFlags().contains(ResultFlag.CONSTRUCTOR)) {
extendedResultMappingsIter.remove();
}
}
}
resultMappings.addAll(extendedResultMappings);
}
resultMapBuilder.discriminator(discriminator);
ResultMap resultMap = resultMapBuilder.build();
configuration.addResultMap(resultMap);
return resultMap;
}
public ResultMapping buildResultMapping(
Class<?> resultType,
String property,
String column,
Class<?> javaType,
JdbcType jdbcType,
String nestedSelect,
String nestedResultMap,
String notNullColumn,
String columnPrefix,
Class<? extends TypeHandler<?>> typeHandler,
List<ResultFlag> flags) {
ResultMapping resultMapping = assembleResultMapping(
resultType,
property,
column,
javaType,
jdbcType,
nestedSelect,
nestedResultMap,
notNullColumn,
columnPrefix,
typeHandler,
flags);
return resultMapping;
}
public Discriminator buildDiscriminator(
Class<?> resultType,
String column,
Class<?> javaType,
JdbcType jdbcType,
Class<? extends TypeHandler<?>> typeHandler,
Map<String, String> discriminatorMap) {
ResultMapping resultMapping = assembleResultMapping(
resultType,
null,
column,
javaType,
jdbcType,
null,
null,
null,
null,
typeHandler,
new ArrayList<ResultFlag>());
Map<String, String> namespaceDiscriminatorMap = new HashMap<String, String>();
for (Map.Entry<String, String> e : discriminatorMap.entrySet()) {
String resultMap = e.getValue();
resultMap = applyCurrentNamespace(resultMap, true);
namespaceDiscriminatorMap.put(e.getKey(), resultMap);
}
Discriminator.Builder discriminatorBuilder = new Discriminator.Builder(configuration, resultMapping, namespaceDiscriminatorMap);
return discriminatorBuilder.build();
}
public MappedStatement addMappedStatement(
String id,
SqlSource sqlSource,
StatementType statementType,
SqlCommandType sqlCommandType,
Integer fetchSize,
Integer timeout,
String parameterMap,
Class<?> parameterType,
String resultMap,
Class<?> resultType,
ResultSetType resultSetType,
boolean flushCache,
boolean useCache,
KeyGenerator keyGenerator,
String keyProperty,
String keyColumn,
String databaseId,
LanguageDriver lang) {
id = applyCurrentNamespace(id, false);
boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration, id, sqlSource, sqlCommandType);
statementBuilder.resource(resource);
statementBuilder.fetchSize(fetchSize);
statementBuilder.statementType(statementType);
statementBuilder.keyGenerator(keyGenerator);
statementBuilder.keyProperty(keyProperty);
statementBuilder.keyColumn(keyColumn);
statementBuilder.databaseId(databaseId);
statementBuilder.lang(lang);
setStatementTimeout(timeout, statementBuilder);
setStatementParameterMap(parameterMap, parameterType, statementBuilder);
setStatementResultMap(resultMap, resultType, resultSetType, statementBuilder);
setStatementCache(isSelect, flushCache, useCache, currentCache, statementBuilder);
MappedStatement statement = statementBuilder.build();
configuration.addMappedStatement(statement);
return statement;
}
private <T> T valueOrDefault(T value, T defaultValue) {
return value == null ? defaultValue : value;
}
private void setStatementCache(
boolean isSelect,
boolean flushCache,
boolean useCache,
Cache cache,
MappedStatement.Builder statementBuilder) {
flushCache = valueOrDefault(flushCache, !isSelect);
useCache = valueOrDefault(useCache, isSelect);
statementBuilder.flushCacheRequired(flushCache);
statementBuilder.useCache(useCache);
statementBuilder.cache(cache);
}
private void setStatementParameterMap(
String parameterMap,
Class<?> parameterTypeClass,
MappedStatement.Builder statementBuilder) {
parameterMap = applyCurrentNamespace(parameterMap, true);
if (parameterMap != null) {
try {
statementBuilder.parameterMap(configuration.getParameterMap(parameterMap));
} catch (IllegalArgumentException e) {
throw new IncompleteElementException("Could not find parameter map " + parameterMap, e);
}
} else if (parameterTypeClass != null) {
List<ParameterMapping> parameterMappings = new ArrayList<ParameterMapping>();
ParameterMap.Builder inlineParameterMapBuilder = new ParameterMap.Builder(
configuration,
statementBuilder.id() + "-Inline",
parameterTypeClass,
parameterMappings);
statementBuilder.parameterMap(inlineParameterMapBuilder.build());
}
}
private void setStatementResultMap(
String resultMap,
Class<?> resultType,
ResultSetType resultSetType,
MappedStatement.Builder statementBuilder) {
resultMap = applyCurrentNamespace(resultMap, true);
List<ResultMap> resultMaps = new ArrayList<ResultMap>();
if (resultMap != null) {
String[] resultMapNames = resultMap.split(",");
for (String resultMapName : resultMapNames) {
try {
resultMaps.add(configuration.getResultMap(resultMapName.trim()));
} catch (IllegalArgumentException e) {
throw new IncompleteElementException("Could not find result map " + resultMapName, e);
}
}
} else if (resultType != null) {
ResultMap.Builder inlineResultMapBuilder = new ResultMap.Builder(
configuration,
statementBuilder.id() + "-Inline",
resultType,
new ArrayList<ResultMapping>(),
null);
resultMaps.add(inlineResultMapBuilder.build());
}
statementBuilder.resultMaps(resultMaps);
statementBuilder.resultSetType(resultSetType);
}
private void setStatementTimeout(Integer timeout, MappedStatement.Builder statementBuilder) {
if (timeout == null) {
timeout = configuration.getDefaultStatementTimeout();
}
statementBuilder.timeout(timeout);
}
private ResultMapping assembleResultMapping(
Class<?> resultType,
String property,
String column,
Class<?> javaType,
JdbcType jdbcType,
String nestedSelect,
String nestedResultMap,
String notNullColumn,
String columnPrefix,
Class<? extends TypeHandler<?>> typeHandler,
List<ResultFlag> flags) {
nestedResultMap = applyCurrentNamespace(nestedResultMap, true);
Class<?> javaTypeClass = resolveResultJavaType(resultType, property, javaType);
TypeHandler<?> typeHandlerInstance = resolveTypeHandler(javaTypeClass, typeHandler);
List<ResultMapping> composites = parseCompositeColumnName(column);
if (composites.size() > 0) {
ResultMapping first = composites.get(0);
column = first.getColumn();
}
// issue #4 column is mandatory on nested queries
if (nestedSelect != null && column == null) {
throw new BuilderException("Missing column attribute for nested select in property " + property);
}
ResultMapping.Builder builder = new ResultMapping.Builder(configuration, property, column, javaTypeClass);
builder.jdbcType(jdbcType);
builder.nestedQueryId(applyCurrentNamespace(nestedSelect, true));
builder.nestedResultMapId(applyCurrentNamespace(nestedResultMap, true));
builder.typeHandler(typeHandlerInstance);
builder.flags(flags == null ? new ArrayList<ResultFlag>() : flags);
builder.composites(composites);
builder.notNullColumns(parseMultipleColumnNames(notNullColumn));
builder.columnPrefix(columnPrefix);
return builder.build();
}
private Set<String> parseMultipleColumnNames(String columnName) {
Set<String> columns = new HashSet<String>();
if (columnName != null) {
if (columnName.indexOf(',') > -1) {
StringTokenizer parser = new StringTokenizer(columnName, "{}, ", false);
while (parser.hasMoreTokens()) {
String column = parser.nextToken();
columns.add(column);
}
} else {
columns.add(columnName);
}
}
return columns;
}
private List<ResultMapping> parseCompositeColumnName(String columnName) {
List<ResultMapping> composites = new ArrayList<ResultMapping>();
if (columnName != null) {
if (columnName.indexOf('=') > -1
|| columnName.indexOf(',') > -1) {
StringTokenizer parser = new StringTokenizer(columnName, "{}=, ", false);
while (parser.hasMoreTokens()) {
String property = parser.nextToken();
String column = parser.nextToken();
ResultMapping.Builder complexBuilder = new ResultMapping.Builder(configuration, property, column, configuration.getTypeHandlerRegistry().getUnknownTypeHandler());
composites.add(complexBuilder.build());
}
}
}
return composites;
}
private Class<?> resolveResultJavaType(Class<?> resultType, String property, Class<?> javaType) {
if (javaType == null && property != null) {
try {
MetaClass metaResultType = MetaClass.forClass(resultType);
javaType = metaResultType.getSetterType(property);
} catch (Exception e) {
//ignore, following null check statement will deal with the situation
}
}
if (javaType == null) {
javaType = Object.class;
}
return javaType;
}
private Class<?> resolveParameterJavaType(Class<?> resultType, String property, Class<?> javaType, JdbcType jdbcType) {
if (javaType == null) {
if (JdbcType.CURSOR.equals(jdbcType)) {
javaType = java.sql.ResultSet.class;
} else if (Map.class.isAssignableFrom(resultType)) {
javaType = Object.class;
} else {
MetaClass metaResultType = MetaClass.forClass(resultType);
javaType = metaResultType.getGetterType(property);
}
}
if (javaType == null) {
javaType = Object.class;
}
return javaType;
}
}
| apache-2.0 |
simpher/FutureStrategy | src/com/future/panels/PanelFactory.java | 298 | package com.future.panels;
import javax.swing.JPanel;
public class PanelFactory {
public static JPanel createPanel(String name)
{
JPanel panel;
if(name.equals("SettingPanel"))
{
panel=new SettingPanel();
}else
{
panel=new MainPanel();
}
return panel;
}
}
| apache-2.0 |
romankagan/DDBWorkbench | platform/platform-api/src/com/intellij/util/Url.java | 785 | package com.intellij.util;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
// We don't use Java URI due to problem — http://cns-etuat-2.localnet.englishtown.com/school/e12/#school/45383/201/221/382?c=countrycode=cc|culturecode=en-us|partnercode=mkge
// it is illegal URI (fragment before query), but we must support such URI
// Semicolon as parameters separator is supported (WEB-6671)
public interface Url {
@NotNull
String getPath();
boolean isInLocalFileSystem();
String toDecodedForm();
@NotNull
String toExternalForm();
@Nullable
String getScheme();
@Nullable
String getAuthority();
@Nullable
String getParameters();
boolean equalsIgnoreParameters(@Nullable Url url);
@NotNull
Url trimParameters();
}
| apache-2.0 |
SAP/cloud-odata-java | odata-api/src/main/java/com/sap/core/odata/api/edm/EdmLiteralKind.java | 959 | /*******************************************************************************
* Copyright 2013 SAP AG
*
* 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.sap.core.odata.api.edm;
/**
* @com.sap.core.odata.DoNotImplement
* EdmLiteralKind indicates the format of an EDM literal.
* @author SAP AG
*/
public enum EdmLiteralKind {
DEFAULT, URI, JSON;
}
| apache-2.0 |
barbarum/barbarum-tutorial | src/main/java/com/barbarum/tutorial/code/array/FindLongestBinarySequence.java | 1761 | package com.barbarum.tutorial.code.array;
import com.barbarum.tutorial.util.PrintUtil;
public class FindLongestBinarySequence {
public static int find(int[] nums) {
int[] ones = new int[nums.length];
countLeftOnes(nums, ones);
countRightOnes(nums, ones);
return findMaximum(ones);
}
private static int findMaximum(int[] ones) {
int maximum = 0;
int index = -1;
for (int i = 0; i < ones.length; i++) {
if (ones[i] > maximum) {
maximum = ones[i];
index = i;
}
}
return index;
}
private static void countLeftOnes(int[] nums, int[] table) {
int currentOnes = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
table[i] += currentOnes;
currentOnes = 0;
} else {
currentOnes++;
}
}
}
public static void countRightOnes(int[] nums, int[] table) {
int currentOnes = 0;
for (int i = nums.length - 1; i >= 0; i--) {
if (nums[i] == 0) {
table[i] += currentOnes;
currentOnes = 0;
} else {
currentOnes++;
}
}
}
public static void main(String args[]) {
PrintUtil.println(new int[]{0, 1, 1, 1, 0, 1, 0}, FindLongestBinarySequence::find);
PrintUtil.println(new int[]{0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0}, FindLongestBinarySequence::find);
PrintUtil.println(new int[]{1, 1, 1, 1, 0, 1}, FindLongestBinarySequence::find);
PrintUtil.println(new int[]{1, 1, 1, 1, 1, 1}, FindLongestBinarySequence::find);
}
}
| apache-2.0 |
domaframework/doma | doma-processor/src/main/java/org/seasar/doma/internal/apt/meta/parameter/OptionalIntListParameterMeta.java | 554 | package org.seasar.doma.internal.apt.meta.parameter;
import static org.seasar.doma.internal.util.AssertionUtil.assertNotNull;
public class OptionalIntListParameterMeta implements CallableSqlParameterMeta {
private final String name;
public OptionalIntListParameterMeta(String name) {
assertNotNull(name);
this.name = name;
}
public String getName() {
return name;
}
@Override
public <R, P> R accept(CallableSqlParameterMetaVisitor<R, P> visitor, P p) {
return visitor.visitOptionalIntListParameterMeta(this, p);
}
}
| apache-2.0 |
interactivespaces/interactivespaces-rosjava | rosjava/src/main/java/org/ros/concurrent/CancellableLoop.java | 2359 | /*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.concurrent;
import com.google.common.base.Preconditions;
import java.util.concurrent.ExecutorService;
/**
* An interruptable loop that can be run by an {@link ExecutorService}.
*
* @author khughes@google.com (Keith M. Hughes)
*/
public abstract class CancellableLoop implements Runnable {
/**
* {@code true} if the code has been run once, {@code false} otherwise.
*/
private boolean ranOnce = false;
/**
* The {@link Thread} the code will be running in.
*/
private Thread thread;
@Override
public void run() {
synchronized (this) {
Preconditions.checkState(!ranOnce, "CancellableLoops cannot be restarted.");
ranOnce = true;
thread = Thread.currentThread();
}
try {
setup();
while (!thread.isInterrupted()) {
loop();
}
} catch (InterruptedException e) {
handleInterruptedException(e);
} finally {
thread = null;
}
}
/**
* The setup block for the loop. This will be called exactly once before
* the first call to {@link #loop()}.
*/
protected void setup() {
}
/**
* The body of the loop. This will run continuously until the
* {@link CancellableLoop} has been interrupted externally or by calling
* {@link #cancel()}.
*/
protected abstract void loop() throws InterruptedException;
/**
* An {@link InterruptedException} was thrown.
*/
protected void handleInterruptedException(InterruptedException e) {
}
/**
* Interrupts the loop.
*/
public void cancel() {
if (thread != null) {
thread.interrupt();
}
}
/**
* @return {@code true} if the loop is running
*/
public boolean isRunning() {
return thread != null && !thread.isInterrupted();
}
}
| apache-2.0 |
zapper59/RangerHale---Space-Adventure | src/org/projectiles/AirBall.java | 2909 | package org.projectiles;
import static java.awt.Color.red;
import static java.lang.Math.*;
import java.awt.image.BufferedImage;
import static java.lang.System.*;
import org.rooms.*;
import org.resources.AudioPack;
import org.resources.Collisions;
import org.resources.Element;
import org.resources.ImagePack;
import org.resources.VisibleObject;
import org.walls.DamageableWall;
import org.walls.Wall;
import org.enemies.*;
public class AirBall extends Projectile {
public static BufferedImage[] ani = airani;
public AirBall(float X, float Y, float vx, float vy) {
image = ani[0];
dead = false;
color = red;
x = X;
y = Y;
vX = vx * 2.5f;
vY = vy * 2.5f;
life = lifeCapacity = -1 - (int) round(150 * random());
w = h = 22;
if (vX == 0 && vY == 0) {
vX = 5 * (float) random() - 2.5f;
vY = 5 * (float) random() - 2.5f;
}
if (abs(vX) > abs(vY)) {
h = 13;
w = 20;
}
// int counter=0;
// while(hypot(vX,vY)<1&&counter<10){counter++;vX*=2;vY*=2;}
if (abs(abs(atan((double) vY / vX)) - PI / 4) > PI / 8)
image = ani[abs(vX) > abs(vY) ? (vX < 0 ? 0 : 1) : (vY > 0 ? 2 : 3)];
else {
image = ani[vX > 0 ? (vY < 0 ? 4 : 6) : (vY < 0 ? 5 : 7)];
w = h = 13;
}
synchronized (sync) {
livePros++;
}
}
public void run() {
// boolean frame=Clock.frame;
if (life != 0) {
if (life > 0)
image = ani[11];
if (life > 3)
image = ani[10];
if (life > 6)
image = ani[9];
if (life > 8)
image = ani[8];
// Clock.waitFor(frame=!frame);
// if(Clock.dead)break;
if (life < 0) {
vX *= .98;
vY *= .98;
x += vX;
y -= vY;
}
if (life == -200) {
vY = vX = 0;
life = 10;
w = h = 16;
image = ani[8];
x += round(10 * random());
y += round(10 * random());
}
life--;
boolean collided = false;
for (int i = 0; i < Room.walls.size(); i++) {
Wall wal = Room.walls.get(i);
if (vY == 0 && vX == 0)
break;
if ((x < wal.x + wal.w && x + w > wal.x) && (y < wal.y + wal.h && y + h > wal.y)) {
collided = true;
if (wal.damagable) {
w = h = 16;
((DamageableWall) wal).life -= 5;
// if
// (Jump.kraidLife<=0&&Jump.countdown<0){Jump.countdown=500;
// AudioPack.playAudio("Ima Firen Mah Lazor!.wav",0.1);
// }
}
}
}
synchronized (Room.enemies) {
for (VisibleObject en : Room.enemies) {
if (Collisions.collides(this, en)) {
if (life < 0 || life > 2) {
((Enemy) en).vMultiplier = -1;
}
if (life < 0) {
((Enemy) en).damage(Element.AIR, 12);
image = ani[8];
collided = true;
}
}
}
}
if (collided) {
vY = vX = 0;
life = 10;
w = h = 16;
image = ani[8];
x += round(10 * random());
y += round(10 * random());
// AudioPack.playAudio("BExplosion2.wav",0.05);
AudioPack.playClip(boom);
}
} else
dead = true;
}
}
| apache-2.0 |
AlexanderSopov/datastruktur | src/lab2/Lab2b.java | 2889 | package lab2;
import java.util.PriorityQueue;
public class Lab2b {
private static class Vector implements Comparable{
public double x, y, d;
public DLList.Node node;
public Vector(double x, double y){
this(x,y,null,100);
}
public Vector(double x, double y, DLList.Node n, double d){
this.x = x;
this.y = y;
node = n;
this.d = d;
}
public void setNode(DLList.Node n){
node = n;
}
public double getDist(Vector v){
double xD = x - v.x;
double yD = y - v.y;
return Math.sqrt(xD*xD + yD*yD);
}
public double getX(){
return x;
}
public double getY(){
return y;
}
public void calculateDelta() {
if (node.prev != null && node.next != null){
Vector v1 = (Vector) node.prev.elt;
Vector v2 = (Vector) node.next.elt;
double l1 = getDist(v1);
double l2 = getDist(v2);
double l3 = v1.getDist(v2);
d= l1 + l2 - l3;
}else
d = 100;
}
@Override
public int compareTo(Object o){
int v = (int) ( (d - ((Vector)o).d) *10000);
calculateDelta();
return v;
}
}
private static DLList listOfPoints = new DLList<Vector>();
private static PriorityQueue<Vector> q = new PriorityQueue<Vector>();
public static double[] simplifyShape(double[] poly, int k) {
int pointsToRemove = (poly.length / 2) - k;
// Populate list of Vectors (points in graph)
listOfPoints.addFirst(new Vector(poly[0], poly[1]));
DLList.Node node = listOfPoints.first;
((Vector) node.elt).setNode(node);
for (int i = 2; i<poly.length;i+=2)
populateList(poly[i], poly[i + 1]);
((Vector)listOfPoints.last.elt).calculateDelta();
q.add(((Vector) listOfPoints.last.elt));
DLList.Node testn = listOfPoints.first;
while (testn != null) {
System.out.println(((Vector) testn.elt).d);
testn = testn.next;
}
for (int i = 0; i<pointsToRemove; i++)
delete(((Vector)(q.remove())).node);
double[] array = new double[poly.length-(pointsToRemove*2)];
DLList.Node curNode = listOfPoints.first;
for (int i = 0; i<array.length; i++){
array[i++] = ((Vector)curNode.elt).x;
array[i] = ((Vector)curNode.elt).y;
curNode = curNode.next;
}
return array;
}
private static void populateList(double x, double y) {
listOfPoints.addLast(new Vector(x, y));
DLList.Node n = listOfPoints.last;
((Vector) n.elt).setNode(n);
((Vector)n.prev.elt).calculateDelta();
q.add(((Vector) n.prev.elt));
}
private static void delete(DLList.Node n){
Vector v = ((Vector)n.elt);
System.out.println("Deleting point: (" + v.x + ", " + v.y + "), d = " + (int)(v.d*100));
DLList.Node prev = n.prev;
DLList.Node next = n.next;
listOfPoints.remove(n);
q.remove((Vector) prev.elt);
((Vector)prev.elt).calculateDelta();
q.add((Vector) prev.elt);
q.remove((Vector) next.elt);
((Vector)next.elt).calculateDelta();
q.add((Vector)next.elt);
}
}
| apache-2.0 |
SUPERCILEX/easypermissions | easypermissions/src/main/java/pub/devrel/easypermissions/helper/ActivityPermissionHelper.java | 1014 | package pub.devrel.easypermissions.helper;
import android.app.Activity;
import android.app.FragmentManager;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
/**
* Permissions helper for {@link Activity}.
*/
class ActivityPermissionHelper extends BaseFrameworkPermissionsHelper<Activity> {
public ActivityPermissionHelper(Activity host) {
super(host);
}
@Override
public FragmentManager getFragmentManager() {
return getHost().getFragmentManager();
}
@Override
public void directRequestPermissions(int requestCode, @NonNull String... perms) {
ActivityCompat.requestPermissions(getHost(), perms, requestCode);
}
@Override
public boolean shouldShowRequestPermissionRationale(@NonNull String perm) {
return ActivityCompat.shouldShowRequestPermissionRationale(getHost(), perm);
}
@Override
public Context getContext() {
return getHost();
}
}
| apache-2.0 |
chenxyzy/cms | src/com/lerx/integral/rule/dao/imp/IntegralRuleDaoImp.java | 3349 | package com.lerx.integral.rule.dao.imp;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.lerx.integral.rule.dao.IIntegralRuleDao;
import com.lerx.integral.rule.vo.IntegralRule;
public class IntegralRuleDaoImp extends HibernateDaoSupport implements IIntegralRuleDao {
@Override
public int add(IntegralRule ir) {
if (findByName(ir.getName())==null){
this.getHibernateTemplate().save(ir);
return ir.getId();
}else{
return 0;
}
}
@Override
public boolean modify(IntegralRule ir) {
try {
IntegralRule irdb=findById(ir.getId());
if (ir.getCreateTime()==null){
ir.setCreateTime(irdb.getCreateTime());
}
if (ir.getLocalPostion()==0){
ir.setLocalPostion(irdb.getLocalPostion());
}
if (ir.isState()){
String hql="update IntegralRule i set i.state=false where i.localPostion=?";
this.getHibernateTemplate().bulkUpdate(hql,ir.getLocalPostion());
}
this.getHibernateTemplate().saveOrUpdate(ir);
return true;
} catch (DataAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
@Override
public boolean deyById(int id) {
try {
this.getHibernateTemplate().delete(
this.getHibernateTemplate()
.get("com.lerx.integral.rule.vo.IntegralRule", id));
return true;
} catch (DataAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
@Override
public IntegralRule findById(int id) {
// TODO Auto-generated method stub
return
(IntegralRule) this.getHibernateTemplate()
.get("com.lerx.integral.rule.vo.IntegralRule", id);
}
@Override
public List<IntegralRule> query(int localPostion) {
String hql="from IntegralRule i where i.localPostion=?";
@SuppressWarnings("unchecked")
List<IntegralRule> list = (List<IntegralRule>)this.getHibernateTemplate().find(hql, localPostion);
return list;
}
@Override
public IntegralRule findByName(String name) {
String hql="from IntegralRule i where i.name=?";
@SuppressWarnings("unchecked")
List<IntegralRule> list=(List<IntegralRule>)this.getHibernateTemplate().find(hql, name);
if (list.isEmpty()){
return null;
}else{
return list.get(0);
}
}
@Override
public boolean changeState(int id,boolean state,int localPostion) {
String hql="";
if (state){
System.out.println("localPostion:"+localPostion);
hql="update IntegralRule i set i.state=false where i.localPostion=?";
this.getHibernateTemplate().bulkUpdate(hql,localPostion);
hql="update IntegralRule i set i.state=true where i.id="+id;
this.getHibernateTemplate().bulkUpdate(hql);
}else{
IntegralRule i=findById(id);
i.setState(state);
this.getHibernateTemplate().saveOrUpdate(i);
// hql="update IntegralRule i set i.state=false where i.id="+id;
// this.getHibernateTemplate().bulkUpdate(hql);
}
return true;
}
@Override
public IntegralRule findDefault(int localPostion) {
String hql="from IntegralRule i where i.state=true and i.localPostion=?";
@SuppressWarnings("unchecked")
List<IntegralRule> list=(List<IntegralRule>)this.getHibernateTemplate().find(hql,localPostion);
if (list.isEmpty()){
return null;
}else{
return list.get(0);
}
// return null;
}
}
| apache-2.0 |
aharpour/user-management-dashboard | cms/src/main/java/nl/openweb/hippo/umd/webservices/HippoAuthenticationRequestHandler.java | 4730 | /*
* Copyright 2014 Hippo B.V. (http://www.onehippo.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.
*
* Modified by Ebrahim Aharpour
* to integrate the authentication of the user with the CMS
*/
package nl.openweb.hippo.umd.webservices;
import java.io.Serializable;
import java.lang.reflect.Method;
import javax.jcr.LoginException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import org.apache.cxf.jaxrs.ext.RequestHandler;
import org.apache.cxf.jaxrs.ext.ResponseHandler;
import org.apache.cxf.jaxrs.model.ClassResourceInfo;
import org.apache.cxf.jaxrs.model.OperationResourceInfo;
import org.apache.cxf.message.Message;
import org.apache.cxf.transport.http.AbstractHTTPDestination;
import org.apache.wicket.Application;
import org.apache.wicket.protocol.http.servlet.ServletWebRequest;
import org.apache.wicket.session.ISessionStore;
import org.hippoecm.frontend.model.UserCredentials;
import org.hippoecm.frontend.session.PluginUserSession;
import org.onehippo.forge.webservices.AuthenticationConstants;
import org.onehippo.forge.webservices.jaxrs.exception.UnauthorizedException;
import org.onehippo.forge.webservices.jaxrs.jcr.util.JcrSessionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Provider
public class HippoAuthenticationRequestHandler implements RequestHandler, ResponseHandler {
private static final Logger LOG = LoggerFactory.getLogger(HippoAuthenticationRequestHandler.class);
private Session session = null;
public static final String[] STREAMING_OUTPUT_SERVICES = new String[] { "getGroupsOverview", "getUsersOverview" };
public Response handleRequest(Message m, ClassResourceInfo resourceClass) {
ISessionStore sessionStore = Application.get().getSessionStore();
Serializable attribute = sessionStore.getAttribute(
new ServletWebRequest((HttpServletRequest) m.get(AbstractHTTPDestination.HTTP_REQUEST), ""), "session");
if (attribute instanceof PluginUserSession) {
UserCredentials userCredentials = ((PluginUserSession) attribute).getUserCredentials();
if (userCredentials != null) {
SimpleCredentials jcrCredentials = (SimpleCredentials) userCredentials.getJcrCredentials();
String username = jcrCredentials.getUserID();
String password = new String(jcrCredentials.getPassword());
try {
session = JcrSessionUtil.createSession(username, password);
if (isAuthenticated()) {
HttpServletRequest request = (HttpServletRequest) m.get(AbstractHTTPDestination.HTTP_REQUEST);
request.setAttribute(AuthenticationConstants.HIPPO_SESSION, session);
return null;
} else {
throw new UnauthorizedException();
}
} catch (LoginException e) {
LOG.debug("Login failed: {}", e);
throw new UnauthorizedException(e.getMessage());
}
}
}
throw new UnauthorizedException();
}
@Override
public Response handleResponse(final Message m, final OperationResourceInfo ori, final Response response) {
if (session != null && session.isLive()) {
if (!(ori != null && ori.getMethodToInvoke() != null && isStreamingOutputServices(ori.getMethodToInvoke()))) {
session.logout();
}
session = null;
}
return null;
}
public boolean isStreamingOutputServices(Method methodToInvoke) {
boolean result = false;
if (methodToInvoke != null) {
String calledMethod = methodToInvoke.getName();
for (String serviceMethod : STREAMING_OUTPUT_SERVICES) {
if (serviceMethod.equals(calledMethod)) {
result = true;
break;
}
}
}
return result;
}
private boolean isAuthenticated() {
return session != null;
}
} | apache-2.0 |
rwinch/spring-security-oauth | spring-security-oauth2/src/main/java/org/springframework/security/oauth2/config/ClientDetailsServiceBeanDefinitionParser.java | 3600 | /*
* Copyright 2008-2009 Web Cohesion
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.config;
import java.util.List;
import org.springframework.beans.BeanMetadataElement;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.ManagedMap;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.security.oauth2.provider.BaseClientDetails;
import org.springframework.security.oauth2.provider.InMemoryClientDetailsService;
import org.springframework.util.StringUtils;
import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;
/**
* @author Ryan Heaton
* @author Andrew McCall
*/
public class ClientDetailsServiceBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {
@Override
protected Class<?> getBeanClass(Element element) {
return InMemoryClientDetailsService.class;
}
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
List<Element> clientElements = DomUtils.getChildElementsByTagName(element, "client");
ManagedMap<String, BeanMetadataElement> clients = new ManagedMap<String, BeanMetadataElement>();
for (Element clientElement : clientElements) {
BeanDefinitionBuilder client = BeanDefinitionBuilder.rootBeanDefinition(BaseClientDetails.class);
String clientId = clientElement.getAttribute("client-id");
if (StringUtils.hasText(clientId)) {
client.addConstructorArgValue(clientId);
}
else {
parserContext.getReaderContext().error("A client id must be supplied with the definition of a client.",
clientElement);
}
String secret = clientElement.getAttribute("secret");
if (StringUtils.hasText(secret)) {
client.addPropertyValue("clientSecret", secret);
}
String resourceIds = clientElement.getAttribute("resource-ids");
if (StringUtils.hasText(clientId)) {
client.addConstructorArgValue(resourceIds);
}
else {
client.addConstructorArgValue("");
}
String redirectUri = clientElement.getAttribute("redirect-uri");
String tokenValidity = clientElement.getAttribute("access-token-validity");
if (StringUtils.hasText(tokenValidity)) {
client.addPropertyValue("accessTokenValiditySeconds", tokenValidity);
}
String refreshValidity = clientElement.getAttribute("refresh-token-validity");
if (StringUtils.hasText(refreshValidity)) {
client.addPropertyValue("refreshTokenValiditySeconds", refreshValidity);
}
client.addConstructorArgValue(clientElement.getAttribute("scope"));
client.addConstructorArgValue(clientElement.getAttribute("authorized-grant-types"));
client.addConstructorArgValue(clientElement.getAttribute("authorities"));
if (StringUtils.hasText(redirectUri)) {
client.addConstructorArgValue(redirectUri);
}
clients.put(clientId, client.getBeanDefinition());
}
builder.addPropertyValue("clientDetailsStore", clients);
}
} | apache-2.0 |
remibergsma/cosmic | cosmic-core/engine/schema/src/main/java/com/cloud/dc/dao/VlanDaoImpl.java | 15800 | package com.cloud.dc.dao;
import com.cloud.dc.AccountVlanMapVO;
import com.cloud.dc.DomainVlanMapVO;
import com.cloud.dc.PodVlanMapVO;
import com.cloud.dc.Vlan;
import com.cloud.dc.Vlan.VlanType;
import com.cloud.dc.VlanVO;
import com.cloud.network.dao.IPAddressDao;
import com.cloud.utils.Pair;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.JoinBuilder;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.TransactionLegacy;
import com.cloud.utils.exception.CloudRuntimeException;
import javax.inject.Inject;
import javax.naming.ConfigurationException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Component;
@Component
public class VlanDaoImpl extends GenericDaoBase<VlanVO, Long> implements VlanDao {
private final String FindZoneWideVlans =
"SELECT * FROM vlan WHERE data_center_id=? and vlan_type=? and vlan_id!=? and id not in (select vlan_db_id from account_vlan_map)";
protected SearchBuilder<VlanVO> ZoneVlanIdSearch;
protected SearchBuilder<VlanVO> ZoneSearch;
protected SearchBuilder<VlanVO> ZoneTypeSearch;
protected SearchBuilder<VlanVO> ZoneTypeAllPodsSearch;
protected SearchBuilder<VlanVO> ZoneTypePodSearch;
protected SearchBuilder<VlanVO> ZoneVlanSearch;
protected SearchBuilder<VlanVO> NetworkVlanSearch;
protected SearchBuilder<VlanVO> PhysicalNetworkVlanSearch;
protected SearchBuilder<VlanVO> ZoneWideNonDedicatedVlanSearch;
protected SearchBuilder<VlanVO> VlanGatewaysearch;
protected SearchBuilder<VlanVO> DedicatedVlanSearch;
protected SearchBuilder<AccountVlanMapVO> AccountVlanMapSearch;
protected SearchBuilder<DomainVlanMapVO> DomainVlanMapSearch;
@Inject
protected PodVlanMapDao _podVlanMapDao;
@Inject
protected AccountVlanMapDao _accountVlanMapDao;
@Inject
protected DomainVlanMapDao _domainVlanMapDao;
@Inject
protected IPAddressDao _ipAddressDao;
public VlanDaoImpl() {
ZoneVlanIdSearch = createSearchBuilder();
ZoneVlanIdSearch.and("zoneId", ZoneVlanIdSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
ZoneVlanIdSearch.and("vlanId", ZoneVlanIdSearch.entity().getVlanTag(), SearchCriteria.Op.EQ);
ZoneVlanIdSearch.done();
ZoneSearch = createSearchBuilder();
ZoneSearch.and("zoneId", ZoneSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
ZoneSearch.done();
ZoneTypeSearch = createSearchBuilder();
ZoneTypeSearch.and("zoneId", ZoneTypeSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
ZoneTypeSearch.and("vlanType", ZoneTypeSearch.entity().getVlanType(), SearchCriteria.Op.EQ);
ZoneTypeSearch.done();
NetworkVlanSearch = createSearchBuilder();
NetworkVlanSearch.and("networkOfferingId", NetworkVlanSearch.entity().getNetworkId(), SearchCriteria.Op.EQ);
NetworkVlanSearch.done();
PhysicalNetworkVlanSearch = createSearchBuilder();
PhysicalNetworkVlanSearch.and("physicalNetworkId", PhysicalNetworkVlanSearch.entity().getPhysicalNetworkId(), SearchCriteria.Op.EQ);
PhysicalNetworkVlanSearch.done();
VlanGatewaysearch = createSearchBuilder();
VlanGatewaysearch.and("gateway", VlanGatewaysearch.entity().getVlanGateway(), SearchCriteria.Op.EQ);
VlanGatewaysearch.and("networkid", VlanGatewaysearch.entity().getNetworkId(), SearchCriteria.Op.EQ);
VlanGatewaysearch.done();
}
@Override
public VlanVO findByZoneAndVlanId(final long zoneId, final String vlanId) {
final SearchCriteria<VlanVO> sc = ZoneVlanIdSearch.create();
sc.setParameters("zoneId", zoneId);
sc.setParameters("vlanId", vlanId);
return findOneBy(sc);
}
@Override
public List<VlanVO> listByZone(final long zoneId) {
final SearchCriteria<VlanVO> sc = ZoneSearch.create();
sc.setParameters("zoneId", zoneId);
return listBy(sc);
}
@Override
public List<VlanVO> listByType(final VlanType vlanType) {
final SearchCriteria<VlanVO> sc = ZoneTypeSearch.create();
sc.setParameters("vlanType", vlanType);
return listBy(sc);
}
@Override
public List<VlanVO> listByZoneAndType(final long zoneId, final VlanType vlanType) {
final SearchCriteria<VlanVO> sc = ZoneTypeSearch.create();
sc.setParameters("zoneId", zoneId);
sc.setParameters("vlanType", vlanType);
return listBy(sc);
}
@Override
public List<VlanVO> listVlansForPod(final long podId) {
//FIXME: use a join statement to improve the performance (should be minor since we expect only one or two
final List<PodVlanMapVO> vlanMaps = _podVlanMapDao.listPodVlanMapsByPod(podId);
final List<VlanVO> result = new ArrayList<>();
for (final PodVlanMapVO pvmvo : vlanMaps) {
result.add(findById(pvmvo.getVlanDbId()));
}
return result;
}
@Override
public List<VlanVO> listVlansForPodByType(final long podId, final VlanType vlanType) {
//FIXME: use a join statement to improve the performance (should be minor since we expect only one or two)
final List<PodVlanMapVO> vlanMaps = _podVlanMapDao.listPodVlanMapsByPod(podId);
final List<VlanVO> result = new ArrayList<>();
for (final PodVlanMapVO pvmvo : vlanMaps) {
final VlanVO vlan = findById(pvmvo.getVlanDbId());
if (vlan.getVlanType() == vlanType) {
result.add(vlan);
}
}
return result;
}
@Override
public void addToPod(final long podId, final long vlanDbId) {
final PodVlanMapVO pvmvo = new PodVlanMapVO(podId, vlanDbId);
_podVlanMapDao.persist(pvmvo);
}
@Override
public List<VlanVO> listVlansForAccountByType(final Long zoneId, final long accountId, final VlanType vlanType) {
//FIXME: use a join statement to improve the performance (should be minor since we expect only one or two)
final List<AccountVlanMapVO> vlanMaps = _accountVlanMapDao.listAccountVlanMapsByAccount(accountId);
final List<VlanVO> result = new ArrayList<>();
for (final AccountVlanMapVO acvmvo : vlanMaps) {
final VlanVO vlan = findById(acvmvo.getVlanDbId());
if (vlan.getVlanType() == vlanType && (zoneId == null || vlan.getDataCenterId() == zoneId)) {
result.add(vlan);
}
}
return result;
}
@Override
public boolean zoneHasDirectAttachUntaggedVlans(final long zoneId) {
final SearchCriteria<VlanVO> sc = ZoneTypeAllPodsSearch.create();
sc.setParameters("zoneId", zoneId);
sc.setParameters("vlanType", VlanType.DirectAttached);
return listIncludingRemovedBy(sc).size() > 0;
}
@Override
public List<VlanVO> listZoneWideVlans(final long zoneId, final VlanType vlanType, final String vlanId) {
final SearchCriteria<VlanVO> sc = ZoneVlanSearch.create();
sc.setParameters("zoneId", zoneId);
sc.setParameters("vlanId", vlanId);
sc.setParameters("vlanType", vlanType);
return listBy(sc);
}
@Override
@DB
public List<VlanVO> searchForZoneWideVlans(final long dcId, final String vlanType, final String vlanId) {
final StringBuilder sql = new StringBuilder(FindZoneWideVlans);
final TransactionLegacy txn = TransactionLegacy.currentTxn();
final List<VlanVO> zoneWideVlans = new ArrayList<>();
try (PreparedStatement pstmt = txn.prepareStatement(sql.toString())) {
if (pstmt != null) {
pstmt.setLong(1, dcId);
pstmt.setString(2, vlanType);
pstmt.setString(3, vlanId);
try (ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
zoneWideVlans.add(toEntityBean(rs, false));
}
} catch (final SQLException e) {
throw new CloudRuntimeException("searchForZoneWideVlans:Exception:" + e.getMessage(), e);
}
}
return zoneWideVlans;
} catch (final SQLException e) {
throw new CloudRuntimeException("searchForZoneWideVlans:Exception:" + e.getMessage(), e);
}
}
@Override
public List<VlanVO> listVlansByNetworkId(final long networkOfferingId) {
final SearchCriteria<VlanVO> sc = NetworkVlanSearch.create();
sc.setParameters("networkOfferingId", networkOfferingId);
return listBy(sc);
}
@Override
public List<VlanVO> listVlansByPhysicalNetworkId(final long physicalNetworkId) {
final SearchCriteria<VlanVO> sc = PhysicalNetworkVlanSearch.create();
sc.setParameters("physicalNetworkId", physicalNetworkId);
return listBy(sc);
}
@Override
public List<VlanVO> listZoneWideNonDedicatedVlans(final long zoneId) {
final SearchCriteria<VlanVO> sc = ZoneWideNonDedicatedVlanSearch.create();
sc.setParameters("zoneId", zoneId);
return listBy(sc);
}
@Override
public List<VlanVO> listVlansByNetworkIdAndGateway(final long networkid, final String gateway) {
final SearchCriteria<VlanVO> sc = VlanGatewaysearch.create();
sc.setParameters("networkid", networkid);
sc.setParameters("gateway", gateway);
return listBy(sc);
}
@Override
public List<VlanVO> listDedicatedVlans(final long accountId) {
final SearchCriteria<VlanVO> sc = DedicatedVlanSearch.create();
sc.setJoinParameters("AccountVlanMapSearch", "accountId", accountId);
return listBy(sc);
}
@Override
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
final boolean result = super.configure(name, params);
ZoneTypeAllPodsSearch = createSearchBuilder();
ZoneTypeAllPodsSearch.and("zoneId", ZoneTypeAllPodsSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
ZoneTypeAllPodsSearch.and("vlanType", ZoneTypeAllPodsSearch.entity().getVlanType(), SearchCriteria.Op.EQ);
final SearchBuilder<PodVlanMapVO> PodVlanSearch = _podVlanMapDao.createSearchBuilder();
PodVlanSearch.and("podId", PodVlanSearch.entity().getPodId(), SearchCriteria.Op.NNULL);
ZoneTypeAllPodsSearch.join("vlan", PodVlanSearch, PodVlanSearch.entity().getVlanDbId(), ZoneTypeAllPodsSearch.entity().getId(), JoinBuilder.JoinType.INNER);
ZoneTypeAllPodsSearch.done();
PodVlanSearch.done();
ZoneTypePodSearch = createSearchBuilder();
ZoneTypePodSearch.and("zoneId", ZoneTypePodSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
ZoneTypePodSearch.and("vlanType", ZoneTypePodSearch.entity().getVlanType(), SearchCriteria.Op.EQ);
final SearchBuilder<PodVlanMapVO> PodVlanSearch2 = _podVlanMapDao.createSearchBuilder();
PodVlanSearch2.and("podId", PodVlanSearch2.entity().getPodId(), SearchCriteria.Op.EQ);
ZoneTypePodSearch.join("vlan", PodVlanSearch2, PodVlanSearch2.entity().getVlanDbId(), ZoneTypePodSearch.entity().getId(), JoinBuilder.JoinType.INNER);
PodVlanSearch2.done();
ZoneTypePodSearch.done();
ZoneWideNonDedicatedVlanSearch = createSearchBuilder();
ZoneWideNonDedicatedVlanSearch.and("zoneId", ZoneWideNonDedicatedVlanSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
AccountVlanMapSearch = _accountVlanMapDao.createSearchBuilder();
AccountVlanMapSearch.and("accountId", AccountVlanMapSearch.entity().getAccountId(), SearchCriteria.Op.NULL);
ZoneWideNonDedicatedVlanSearch.join("AccountVlanMapSearch", AccountVlanMapSearch, ZoneWideNonDedicatedVlanSearch.entity().getId(), AccountVlanMapSearch.entity()
.getVlanDbId(),
JoinBuilder.JoinType.LEFTOUTER);
DomainVlanMapSearch = _domainVlanMapDao.createSearchBuilder();
DomainVlanMapSearch.and("domainId", DomainVlanMapSearch.entity().getDomainId(), SearchCriteria.Op.NULL);
ZoneWideNonDedicatedVlanSearch.join("DomainVlanMapSearch", DomainVlanMapSearch, ZoneWideNonDedicatedVlanSearch.entity().getId(), DomainVlanMapSearch.entity().getVlanDbId
(), JoinBuilder.JoinType.LEFTOUTER);
ZoneWideNonDedicatedVlanSearch.done();
AccountVlanMapSearch.done();
DomainVlanMapSearch.done();
DedicatedVlanSearch = createSearchBuilder();
AccountVlanMapSearch = _accountVlanMapDao.createSearchBuilder();
AccountVlanMapSearch.and("accountId", AccountVlanMapSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
DedicatedVlanSearch.join("AccountVlanMapSearch", AccountVlanMapSearch, DedicatedVlanSearch.entity().getId(), AccountVlanMapSearch.entity().getVlanDbId(),
JoinBuilder.JoinType.LEFTOUTER);
DedicatedVlanSearch.done();
AccountVlanMapSearch.done();
return result;
}
private VlanVO findNextVlan(final long zoneId, final Vlan.VlanType vlanType) {
final List<VlanVO> allVlans = listByZoneAndType(zoneId, vlanType);
final List<VlanVO> emptyVlans = new ArrayList<>();
final List<VlanVO> fullVlans = new ArrayList<>();
// Try to find a VLAN that is partially allocated
for (final VlanVO vlan : allVlans) {
final long vlanDbId = vlan.getId();
final int countOfAllocatedIps = _ipAddressDao.countIPs(zoneId, vlanDbId, true);
final int countOfAllIps = _ipAddressDao.countIPs(zoneId, vlanDbId, false);
if ((countOfAllocatedIps > 0) && (countOfAllocatedIps < countOfAllIps)) {
return vlan;
} else if (countOfAllocatedIps == 0) {
emptyVlans.add(vlan);
} else if (countOfAllocatedIps == countOfAllIps) {
fullVlans.add(vlan);
}
}
if (emptyVlans.isEmpty()) {
return null;
}
// Try to find an empty VLAN with the same tag/subnet as a VLAN that is full
for (final VlanVO fullVlan : fullVlans) {
for (final VlanVO emptyVlan : emptyVlans) {
if (fullVlan.getVlanTag().equals(emptyVlan.getVlanTag()) && fullVlan.getVlanGateway().equals(emptyVlan.getVlanGateway()) &&
fullVlan.getVlanNetmask().equals(emptyVlan.getVlanNetmask())) {
return emptyVlan;
}
}
}
// Return a random empty VLAN
return emptyVlans.get(0);
}
public Pair<String, VlanVO> assignPodDirectAttachIpAddress(final long zoneId, final long podId, final long accountId, final long domainId) {
final SearchCriteria<VlanVO> sc = ZoneTypePodSearch.create();
sc.setParameters("zoneId", zoneId);
sc.setParameters("vlanType", VlanType.DirectAttached);
sc.setJoinParameters("vlan", "podId", podId);
final VlanVO vlan = findOneIncludingRemovedBy(sc);
if (vlan == null) {
return null;
}
return null;
// String ipAddress = _ipAddressDao.assignIpAddress(accountId, domainId, vlan.getId(), false).getAddress();
// if (ipAddress == null) {
// return null;
// }
// return new Pair<String, VlanVO>(ipAddress, vlan);
}
}
| apache-2.0 |
SkyZhang007/LazyCat | gankio/src/main/java/com/sky/gank/data/douban/RemoteDoubanMovieDataSource.java | 1499 | package com.sky.gank.data.douban;
import com.sky.gank.net.HttpUtil;
import com.sky.gank.net.RetrofitService;
import com.sky.gank.net.Urls;
import io.reactivex.Observable;
/**
* 类名称:
* 类功能:
* 类作者:Sky
* 类日期:2018/12/31 0031.
**/
public class RemoteDoubanMovieDataSource implements DoubanMovieDataSource{
public static final String MOVETYPE_IN_THEATERS = "in_theaters";
public static final String MOVETYPE_TOP250 = "top250";
private static RemoteDoubanMovieDataSource sInstance;
private RemoteDoubanMovieDataSource() {
}
public static RemoteDoubanMovieDataSource getInstance() {
if (sInstance == null) {
synchronized (RemoteDoubanMovieDataSource.class) {
if (sInstance == null) {
sInstance = new RemoteDoubanMovieDataSource();
}
}
}
return sInstance;
}
@Override
public Observable<DoubanMovieData> getDouBanMovies(String type,int start,int count) {
return HttpUtil.getInstance()
.setBaseUrl(Urls.DOUBAN_API_BASE)
.create(RetrofitService.class)
.getDouBanMovies(type,start,count);
}
@Override
public Observable<DoubanMovieDetailData> getDouBanMovieDetail(String id) {
return HttpUtil.getInstance()
.setBaseUrl(Urls.DOUBAN_API_BASE)
.create(RetrofitService.class)
.getDouBanMovieDetail(id);
}
}
| apache-2.0 |
c340c340/mybatis-3.2.22 | src/test/java/com/ibatis/sqlmap/ComplexTypeTest.java | 1486 | /*
* Copyright 2009-2012 The MyBatis Team
*
* 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.ibatis.sqlmap;
import com.testdomain.ComplexBean;
import java.util.HashMap;
import java.util.Map;
public class ComplexTypeTest extends BaseSqlMapTest {
// SETUP & TEARDOWN
protected void setUp() throws Exception {
initSqlMap("com/ibatis/sqlmap/maps/SqlMapConfig.xml", null);
initScript("com/scripts/account-init.sql");
initScript("com/scripts/order-init.sql");
initScript("com/scripts/line_item-init.sql");
}
protected void tearDown() throws Exception {
}
public void testMapBeanMap() throws Exception {
Map map = new HashMap();
ComplexBean bean = new ComplexBean();
bean.setMap(new HashMap());
bean.getMap().put("id", new Integer(1));
map.put("bean", bean);
Integer id = (Integer) sqlMap.queryForObject("mapBeanMap", map);
assertEquals(id, bean.getMap().get("id"));
}
}
| apache-2.0 |
orangemile/chronicle-replay | src/app/java/com/orangemile/replay/ReplayHandler.java | 283 | package com.orangemile.replay;
import com.higherfrequencytrading.chronicle.Excerpt;
public interface ReplayHandler<T> {
public T parse(int id, Excerpt e);
public long getTime(int id, T t);
public void replay(int id, T t, long realTime, long relativeTime);
}
| apache-2.0 |
strapdata/elassandra5-rc | core/src/main/java/org/elasticsearch/search/profile/query/CollectorResult.java | 7878 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.search.profile.query;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import static org.elasticsearch.common.xcontent.XContentParserUtils.ensureExpectedToken;
import static org.elasticsearch.common.xcontent.XContentParserUtils.throwUnknownField;
import static org.elasticsearch.common.xcontent.XContentParserUtils.throwUnknownToken;
/**
* Public interface and serialization container for profiled timings of the
* Collectors used in the search. Children CollectorResult's may be
* embedded inside of a parent CollectorResult
*/
public class CollectorResult implements ToXContentObject, Writeable {
public static final String REASON_SEARCH_COUNT = "search_count";
public static final String REASON_SEARCH_TOP_HITS = "search_top_hits";
public static final String REASON_SEARCH_TERMINATE_AFTER_COUNT = "search_terminate_after_count";
public static final String REASON_SEARCH_POST_FILTER = "search_post_filter";
public static final String REASON_SEARCH_MIN_SCORE = "search_min_score";
public static final String REASON_SEARCH_MULTI = "search_multi";
public static final String REASON_SEARCH_TIMEOUT = "search_timeout";
public static final String REASON_SEARCH_CANCELLED = "search_cancelled";
public static final String REASON_AGGREGATION = "aggregation";
public static final String REASON_AGGREGATION_GLOBAL = "aggregation_global";
private static final ParseField NAME = new ParseField("name");
private static final ParseField REASON = new ParseField("reason");
private static final ParseField TIME = new ParseField("time");
private static final ParseField TIME_NANOS = new ParseField("time_in_nanos");
private static final ParseField CHILDREN = new ParseField("children");
/**
* A more friendly representation of the Collector's class name
*/
private final String collectorName;
/**
* A "hint" to help provide some context about this Collector
*/
private final String reason;
/**
* The total elapsed time for this Collector
*/
private final Long time;
/**
* A list of children collectors "embedded" inside this collector
*/
private List<CollectorResult> children;
public CollectorResult(String collectorName, String reason, Long time, List<CollectorResult> children) {
this.collectorName = collectorName;
this.reason = reason;
this.time = time;
this.children = children;
}
/**
* Read from a stream.
*/
public CollectorResult(StreamInput in) throws IOException {
this.collectorName = in.readString();
this.reason = in.readString();
this.time = in.readLong();
int size = in.readVInt();
this.children = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
CollectorResult child = new CollectorResult(in);
this.children.add(child);
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(collectorName);
out.writeString(reason);
out.writeLong(time);
out.writeVInt(children.size());
for (CollectorResult child : children) {
child.writeTo(out);
}
}
/**
* @return the profiled time for this collector (inclusive of children)
*/
public long getTime() {
return this.time;
}
/**
* @return a human readable "hint" about what this collector was used for
*/
public String getReason() {
return this.reason;
}
/**
* @return the lucene class name of the collector
*/
public String getName() {
return this.collectorName;
}
/**
* @return a list of children collectors
*/
public List<CollectorResult> getProfiledChildren() {
return children;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException {
builder = builder.startObject()
.field(NAME.getPreferredName(), getName())
.field(REASON.getPreferredName(), getReason())
.field(TIME.getPreferredName(), String.format(Locale.US, "%.10gms", getTime() / 1000000.0))
.field(TIME_NANOS.getPreferredName(), getTime());
if (!children.isEmpty()) {
builder = builder.startArray(CHILDREN.getPreferredName());
for (CollectorResult child : children) {
builder = child.toXContent(builder, params);
}
builder = builder.endArray();
}
builder = builder.endObject();
return builder;
}
public static CollectorResult fromXContent(XContentParser parser) throws IOException {
XContentParser.Token token = parser.currentToken();
ensureExpectedToken(XContentParser.Token.START_OBJECT, token, parser::getTokenLocation);
String currentFieldName = null;
String name = null, reason = null;
long time = -1;
List<CollectorResult> children = new ArrayList<>();
while((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token.isValue()) {
if (NAME.match(currentFieldName)) {
name = parser.text();
} else if (REASON.match(currentFieldName)) {
reason = parser.text();
} else if (TIME.match(currentFieldName)) {
// we need to consume this value, but we use the raw nanosecond value
parser.text();
} else if (TIME_NANOS.match(currentFieldName)) {
time = parser.longValue();
} else {
throwUnknownField(currentFieldName, parser.getTokenLocation());
}
} else if (token == XContentParser.Token.START_ARRAY) {
if (CHILDREN.match(currentFieldName)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
children.add(CollectorResult.fromXContent(parser));
}
} else {
throwUnknownField(currentFieldName, parser.getTokenLocation());
}
} else {
throwUnknownToken(token, parser.getTokenLocation());
}
}
return new CollectorResult(name, reason, time, children);
}
}
| apache-2.0 |
codyer/CleanFramework | app/src/demo/java/com/cody/app/business/launch/CharacterView.java | 3979 | package com.cody.app.business.launch;
import android.animation.AnimatorSet;
import android.animation.ValueAnimator;
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.animation.AccelerateDecelerateInterpolator;
import java.util.ArrayList;
import java.util.List;
/**
* Created by cody.yi on 2017/9/6.
* some useful information
*/
public class CharacterView extends android.support.v7.widget.AppCompatTextView {
private Position mCurrentPosition;
private int mDuration = 2000;
public int getDuration() {
return mDuration;
}
public void setDuration(int duration) {
mDuration = duration;
}
private List<Position> mPositions = new ArrayList<>();
private AnimatorSet mAnimatorSet;
public Position getLastPosition() {
return mPositions.get(mPositions.size() - 1);
}
public Position getCurrentPosition() {
return mCurrentPosition;
}
public List<Position> getPositions() {
return mPositions;
}
public CharacterView addPosition(Position position) {
mPositions.add(position);
return this;
}
public CharacterView addPosition(float x, float y) {
mPositions.add(new Position(x, y));
return this;
}
public CharacterView addLineToX(float x) {
mPositions.add(new Position(x, getLastPosition().y));
return this;
}
public CharacterView addLineToY(float y) {
mPositions.add(new Position(getLastPosition().x, y));
return this;
}
public CharacterView(Context context) {
this(context, null);
}
public CharacterView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (mCurrentPosition == null) {
mCurrentPosition = new Position(getX(), getY());
mPositions.clear();
addPosition(mCurrentPosition);
}
}
public CharacterView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void startAnimation() {
if (mAnimatorSet == null) {
mAnimatorSet = new AnimatorSet();
ValueAnimator positionAnimator = ValueAnimator.ofObject(new PositionEvaluator(), mPositions.toArray());
positionAnimator.setDuration(mDuration);
positionAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
mCurrentPosition = (Position) animation.getAnimatedValue();
setX(mCurrentPosition.x);
setY(mCurrentPosition.y);
invalidate();
}
});
positionAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
ValueAnimator scaleAnimator = ValueAnimator.ofFloat(1.0f, 0.5f);
scaleAnimator.setDuration(mDuration);
scaleAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float scale = (float) animation.getAnimatedValue();
setPivotX(0);
setScaleX(scale);
setScaleY(scale);
invalidate();
}
});
mAnimatorSet.playTogether(positionAnimator, scaleAnimator);
}
if (!mAnimatorSet.isStarted()) {
mAnimatorSet.start();
}
}
public void stopAnimation() {
if (mAnimatorSet != null && mAnimatorSet.isStarted()) {
mAnimatorSet.end();
}
}
}
| apache-2.0 |
griffon-plugins/griffon-domain-plugin | subprojects/griffon-domain-core/src/main/java/org/codehaus/griffon/runtime/domain/AbstractGriffonDomainClassProperty.java | 1607 | /*
* Copyright 2014-2016 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.codehaus.griffon.runtime.domain;
import griffon.plugins.domain.GriffonDomainClass;
import griffon.plugins.domain.GriffonDomainClassProperty;
import javax.annotation.Nonnull;
import java.beans.PropertyDescriptor;
import static java.util.Objects.requireNonNull;
/**
* @author Andres Almiray
*/
public abstract class AbstractGriffonDomainClassProperty extends DefaultGriffonDomainProperty implements GriffonDomainClassProperty {
private static final String ERROR_DOMAIN_CLASS_NULL = "Argument 'domainClass' must not be null";
private final GriffonDomainClass<?> domainClass;
public AbstractGriffonDomainClassProperty(@Nonnull GriffonDomainClass<?> domainClass, @Nonnull PropertyDescriptor propertyDescriptor) {
super(propertyDescriptor, requireNonNull(domainClass, ERROR_DOMAIN_CLASS_NULL).getClazz());
this.domainClass = domainClass;
}
@Nonnull
public GriffonDomainClass<?> getDomainClass() {
return domainClass;
}
}
| apache-2.0 |
alexduch/grobid | grobid-core/src/main/java/org/grobid/core/utilities/TextUtilities.java | 47103 | package org.grobid.core.utilities;
import org.apache.commons.lang3.StringUtils;
import org.grobid.core.analyzers.GrobidAnalyzer;
import org.grobid.core.exceptions.GrobidException;
import org.grobid.core.layout.LayoutToken;
import org.grobid.core.lexicon.Lexicon;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Class for holding static methods for text processing.
*
* @author Patrice Lopez
*/
public class TextUtilities {
public static final String punctuations = " •*,:;?.!)-−–\"“”‘’'`$]*\u2666\u2665\u2663\u2660\u00A0";
public static final String fullPunctuations = "(([ •*,:;?.!/))-−–‐«»„\"“”‘’'`$]*\u2666\u2665\u2663\u2660\u00A0";
public static final String restrictedPunctuations = ",:;?.!/-–«»„\"“”‘’'`*\u2666\u2665\u2663\u2660";
public static String delimiters = "\n\r\t\f\u00A0" + fullPunctuations;
public static final String OR = "|";
public static final String NEW_LINE = "\n";
public static final String SPACE = " ";
public static final String COMMA = ",";
public static final String QUOTE = "'";
public static final String END_BRACKET = ")";
public static final String START_BRACKET = "(";
public static final String SHARP = "#";
public static final String COLON = ":";
public static final String DOUBLE_QUOTE = "\"";
public static final String ESC_DOUBLE_QUOTE = """;
public static final String LESS_THAN = "<";
public static final String ESC_LESS_THAN = "<";
public static final String GREATER_THAN = ">";
public static final String ESC_GREATER_THAN = ">";
public static final String AND = "&";
public static final String ESC_AND = "&";
public static final String SLASH = "/";
// the magical DOI regular expression...
static public final Pattern DOIPattern = Pattern
.compile("(10\\.\\d{4,5}\\/[\\S]+[^;,.\\s])");
// a regular expression for arXiv identifiers
// see https://arxiv.org/help/arxiv_identifier and https://arxiv.org/help/arxiv_identifier_for_services
static public final Pattern arXivPattern = Pattern
.compile("(arXiv\\s?(\\.org)?\\s?\\:\\s?\\d{4}\\s?\\.\\s?\\d{4,5}(v\\d+)?)|(arXiv\\s?(\\.org)?\\s?\\:\\s?[ a-zA-Z\\-\\.]*\\s?/\\s?\\d{7}(v\\d+)?)");
// a regular expression for identifying url pattern in text
// TODO: maybe find a better regex
static public final Pattern urlPattern = Pattern
.compile("(?i)(https?|ftp)\\s?:\\s?//\\s?[-A-Z0-9+&@#/%?=~_()|!:,.;]*[-A-Z0-9+&@#/%=~_()|]");
/**
* Replace numbers in the string by a dummy character for string distance evaluations
*
* @param string the string to be processed.
* @return Returns the string with numbers replaced by 'X'.
*/
public static String shadowNumbers(String string) {
int i = 0;
if (string == null)
return string;
String res = "";
while (i < string.length()) {
char c = string.charAt(i);
if (Character.isDigit(c))
res += 'X';
else
res += c;
i++;
}
return res;
}
private static int getLastPunctuationCharacter(String section) {
int res = -1;
for (int i = section.length() - 1; i >= 0; i--) {
if (fullPunctuations.contains("" + section.charAt(i))) {
res = i;
}
}
return res;
}
public static List<LayoutToken> dehyphenize(List<LayoutToken> tokens) {
List<LayoutToken> output = new ArrayList<>();
for (int i = 0; i < tokens.size(); i++) {
LayoutToken currentToken = tokens.get(i);
//the current token is dash checking what's around
if (currentToken.getText().equals("-")) {
if (doesRequireDehypenisation(tokens, i)) {
//Cleanup eventual additional spaces before the hypen that have been already written to the output
int z = output.size() - 1;
while (z >= 0 && output.get(z).getText().equals(" ")) {
String tokenString = output.get(z).getText();
if (tokenString.equals(" ")) {
output.remove(z);
}
z--;
}
List<Integer> breakLines = new ArrayList<>();
List<Integer> spaces = new ArrayList<>();
int j = i + 1;
while (j < tokens.size() && tokens.get(j).getText().equals(" ") || tokens.get(j).getText().equals("\n")) {
String tokenString = tokens.get(j).getText();
if (tokenString.equals("\n")) {
breakLines.add(j);
}
if (tokenString.equals(" ")) {
spaces.add(j);
}
j++;
}
i += breakLines.size() + spaces.size();
} else {
output.add(currentToken);
List<Integer> breakLines = new ArrayList<>();
List<Integer> spaces = new ArrayList<>();
int j = i + 1;
while (j < tokens.size() && tokens.get(j).getText().equals("\n")) {
String tokenString = tokens.get(j).getText();
if (tokenString.equals("\n")) {
breakLines.add(j);
}
j++;
}
i += breakLines.size() + spaces.size();
}
} else {
output.add(currentToken);
}
}
return output;
}
/**
* Check if the current token (place i), or the hypen, needs to be removed or not.
* <p>
* It will check the tokens before and after. It will get to the next "non space" tokens and verify
* that it's a plain word. If it's not it's keeping the hypen.
* <p>
* TODO: add the check on the bounding box of the next token to see whether there is really a break line.
* TODO: What to do in case of a punctuation is found?
*/
protected static boolean doesRequireDehypenisation(List<LayoutToken> tokens, int i) {
boolean forward = false;
boolean backward = false;
int j = i + 1;
int breakLine = 0;
while (j < tokens.size() && (tokens.get(j).getText().equals(" ") || tokens.get(j).getText().equals("\n"))) {
String tokenString = tokens.get(j).getText();
if (tokenString.equals("\n")) {
breakLine++;
}
j++;
}
if (breakLine == 0) {
return false;
}
Pattern onlyLowercaseLetters = Pattern.compile("[a-z]+");
if (j < tokens.size()) {
Matcher matcher = onlyLowercaseLetters.matcher(tokens.get(j).getText());
if (matcher.find()) {
forward = true;
}
if (forward) {
if(i < 1) {
//If nothing before the hypen, but it looks like a forward hypenisation, let's trust it
return forward;
}
int z = i - 1;
while (z > 0 && tokens.get(z).getText().equals(" ")) {
z--;
}
Matcher backwardMatcher = Pattern.compile("^[A-Za-z]+$").matcher(tokens.get(z).getText());
if (backwardMatcher.find()) {
backward = true;
}
}
}
return backward;
}
public static String dehyphenize(String text) {
GrobidAnalyzer analyser = GrobidAnalyzer.getInstance();
final List<LayoutToken> layoutTokens = analyser.tokenizeWithLayoutToken(text);
return LayoutTokensUtil.toText(dehyphenize(layoutTokens));
}
public static String getLastToken(String section) {
String lastToken = section;
int lastSpaceIndex = section.lastIndexOf(' ');
//The last parenthesis cover the case 'this is a (special-one) case'
// where the lastToken before the hypen should be 'special' and not '(special'
/* int lastParenthesisIndex = section.lastIndexOf('(');
if (lastParenthesisIndex > lastSpaceIndex)
lastSpaceIndex = lastParenthesisIndex;*/
if (lastSpaceIndex != -1) {
lastToken = section.substring(lastSpaceIndex + 1, section.length());
} else {
lastToken = section.substring(0, section.length());
}
return lastToken;
}
public static String getFirstToken(String section) {
int firstSpaceIndex = section.indexOf(' ');
if (firstSpaceIndex == 0) {
return getFirstToken(section.substring(1, section.length()));
} else if (firstSpaceIndex != -1) {
return section.substring(0, firstSpaceIndex);
} else {
return section.substring(0, section.length());
}
}
/**
* Text extracted from a PDF is usually hyphenized, which is not desirable.
* This version supposes that the end of line are lost and than hyphenation
* could appear everywhere. So a dictionary is used to control the recognition
* of hyphen.
*
* @param text the string to be processed without preserved end of lines.
* @return Returns the dehyphenized string.
* <p>
* Deprecated method, not needed anymore since the @newline are preserved thanks to the LayoutTokens
* Use dehypenize
*/
@Deprecated
public static String dehyphenizeHard(String text) {
if (text == null)
return null;
String res = "";
text.replaceAll("\n", SPACE);
StringTokenizer st = new StringTokenizer(text, "-");
boolean hyphen = false;
boolean failure = false;
String lastToken = null;
while (st.hasMoreTokens()) {
String section = st.nextToken().trim();
if (hyphen) {
// we get the first token
StringTokenizer st2 = new StringTokenizer(section, " ,.);!");
if (st2.countTokens() > 0) {
String firstToken = st2.nextToken();
// we check if the composed token is in the lexicon
String hyphenToken = lastToken + firstToken;
//System.out.println(hyphenToken);
/*if (lex == null)
featureFactory.loadLexicon();*/
Lexicon lex = Lexicon.getInstance();
if (lex.inDictionary(hyphenToken.toLowerCase()) &
!(test_digit(hyphenToken))) {
// if yes, it is hyphenization
res += firstToken;
section = section.substring(firstToken.length(), section.length());
} else {
// if not
res += "-";
failure = true;
}
} else {
res += "-";
}
hyphen = false;
}
// we get the last token
hyphen = true;
lastToken = getLastToken(section);
if (failure) {
res += section;
failure = false;
} else
res += SPACE + section;
}
res = res.replace(" . ", ". ");
res = res.replace(" ", SPACE);
return res.trim();
}
/**
* Levenstein distance between two strings
*
* @param s the first string to be compared.
* @param t the second string to be compared.
* @return Returns the Levenshtein distance.
*/
public static int getLevenshteinDistance(String s, String t) {
//if (s == null || t == null) {
// throw new IllegalArgumentException("Strings must not be null");
//}
int n = s.length(); // length of s
int m = t.length(); // length of t
if (n == 0) {
return m;
} else if (m == 0) {
return n;
}
int p[] = new int[n + 1]; //'previous' cost array, horizontally
int d[] = new int[n + 1]; // cost array, horizontally
int _d[]; //placeholder to assist in swapping p and d
// indexes into strings s and t
int i; // iterates through s
int j; // iterates through t
char t_j; // jth character of t
int cost; // cost
for (i = 0; i <= n; i++) {
p[i] = i;
}
for (j = 1; j <= m; j++) {
t_j = t.charAt(j - 1);
d[0] = j;
for (i = 1; i <= n; i++) {
cost = s.charAt(i - 1) == t_j ? 0 : 1;
// minimum of cell to the left+1, to the top+1, diagonally left and up +cost
d[i] = Math.min(Math.min(d[i - 1] + 1, p[i] + 1), p[i - 1] + cost);
}
// copy current distance counts to 'previous row' distance counts
_d = p;
p = d;
d = _d;
}
// our last action in the above loop was to switch d and p, so p now
// actually has the most recent cost counts
return p[n];
}
/**
* Appending nb times the char c to the a StringBuffer...
*/
public final static void appendN(StringBuffer buffer, char c, int nb) {
for (int i = 0; i < nb; i++) {
buffer.append(c);
}
}
/**
* To replace accented characters in a unicode string by unaccented equivalents:
* é -> e, ü -> ue, ß -> ss, etc. following the standard transcription conventions
*
* @param input the string to be processed.
* @return Returns the string without accent.
*/
public final static String removeAccents(String input) {
if (input == null)
return null;
final StringBuffer output = new StringBuffer();
for (int i = 0; i < input.length(); i++) {
switch (input.charAt(i)) {
case '\u00C0': // À
case '\u00C1': // Ã
case '\u00C2': // Â
case '\u00C3': // Ã
case '\u00C5': // Ã…
output.append("A");
break;
case '\u00C4': // Ä
case '\u00C6': // Æ
output.append("AE");
break;
case '\u00C7': // Ç
output.append("C");
break;
case '\u00C8': // È
case '\u00C9': // É
case '\u00CA': // Ê
case '\u00CB': // Ë
output.append("E");
break;
case '\u00CC': // Ì
case '\u00CD': // Ã
case '\u00CE': // ÃŽ
case '\u00CF': // Ã
output.append("I");
break;
case '\u00D0': // Ã
output.append("D");
break;
case '\u00D1': // Ñ
output.append("N");
break;
case '\u00D2': // Ã’
case '\u00D3': // Ó
case '\u00D4': // Ô
case '\u00D5': // Õ
case '\u00D8': // Ø
output.append("O");
break;
case '\u00D6': // Ö
case '\u0152': // Å’
output.append("OE");
break;
case '\u00DE': // Þ
output.append("TH");
break;
case '\u00D9': // Ù
case '\u00DA': // Ú
case '\u00DB': // Û
output.append("U");
break;
case '\u00DC': // Ü
output.append("UE");
break;
case '\u00DD': // Ã
case '\u0178': // Ÿ
output.append("Y");
break;
case '\u00E0': // Ã
case '\u00E1': // á
case '\u00E2': // â
case '\u00E3': // ã
case '\u00E5': // å
output.append("a");
break;
case '\u00E4': // ä
case '\u00E6': // æ
output.append("ae");
break;
case '\u00E7': // ç
output.append("c");
break;
case '\u00E8': // è
case '\u00E9': // é
case '\u00EA': // ê
case '\u00EB': // ë
output.append("e");
break;
case '\u00EC': // ì
case '\u00ED': // Ã
case '\u00EE': // î
case '\u00EF': // ï
output.append("i");
break;
case '\u00F0': // ð
output.append("d");
break;
case '\u00F1': // ñ
output.append("n");
break;
case '\u00F2': // ò
case '\u00F3': // ó
case '\u00F4': // ô
case '\u00F5': // õ
case '\u00F8': // ø
output.append("o");
break;
case '\u00F6': // ö
case '\u0153': // Å“
output.append("oe");
break;
case '\u00DF': // ß
output.append("ss");
break;
case '\u00FE': // þ
output.append("th");
break;
case '\u00F9': // ù
case '\u00FA': // ú
case '\u00FB': // û
output.append("u");
break;
case '\u00FC': // ü
output.append("ue");
break;
case '\u00FD': // ý
case '\u00FF': // ÿ
output.append("y");
break;
default:
output.append(input.charAt(i));
break;
}
}
return output.toString();
}
// ad hoc stopword list for the cleanField method
public final static List<String> stopwords =
Arrays.asList("the", "of", "and", "du", "de le", "de la", "des", "der", "an", "und");
/**
* Remove useless punctuation at the end and beginning of a metadata field.
* <p/>
* Still experimental ! Use with care !
*/
public final static String cleanField(String input0, boolean applyStopwordsFilter) {
if (input0 == null) {
return null;
}
if (input0.length() == 0) {
return null;
}
String input = input0.replace(",,", ",");
input = input.replace(", ,", ",");
int n = input.length();
// characters at the end
for (int i = input.length() - 1; i > 0; i--) {
char c = input.charAt(i);
if ((c == ',') ||
(c == ' ') ||
(c == '.') ||
(c == '-') ||
(c == '_') ||
(c == '/') ||
//(c == ')') ||
//(c == '(') ||
(c == ':')) {
n = i;
} else if (c == ';') {
// we have to check if we have an html entity finishing
if (i - 3 >= 0) {
char c0 = input.charAt(i - 3);
if (c0 == '&') {
break;
}
}
if (i - 4 >= 0) {
char c0 = input.charAt(i - 4);
if (c0 == '&') {
break;
}
}
if (i - 5 >= 0) {
char c0 = input.charAt(i - 5);
if (c0 == '&') {
break;
}
}
if (i - 6 >= 0) {
char c0 = input.charAt(i - 6);
if (c0 == '&') {
break;
}
}
n = i;
} else break;
}
input = input.substring(0, n);
// characters at the begining
n = 0;
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if ((c == ',') ||
(c == ' ') ||
(c == '.') ||
(c == ';') ||
(c == '-') ||
(c == '_') ||
//(c == ')') ||
//(c == '(') ||
(c == ':')) {
n = i;
} else break;
}
input = input.substring(n, input.length()).trim();
if ((input.endsWith(")")) && (input.startsWith("("))) {
input = input.substring(1, input.length() - 1).trim();
}
if ((input.length() > 12) &&
(input.endsWith(""")) &&
(input.startsWith("""))) {
input = input.substring(6, input.length() - 6).trim();
}
if (applyStopwordsFilter) {
boolean stop = false;
while (!stop) {
stop = true;
for (String word : stopwords) {
if (input.endsWith(SPACE + word)) {
input = input.substring(0, input.length() - word.length()).trim();
stop = false;
break;
}
}
}
}
return input.trim();
}
/**
* Segment piece of text following a list of segmentation characters.
* "hello, world." -> [ "hello", ",", "world", "." ]
*
* @param input the string to be processed.
* @param input the characters creating a segment (typically space and punctuations).
* @return Returns the string without accent.
*/
public final static List<String> segment(String input, String segments) {
if (input == null)
return null;
ArrayList<String> result = new ArrayList<String>();
String token = null;
String seg = " \n\t";
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
int ind = seg.indexOf(c);
if (ind != -1) {
if (token != null) {
result.add(token);
token = null;
}
} else {
int ind2 = segments.indexOf(c);
if (ind2 == -1) {
if (token == null)
token = "" + c;
else
token += c;
} else {
if (token != null) {
result.add(token);
token = null;
}
result.add("" + segments.charAt(ind2));
}
}
}
if (token != null)
result.add(token);
return result;
}
/**
* Encode a string to be displayed in HTML
* <p/>
* If fullHTML encode, then all unicode characters above 7 bits are converted into
* HTML entitites
*/
public static String HTMLEncode(String string) {
return HTMLEncode(string, false);
}
public static String HTMLEncode(String string, boolean fullHTML) {
if (string == null)
return null;
if (string.length() == 0)
return string;
//string = string.replace("@BULLET", "•");
StringBuffer sb = new StringBuffer(string.length());
// true if last char was blank
boolean lastWasBlankChar = false;
int len = string.length();
char c;
for (int i = 0; i < len; i++) {
c = string.charAt(i);
if (c == ' ') {
// blank gets extra work,
// this solves the problem you get if you replace all
// blanks with , if you do that you loss
// word breaking
if (lastWasBlankChar) {
lastWasBlankChar = false;
//sb.append(" ");
} else {
lastWasBlankChar = true;
sb.append(' ');
}
} else {
lastWasBlankChar = false;
//
// HTML Special Chars
if (c == '"')
sb.append(""");
else if (c == '\'')
sb.append("'");
else if (c == '&') {
boolean skip = false;
// we don't want to recode an existing hmlt entity
if (string.length() > i + 3) {
char c2 = string.charAt(i + 1);
char c3 = string.charAt(i + 2);
char c4 = string.charAt(i + 3);
if (c2 == 'a') {
if (c3 == 'm') {
if (c4 == 'p') {
if (string.length() > i + 4) {
char c5 = string.charAt(i + 4);
if (c5 == ';') {
skip = true;
}
}
}
}
} else if (c2 == 'q') {
if (c3 == 'u') {
if (c4 == 'o') {
if (string.length() > i + 5) {
char c5 = string.charAt(i + 4);
char c6 = string.charAt(i + 5);
if (c5 == 't') {
if (c6 == ';') {
skip = true;
}
}
}
}
}
} else if (c2 == 'l' || c2 == 'g') {
if (c3 == 't') {
if (c4 == ';') {
skip = true;
}
}
}
}
if (!skip) {
sb.append("&");
} else {
sb.append("&");
}
} else if (c == '<')
sb.append("<");
else if (c == '>')
sb.append(">");
/*else if (c == '\n') {
// warning: this can be too much html!
sb.append("<br/>");
}*/
else {
int ci = 0xffff & c;
if (ci < 160) {
// nothing special only 7 Bit
sb.append(c);
} else {
if (fullHTML) {
// Not 7 Bit use the unicode system
sb.append("&#");
sb.append(Integer.valueOf(ci).toString());
sb.append(';');
} else
sb.append(c);
}
}
}
}
return sb.toString();
}
public static String normalizeRegex(String string) {
string = string.replace("&", "\\\\&");
string = string.replace("&", "\\\\&");
string = string.replace("+", "\\\\+");
return string;
}
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
static public String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
// e.printStackTrace();
throw new GrobidException("An exception occured while running Grobid.", e);
} finally {
try {
is.close();
} catch (IOException e) {
// e.printStackTrace();
throw new GrobidException("An exception occured while running Grobid.", e);
}
}
return sb.toString();
}
/**
* Count the number of digit in a given string.
*
* @param text the string to be processed.
* @return Returns the number of digit chracaters in the string...
*/
static public int countDigit(String text) {
int count = 0;
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (Character.isDigit(c))
count++;
}
return count;
}
/**
* Map special ligature and characters coming from the pdf
*/
static public String clean(String token) {
if (token == null)
return null;
if (token.length() == 0)
return token;
String res = "";
int i = 0;
while (i < token.length()) {
switch (token.charAt(i)) {
// ligature
case '\uFB00': {
res += "ff";
break;
}
case '\uFB01': {
res += "fi";
break;
}
case '\uFB02': {
res += "fl";
break;
}
case '\uFB03': {
res += "ffi";
break;
}
case '\uFB04': {
res += "ffl";
break;
}
case '\uFB06': {
res += "st";
break;
}
case '\uFB05': {
res += "ft";
break;
}
case '\u00E6': {
res += "ae";
break;
}
case '\u00C6': {
res += "AE";
break;
}
case '\u0153': {
res += "oe";
break;
}
case '\u0152': {
res += "OE";
break;
}
// quote
case '\u201C': {
res += "\"";
break;
}
case '\u201D': {
res += "\"";
break;
}
case '\u201E': {
res += "\"";
break;
}
case '\u201F': {
res += "\"";
break;
}
case '\u2019': {
res += "'";
break;
}
case '\u2018': {
res += "'";
break;
}
// bullet uniformity
case '\u2022': {
res += "•";
break;
}
case '\u2023': {
res += "•";
break;
}
case '\u2043': {
res += "•";
break;
}
case '\u204C': {
res += "•";
break;
}
case '\u204D': {
res += "•";
break;
}
case '\u2219': {
res += "•";
break;
}
case '\u25C9': {
res += "•";
break;
}
case '\u25D8': {
res += "•";
break;
}
case '\u25E6': {
res += "•";
break;
}
case '\u2619': {
res += "•";
break;
}
case '\u2765': {
res += "•";
break;
}
case '\u2767': {
res += "•";
break;
}
case '\u29BE': {
res += "•";
break;
}
case '\u29BF': {
res += "•";
break;
}
// asterix
case '\u2217': {
res += " * ";
break;
}
// typical author/affiliation markers
case '\u2020': {
res += SPACE + '\u2020';
break;
}
case '\u2021': {
res += SPACE + '\u2021';
break;
}
case '\u00A7': {
res += SPACE + '\u00A7';
break;
}
case '\u00B6': {
res += SPACE + '\u00B6';
break;
}
case '\u204B': {
res += SPACE + '\u204B';
break;
}
case '\u01C2': {
res += SPACE + '\u01C2';
break;
}
// default
default: {
res += token.charAt(i);
break;
}
}
i++;
}
return res;
}
public static String formatTwoDecimals(double d) {
NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
DecimalFormat df = (DecimalFormat) nf;
df.applyPattern("#.##");
return df.format(d);
}
public static String formatFourDecimals(double d) {
NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
DecimalFormat df = (DecimalFormat) nf;
df.applyPattern("#.####");
return df.format(d);
}
public static boolean isAllUpperCase(String text) {
for (int i = 0; i < text.length(); i++) {
if (!Character.isUpperCase(text.charAt(i))) {
return false;
}
}
return true;
}
public static boolean isAllLowerCase(String text) {
for (int i = 0; i < text.length(); i++) {
if (!Character.isLowerCase(text.charAt(i))) {
return false;
}
}
return true;
}
public static List<String> generateEmailVariants(String firstName, String lastName) {
// current heuristics:
// "First Last"
// "First L"
// "F Last"
// "First"
// "Last"
// "Last First"
// "Last F"
List<String> variants = new ArrayList<String>();
if (lastName != null) {
variants.add(lastName);
if (firstName != null) {
variants.add(firstName + SPACE + lastName);
variants.add(lastName + SPACE + firstName);
if (firstName.length() > 1) {
String firstInitial = firstName.substring(0, 1);
variants.add(firstInitial + SPACE + lastName);
variants.add(lastName + SPACE + firstInitial);
}
if (lastName.length() > 1) {
String lastInitial = lastName.substring(0, 1);
variants.add(firstName + SPACE + lastInitial);
}
}
} else {
if (firstName != null) {
variants.add(firstName);
}
}
return variants;
}
/**
* This is a re-implementation of the capitalizeFully of Apache commons lang, because it appears not working
* properly.
* <p/>
* Convert a string so that each word is made up of a titlecase character and then a series of lowercase
* characters. Words are defined as token delimited by one of the character in delimiters or the begining
* of the string.
*/
public static String capitalizeFully(String input, String delimiters) {
if (input == null) {
return null;
}
//input = input.toLowerCase();
String output = "";
boolean toUpper = true;
for (int c = 0; c < input.length(); c++) {
char ch = input.charAt(c);
if (delimiters.indexOf(ch) != -1) {
toUpper = true;
output += ch;
} else {
if (toUpper == true) {
output += Character.toUpperCase(ch);
toUpper = false;
} else {
output += Character.toLowerCase(ch);
}
}
}
return output;
}
public static String wordShape(String word) {
StringBuilder shape = new StringBuilder();
for (char c : word.toCharArray()) {
if (Character.isLetter(c)) {
if (Character.isUpperCase(c)) {
shape.append("X");
} else {
shape.append("x");
}
} else if (Character.isDigit(c)) {
shape.append("d");
} else {
shape.append(c);
}
}
StringBuilder finalShape = new StringBuilder().append(shape.charAt(0));
String suffix = "";
if (word.length() > 2) {
suffix = shape.substring(shape.length() - 2);
} else if (word.length() > 1) {
suffix = shape.substring(shape.length() - 1);
}
StringBuilder middle = new StringBuilder();
if (shape.length() > 3) {
char ch = shape.charAt(1);
for (int i = 1; i < shape.length() - 2; i++) {
middle.append(ch);
while (ch == shape.charAt(i) && i < shape.length() - 2) {
i++;
}
ch = shape.charAt(i);
}
if (ch != middle.charAt(middle.length() - 1)) {
middle.append(ch);
}
}
return finalShape.append(middle).append(suffix).toString();
}
public static String wordShapeTrimmed(String word) {
StringBuilder shape = new StringBuilder();
for (char c : word.toCharArray()) {
if (Character.isLetter(c)) {
if (Character.isUpperCase(c)) {
shape.append("X");
} else {
shape.append("x");
}
} else if (Character.isDigit(c)) {
shape.append("d");
} else {
shape.append(c);
}
}
StringBuilder middle = new StringBuilder();
char ch = shape.charAt(0);
for (int i = 0; i < shape.length(); i++) {
middle.append(ch);
while (ch == shape.charAt(i) && i < shape.length() - 1) {
i++;
}
ch = shape.charAt(i);
}
if (ch != middle.charAt(middle.length() - 1)) {
middle.append(ch);
}
return middle.toString();
}
/**
* Give the punctuation profile of a line, i.e. the concatenation of all the punctuations
* occuring in the line.
*
* @param line the string corresponding to a line
* @return the punctuation profile as a string, empty string is no punctuation
* @throws Exception
*/
public static String punctuationProfile(String line) {
String profile = "";
if ((line == null) || (line.length() == 0)) {
return profile;
}
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (c == ' ') {
continue;
}
if (fullPunctuations.indexOf(c) != -1)
profile += c;
}
return profile;
}
/**
* Return the number of token in a line given an existing global tokenization and a current
* start position of the line in this global tokenization.
*
* @param line the string corresponding to a line
* @param currentLinePos position of the line in the tokenization
* @param tokenization the global tokenization where the line appears
* @return the punctuation profile as a string, empty string is no punctuation
* @throws Exception
*/
public static int getNbTokens(String line, int currentLinePos, List<String> tokenization)
throws Exception {
if ((line == null) || (line.length() == 0))
return 0;
String currentToken = tokenization.get(currentLinePos);
while ((currentLinePos < tokenization.size()) &&
(currentToken.equals(" ") || currentToken.equals("\n"))) {
currentLinePos++;
currentToken = tokenization.get(currentLinePos);
}
if (!line.trim().startsWith(currentToken)) {
System.out.println("out of sync. : " + currentToken);
throw new IllegalArgumentException("line start does not match given tokenization start");
}
int nbTokens = 0;
int posMatch = 0; // current position in line
for (int p = currentLinePos; p < tokenization.size(); p++) {
currentToken = tokenization.get(p);
posMatch = line.indexOf(currentToken, posMatch);
if (posMatch == -1)
break;
nbTokens++;
}
return nbTokens;
}
/**
* Ensure that special XML characters are correctly encoded.
*/
public static String trimEncodedCharaters(String string) {
return string.replaceAll("&\\s+;", "&").
replaceAll(""\\s+;|&quot\\s*;", """).
replaceAll("<\\s+;|&lt\\s*;", "<").
replaceAll(">\\s+;|&gt\\s*;", ">").
replaceAll("&apos\\s+;|&apos\\s*;", "'");
}
public static boolean filterLine(String line) {
boolean filter = false;
if ((line == null) || (line.length() == 0))
filter = true;
else if (line.contains("@IMAGE") || line.contains("@PAGE")) {
filter = true;
} else if (line.contains(".pbm") || line.contains(".ppm") ||
line.contains(".svg") || line.contains(".jpg") ||
line.contains(".png")) {
filter = true;
}
return filter;
}
/**
* The equivalent of String.replaceAll() for StringBuilder
*/
public static StringBuilder replaceAll(StringBuilder sb, String regex, String replacement) {
Pattern pattern = Pattern.compile(regex);
Matcher m = pattern.matcher(sb);
int start = 0;
while (m.find(start)) {
sb.replace(m.start(), m.end(), replacement);
start = m.start() + replacement.length();
}
return sb;
}
/**
* Return the prefix of a string.
*/
public static String prefix(String s, int count) {
if (s == null) {
return null;
}
if (s.length() < count) {
return s;
}
return s.substring(0, count);
}
/**
* Return the suffix of a string.
*/
public static String suffix(String s, int count) {
if (s == null) {
return null;
}
if (s.length() < count) {
return s;
}
return s.substring(s.length() - count);
}
public static String JSONEncode(String json) {
// we assume all json string will be bounded by double quotes
return json.replaceAll("\"", "\\\"").replaceAll("\n", "\\\n");
}
public static String strrep(char c, int times) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < times; i++) {
builder.append(c);
}
return builder.toString();
}
public static int getOccCount(String term, String string) {
return StringUtils.countMatches(term, string);
}
/**
* Test for the current string contains at least one digit.
*
* @param tok the string to be processed.
* @return true if contains a digit
*/
public static boolean test_digit(String tok) {
if (tok == null)
return false;
if (tok.length() == 0)
return false;
char a;
for (int i = 0; i < tok.length(); i++) {
a = tok.charAt(i);
if (Character.isDigit(a))
return true;
}
return false;
}
/**
* Useful for recognising an acronym candidate: check if a text is only
* composed of upper case, dot and digit characters
*/
public static boolean isAllUpperCaseOrDigitOrDot(String text) {
for (int i = 0; i < text.length(); i++) {
final char charAt = text.charAt(i);
if (!Character.isUpperCase(charAt) && !Character.isDigit(charAt) && charAt != '.') {
return false;
}
}
return true;
}
}
| apache-2.0 |
xiaofei-dev/SuspendNotification | app/src/main/java/com/github/xiaofei_dev/suspensionnotification/util/bean/HomeData.java | 480 | package com.github.xiaofei_dev.suspensionnotification.util.bean;
public class HomeData {
private boolean isClickHome;
private boolean isClickMenu;
public boolean isClickHome() {
return isClickHome;
}
public void setClickHome(boolean clickHome) {
isClickHome = clickHome;
}
public boolean isClickMenu() {
return isClickMenu;
}
public void setClickMenu(boolean clickMenu) {
isClickMenu = clickMenu;
}
}
| apache-2.0 |
whitesource/fs-agent | test_input/ksa/ksa-web-root/ksa-system-web/src/main/java/com/ksa/system/initialize/convert/UserConverter.java | 3005 | package com.ksa.system.initialize.convert;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import com.ksa.context.ServiceContextUtils;
import com.ksa.dao.security.RoleDao;
import com.ksa.model.ModelUtils;
import com.ksa.model.security.Role;
import com.ksa.model.security.User;
import com.ksa.service.security.SecurityService;
import com.ksa.system.initialize.model.YongHu;
import com.ksa.util.StringUtils;
public class UserConverter {
// 供别的转换器使用的 合作伙伴缓存
private static Map<String, User> userMap = new HashMap<String, User>();
public static Map<String, User> getUserMap() {
return userMap;
}
public static void doConvert( SqlSession session ) {
List<YongHu> list = getAllYongHu( session );
Map<String, Role> map = getRoleMap();
SecurityService service = ServiceContextUtils.getService( SecurityService.class );
// 保存用户
for( YongHu yh : list ) {
User user = new User();
user.setId( yh.getId() );
user.setEmail( yh.getEmail() );
user.setName( yh.getUsername() );
user.setPassword( yh.getPassword() );
user.setTelephone( yh.getTelephone() );
if( map.containsKey( yh.getRole() ) ) {
service.createUser( user, new String[]{ map.get( yh.getRole() ).getId() } );
} else {
service.createUser( user );
}
userMap.put( user.getName(), user );
}
}
/**
* 插入已被删除但是业务中使用的用户
*/
private static User createdDeletedUser( String userName ) {
SecurityService service = ServiceContextUtils.getService( SecurityService.class );
User user = new User();
user.setId( ModelUtils.generateRandomId() );
user.setName( userName );
user.setEmail( "" );
user.setLocked( true );
user.setTelephone( "" );
user.setPassword( "123456" );
user = service.createUser( user );
userMap.put( userName, user );
return user;
}
public static User getUser( String name ) {
if( ! StringUtils.hasText( name ) ) {
return null;
}
User user = userMap.get( name );
if( user != null ) {
return user;
} else {
user = createdDeletedUser( name );
return user;
}
}
private static Map<String, Role> getRoleMap() {
List<Role> roles = ServiceContextUtils.getService( RoleDao.class ).selectAllRole();
Map<String, Role> map = new HashMap<String, Role>();
for(Role role : roles) {
map.put( role.getName(), role );
}
return map;
}
private static List<YongHu> getAllYongHu( SqlSession session ) {
return session.selectList( "select-init-yonghu" );
}
}
| apache-2.0 |
wso2/wso2-httpcore-nio | modules/httpcore-nio/src/test/java/org/apache/http/impl/nio/TestDefaultNHttpClientConnection.java | 30286 | /*
* ====================================================================
* 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.nio.channels.SelectionKey;
import java.util.LinkedList;
import org.apache.http.ByteChannelMock;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.ReadableByteChannelMock;
import org.apache.http.WritableByteChannelMock;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.nio.codecs.LengthDelimitedDecoder;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.NHttpClientConnection;
import org.apache.http.nio.NHttpClientEventHandler;
import org.apache.http.nio.NHttpConnection;
import org.apache.http.nio.entity.HttpAsyncContentProducer;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.util.SimpleInputBuffer;
import org.apache.http.protocol.HTTP;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
public class TestDefaultNHttpClientConnection {
@Mock
private IOSession session;
@Mock
private ByteChannel byteChan;
@Mock
private NHttpClientEventHandler handler;
private DefaultNHttpClientConnection conn;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
conn = new DefaultNHttpClientConnection(session, 32);
}
@Test
public void testSubmitRequest() throws Exception {
final BasicHttpRequest request = new BasicHttpRequest("GET", "/");
conn.submitRequest(request);
Assert.assertNull(conn.getHttpRequest());
Assert.assertTrue(conn.hasBufferedOutput());
Mockito.verify(session).setEvent(SelectionKey.OP_WRITE);
}
@Test
public void testSubmitEntityEnclosingRequest() throws Exception {
final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/");
request.setEntity(new StringEntity("stuff"));
Mockito.when(session.channel()).thenReturn(byteChan);
Assert.assertEquals(0, conn.getMetrics().getRequestCount());
conn.submitRequest(request);
Assert.assertSame(request, conn.getHttpRequest());
Assert.assertTrue(conn.hasBufferedOutput());
Assert.assertTrue(conn.isRequestSubmitted());
Assert.assertNotNull(conn.contentEncoder);
Assert.assertEquals(1, conn.getMetrics().getRequestCount());
Mockito.verify(session).setEvent(SelectionKey.OP_WRITE);
}
@Test
public void testOutputReset() throws Exception {
final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/");
request.setEntity(new StringEntity("stuff"));
Mockito.when(session.channel()).thenReturn(byteChan);
conn.submitRequest(request);
Assert.assertNotNull(conn.getHttpRequest());
Assert.assertNotNull(conn.contentEncoder);
conn.resetOutput();
Assert.assertNull(conn.getHttpRequest());
Assert.assertNull(conn.contentEncoder);
}
static class RequestReadyAnswer implements Answer<Void> {
private final HttpRequest request;
RequestReadyAnswer(final HttpRequest request) {
super();
this.request = request;
}
public Void answer(final InvocationOnMock invocation) throws Throwable {
final Object[] args = invocation.getArguments();
final NHttpClientConnection conn = (NHttpClientConnection) args[0];
conn.submitRequest(request);
return null;
}
}
static class ProduceContentAnswer implements Answer<Void> {
private final HttpAsyncContentProducer contentProducer;
ProduceContentAnswer(final HttpAsyncContentProducer contentProducer) {
super();
this.contentProducer = contentProducer;
}
public Void answer(final InvocationOnMock invocation) throws Throwable {
final Object[] args = invocation.getArguments();
final IOControl ioctrl = (IOControl) args[0];
final ContentEncoder encoder = (ContentEncoder) args[1];
contentProducer.produceContent(encoder, ioctrl);
return null;
}
}
@Test
public void testProduceOutputShortMessageAfterSubmit() throws Exception {
final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/");
final NStringEntity entity = new NStringEntity("stuff");
request.setEntity(entity);
final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64));
final ByteChannelMock channel = new ByteChannelMock(null, wchannel);
Mockito.when(session.channel()).thenReturn(channel);
conn.submitRequest(request);
Assert.assertEquals(19, conn.outbuf.length());
Mockito.doAnswer(new ProduceContentAnswer(entity)).when(
handler).outputReady(Mockito.<NHttpClientConnection>any(), Mockito.<ContentEncoder>any());
conn.produceOutput(handler);
Assert.assertNull(conn.getHttpRequest());
Assert.assertNull(conn.contentEncoder);
Assert.assertEquals("POST / HTTP/1.1\r\n\r\nstuff", wchannel.dump(Consts.ASCII));
Mockito.verify(session, Mockito.times(1)).clearEvent(SelectionKey.OP_WRITE);
Mockito.verify(wchannel, Mockito.times(1)).write(Matchers.<ByteBuffer>any());
}
@Test
public void testProduceOutputLongMessageAfterSubmit() throws Exception {
final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/");
final NStringEntity entity = new NStringEntity("a lot of various stuff");
request.setEntity(entity);
final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64));
final ByteChannelMock channel = new ByteChannelMock(null, wchannel);
Mockito.when(session.channel()).thenReturn(channel);
conn.submitRequest(request);
Assert.assertEquals(19, conn.outbuf.length());
Mockito.doAnswer(new ProduceContentAnswer(entity)).when(
handler).outputReady(Mockito.<NHttpClientConnection>any(), Mockito.<ContentEncoder>any());
conn.produceOutput(handler);
Assert.assertNull(conn.getHttpRequest());
Assert.assertNull(conn.contentEncoder);
Assert.assertEquals("POST / HTTP/1.1\r\n\r\na lot of various stuff", wchannel.dump(Consts.ASCII));
Mockito.verify(session, Mockito.times(1)).clearEvent(SelectionKey.OP_WRITE);
Mockito.verify(wchannel, Mockito.times(2)).write(Matchers.<ByteBuffer>any());
}
@Test
public void testProduceOutputShortMessage() throws Exception {
final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/");
final NStringEntity entity = new NStringEntity("stuff");
request.setEntity(entity);
final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64));
final ByteChannelMock channel = new ByteChannelMock(null, wchannel);
Mockito.when(session.channel()).thenReturn(channel);
Mockito.doAnswer(new RequestReadyAnswer(request)).when(
handler).requestReady(Mockito.<NHttpClientConnection>any());
Mockito.doAnswer(new ProduceContentAnswer(entity)).when(
handler).outputReady(Mockito.<NHttpClientConnection>any(), Mockito.<ContentEncoder>any());
conn.produceOutput(handler);
Assert.assertNull(conn.getHttpRequest());
Assert.assertNull(conn.contentEncoder);
Assert.assertEquals("POST / HTTP/1.1\r\n\r\nstuff", wchannel.dump(Consts.ASCII));
Mockito.verify(session, Mockito.times(1)).clearEvent(SelectionKey.OP_WRITE);
Mockito.verify(wchannel, Mockito.times(1)).write(Matchers.<ByteBuffer>any());
}
@Test
public void testProduceOutputLongMessage() throws Exception {
final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/");
final NStringEntity entity = new NStringEntity("a lot of various stuff");
request.setEntity(entity);
final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64));
final ByteChannelMock channel = new ByteChannelMock(null, wchannel);
Mockito.when(session.channel()).thenReturn(channel);
Mockito.doAnswer(new RequestReadyAnswer(request)).when(
handler).requestReady(Mockito.<NHttpClientConnection>any());
Mockito.doAnswer(new ProduceContentAnswer(entity)).when(
handler).outputReady(Mockito.<NHttpClientConnection>any(), Mockito.<ContentEncoder>any());
conn.produceOutput(handler);
Assert.assertNull(conn.getHttpRequest());
Assert.assertNull(conn.contentEncoder);
Assert.assertEquals("POST / HTTP/1.1\r\n\r\na lot of various stuff", wchannel.dump(Consts.ASCII));
Mockito.verify(session, Mockito.times(1)).clearEvent(SelectionKey.OP_WRITE);
Mockito.verify(wchannel, Mockito.times(2)).write(Matchers.<ByteBuffer>any());
}
@Test
public void testProduceOutputLongMessageSaturatedChannel() throws Exception {
final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/");
final NStringEntity entity = new NStringEntity("a lot of various stuff");
request.setEntity(entity);
final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64, 24));
final ByteChannelMock channel = new ByteChannelMock(null, wchannel);
Mockito.when(session.channel()).thenReturn(channel);
Mockito.doAnswer(new RequestReadyAnswer(request)).when(
handler).requestReady(Mockito.<NHttpClientConnection>any());
Mockito.doAnswer(new ProduceContentAnswer(entity)).when(
handler).outputReady(Mockito.<NHttpClientConnection>any(), Mockito.<ContentEncoder>any());
conn.produceOutput(handler);
Assert.assertNull(conn.getHttpRequest());
Assert.assertNull(conn.contentEncoder);
Assert.assertEquals("POST / HTTP/1.1\r\n\r\na lot", wchannel.dump(Consts.ASCII));
Assert.assertEquals(17, conn.outbuf.length());
Mockito.verify(session, Mockito.never()).clearEvent(SelectionKey.OP_WRITE);
Mockito.verify(wchannel, Mockito.times(2)).write(Matchers.<ByteBuffer>any());
}
@Test
public void testProduceOutputLongMessageSaturatedChannel2() throws Exception {
conn = new DefaultNHttpClientConnection(session, 24);
final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/");
final NStringEntity entity = new NStringEntity("a loooooooooooooooooooooooot of various stuff");
request.setEntity(entity);
final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64, 24));
final ByteChannelMock channel = new ByteChannelMock(null, wchannel);
Mockito.when(session.channel()).thenReturn(channel);
Mockito.doAnswer(new RequestReadyAnswer(request)).when(
handler).requestReady(Mockito.<NHttpClientConnection>any());
Mockito.doAnswer(new ProduceContentAnswer(entity)).when(
handler).outputReady(Mockito.<NHttpClientConnection>any(), Mockito.<ContentEncoder>any());
conn.produceOutput(handler);
Assert.assertNotNull(conn.getHttpRequest());
Assert.assertNotNull(conn.contentEncoder);
Assert.assertEquals("POST / HTTP/1.1\r\n\r\na loo", wchannel.dump(Consts.ASCII));
Mockito.verify(session, Mockito.never()).clearEvent(SelectionKey.OP_WRITE);
Mockito.verify(wchannel, Mockito.times(3)).write(Matchers.<ByteBuffer>any());
}
// @Test
public void testProduceOutputLongChunkedMessage() throws Exception {
conn = new DefaultNHttpClientConnection(session, 64);
final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/");
request.addHeader(HTTP.TRANSFER_ENCODING, HTTP.CHUNK_CODING);
final NStringEntity entity = new NStringEntity("a lot of various stuff");
entity.setChunked(true);
request.setEntity(entity);
final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64));
final ByteChannelMock channel = new ByteChannelMock(null, wchannel);
Mockito.when(session.channel()).thenReturn(channel);
Mockito.doAnswer(new RequestReadyAnswer(request)).when(
handler).requestReady(Mockito.<NHttpClientConnection>any());
Mockito.doAnswer(new ProduceContentAnswer(entity)).when(
handler).outputReady(Mockito.<NHttpClientConnection>any(), Mockito.<ContentEncoder>any());
conn.produceOutput(handler);
Assert.assertNull(conn.getHttpRequest());
Assert.assertNull(conn.contentEncoder);
Assert.assertEquals("POST / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n" +
"5\r\na lot\r\n11\r\n of various stuff\r\n0\r\n\r\n", wchannel.dump(Consts.ASCII));
Mockito.verify(session, Mockito.times(1)).clearEvent(SelectionKey.OP_WRITE);
Mockito.verify(wchannel, Mockito.times(2)).write(Matchers.<ByteBuffer>any());
}
// @Test
public void testProduceOutputLongChunkedMessageSaturatedChannel() throws Exception {
conn = new DefaultNHttpClientConnection(session, 64);
final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/");
request.addHeader(HTTP.TRANSFER_ENCODING, HTTP.CHUNK_CODING);
final NStringEntity entity = new NStringEntity("a lot of various stuff");
entity.setChunked(true);
request.setEntity(entity);
final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64, 64));
final ByteChannelMock channel = new ByteChannelMock(null, wchannel);
Mockito.when(session.channel()).thenReturn(channel);
Mockito.doAnswer(new RequestReadyAnswer(request)).when(
handler).requestReady(Mockito.<NHttpClientConnection>any());
Mockito.doAnswer(new ProduceContentAnswer(entity)).when(
handler).outputReady(Mockito.<NHttpClientConnection>any(), Mockito.<ContentEncoder>any());
conn.produceOutput(handler);
Assert.assertNull(conn.getHttpRequest());
Assert.assertNull(conn.contentEncoder);
Assert.assertEquals("POST / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n" +
"5\r\na lot\r\n11\r\n of", wchannel.dump(Consts.ASCII));
Assert.assertEquals(21, conn.outbuf.length());
Mockito.verify(session, Mockito.never()).clearEvent(SelectionKey.OP_WRITE);
Mockito.verify(wchannel, Mockito.times(2)).write(Matchers.<ByteBuffer>any());
}
@Test
public void testProduceOutputClosingConnection() throws Exception {
final BasicHttpRequest request = new BasicHttpRequest("GET", "/");
final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64));
final ByteChannelMock channel = new ByteChannelMock(null, wchannel);
Mockito.when(session.channel()).thenReturn(channel);
conn.submitRequest(request);
conn.close();
Assert.assertEquals(NHttpConnection.CLOSING, conn.getStatus());
conn.produceOutput(handler);
Assert.assertEquals(NHttpConnection.CLOSED, conn.getStatus());
Mockito.verify(wchannel, Mockito.times(1)).write(Matchers.<ByteBuffer>any());
Mockito.verify(session, Mockito.times(1)).close();
Mockito.verify(session, Mockito.never()).clearEvent(SelectionKey.OP_WRITE);
Mockito.verify(handler, Mockito.never()).requestReady(
Mockito.<NHttpClientConnection>any());
Mockito.verify(handler, Mockito.never()).outputReady(
Mockito.<NHttpClientConnection>any(), Mockito.<ContentEncoder>any());
}
static class ResponseCapturingAnswer implements Answer<Void> {
private final LinkedList<HttpResponse> responses;
ResponseCapturingAnswer(final LinkedList<HttpResponse> responses) {
super();
this.responses = responses;
}
public Void answer(final InvocationOnMock invocation) throws Throwable {
final Object[] args = invocation.getArguments();
final NHttpClientConnection conn = (NHttpClientConnection) args[0];
if (conn != null) {
final HttpResponse response = conn.getHttpResponse();
if (response != null) {
responses.add(response);
}
}
return null;
}
}
static class ConsumeContentAnswer implements Answer<Void> {
private final SimpleInputBuffer buf;
ConsumeContentAnswer(final SimpleInputBuffer buf) {
super();
this.buf = buf;
}
public Void answer(final InvocationOnMock invocation) throws Throwable {
final Object[] args = invocation.getArguments();
final ContentDecoder decoder = (ContentDecoder) args[1];
buf.consumeContent(decoder);
return null;
}
}
@Test
public void testConsumeInputShortMessage() throws Exception {
final ReadableByteChannelMock rchannel = Mockito.spy(new ReadableByteChannelMock(
new String[] {"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nstuff"}, Consts.ASCII));
final ByteChannelMock channel = new ByteChannelMock(rchannel, null);
Mockito.when(session.channel()).thenReturn(channel);
Mockito.when(session.getEventMask()).thenReturn(SelectionKey.OP_READ);
final LinkedList<HttpResponse> responses = new LinkedList<HttpResponse>();
Mockito.doAnswer(new ResponseCapturingAnswer(responses)).when(
handler).responseReceived(Mockito.<NHttpClientConnection>any());
Mockito.doAnswer(new ConsumeContentAnswer(new SimpleInputBuffer(64))).when(
handler).inputReady(Mockito.<NHttpClientConnection>any(), Mockito.<ContentDecoder>any());
Assert.assertEquals(0, conn.getMetrics().getResponseCount());
conn.consumeInput(handler);
Assert.assertNull(conn.getHttpResponse());
Assert.assertNull(conn.contentDecoder);
Assert.assertEquals(1, conn.getMetrics().getResponseCount());
Assert.assertEquals(43, conn.getMetrics().getReceivedBytesCount());
Mockito.verify(handler, Mockito.times(1)).responseReceived(
Mockito.<NHttpClientConnection>any());
Mockito.verify(handler, Mockito.times(1)).inputReady(
Mockito.<NHttpClientConnection>any(), Mockito.<LengthDelimitedDecoder>any());
Mockito.verify(rchannel, Mockito.times(2)).read(Mockito.<ByteBuffer>any());
Mockito.verify(handler, Mockito.never()).exception(
Mockito.<NHttpClientConnection>any(), Mockito.<Exception>any());
Assert.assertFalse(responses.isEmpty());
final HttpResponse response = responses.getFirst();
Assert.assertNotNull(response);
Assert.assertEquals(HttpVersion.HTTP_1_1, response.getStatusLine().getProtocolVersion());
Assert.assertEquals(200, response.getStatusLine().getStatusCode());
Assert.assertEquals("OK", response.getStatusLine().getReasonPhrase());
final HttpEntity entity = response.getEntity();
Assert.assertNotNull(entity);
Assert.assertEquals(5, entity.getContentLength());
}
@Test
public void testConsumeInputLongMessage() throws Exception {
conn = new DefaultNHttpClientConnection(session, 1024);
final ReadableByteChannelMock rchannel = Mockito.spy(new ReadableByteChannelMock(
new String[] {"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\na lot of stuff",
"", ""}, Consts.ASCII));
final ByteChannelMock channel = new ByteChannelMock(rchannel, null);
Mockito.when(session.channel()).thenReturn(channel);
Mockito.when(session.getEventMask()).thenReturn(SelectionKey.OP_READ);
final LinkedList<HttpResponse> responses = new LinkedList<HttpResponse>();
Mockito.doAnswer(new ResponseCapturingAnswer(responses)).when(
handler).responseReceived(Mockito.<NHttpClientConnection>any());
Mockito.doAnswer(new ConsumeContentAnswer(new SimpleInputBuffer(64))).when(
handler).inputReady(Mockito.<NHttpClientConnection>any(), Mockito.<ContentDecoder>any());
Assert.assertEquals(0, conn.getMetrics().getResponseCount());
conn.consumeInput(handler);
Assert.assertNotNull(conn.getHttpResponse());
Assert.assertNotNull(conn.contentDecoder);
Assert.assertEquals(1, conn.getMetrics().getResponseCount());
Assert.assertEquals(54, conn.getMetrics().getReceivedBytesCount());
Mockito.verify(handler, Mockito.times(1)).responseReceived(
Mockito.<NHttpClientConnection>any());
Mockito.verify(handler, Mockito.times(1)).inputReady(
Mockito.<NHttpClientConnection>any(), Mockito.<LengthDelimitedDecoder>any());
Mockito.verify(rchannel, Mockito.times(2)).read(Mockito.<ByteBuffer>any());
Mockito.verify(handler, Mockito.never()).exception(
Mockito.<NHttpClientConnection>any(), Mockito.<Exception>any());
Assert.assertFalse(responses.isEmpty());
final HttpResponse response = responses.getFirst();
Assert.assertNotNull(response);
Assert.assertEquals(HttpVersion.HTTP_1_1, response.getStatusLine().getProtocolVersion());
Assert.assertEquals(200, response.getStatusLine().getStatusCode());
Assert.assertEquals("OK", response.getStatusLine().getReasonPhrase());
final HttpEntity entity = response.getEntity();
Assert.assertNotNull(entity);
Assert.assertEquals(100, entity.getContentLength());
conn.consumeInput(handler);
Assert.assertEquals(1, conn.getMetrics().getResponseCount());
Assert.assertEquals(54, conn.getMetrics().getReceivedBytesCount());
Mockito.verify(rchannel, Mockito.times(3)).read(Mockito.<ByteBuffer>any());
Mockito.verify(handler, Mockito.never()).exception(
Mockito.<NHttpClientConnection>any(), Mockito.<Exception>any());
}
@Test
public void testConsumeInputBasicMessageNoEntity() throws Exception {
final ReadableByteChannelMock rchannel = Mockito.spy(new ReadableByteChannelMock(
new String[] {"HTTP/1.1 100 Continue\r\n\r\n"}, Consts.ASCII));
final ByteChannelMock channel = new ByteChannelMock(rchannel, null);
Mockito.when(session.channel()).thenReturn(channel);
Mockito.when(session.getEventMask()).thenReturn(SelectionKey.OP_READ);
final LinkedList<HttpResponse> responses = new LinkedList<HttpResponse>();
Mockito.doAnswer(new ResponseCapturingAnswer(responses)).when(
handler).responseReceived(Mockito.<NHttpClientConnection>any());
Mockito.doAnswer(new ConsumeContentAnswer(new SimpleInputBuffer(64))).when(
handler).inputReady(Mockito.<NHttpClientConnection>any(), Mockito.<ContentDecoder>any());
conn.consumeInput(handler);
Assert.assertNull(conn.getHttpResponse());
Assert.assertNull(conn.contentDecoder);
Mockito.verify(handler, Mockito.times(1)).responseReceived(
Mockito.<NHttpClientConnection>any());
Mockito.verify(handler, Mockito.never()).inputReady(
Mockito.<NHttpClientConnection>any(), Mockito.<LengthDelimitedDecoder>any());
Mockito.verify(rchannel, Mockito.times(1)).read(Mockito.<ByteBuffer>any());
Mockito.verify(handler, Mockito.never()).exception(
Mockito.<NHttpClientConnection>any(), Mockito.<Exception>any());
Assert.assertFalse(responses.isEmpty());
final HttpResponse response = responses.getFirst();
Assert.assertNotNull(response);
Assert.assertEquals(HttpVersion.HTTP_1_1, response.getStatusLine().getProtocolVersion());
Assert.assertEquals(100, response.getStatusLine().getStatusCode());
final HttpEntity entity = response.getEntity();
Assert.assertNull(entity);
}
@Test
public void testConsumeInputNoData() throws Exception {
conn = new DefaultNHttpClientConnection(session, 1024);
final ReadableByteChannelMock rchannel = Mockito.spy(new ReadableByteChannelMock(
new String[] {"", ""}, Consts.ASCII));
final ByteChannelMock channel = new ByteChannelMock(rchannel, null);
Mockito.when(session.channel()).thenReturn(channel);
Mockito.when(session.getEventMask()).thenReturn(SelectionKey.OP_READ);
final LinkedList<HttpResponse> responses = new LinkedList<HttpResponse>();
Mockito.doAnswer(new ResponseCapturingAnswer(responses)).when(
handler).responseReceived(Mockito.<NHttpClientConnection>any());
Mockito.doAnswer(new ConsumeContentAnswer(new SimpleInputBuffer(64))).when(
handler).inputReady(Mockito.<NHttpClientConnection>any(), Mockito.<ContentDecoder>any());
Assert.assertEquals(0, conn.getMetrics().getResponseCount());
conn.consumeInput(handler);
Assert.assertNull(conn.getHttpResponse());
Assert.assertNull(conn.contentDecoder);
Assert.assertEquals(0, conn.getMetrics().getResponseCount());
Assert.assertEquals(0, conn.getMetrics().getReceivedBytesCount());
Mockito.verify(handler, Mockito.never()).responseReceived(
Mockito.<NHttpClientConnection>any());
Mockito.verify(handler, Mockito.never()).inputReady(
Mockito.<NHttpClientConnection>any(), Mockito.<LengthDelimitedDecoder>any());
Mockito.verify(rchannel, Mockito.times(1)).read(Mockito.<ByteBuffer>any());
Mockito.verify(handler, Mockito.never()).exception(
Mockito.<NHttpClientConnection>any(), Mockito.<Exception>any());
conn.consumeInput(handler);
Assert.assertNull(conn.getHttpResponse());
Assert.assertNull(conn.contentDecoder);
Assert.assertEquals(0, conn.getMetrics().getResponseCount());
Assert.assertEquals(0, conn.getMetrics().getReceivedBytesCount());
Mockito.verify(handler, Mockito.never()).responseReceived(
Mockito.<NHttpClientConnection>any());
Mockito.verify(handler, Mockito.never()).inputReady(
Mockito.<NHttpClientConnection>any(), Mockito.<LengthDelimitedDecoder>any());
Mockito.verify(rchannel, Mockito.times(2)).read(Mockito.<ByteBuffer>any());
Mockito.verify(handler, Mockito.never()).exception(
Mockito.<NHttpClientConnection>any(), Mockito.<Exception>any());
conn.consumeInput(handler);
Assert.assertNull(conn.getHttpResponse());
Assert.assertNull(conn.contentDecoder);
Assert.assertEquals(0, conn.getMetrics().getResponseCount());
Assert.assertEquals(0, conn.getMetrics().getReceivedBytesCount());
Mockito.verify(handler, Mockito.never()).responseReceived(
Mockito.<NHttpClientConnection>any());
Mockito.verify(handler, Mockito.never()).inputReady(
Mockito.<NHttpClientConnection>any(), Mockito.<LengthDelimitedDecoder>any());
Mockito.verify(rchannel, Mockito.times(3)).read(Mockito.<ByteBuffer>any());
Mockito.verify(handler, Mockito.times(1)).endOfInput(
Mockito.<NHttpClientConnection>any());
Mockito.verify(handler, Mockito.never()).exception(
Mockito.<NHttpClientConnection>any(), Mockito.<Exception>any());
}
@Test
public void testConsumeInputConnectionClosed() throws Exception {
conn = new DefaultNHttpClientConnection(session, 1024);
final ReadableByteChannelMock rchannel = Mockito.spy(new ReadableByteChannelMock(
new String[] {"", ""}, Consts.ASCII));
final ByteChannelMock channel = new ByteChannelMock(rchannel, null);
Mockito.when(session.channel()).thenReturn(channel);
Mockito.when(session.getEventMask()).thenReturn(SelectionKey.OP_READ);
conn.close();
conn.consumeInput(handler);
Mockito.verify(rchannel, Mockito.never()).read(Mockito.<ByteBuffer>any());
Mockito.verify(session, Mockito.times(1)).clearEvent(SelectionKey.OP_READ);
}
}
| apache-2.0 |
sinoz/nds-api | src/main/java/nds_api/fs/btx0/BasicTextureReader.java | 828 | package nds_api.fs.btx0;
import nds_api.RomMapping;
import java.io.IOException;
/**
*
* Reads data to translate to a {@link BasicTexture}.
*
* @author Whis
*
*/
public final class BasicTextureReader {
/**
* The expected BTX0 file extension.
*/
private static final String BTX0_EXT = "BTX0";
/**
* The {@link RomMapping} to read from.
*/
private final RomMapping mapping;
/**
* Creates a new {@link BasicTextureReader}.
*/
public BasicTextureReader(RomMapping mapping) {
this.mapping = mapping;
}
public BasicTexture read() throws IOException {
String stamp = mapping.readString(BTX0_EXT.length());
if (!stamp.equals(BTX0_EXT)) {
throw new IOException();
}
return new BasicTexture(null, null);
}
}
| apache-2.0 |
BioStar2/BioStar2Android | BioStar2Android/BioStar2Client/src/main/java/com/supremainc/biostar2/adapter/base/BasePermissionAdapter.java | 6611 | /*
* Copyright 2015 Suprema(biostar2@suprema.co.kr)
*
* 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.supremainc.biostar2.adapter.base;
import android.app.Activity;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayoutDirection;
import com.supremainc.biostar2.R;
import com.supremainc.biostar2.meta.Setting;
import com.supremainc.biostar2.sdk.models.v1.permission.CloudRole;
import com.supremainc.biostar2.sdk.models.v1.permission.CloudRoles;
import com.supremainc.biostar2.sdk.provider.PermissionDataProvider;
import com.supremainc.biostar2.widget.popup.Popup;
import com.supremainc.biostar2.widget.popup.Popup.OnPopupClickListener;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public abstract class BasePermissionAdapter extends BaseListAdapter<CloudRole> {
protected static final int FIRST_LIMIT = 50;
protected boolean mIsLastItemVisible = false;
protected int mLimit = FIRST_LIMIT;
protected int mOffset = 0;
protected PermissionDataProvider mPermissionDataProvider;
private Callback<CloudRoles> mItemListener = new Callback<CloudRoles>() {
@Override
public void onFailure(Call<CloudRoles> call, Throwable t) {
if (isIgnoreCallback(call, true)) {
return;
}
showRetryPopup(t.getMessage(), new OnPopupClickListener() {
@Override
public void OnNegative() {
}
@Override
public void OnPositive() {
showWait(null);
mHandler.removeCallbacks(mRunGetItems);
mHandler.post(mRunGetItems);
}
});
}
@Override
public void onResponse(Call<CloudRoles> call, Response<CloudRoles> response) {
if (isIgnoreCallback(call, response, true)) {
return;
}
if (isInvalidResponse(response, false, false)) {
mItemListener.onFailure(call, new Throwable(getResponseErrorMessage(response)));
return;
}
CloudRoles cloudRoles = response.body();
if (cloudRoles.records == null || cloudRoles.records.size() < 1) {
if (mItems == null || mItems.size() < 1) {
mTotal = 0;
mOnItemsListener.onNoneData();
} else {
mTotal = mItems.size();
mOnItemsListener.onSuccessNull(mItems.size());
}
return;
}
if (mItems == null) {
mItems = new ArrayList<CloudRole>();
CloudRole none = new CloudRole();
none.code = Setting.NONE_ITEM;
none.description = mActivity.getString(R.string.none);
mItems.add(none);
} else {
mItems.clear();
CloudRole none = new CloudRole();
none.code = Setting.NONE_ITEM;
none.description = mActivity.getString(R.string.none);
mItems.add(none);
}
if (mOnItemsListener != null) {
mOnItemsListener.onTotalReceive(cloudRoles.total);
}
for (CloudRole ListCard : cloudRoles.records) {
mItems.add(ListCard);
}
setData(mItems);
mOffset = mItems.size();
mTotal = cloudRoles.total;
}
};
private Runnable mRunGetItems = new Runnable() {
@Override
public void run() {
if (isInValidCheck()) {
return;
}
if (isMemoryPoor()) {
dismissWait();
mToastPopup.show(mActivity.getString(R.string.memory_poor), null);
return;
}
request(mPermissionDataProvider.getCloudRoles(mItemListener));
}
};
public BasePermissionAdapter(Activity context, ArrayList<CloudRole> items, ListView listView, OnItemClickListener itemClickListener, Popup popup, OnItemsListener onItemsListener) {
super(context, items, listView, itemClickListener, popup, onItemsListener);
mPermissionDataProvider = PermissionDataProvider.getInstance(context);
setOnScrollListener(new OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && mIsLastItemVisible && mTotal - 1 > mOffset) {
if (mPopup != null) {
mPopup.showWait(true);
}
mHandler.removeCallbacks(mRunGetItems);
mHandler.postDelayed(mRunGetItems, 100);
} else {
if (mPopup != null) {
mPopup.dismissWiat();
}
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
mIsLastItemVisible = (totalItemCount > 0) && (firstVisibleItem + visibleItemCount >= totalItemCount);
}
});
}
@Override
public void getItems(String query) {
mQuery = query;
mOffset = 0;
mTotal = 0;
mLimit = FIRST_LIMIT;
mHandler.removeCallbacks(mRunGetItems);
clearRequest();
showWait(SwipyRefreshLayoutDirection.TOP);
if (mItems != null) {
mItems.clear();
notifyDataSetChanged();
}
mHandler.postDelayed(mRunGetItems, 500);
}
}
| apache-2.0 |
jiangerji/iam007-mobile-android | src/cn/iam007/app/mall/TestMainActivity.java | 10705 | package cn.iam007.app.mall;
import java.util.ArrayList;
import android.annotation.TargetApi;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.widget.TextView;
import cn.iam007.app.common.utils.logging.LogUtil;
import cn.iam007.app.mall.base.BaseActivity;
import cn.iam007.app.mall.home.MyFragmentPagerAdapter;
import com.baidu.mobstat.StatService;
public class TestMainActivity extends BaseActivity {
private MyFragmentPagerAdapter mMyFragmentPagerAdapter;
private ViewPager mPager;
@Override
protected int getFlag() {
return FLAG_SEARCH_VIEW | FLAG_DISABLE_HOME_AS_UP;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private View mRecommentBtn = null;
private View mLiveBtn = null;
private View mGameBtn = null;
private View mAccountBtn = null;
private MyFragmentPagerAdapter mFragmentPagerAdapter;
private int mPanelTitleNormalColor = 0;
private int mPanelTitleSelectedColor = 0;
private ArrayList<TextView> mPanelTitles = new ArrayList<TextView>();
private ArrayList<View> mPanelImageNormal = new ArrayList<View>();
private ArrayList<View> mPanelImageSelected = new ArrayList<View>();
/*
* 初始化ViewPager
*/
public void initView() {
mPager = (ViewPager) findViewById(R.id.viewpager);
// 给ViewPager设置适配器
mFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
mPager.setOffscreenPageLimit(mFragmentPagerAdapter.getCount());//
mPager.setAdapter(mFragmentPagerAdapter);
mPager.setOnPageChangeListener(new MyOnPageChangeListener());
mRecommentBtn = findViewById(R.id.recomment_btn);
mRecommentBtn.setOnClickListener(mBtnClickListener);
mPanelImageNormal.add(findViewById(R.id.recomment_img));
mPanelImageSelected.add(findViewById(R.id.recomment_img_selected));
mPanelTitles.add((TextView) findViewById(R.id.recommend_title));
mLiveBtn = findViewById(R.id.live_btn);
mLiveBtn.setOnClickListener(mBtnClickListener);
mPanelImageNormal.add(findViewById(R.id.live_img));
mPanelImageSelected.add(findViewById(R.id.live_img_selected));
mPanelTitles.add((TextView) findViewById(R.id.live_title));
mGameBtn = findViewById(R.id.game_btn);
mGameBtn.setOnClickListener(mBtnClickListener);
mPanelImageNormal.add(findViewById(R.id.game_img));
mPanelImageSelected.add(findViewById(R.id.game_img_selected));
mPanelTitles.add((TextView) findViewById(R.id.game_title));
mAccountBtn = findViewById(R.id.account_btn);
mAccountBtn.setOnClickListener(mBtnClickListener);
mPanelImageNormal.add(findViewById(R.id.account_img));
mPanelImageSelected.add(findViewById(R.id.account_img_selected));
mPanelTitles.add((TextView) findViewById(R.id.account_title));
setCurrentPage(0);// 设置当前显示标签页为第一页
mPanelTitleNormalColor = getResources().getColor(R.color.panel_title_normal_color);
mPanelTitleSelectedColor = getResources().getColor(R.color.panel_title_selected_color);
}
private OnClickListener mBtnClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
int id = v.getId();
int pageIndex = -1;
if (id == R.id.recomment_btn) {
pageIndex = 0;
} else if (id == R.id.live_btn) {
pageIndex = 1;
} else if (id == R.id.game_btn) {
pageIndex = 2;
} else if (id == R.id.account_btn) {
pageIndex = 3;
}
if (pageIndex >= 0 && pageIndex < mFragmentPagerAdapter.getCount()) {
setCurrentPage(pageIndex);
}
}
};
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setViewAlpha(View view, float alpha) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
view.setAlpha(alpha);
} else {
AlphaAnimation alphaAnim = new AlphaAnimation(alpha, alpha);
alphaAnim.setDuration(0); // Make animation instant
alphaAnim.setFillAfter(true); // Tell it to persist after the animation ends
view.startAnimation(alphaAnim);
}
}
private boolean mBackFromOtherPlace = false;
@Override
protected void onResume() {
super.onResume();
if (mCurrentPageIndex >= 0 && mBackFromOtherPlace) {
StatService.onPageStart(this, "fragment:" + mCurrentPageIndex);
LogUtil.d("service", "page start " + mCurrentPageIndex);
}
mBackFromOtherPlace = false;
}
@Override
protected void onPause() {
super.onPause();
mBackFromOtherPlace = true;
if (mCurrentPageIndex >= 0) {
LogUtil.d("service", "page end " + mCurrentPageIndex);
StatService.onPageEnd(this, "fragment:" + mCurrentPageIndex);
}
}
private int mCurrentPageIndex = -1;
private void setCurrentPage(int index) {
if (mCurrentPageIndex != index) {
if (mCurrentPageIndex >= 0) {
LogUtil.d("service", "page end " + mCurrentPageIndex);
StatService.onPageEnd(this, "fragment:" + mCurrentPageIndex);
}
LogUtil.d("service", "page start " + index);
StatService.onPageStart(this, "fragment:" + index);
mCurrentPageIndex = index;
}
if (index >= 0 && index < mFragmentPagerAdapter.getCount()) {
mPager.setCurrentItem(index, false);
mAccountBtn.setSelected(false);
mGameBtn.setSelected(false);
mLiveBtn.setSelected(false);
mRecommentBtn.setSelected(false);
for (int i = 0; i < mPanelImageNormal.size(); i++) {
if (i != index) {
setViewAlpha(mPanelImageNormal.get(i), 1);
setViewAlpha(mPanelImageSelected.get(i), 0);
mPanelTitles.get(i).setTextColor(mPanelTitleNormalColor);
} else {
setViewAlpha(mPanelImageNormal.get(i), 0);
setViewAlpha(mPanelImageSelected.get(i), 1);
mPanelTitles.get(i).setTextColor(mPanelTitleSelectedColor);
}
}
switch (index) {
case 0:
mRecommentBtn.setSelected(true);
break;
case 1:
mLiveBtn.setSelected(true);
break;
case 2:
mGameBtn.setSelected(true);
break;
case 3:
mAccountBtn.setSelected(true);
break;
default:
break;
}
}
}
private void changePanelDisplay(
int position, float positionOffset, int positionOffsetPixels) {
if (positionOffset < 0.0000001) {
setCurrentPage(position);
return;
}
changePanelTitleColor(position, positionOffset, positionOffsetPixels);
changePanelImage(position, positionOffset, positionOffsetPixels);
}
private void changePanelImage(
int position, float positionOffset, int positionOffsetPixels) {
setViewAlpha(mPanelImageNormal.get(position), positionOffset);
setViewAlpha(mPanelImageSelected.get(position), 1 - positionOffset);
setViewAlpha(mPanelImageNormal.get(position + 1), 1 - positionOffset);
setViewAlpha(mPanelImageSelected.get(position + 1), positionOffset);
}
private void changePanelTitleColor(
int position, float positionOffset, int positionOffsetPixels) {
/*
* 根据viewerpager渐变修改文字的颜色
*/
int normalColorRed = Color.red(mPanelTitleNormalColor);
int normalColorBlue = Color.blue(mPanelTitleNormalColor);
int normalColorGreen = Color.green(mPanelTitleNormalColor);
int selectedColorRed = Color.red(mPanelTitleSelectedColor);
int selectedColorBlue = Color.blue(mPanelTitleSelectedColor);
int selectedColorGreen = Color.green(mPanelTitleSelectedColor);
// 设置左边item的title
int leftRed = (int) ((1.0 - positionOffset) * selectedColorRed + positionOffset
* normalColorRed);
int leftBlue = (int) ((1.0 - positionOffset) * selectedColorBlue + positionOffset
* normalColorBlue);
int leftGreen = (int) ((1.0 - positionOffset) * selectedColorGreen + positionOffset
* normalColorGreen);
mPanelTitles.get(position).setTextColor(Color.argb(255,
leftRed, leftGreen, leftBlue));
// 设置右边item的title
int rightRed = (int) ((1.0 - positionOffset) * normalColorRed + positionOffset
* selectedColorRed);
int rightBlue = (int) ((1.0 - positionOffset) * normalColorBlue + positionOffset
* selectedColorBlue);
int rightGreen = (int) ((1.0 - positionOffset) * normalColorGreen + positionOffset
* selectedColorGreen);
mPanelTitles.get(position + 1).setTextColor(Color.argb(255,
rightRed, rightGreen, rightBlue));
}
private class MyOnPageChangeListener implements OnPageChangeListener {
@Override
public void onPageScrollStateChanged(int state) {
debug("onPageScrollStateChanged:" + state);
}
@Override
public void onPageScrolled(
int position, float positionOffset, int positionOffsetPixels) {
changePanelDisplay(position,
positionOffset,
positionOffsetPixels);
}
@Override
public void onPageSelected(int position) {
setCurrentPage(position);
debug("onPageSelected:" + position);
}
}
}
| apache-2.0 |
romawkad/java_pft | sandbox/src/test/java/ru/stqa/pft/sandbox/PointTests.java | 947 | package ru.stqa.pft.sandbox;
import org.testng.Assert;
import org.testng.annotations.Test;
import ru.stqa.rft.sandbox.Point;
/**
* Created by RomanovaD on 15.05.2017.
*/
public class PointTests {
//Нулевые координаты
@Test
public void testDistanceZeroCoordinates(){
Point p1 = new Point(0,0);
Point p2 = new Point(0,0);
Assert.assertEquals(p1.distance(p2), 0.0);
}
//Положительные координаты
@Test
public void testDistancePositiveCoordinates(){
Point p1 = new Point(1,1);
Point p2 = new Point(3,5);
Assert.assertEquals(p1.distance(p2), 4.47213595499958);
}
//Отрицательные координаты
@Test
public void testDistanceNegativeCoordinates(){
Point p1 = new Point(-2,-1);
Point p2 = new Point(-6,-5);
Assert.assertEquals(p1.distance(p2), 5.656854249492381);
}
}
| apache-2.0 |
nafae/developer | modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201406/cm/CampaignSharedSetErrorReason.java | 1010 |
package com.google.api.ads.adwords.jaxws.v201406.cm;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for CampaignSharedSetError.Reason.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="CampaignSharedSetError.Reason">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="CAMPAIGN_SHARED_SET_DOES_NOT_EXIST"/>
* <enumeration value="SHARED_SET_NOT_ACTIVE"/>
* <enumeration value="UNKNOWN"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "CampaignSharedSetError.Reason")
@XmlEnum
public enum CampaignSharedSetErrorReason {
CAMPAIGN_SHARED_SET_DOES_NOT_EXIST,
SHARED_SET_NOT_ACTIVE,
UNKNOWN;
public String value() {
return name();
}
public static CampaignSharedSetErrorReason fromValue(String v) {
return valueOf(v);
}
}
| apache-2.0 |
lsimons/phloc-schematron-standalone | phloc-schematron/jing/src/main/java/com/thaiopensource/relaxng/parse/Parseable.java | 505 | package com.thaiopensource.relaxng.parse;
public interface Parseable <P, NC, L, EA, CL extends CommentList <L>, A extends Annotations <L, EA, CL>> extends
SubParser <P, NC, L, EA, CL, A>
{
P parse (SchemaBuilder <P, NC, L, EA, CL, A> f, Scope <P, L, EA, CL, A> scope) throws BuildException,
IllegalSchemaException;
}
| apache-2.0 |
paplorinc/intellij-community | platform/core-api/src/com/intellij/psi/util/CachedValue.java | 6496 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.util;
import com.intellij.openapi.util.Getter;
import com.intellij.openapi.util.RecursionGuard;
import org.jetbrains.annotations.NotNull;
/**
* A wrapper object that holds a computation ({@link #getValueProvider()}) and caches the result of the computation.
* The recommended way of creation is to use one of {@link CachedValuesManager#getCachedValue} methods.<p></p>
*
* When {@link #getValue()} is invoked the first time, the computation is run and its result is returned and remembered internally.
* In subsequent invocations, the result will be reused to avoid running the same code again and again.<p/>
*
* The computation will be re-run in the following circumstances:
* <ol>
* <li/>Garbage collector collects the result cached internally (it's kept via a {@link java.lang.ref.SoftReference}).
* <li/>IDEA determines that cached value is outdated because some its dependencies are changed. See
* {@link CachedValueProvider.Result#getDependencyItems()}
* </ol>
*
* The implementation is thread-safe but not atomic, i.e. if several threads request the cached value simultaneously, the computation may
* be run concurrently on more than one thread. Due to this and unpredictable garbage collection,
* cached value providers shouldn't have side effects.<p></p>
*
* <b>Result equivalence</b>: CachedValue might return a different result even if the previous one
* is still reachable and not garbage-collected, and dependencies haven't changed. Therefore CachedValue results
* should be equivalent and interchangeable if they're called multiple times. Examples:
* <ul>
* <li>If PSI declarations are cached, {@link #equals} or at least {@link com.intellij.psi.PsiManager#areElementsEquivalent}
* should hold for results from the same CachedValue.</li>
* <li>{@link com.intellij.psi.ResolveResult} objects should have equivalent {@code getElement()} values.</li>
* <li>Cached arrays or lists should have the same number of elements, and they also should be equivalent and come in the same order.</li>
* <li>If the result object's class has a meaningful {@link #equals} method, it should hold.</li>
* </ul>
* This is enforced at runtime by occasional checks in {@link com.intellij.util.IdempotenceChecker#checkEquivalence(Object, Object, Class)}.
* See that method's documentation for further information and advice, when a failure happens.<p></p>
*
* <b>Context-independence</b>: if you store the CachedValue in a field or user data of some object {@code X}, then its {@link CachedValueProvider}
* may only depend on X and parts of global system state that don't change while {@code X} is alive and valid (e.g. application/project components/services).
* Otherwise re-invoking the CachedValueProvider after invalidation would use outdated data and produce incorrect results,
* possibly causing exceptions in places far, far away. In particular, the provider may not capture:
* <ul>
* <li>Parameters of a method where CachedValue is created, except for {@code X} itself. Example:
* <pre>
* PsiElement resolve(PsiElement e, boolean incompleteCode) {
* return CachedValuesManager.getCachedValue(e, () -> doResolve(e, incompleteCode)); // WRONG!!!
* }
* </pre>
*
* </li>
* <li>"this" object creating the CachedValue, if {@code X} can outlive it,
* or if there can be several non-equivalent instances of "this"-object's class all creating a cached value for the same place</li>
* <li>Thread-locals at the moment of creation. If you use them (either directly or via {@link RecursionGuard#currentStack()}),
* please try not to. If you really have to, also use {@link RecursionGuard#prohibitResultCaching(Object)}
* to ensure values depending on unstable data won't be cached.</li>
* <li>PSI elements around {@code X}, when {@code X} is a {@link com.intellij.psi.PsiElement} itself,
* as they can change during the lifetime of that PSI element. Example:
* <pre>
* PsiMethod[] methods = psiClass.getMethods();
* return CachedValuesManager.getCachedValue(psiClass, () -> calculateSomeResult(methods)); // WRONG!!!
* </pre>
* </ul>
* </ul>
* This is enforced at runtime by occasional checks in {@link com.intellij.util.CachedValueStabilityChecker}.
* See that class's documentation for further information and advice, when a failure happens.<p></p>
*
* <b>Recursion prevention</b>: The same cached value provider can be re-entered recursively on the same thread,
* if the computation is inherently cyclic. Note that this is likely to result in {@link StackOverflowError},
* so avoid such situations at all cost. If there's no other way, use
* {@link com.intellij.openapi.util.RecursionManager#doPreventingRecursion} instead of custom thread-locals to help get out of the endless loop. Please ensure this call happens inside
* the {@link CachedValueProvider}, not outside {@link CachedValue#getValue()} call. Otherwise you might get no caching at all, because
* CachedValue uses {@link RecursionGuard.StackStamp#mayCacheNow()} to prevent caching incomplete values, and even the top-level
* call would be considered incomplete if it happens inside {@code doPreventingRecursion}.
*
* @param <T> The type of the computation result.
*
* @see CachedValueProvider
* @see CachedValuesManager
*/
public interface CachedValue<T> {
/**
* @return cached value if it's already computed and not outdated, newly computed value otherwise
*/
T getValue();
/**
* @return the object calculating the value to cache
*/
@NotNull
CachedValueProvider<T> getValueProvider();
/**
* @return whether there is a cached result inside this object and it's not outdated
*/
boolean hasUpToDateValue();
/**
* @return if {@link #hasUpToDateValue()}, then a wrapper around the cached value, otherwise null.
*/
Getter<T> getUpToDateOrNull();
}
| apache-2.0 |
kexinrong/macrobase | lib/src/main/java/edu/stanford/futuredata/macrobase/analysis/classify/stats/LinearInterpolator.java | 1539 | package edu.stanford.futuredata.macrobase.analysis.classify.stats;
import edu.stanford.futuredata.macrobase.util.MacrobaseInternalError;
/**
* Performs linear interpolation in a lazy manner: interpolation does not actually
* occur until an evaluation is requested.
*/
public class LinearInterpolator {
private double[] x;
private double[] y;
/**
* @param x Should be sorted in non-descending order. Assumed to not be very large.
*/
public LinearInterpolator(double[] x, double[] y) throws IllegalArgumentException {
if (x.length != y.length) {
throw new IllegalArgumentException("X and Y must be the same length");
}
if (x.length == 1) {
throw new IllegalArgumentException("X must contain more than one value");
}
this.x = x;
this.y = y;
}
public double evaluate(double value) throws MacrobaseInternalError {
if ((value > x[x.length - 1]) || (value < x[0])) {
return Double.NaN;
}
for (int i = 0; i < x.length; i++) {
if (value == x[i]) {
return y[i];
}
if (value >= x[i+1]) {
continue;
}
double dx = x[i+1] - x[i];
double dy = y[i+1] - y[i];
double slope = dy / dx;
double intercept = y[i] - x[i] * slope;
return slope * value + intercept;
}
throw new MacrobaseInternalError("Linear interpolator implemented incorrectly");
}
}
| apache-2.0 |
nafae/developer | modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201403/CreativePlaceholder.java | 7288 |
package com.google.api.ads.dfp.jaxws.v201403;
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.XmlType;
/**
*
* A {@code CreativePlaceholder} describes a slot that a creative is expected to
* fill. This is used primarily to help in forecasting, and also to validate
* that the correct creatives are associated with the line item. A
* {@code CreativePlaceholder} must contain a size, and it can optionally
* contain companions. Companions are only valid if the line item's environment
* type is {@link EnvironmentType#VIDEO_PLAYER}.
*
*
* <p>Java class for CreativePlaceholder complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="CreativePlaceholder">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="size" type="{https://www.google.com/apis/ads/publisher/v201403}Size" minOccurs="0"/>
* <element name="companions" type="{https://www.google.com/apis/ads/publisher/v201403}CreativePlaceholder" maxOccurs="unbounded" minOccurs="0"/>
* <element name="appliedLabels" type="{https://www.google.com/apis/ads/publisher/v201403}AppliedLabel" maxOccurs="unbounded" minOccurs="0"/>
* <element name="effectiveAppliedLabels" type="{https://www.google.com/apis/ads/publisher/v201403}AppliedLabel" maxOccurs="unbounded" minOccurs="0"/>
* <element name="id" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
* <element name="expectedCreativeCount" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="creativeSizeType" type="{https://www.google.com/apis/ads/publisher/v201403}CreativeSizeType" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CreativePlaceholder", propOrder = {
"size",
"companions",
"appliedLabels",
"effectiveAppliedLabels",
"id",
"expectedCreativeCount",
"creativeSizeType"
})
public class CreativePlaceholder {
protected Size size;
protected List<CreativePlaceholder> companions;
protected List<AppliedLabel> appliedLabels;
protected List<AppliedLabel> effectiveAppliedLabels;
protected Long id;
protected Integer expectedCreativeCount;
protected CreativeSizeType creativeSizeType;
/**
* Gets the value of the size property.
*
* @return
* possible object is
* {@link Size }
*
*/
public Size getSize() {
return size;
}
/**
* Sets the value of the size property.
*
* @param value
* allowed object is
* {@link Size }
*
*/
public void setSize(Size value) {
this.size = value;
}
/**
* Gets the value of the companions 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 companions property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCompanions().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CreativePlaceholder }
*
*
*/
public List<CreativePlaceholder> getCompanions() {
if (companions == null) {
companions = new ArrayList<CreativePlaceholder>();
}
return this.companions;
}
/**
* Gets the value of the appliedLabels 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 appliedLabels property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAppliedLabels().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link AppliedLabel }
*
*
*/
public List<AppliedLabel> getAppliedLabels() {
if (appliedLabels == null) {
appliedLabels = new ArrayList<AppliedLabel>();
}
return this.appliedLabels;
}
/**
* Gets the value of the effectiveAppliedLabels 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 effectiveAppliedLabels property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getEffectiveAppliedLabels().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link AppliedLabel }
*
*
*/
public List<AppliedLabel> getEffectiveAppliedLabels() {
if (effectiveAppliedLabels == null) {
effectiveAppliedLabels = new ArrayList<AppliedLabel>();
}
return this.effectiveAppliedLabels;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setId(Long value) {
this.id = value;
}
/**
* Gets the value of the expectedCreativeCount property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getExpectedCreativeCount() {
return expectedCreativeCount;
}
/**
* Sets the value of the expectedCreativeCount property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setExpectedCreativeCount(Integer value) {
this.expectedCreativeCount = value;
}
/**
* Gets the value of the creativeSizeType property.
*
* @return
* possible object is
* {@link CreativeSizeType }
*
*/
public CreativeSizeType getCreativeSizeType() {
return creativeSizeType;
}
/**
* Sets the value of the creativeSizeType property.
*
* @param value
* allowed object is
* {@link CreativeSizeType }
*
*/
public void setCreativeSizeType(CreativeSizeType value) {
this.creativeSizeType = value;
}
}
| apache-2.0 |
mindcrime/AISandbox | blackboard/src/main/java/org/fogbeam/experimental/blackboard/concurrencystuff/jtp/hyde/chapter11/Squish.java | 2409 | package org.fogbeam.experimental.blackboard.concurrencystuff.jtp.hyde.chapter11;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import javax.swing.JComponent;
public class Squish extends JComponent
{
private static final long serialVersionUID = 1L;
private Image[] frameList;
private long msPerFrame;
private volatile int currFrame;
private Thread internalThread;
private volatile boolean noStopRequested = true;
public Squish( int width, int height, long msPerCycle, int framesPerSec, Color fgColor )
{
setPreferredSize( new Dimension( width, height ) );
int framesPerCycle = (int) ( (framesPerSec * msPerCycle ) / 1000 );
msPerFrame = 1000L / framesPerSec;
frameList = buildImages( width, height, fgColor, framesPerCycle );
currFrame = 0;
Runnable r = new Runnable()
{
@Override
public void run()
{
try
{
runWork();
}
catch( Exception e )
{
e.printStackTrace();
}
}
};
internalThread = new Thread( r );
internalThread.start();
}
private Image[] buildImages( int width, int height, Color fgColor, int count )
{
BufferedImage[] images = new BufferedImage[count];
for( int i = 0; i < count; i++ )
{
images[i] = new BufferedImage( width, height, BufferedImage.TYPE_INT_ARGB );
double xShape = 0.0;
double yShape = ( (double) (i*height) ) / ( (double)count );
double wShape = width;
double hShape = 2.0 * (height - yShape );
Ellipse2D shape = new Ellipse2D.Double( xShape, yShape, wShape, hShape );
Graphics2D g2 = images[i].createGraphics();
g2.setColor( fgColor );
g2.fill( shape );
g2.dispose();
}
return images;
}
private void runWork()
{
while( noStopRequested )
{
currFrame = (currFrame + 1 ) % frameList.length;
repaint();
try
{
Thread.sleep( msPerFrame );
}
catch( InterruptedException e )
{
// reassert interrupt and continue on
Thread.currentThread().interrupt();
}
}
}
@Override
public void paint( Graphics g )
{
g.drawImage( frameList[currFrame], 0, 0, this );
}
public void stopRequest()
{
noStopRequested = false;
internalThread.interrupt();
}
public boolean isAlive()
{
return internalThread.isAlive();
}
}
| apache-2.0 |
cap-framework/cap-http | src/main/java/capframework/http/constant/Regular.java | 1095 | //region Copyright
/*Copyright 2015-2016 尚尔路(sel8616@gmail.com/philshang@163.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.
*/
//endregion
package capframework.http.constant;
public class Regular
{
public static final String PAGE_DIRECTORY = "^/([A-Za-z0-9][A-Za-z0-9_\\-]{0,254}/){0,10}$";
public static final String PAGE_NAME = "^[A-Za-z0-9][A-Za-z0-9_\\-]{0,254}\\.[A-Za-z]{1,4}$";
public static final String ACTION_PATH = "^/{0,1}|/([A-Za-z0-9][A-Za-z0-9_\\-]{0,254}/)*([A-Za-z0-9][A-Za-z0-9_\\-]{0,254})$";
public static final String INTERCEPTOR_EXCLUDES = "^[A-Za-z0-9_/]{1,255}$";
} | apache-2.0 |
leafclick/intellij-community | xml/xml-analysis-impl/src/com/intellij/xml/util/CheckTagEmptyBodyInspection.java | 3650 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.xml.util;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.codeInspection.XmlInspectionGroupNames;
import com.intellij.codeInspection.XmlSuppressableInspectionTool;
import com.intellij.lang.ASTNode;
import com.intellij.lang.xml.XMLLanguage;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.xml.XmlChildRole;
import com.intellij.psi.xml.XmlTag;
import com.intellij.psi.xml.XmlTokenType;
import com.intellij.util.IncorrectOperationException;
import com.intellij.xml.XmlBundle;
import com.intellij.xml.XmlExtension;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
/**
* @author Maxim Mossienko
*/
public class CheckTagEmptyBodyInspection extends XmlSuppressableInspectionTool {
@Override
public boolean isEnabledByDefault() {
return true;
}
@Override
@NotNull
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
return new XmlElementVisitor() {
@Override public void visitXmlTag(final XmlTag tag) {
if (!CheckEmptyTagInspection.isTagWithEmptyEndNotAllowed(tag)) {
final ASTNode child = XmlChildRole.START_TAG_END_FINDER.findChild(tag.getNode());
if (child != null) {
final ASTNode node = child.getTreeNext();
if (node != null &&
node.getElementType() == XmlTokenType.XML_END_TAG_START) {
holder.registerProblem(
tag,
XmlBundle.message("xml.inspections.tag.empty.body"),
isCollapsibleTag(tag) ? new Fix(tag) : null
);
}
}
}
}
};
}
static boolean isCollapsibleTag(final XmlTag tag) {
final String name = StringUtil.toLowerCase(tag.getName());
return tag.getLanguage() == XMLLanguage.INSTANCE ||
"link".equals(name) || "br".equals(name) || "meta".equals(name) || "img".equals(name) || "input".equals(name) || "hr".equals(name) ||
XmlExtension.isCollapsible(tag);
}
@Override
@NotNull
public String getGroupDisplayName() {
return XmlInspectionGroupNames.XML_INSPECTIONS;
}
@Override
@NotNull
@NonNls
public String getShortName() {
return "CheckTagEmptyBody";
}
public static class Fix extends CollapseTagIntention {
private final SmartPsiElementPointer<XmlTag> myPointer;
public Fix(XmlTag tag) {
myPointer = SmartPointerManager.getInstance(tag.getProject()).createSmartPsiElementPointer(tag);
}
@Override
public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
XmlTag tag = myPointer.getElement();
if (tag == null) {
return;
}
applyFix(project, tag);
}
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
return true;
}
}
} | apache-2.0 |
suood/muses-mainproject | muses-manage-mapper/src/main/java/com/muses/data/model/AdminDataRecordExample.java | 23831 | package com.muses.data.model;
import java.util.ArrayList;
import java.util.List;
public class AdminDataRecordExample {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table suood_admin
*
* @mbggenerated
*/
protected String orderByClause;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table suood_admin
*
* @mbggenerated
*/
protected boolean distinct;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table suood_admin
*
* @mbggenerated
*/
protected List<Criteria> oredCriteria;
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table suood_admin
*
* @mbggenerated
*/
public AdminDataRecordExample() {
oredCriteria = new ArrayList<Criteria>();
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table suood_admin
*
* @mbggenerated
*/
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table suood_admin
*
* @mbggenerated
*/
public String getOrderByClause() {
return orderByClause;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table suood_admin
*
* @mbggenerated
*/
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table suood_admin
*
* @mbggenerated
*/
public boolean isDistinct() {
return distinct;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table suood_admin
*
* @mbggenerated
*/
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table suood_admin
*
* @mbggenerated
*/
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table suood_admin
*
* @mbggenerated
*/
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table suood_admin
*
* @mbggenerated
*/
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table suood_admin
*
* @mbggenerated
*/
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table suood_admin
*
* @mbggenerated
*/
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table suood_admin
*
* @mbggenerated
*/
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andAdminIdIsNull() {
addCriterion("admin_id is null");
return (Criteria) this;
}
public Criteria andAdminIdIsNotNull() {
addCriterion("admin_id is not null");
return (Criteria) this;
}
public Criteria andAdminIdEqualTo(Integer value) {
addCriterion("admin_id =", value, "adminId");
return (Criteria) this;
}
public Criteria andAdminIdNotEqualTo(Integer value) {
addCriterion("admin_id <>", value, "adminId");
return (Criteria) this;
}
public Criteria andAdminIdGreaterThan(Integer value) {
addCriterion("admin_id >", value, "adminId");
return (Criteria) this;
}
public Criteria andAdminIdGreaterThanOrEqualTo(Integer value) {
addCriterion("admin_id >=", value, "adminId");
return (Criteria) this;
}
public Criteria andAdminIdLessThan(Integer value) {
addCriterion("admin_id <", value, "adminId");
return (Criteria) this;
}
public Criteria andAdminIdLessThanOrEqualTo(Integer value) {
addCriterion("admin_id <=", value, "adminId");
return (Criteria) this;
}
public Criteria andAdminIdIn(List<Integer> values) {
addCriterion("admin_id in", values, "adminId");
return (Criteria) this;
}
public Criteria andAdminIdNotIn(List<Integer> values) {
addCriterion("admin_id not in", values, "adminId");
return (Criteria) this;
}
public Criteria andAdminIdBetween(Integer value1, Integer value2) {
addCriterion("admin_id between", value1, value2, "adminId");
return (Criteria) this;
}
public Criteria andAdminIdNotBetween(Integer value1, Integer value2) {
addCriterion("admin_id not between", value1, value2, "adminId");
return (Criteria) this;
}
public Criteria andAdminNameIsNull() {
addCriterion("admin_name is null");
return (Criteria) this;
}
public Criteria andAdminNameIsNotNull() {
addCriterion("admin_name is not null");
return (Criteria) this;
}
public Criteria andAdminNameEqualTo(String value) {
addCriterion("admin_name =", value, "adminName");
return (Criteria) this;
}
public Criteria andAdminNameNotEqualTo(String value) {
addCriterion("admin_name <>", value, "adminName");
return (Criteria) this;
}
public Criteria andAdminNameGreaterThan(String value) {
addCriterion("admin_name >", value, "adminName");
return (Criteria) this;
}
public Criteria andAdminNameGreaterThanOrEqualTo(String value) {
addCriterion("admin_name >=", value, "adminName");
return (Criteria) this;
}
public Criteria andAdminNameLessThan(String value) {
addCriterion("admin_name <", value, "adminName");
return (Criteria) this;
}
public Criteria andAdminNameLessThanOrEqualTo(String value) {
addCriterion("admin_name <=", value, "adminName");
return (Criteria) this;
}
public Criteria andAdminNameLike(String value) {
addCriterion("admin_name like", value, "adminName");
return (Criteria) this;
}
public Criteria andAdminNameNotLike(String value) {
addCriterion("admin_name not like", value, "adminName");
return (Criteria) this;
}
public Criteria andAdminNameIn(List<String> values) {
addCriterion("admin_name in", values, "adminName");
return (Criteria) this;
}
public Criteria andAdminNameNotIn(List<String> values) {
addCriterion("admin_name not in", values, "adminName");
return (Criteria) this;
}
public Criteria andAdminNameBetween(String value1, String value2) {
addCriterion("admin_name between", value1, value2, "adminName");
return (Criteria) this;
}
public Criteria andAdminNameNotBetween(String value1, String value2) {
addCriterion("admin_name not between", value1, value2, "adminName");
return (Criteria) this;
}
public Criteria andAdminPasswordIsNull() {
addCriterion("admin_password is null");
return (Criteria) this;
}
public Criteria andAdminPasswordIsNotNull() {
addCriterion("admin_password is not null");
return (Criteria) this;
}
public Criteria andAdminPasswordEqualTo(String value) {
addCriterion("admin_password =", value, "adminPassword");
return (Criteria) this;
}
public Criteria andAdminPasswordNotEqualTo(String value) {
addCriterion("admin_password <>", value, "adminPassword");
return (Criteria) this;
}
public Criteria andAdminPasswordGreaterThan(String value) {
addCriterion("admin_password >", value, "adminPassword");
return (Criteria) this;
}
public Criteria andAdminPasswordGreaterThanOrEqualTo(String value) {
addCriterion("admin_password >=", value, "adminPassword");
return (Criteria) this;
}
public Criteria andAdminPasswordLessThan(String value) {
addCriterion("admin_password <", value, "adminPassword");
return (Criteria) this;
}
public Criteria andAdminPasswordLessThanOrEqualTo(String value) {
addCriterion("admin_password <=", value, "adminPassword");
return (Criteria) this;
}
public Criteria andAdminPasswordLike(String value) {
addCriterion("admin_password like", value, "adminPassword");
return (Criteria) this;
}
public Criteria andAdminPasswordNotLike(String value) {
addCriterion("admin_password not like", value, "adminPassword");
return (Criteria) this;
}
public Criteria andAdminPasswordIn(List<String> values) {
addCriterion("admin_password in", values, "adminPassword");
return (Criteria) this;
}
public Criteria andAdminPasswordNotIn(List<String> values) {
addCriterion("admin_password not in", values, "adminPassword");
return (Criteria) this;
}
public Criteria andAdminPasswordBetween(String value1, String value2) {
addCriterion("admin_password between", value1, value2, "adminPassword");
return (Criteria) this;
}
public Criteria andAdminPasswordNotBetween(String value1, String value2) {
addCriterion("admin_password not between", value1, value2, "adminPassword");
return (Criteria) this;
}
public Criteria andAdminLoginTimeIsNull() {
addCriterion("admin_login_time is null");
return (Criteria) this;
}
public Criteria andAdminLoginTimeIsNotNull() {
addCriterion("admin_login_time is not null");
return (Criteria) this;
}
public Criteria andAdminLoginTimeEqualTo(Integer value) {
addCriterion("admin_login_time =", value, "adminLoginTime");
return (Criteria) this;
}
public Criteria andAdminLoginTimeNotEqualTo(Integer value) {
addCriterion("admin_login_time <>", value, "adminLoginTime");
return (Criteria) this;
}
public Criteria andAdminLoginTimeGreaterThan(Integer value) {
addCriterion("admin_login_time >", value, "adminLoginTime");
return (Criteria) this;
}
public Criteria andAdminLoginTimeGreaterThanOrEqualTo(Integer value) {
addCriterion("admin_login_time >=", value, "adminLoginTime");
return (Criteria) this;
}
public Criteria andAdminLoginTimeLessThan(Integer value) {
addCriterion("admin_login_time <", value, "adminLoginTime");
return (Criteria) this;
}
public Criteria andAdminLoginTimeLessThanOrEqualTo(Integer value) {
addCriterion("admin_login_time <=", value, "adminLoginTime");
return (Criteria) this;
}
public Criteria andAdminLoginTimeIn(List<Integer> values) {
addCriterion("admin_login_time in", values, "adminLoginTime");
return (Criteria) this;
}
public Criteria andAdminLoginTimeNotIn(List<Integer> values) {
addCriterion("admin_login_time not in", values, "adminLoginTime");
return (Criteria) this;
}
public Criteria andAdminLoginTimeBetween(Integer value1, Integer value2) {
addCriterion("admin_login_time between", value1, value2, "adminLoginTime");
return (Criteria) this;
}
public Criteria andAdminLoginTimeNotBetween(Integer value1, Integer value2) {
addCriterion("admin_login_time not between", value1, value2, "adminLoginTime");
return (Criteria) this;
}
public Criteria andAdminLoginNumIsNull() {
addCriterion("admin_login_num is null");
return (Criteria) this;
}
public Criteria andAdminLoginNumIsNotNull() {
addCriterion("admin_login_num is not null");
return (Criteria) this;
}
public Criteria andAdminLoginNumEqualTo(Integer value) {
addCriterion("admin_login_num =", value, "adminLoginNum");
return (Criteria) this;
}
public Criteria andAdminLoginNumNotEqualTo(Integer value) {
addCriterion("admin_login_num <>", value, "adminLoginNum");
return (Criteria) this;
}
public Criteria andAdminLoginNumGreaterThan(Integer value) {
addCriterion("admin_login_num >", value, "adminLoginNum");
return (Criteria) this;
}
public Criteria andAdminLoginNumGreaterThanOrEqualTo(Integer value) {
addCriterion("admin_login_num >=", value, "adminLoginNum");
return (Criteria) this;
}
public Criteria andAdminLoginNumLessThan(Integer value) {
addCriterion("admin_login_num <", value, "adminLoginNum");
return (Criteria) this;
}
public Criteria andAdminLoginNumLessThanOrEqualTo(Integer value) {
addCriterion("admin_login_num <=", value, "adminLoginNum");
return (Criteria) this;
}
public Criteria andAdminLoginNumIn(List<Integer> values) {
addCriterion("admin_login_num in", values, "adminLoginNum");
return (Criteria) this;
}
public Criteria andAdminLoginNumNotIn(List<Integer> values) {
addCriterion("admin_login_num not in", values, "adminLoginNum");
return (Criteria) this;
}
public Criteria andAdminLoginNumBetween(Integer value1, Integer value2) {
addCriterion("admin_login_num between", value1, value2, "adminLoginNum");
return (Criteria) this;
}
public Criteria andAdminLoginNumNotBetween(Integer value1, Integer value2) {
addCriterion("admin_login_num not between", value1, value2, "adminLoginNum");
return (Criteria) this;
}
public Criteria andAdminIsSuperIsNull() {
addCriterion("admin_is_super is null");
return (Criteria) this;
}
public Criteria andAdminIsSuperIsNotNull() {
addCriterion("admin_is_super is not null");
return (Criteria) this;
}
public Criteria andAdminIsSuperEqualTo(Boolean value) {
addCriterion("admin_is_super =", value, "adminIsSuper");
return (Criteria) this;
}
public Criteria andAdminIsSuperNotEqualTo(Boolean value) {
addCriterion("admin_is_super <>", value, "adminIsSuper");
return (Criteria) this;
}
public Criteria andAdminIsSuperGreaterThan(Boolean value) {
addCriterion("admin_is_super >", value, "adminIsSuper");
return (Criteria) this;
}
public Criteria andAdminIsSuperGreaterThanOrEqualTo(Boolean value) {
addCriterion("admin_is_super >=", value, "adminIsSuper");
return (Criteria) this;
}
public Criteria andAdminIsSuperLessThan(Boolean value) {
addCriterion("admin_is_super <", value, "adminIsSuper");
return (Criteria) this;
}
public Criteria andAdminIsSuperLessThanOrEqualTo(Boolean value) {
addCriterion("admin_is_super <=", value, "adminIsSuper");
return (Criteria) this;
}
public Criteria andAdminIsSuperIn(List<Boolean> values) {
addCriterion("admin_is_super in", values, "adminIsSuper");
return (Criteria) this;
}
public Criteria andAdminIsSuperNotIn(List<Boolean> values) {
addCriterion("admin_is_super not in", values, "adminIsSuper");
return (Criteria) this;
}
public Criteria andAdminIsSuperBetween(Boolean value1, Boolean value2) {
addCriterion("admin_is_super between", value1, value2, "adminIsSuper");
return (Criteria) this;
}
public Criteria andAdminIsSuperNotBetween(Boolean value1, Boolean value2) {
addCriterion("admin_is_super not between", value1, value2, "adminIsSuper");
return (Criteria) this;
}
public Criteria andAdminGidIsNull() {
addCriterion("admin_gid is null");
return (Criteria) this;
}
public Criteria andAdminGidIsNotNull() {
addCriterion("admin_gid is not null");
return (Criteria) this;
}
public Criteria andAdminGidEqualTo(Short value) {
addCriterion("admin_gid =", value, "adminGid");
return (Criteria) this;
}
public Criteria andAdminGidNotEqualTo(Short value) {
addCriterion("admin_gid <>", value, "adminGid");
return (Criteria) this;
}
public Criteria andAdminGidGreaterThan(Short value) {
addCriterion("admin_gid >", value, "adminGid");
return (Criteria) this;
}
public Criteria andAdminGidGreaterThanOrEqualTo(Short value) {
addCriterion("admin_gid >=", value, "adminGid");
return (Criteria) this;
}
public Criteria andAdminGidLessThan(Short value) {
addCriterion("admin_gid <", value, "adminGid");
return (Criteria) this;
}
public Criteria andAdminGidLessThanOrEqualTo(Short value) {
addCriterion("admin_gid <=", value, "adminGid");
return (Criteria) this;
}
public Criteria andAdminGidIn(List<Short> values) {
addCriterion("admin_gid in", values, "adminGid");
return (Criteria) this;
}
public Criteria andAdminGidNotIn(List<Short> values) {
addCriterion("admin_gid not in", values, "adminGid");
return (Criteria) this;
}
public Criteria andAdminGidBetween(Short value1, Short value2) {
addCriterion("admin_gid between", value1, value2, "adminGid");
return (Criteria) this;
}
public Criteria andAdminGidNotBetween(Short value1, Short value2) {
addCriterion("admin_gid not between", value1, value2, "adminGid");
return (Criteria) this;
}
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table suood_admin
*
* @mbggenerated do_not_delete_during_merge
*/
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table suood_admin
*
* @mbggenerated
*/
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | apache-2.0 |