text
stringlengths 7
1.01M
|
|---|
/*************************GO-LICENSE-START*********************************
* Copyright 2014 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*************************GO-LICENSE-END***********************************/
package com.thoughtworks.go.config;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* @understands key for error validation (used by views)
*/
@Retention(RUNTIME)
@Target(FIELD)
public @interface ValidationErrorKey {
String value();
}
|
package com.deer.wms.system.manage.model.department;
import com.deer.wms.project.seed.core.service.QueryParams;
/**
* Created by gtt on 2019/07/15.
*/
public class MtAloneDepartmentGroupParams extends QueryParams {
private String begDate;
private String endDate;
public String getBegDate() {
return begDate;
}
public void setBegDate(String begDate) {
this.begDate = begDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
}
|
package seedu.address.logic.parser;
import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import java.util.StringTokenizer;
import seedu.address.commons.core.index.Index;
import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.logic.commands.CustomCommand;
import seedu.address.logic.parser.exceptions.ParseException;
import seedu.address.model.customField.CustomField;
//@@author LuLechuan
/**
* Parses input arguments and creates a new CustomCommand object
*/
public class CustomCommandParser implements Parser<CustomCommand> {
/**
* Parses the given {@code String} of arguments in the context of the CustomCommand
* and returns a CustomCommand object for execution.
* @throws ParseException if the user input does not conform the expected format
*/
public CustomCommand parse(String args) throws ParseException {
try {
StringTokenizer st = new StringTokenizer(args);
Index index = ParserUtil.parseIndex(st.nextToken());
String customFieldName = st.nextToken();
String customFieldValue;
if (st.hasMoreTokens()) {
customFieldValue = st.nextToken();
} else {
customFieldValue = "";
}
CustomField customField = new CustomField(customFieldName, customFieldValue);
return new CustomCommand(index, customField);
} catch (IllegalValueException ive) {
throw new ParseException(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, CustomCommand.MESSAGE_USAGE));
}
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.builder.component.dsl;
import javax.annotation.Generated;
import org.apache.camel.Component;
import org.apache.camel.builder.component.AbstractComponentBuilder;
import org.apache.camel.builder.component.ComponentBuilder;
import org.apache.camel.component.google.bigquery.GoogleBigQueryComponent;
/**
* Google BigQuery data warehouse for analytics.
*
* Generated by camel-package-maven-plugin - do not edit this file!
*/
@Generated("org.apache.camel.maven.packaging.ComponentDslMojo")
public interface GoogleBigqueryComponentBuilderFactory {
/**
* Google BigQuery (camel-google-bigquery)
* Google BigQuery data warehouse for analytics.
*
* Category: cloud,bigdata
* Since: 2.20
* Maven coordinates: org.apache.camel:camel-google-bigquery
*/
static GoogleBigqueryComponentBuilder googleBigquery() {
return new GoogleBigqueryComponentBuilderImpl();
}
/**
* Builder for the Google BigQuery component.
*/
interface GoogleBigqueryComponentBuilder
extends
ComponentBuilder<GoogleBigQueryComponent> {
/**
* ConnectionFactory to obtain connection to Bigquery Service. If non
* provided the default one will be used.
*
* The option is a:
* <code>org.apache.camel.component.google.bigquery.GoogleBigQueryConnectionFactory</code> type.
*
* Group: producer
*/
default GoogleBigqueryComponentBuilder connectionFactory(
org.apache.camel.component.google.bigquery.GoogleBigQueryConnectionFactory connectionFactory) {
doSetProperty("connectionFactory", connectionFactory);
return this;
}
/**
* BigQuery Dataset Id.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*/
default GoogleBigqueryComponentBuilder datasetId(
java.lang.String datasetId) {
doSetProperty("datasetId", datasetId);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*/
default GoogleBigqueryComponentBuilder lazyStartProducer(
boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Google Cloud Project Id.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*/
default GoogleBigqueryComponentBuilder projectId(
java.lang.String projectId) {
doSetProperty("projectId", projectId);
return this;
}
/**
* Whether autowiring is enabled. This is used for automatic autowiring
* options (the option must be marked as autowired) by looking up in the
* registry to find if there is a single instance of matching type,
* which then gets configured on the component. This can be used for
* automatic configuring JDBC data sources, JMS connection factories,
* AWS Clients, etc.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: advanced
*/
default GoogleBigqueryComponentBuilder autowiredEnabled(
boolean autowiredEnabled) {
doSetProperty("autowiredEnabled", autowiredEnabled);
return this;
}
}
class GoogleBigqueryComponentBuilderImpl
extends
AbstractComponentBuilder<GoogleBigQueryComponent>
implements
GoogleBigqueryComponentBuilder {
@Override
protected GoogleBigQueryComponent buildConcreteComponent() {
return new GoogleBigQueryComponent();
}
@Override
protected boolean setPropertyOnComponent(
Component component,
String name,
Object value) {
switch (name) {
case "connectionFactory": ((GoogleBigQueryComponent) component).setConnectionFactory((org.apache.camel.component.google.bigquery.GoogleBigQueryConnectionFactory) value); return true;
case "datasetId": ((GoogleBigQueryComponent) component).setDatasetId((java.lang.String) value); return true;
case "lazyStartProducer": ((GoogleBigQueryComponent) component).setLazyStartProducer((boolean) value); return true;
case "projectId": ((GoogleBigQueryComponent) component).setProjectId((java.lang.String) value); return true;
case "autowiredEnabled": ((GoogleBigQueryComponent) component).setAutowiredEnabled((boolean) value); return true;
default: return false;
}
}
}
}
|
package org.smartregister.pnc.repository;
import android.content.ContentValues;
import androidx.annotation.NonNull;
import net.sqlcipher.database.SQLiteDatabase;
import org.apache.commons.lang3.NotImplementedException;
import org.smartregister.pnc.dao.PncGenericDao;
import org.smartregister.pnc.utils.PncDbConstants;
import org.smartregister.repository.BaseRepository;
import java.util.List;
import java.util.Map;
public class PncVisitChildStatusRepository extends BaseRepository implements PncGenericDao<Map<String, String>> {
private static final String CREATE_TABLE_SQL = "CREATE TABLE " + PncDbConstants.Table.PNC_VISIT_CHILD_STATUS + "("
+ PncDbConstants.Column.PncVisitChildStatus.ID + " INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "
+ PncDbConstants.Column.PncVisitChildStatus.VISIT_ID + " VARCHAR NOT NULL, "
+ PncDbConstants.Column.PncVisitChildStatus.BASE_ENTITY_ID + " VARCHAR NOT NULL, "
+ PncDbConstants.Column.PncVisitChildStatus.BABY_AGE + " VARCHAR NULL, "
+ PncDbConstants.Column.PncVisitChildStatus.BABY_STATUS + " VARCHAR NULL, "
+ PncDbConstants.Column.PncVisitChildStatus.DATE_OF_DEATH_BABY + " VARCHAR NULL, "
+ PncDbConstants.Column.PncVisitChildStatus.PLACE_OF_DEATH_BABY + " VARCHAR NULL, "
+ PncDbConstants.Column.PncVisitChildStatus.CAUSE_OF_DEATH_BABY + " VARCHAR NULL, "
+ PncDbConstants.Column.PncVisitChildStatus.DEATH_FOLLOW_UP_BABY + " VARCHAR NULL, "
+ PncDbConstants.Column.PncVisitChildStatus.BABY_BREAST_FEEDING + " VARCHAR NULL, "
+ PncDbConstants.Column.PncVisitChildStatus.BABY_NOT_BREAST_FEEDING_REASON + " VARCHAR NULL, "
+ PncDbConstants.Column.PncVisitChildStatus.BABY_DANGER_SIGNS + " VARCHAR NULL, "
+ PncDbConstants.Column.PncVisitChildStatus.BABY_DANGER_SIGNS_OTHER + " VARCHAR NULL, "
+ PncDbConstants.Column.PncVisitChildStatus.BABY_REFERRED_OUT + " VARCHAR NULL, "
+ PncDbConstants.Column.PncVisitChildStatus.BABY_HIV_EXPOSED + " VARCHAR NULL, "
+ PncDbConstants.Column.PncVisitChildStatus.MOTHER_BABY_PAIRING + " VARCHAR NULL, "
+ PncDbConstants.Column.PncVisitChildStatus.BABY_HIV_TREATMENT + " VARCHAR NULL, "
+ PncDbConstants.Column.PncVisitChildStatus.NOT_ART_PAIRING_REASON + " VARCHAR NULL, "
+ PncDbConstants.Column.PncVisitChildStatus.NOT_ART_PAIRING_REASON_OTHER + " VARCHAR NULL, "
+ PncDbConstants.Column.PncVisitChildStatus.BABY_DBS + " VARCHAR NULL, "
+ PncDbConstants.Column.PncVisitChildStatus.BABY_CARE_MGMT + " VARCHAR NULL, UNIQUE(" + PncDbConstants.Column.PncVisitChildStatus.VISIT_ID + "," + PncDbConstants.Column.PncVisitChildStatus.BASE_ENTITY_ID + "))";
private static final String INDEX_VISIT_ID = "CREATE INDEX " + PncDbConstants.Table.PNC_VISIT_CHILD_STATUS
+ "_" + PncDbConstants.Column.PncVisitChildStatus.VISIT_ID + "_index ON " + PncDbConstants.Table.PNC_VISIT_CHILD_STATUS +
"(" + PncDbConstants.Column.PncVisitChildStatus.VISIT_ID + " COLLATE NOCASE);";
public static void createTable(@NonNull SQLiteDatabase database) {
database.execSQL(CREATE_TABLE_SQL);
database.execSQL(INDEX_VISIT_ID);
}
@Override
public boolean saveOrUpdate(Map<String, String> data) {
ContentValues contentValues = new ContentValues();
contentValues.put(PncDbConstants.Column.PncVisitChildStatus.VISIT_ID, data.get(PncDbConstants.Column.PncVisitChildStatus.VISIT_ID));
contentValues.put(PncDbConstants.Column.PncVisitChildStatus.BASE_ENTITY_ID, data.get(PncDbConstants.Column.PncVisitChildStatus.BASE_ENTITY_ID));
contentValues.put(PncDbConstants.Column.PncVisitChildStatus.BABY_AGE, data.get(PncDbConstants.Column.PncVisitChildStatus.BABY_AGE));
contentValues.put(PncDbConstants.Column.PncVisitChildStatus.BABY_STATUS, data.get(PncDbConstants.Column.PncVisitChildStatus.BABY_STATUS));
contentValues.put(PncDbConstants.Column.PncVisitChildStatus.DATE_OF_DEATH_BABY, data.get(PncDbConstants.Column.PncVisitChildStatus.DATE_OF_DEATH_BABY));
contentValues.put(PncDbConstants.Column.PncVisitChildStatus.PLACE_OF_DEATH_BABY, data.get(PncDbConstants.Column.PncVisitChildStatus.PLACE_OF_DEATH_BABY));
contentValues.put(PncDbConstants.Column.PncVisitChildStatus.CAUSE_OF_DEATH_BABY, data.get(PncDbConstants.Column.PncVisitChildStatus.CAUSE_OF_DEATH_BABY));
contentValues.put(PncDbConstants.Column.PncVisitChildStatus.DEATH_FOLLOW_UP_BABY, data.get(PncDbConstants.Column.PncVisitChildStatus.DEATH_FOLLOW_UP_BABY));
contentValues.put(PncDbConstants.Column.PncVisitChildStatus.BABY_BREAST_FEEDING, data.get(PncDbConstants.Column.PncVisitChildStatus.BABY_BREAST_FEEDING));
contentValues.put(PncDbConstants.Column.PncVisitChildStatus.BABY_NOT_BREAST_FEEDING_REASON, data.get(PncDbConstants.Column.PncVisitChildStatus.BABY_NOT_BREAST_FEEDING_REASON));
contentValues.put(PncDbConstants.Column.PncVisitChildStatus.BABY_DANGER_SIGNS, data.get(PncDbConstants.Column.PncVisitChildStatus.BABY_DANGER_SIGNS));
contentValues.put(PncDbConstants.Column.PncVisitChildStatus.BABY_DANGER_SIGNS_OTHER, data.get(PncDbConstants.Column.PncVisitChildStatus.BABY_DANGER_SIGNS_OTHER));
contentValues.put(PncDbConstants.Column.PncVisitChildStatus.BABY_REFERRED_OUT, data.get(PncDbConstants.Column.PncVisitChildStatus.BABY_REFERRED_OUT));
contentValues.put(PncDbConstants.Column.PncVisitChildStatus.BABY_HIV_EXPOSED, data.get(PncDbConstants.Column.PncVisitChildStatus.BABY_HIV_EXPOSED));
contentValues.put(PncDbConstants.Column.PncVisitChildStatus.MOTHER_BABY_PAIRING, data.get(PncDbConstants.Column.PncVisitChildStatus.MOTHER_BABY_PAIRING));
contentValues.put(PncDbConstants.Column.PncVisitChildStatus.BABY_HIV_TREATMENT, data.get(PncDbConstants.Column.PncVisitChildStatus.BABY_HIV_TREATMENT));
contentValues.put(PncDbConstants.Column.PncVisitChildStatus.NOT_ART_PAIRING_REASON, data.get(PncDbConstants.Column.PncVisitChildStatus.NOT_ART_PAIRING_REASON));
contentValues.put(PncDbConstants.Column.PncVisitChildStatus.NOT_ART_PAIRING_REASON_OTHER, data.get(PncDbConstants.Column.PncVisitChildStatus.NOT_ART_PAIRING_REASON_OTHER));
contentValues.put(PncDbConstants.Column.PncVisitChildStatus.BABY_DBS, data.get(PncDbConstants.Column.PncVisitChildStatus.BABY_DBS));
contentValues.put(PncDbConstants.Column.PncVisitChildStatus.BABY_CARE_MGMT, data.get(PncDbConstants.Column.PncVisitChildStatus.BABY_CARE_MGMT));
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
long rows = sqLiteDatabase.insert(PncDbConstants.Table.PNC_VISIT_CHILD_STATUS, null, contentValues);
return rows != -1;
}
@Override
public Map<String, String> findOne(Map<String, String> pncChild) {
throw new NotImplementedException("");
}
@Override
public boolean delete(Map<String, String> pncChild) {
throw new NotImplementedException("");
}
@Override
public List<Map<String, String>> findAll() {
throw new NotImplementedException("");
}
}
|
package mybatis.mapper;
import java.util.List;
import mybatis.entity.BlogContent;
import mybatis.entity.BlogContentExample;
public interface BlogContentMapper {
int deleteByPrimaryKey(Long id);
int insert(BlogContent record);
int insertSelective(BlogContent record);
List<BlogContent> selectByExampleWithBLOBs(BlogContentExample example);
List<BlogContent> selectByExample(BlogContentExample example);
BlogContent selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(BlogContent record);
int updateByPrimaryKeyWithBLOBs(BlogContent record);
int updateByPrimaryKey(BlogContent record);
}
|
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.material.picker;
import com.google.android.material.R;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import android.content.Context;
import com.google.android.material.picker.selector.DateGridSelector;
import androidx.appcompat.app.AppCompatActivity;
import androidx.test.core.app.ApplicationProvider;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.internal.DoNotInstrument;
@RunWith(RobolectricTestRunner.class)
@DoNotInstrument
public class MonthAdapterTest {
private static final Locale ISRAEL = new Locale("iw", "IL");
private Context context;
private MonthAdapter monthFeb2019;
private MonthAdapter monthFeb2016;
private MonthAdapter monthJuly2018;
private MonthAdapter monthMarch2019;
@Before
public void setupMonthAdapters() {
ApplicationProvider.getApplicationContext().setTheme(R.style.Theme_MaterialComponents_Light);
AppCompatActivity activity = Robolectric.buildActivity(AppCompatActivity.class).setup().get();
context = activity.getApplicationContext();
}
private void setupLocalizedCalendars(Locale locale) {
Locale.setDefault(locale);
DateGridSelector dateGridSelector = new DateGridSelector();
Month feb2016 = Month.create(2016, Calendar.FEBRUARY);
monthFeb2016 = new MonthAdapter(context, feb2016, dateGridSelector);
Month july2018 = Month.create(2018, Calendar.JULY);
monthJuly2018 = new MonthAdapter(context, july2018, dateGridSelector);
Month feb2019 = Month.create(2019, Calendar.FEBRUARY);
monthFeb2019 = new MonthAdapter(context, feb2019, dateGridSelector);
Month march2019 = Month.create(2019, Calendar.MARCH);
monthMarch2019 = new MonthAdapter(context, march2019, dateGridSelector);
}
@Test
public void usLastPositionMatchesMonthLength() {
setupLocalizedCalendars(Locale.US);
assertLastPositionMatchesMonthLength();
}
@Test
public void frLastPositionMatchesMonthLength() {
setupLocalizedCalendars(Locale.FRANCE);
assertLastPositionMatchesMonthLength();
}
@Test
public void ilLastPositionMatchesMonthLength() {
setupLocalizedCalendars(ISRAEL);
assertLastPositionMatchesMonthLength();
}
private void assertLastPositionMatchesMonthLength() {
assertEquals(29, monthFeb2016.positionToDay(monthFeb2016.lastPositionInMonth()));
assertEquals(31, monthJuly2018.positionToDay(monthJuly2018.lastPositionInMonth()));
assertEquals(28, monthFeb2019.positionToDay(monthFeb2019.lastPositionInMonth()));
}
@Test
public void usMaxPosition() {
setupLocalizedCalendars(Locale.US);
Map<MonthAdapter, Integer> localizedMaxPositionInMonth = new HashMap<>();
localizedMaxPositionInMonth.put(monthFeb2016, 29);
localizedMaxPositionInMonth.put(monthJuly2018, 30);
localizedMaxPositionInMonth.put(monthFeb2019, 32);
assertMaxPosition(localizedMaxPositionInMonth);
}
@Test
public void frMaxPosition() {
setupLocalizedCalendars(Locale.FRANCE);
Map<MonthAdapter, Integer> localizedMaxPositionInMonth = new HashMap<>();
localizedMaxPositionInMonth.put(monthFeb2016, 28);
localizedMaxPositionInMonth.put(monthJuly2018, 36);
localizedMaxPositionInMonth.put(monthFeb2019, 31);
assertMaxPosition(localizedMaxPositionInMonth);
}
@Test
public void ilMaxPosition() {
setupLocalizedCalendars(ISRAEL);
Map<MonthAdapter, Integer> localizedMaxPositionInMonth = new HashMap<>();
localizedMaxPositionInMonth.put(monthFeb2016, 29);
localizedMaxPositionInMonth.put(monthJuly2018, 30);
localizedMaxPositionInMonth.put(monthFeb2019, 32);
assertMaxPosition(localizedMaxPositionInMonth);
}
private void assertMaxPosition(Map<MonthAdapter, Integer> localizedMaxPositionInMonth) {
assertEquals(
(int) localizedMaxPositionInMonth.get(monthFeb2016),
monthFeb2016.lastPositionInMonth());
assertEquals(
(int) localizedMaxPositionInMonth.get(monthJuly2018),
monthJuly2018.lastPositionInMonth());
assertEquals(
(int) localizedMaxPositionInMonth.get(monthFeb2019),
monthFeb2019.lastPositionInMonth());
}
@Test
public void usPositions() {
setupLocalizedCalendars(Locale.US);
Map<MonthAdapter, Integer> localizedPositionToDay =
localizedPositionToDay = new HashMap<>();
localizedPositionToDay.put(monthFeb2016, 1);
localizedPositionToDay.put(monthJuly2018, 7);
localizedPositionToDay.put(monthFeb2019, 11);
assertPositionsForDays(localizedPositionToDay);
}
@Test
public void frPositions() {
setupLocalizedCalendars(Locale.FRANCE);
Map<MonthAdapter, Integer> localizedPositionToDay =
localizedPositionToDay = new HashMap<>();
localizedPositionToDay.put(monthFeb2016, 2);
localizedPositionToDay.put(monthJuly2018, 1);
localizedPositionToDay.put(monthFeb2019, 12);
assertPositionsForDays(localizedPositionToDay);
}
@Test
public void ilPositions() {
setupLocalizedCalendars(ISRAEL);
Map<MonthAdapter, Integer> localizedPositionToDay =
localizedPositionToDay = new HashMap<>();
localizedPositionToDay.put(monthFeb2016, 1);
localizedPositionToDay.put(monthJuly2018, 7);
localizedPositionToDay.put(monthFeb2019, 11);
assertPositionsForDays(localizedPositionToDay);
}
private void assertPositionsForDays(Map<MonthAdapter, Integer> localizedPositionToDay) {
assertEquals(
(int) localizedPositionToDay.get(monthFeb2016), monthFeb2016.positionToDay(1));
assertEquals(
(int) localizedPositionToDay.get(monthJuly2018), monthJuly2018.positionToDay(6));
assertEquals(
(int) localizedPositionToDay.get(monthFeb2019), monthFeb2019.positionToDay(15));
}
@Test
public void usStableCount() {
setupLocalizedCalendars(Locale.US);
assertStableCount();
}
@Test
public void frStableCount() {
setupLocalizedCalendars(Locale.FRANCE);
assertStableCount();
}
@Test
public void ilStableCount() {
setupLocalizedCalendars(ISRAEL);
assertStableCount();
}
private void assertStableCount() {
assertEquals(6 * 7, monthFeb2016.getCount());
assertEquals(6 * 7, monthJuly2018.getCount());
assertEquals(6 * 7, monthFeb2019.getCount());
}
@Test
public void usPositionsWithinMonthReturnAValidItem() {
setupLocalizedCalendars(Locale.US);
Collection<Integer> localizedNullPositionsInFebruary2019 = Arrays.asList(-5, 0, 4, 33, 100);
Collection<Integer> localizedNonNullPositionsInFebruary2019 = Arrays.asList(5, 32);
assertPositionsWithinMonthReturnAValidItem(
localizedNullPositionsInFebruary2019, localizedNonNullPositionsInFebruary2019);
}
@Test
public void frPositionsWithinMonthReturnAValidItem() {
setupLocalizedCalendars(Locale.FRANCE);
Collection<Integer> localizedNullPositionsInFebruary2019 = Arrays.asList(-5, 0, 3, 32, 100);
Collection<Integer> localizedNonNullPositionsInFebruary2019 = Arrays.asList(4, 31);
assertPositionsWithinMonthReturnAValidItem(
localizedNullPositionsInFebruary2019, localizedNonNullPositionsInFebruary2019);
}
@Test
public void ilPositionsWithinMonthReturnAValidItem() {
setupLocalizedCalendars(ISRAEL);
Collection<Integer> localizedNullPositionsInFebruary2019 = Arrays.asList(-5, 0, 4, 33, 100);
Collection<Integer> localizedNonNullPositionsInFebruary2019 = Arrays.asList(5, 32);
assertPositionsWithinMonthReturnAValidItem(
localizedNullPositionsInFebruary2019, localizedNonNullPositionsInFebruary2019);
}
private void assertPositionsWithinMonthReturnAValidItem(
Collection<Integer> localizedNullPositionsInFebruary2019,
Collection<Integer> localizedNonNullPositionsInFebruary2019) {
for (int position : localizedNullPositionsInFebruary2019) {
assertNull(monthFeb2019.getItem(position));
}
for (int position : localizedNonNullPositionsInFebruary2019) {
assertNotNull(monthFeb2019.getItem(position));
}
}
@Test
public void usDaysOfPositions() {
setupLocalizedCalendars(Locale.US);
Map<Integer, Integer> localizedDaysOfPositionsInFebruary2019 = new HashMap<>();
localizedDaysOfPositionsInFebruary2019.put(6, 2);
localizedDaysOfPositionsInFebruary2019.put(32, 28);
assertDaysOfPositions(localizedDaysOfPositionsInFebruary2019);
}
@Test
public void frDaysOfPositions() {
setupLocalizedCalendars(Locale.FRANCE);
Map<Integer, Integer> localizedDaysOfPositionsInFebruary2019 = new HashMap<>();
localizedDaysOfPositionsInFebruary2019.put(6, 3);
localizedDaysOfPositionsInFebruary2019.put(31, 28);
assertDaysOfPositions(localizedDaysOfPositionsInFebruary2019);
}
@Test
public void ilDaysOfPositions() {
setupLocalizedCalendars(ISRAEL);
Map<Integer, Integer> localizedDaysOfPositionsInFebruary2019 = new HashMap<>();
localizedDaysOfPositionsInFebruary2019.put(6, 2);
localizedDaysOfPositionsInFebruary2019.put(32, 28);
assertDaysOfPositions(localizedDaysOfPositionsInFebruary2019);
}
private void assertDaysOfPositions(Map<Integer, Integer> localizedDaysOfPositionsInFebruary2019) {
for (int day : localizedDaysOfPositionsInFebruary2019.keySet()) {
assertEquals(
(int) localizedDaysOfPositionsInFebruary2019.get(day),
monthFeb2019.getItem(day).get(Calendar.DAY_OF_MONTH));
}
}
@Test
public void rowIds() {
setupLocalizedCalendars(Locale.FRANCE);
assertEquals(0, monthFeb2019.getItemId(0));
assertEquals(1, monthFeb2019.getItemId(7));
assertEquals(3, monthFeb2019.getItemId(26));
assertEquals(5, monthMarch2019.getItemId(35));
}
}
|
package org.stjs.generator.writer.specialMethods;
import static org.stjs.javascript.JSCollections.$map;
import org.stjs.javascript.Map;
public class SpecialMethod12 {
public void method() {
Map<String, Object> obj = $map();
obj.$get("a");
}
}
|
package WaTor;
import cellsociety.Controller;
import cellsociety.FileReader.ReadCSVFile;
import cellsociety.Models.CellModel;
import cellsociety.Models.GridModels.GridData;
import cellsociety.Models.GridModels.GridDataArray;
import cellsociety.Models.GridModels.GridModel;
import cellsociety.Views.GridView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.stage.Stage;
//import util.DukeApplicationTest;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import util.DukeTest;
public class WaTorTest3 extends DukeTest {
private Controller test1GameofLifeController;
private ReadCSVFile thisFileReader;
private GridData thisGridData;
@Override
public void start(Stage stage) throws IOException {
thisFileReader = new ReadCSVFile("Examples/WaTor/Test3.csv");
thisGridData = new GridDataArray(thisFileReader.getGrid());
test1GameofLifeController = new Controller();
test1GameofLifeController.PROPERTIES_FILE = "WaTor/WaTor3.properties";
test1GameofLifeController.start(new Stage());
}
private boolean aresame(int[][] a,int[][] b){
for(int i = 0;i<a.length;i++){
for(int j=0; i<b[0].length;i++){
if(a[i][j]!=b[i][j]){
return false;
}
}
}
return true;
}
//test reading the file
@Test
public void testFile() throws IOException {
assertEquals(0,thisFileReader.getGrid()[0][0]);
int[][] testArray = {{0,2,0,0},{0,2,1,1},{2,0,2,1},{1,0,0,0}};
assertTrue(aresame(testArray,thisFileReader.getGrid()));
}
//check that the Grid Data class is holding the data correctly
@Test
public void testGridData() throws IOException {
//check cells in grid have proper values
CellModel testCell = new CellModel(0);
assertEquals(testCell.getState(),thisGridData.getCell(0,0).getState());
assertEquals(testCell.getInfo(),thisGridData.getCell(0,0).getInfo());
//test that the neighbors are correctly found using "Surrounding"
List<Integer> knownNeighbors = new ArrayList<Integer>(Arrays.asList(0,1,0,0,0,2,0,2));
List<CellModel> testNeighbors= thisGridData.getNeighbors(1,1,"Surrounding", "Finite");
for(int i=0; i<testNeighbors.size();i++){
assertEquals(knownNeighbors.get(i),testNeighbors.get(i).getState());
}
//test that the neighbors are correctly found using "adjacent"
List<Integer> knownNeighbors2 = new ArrayList<Integer>(Arrays.asList(1,0,0,0));
List<CellModel> testNeighbors2= thisGridData.getNeighbors(1,1,"Adjacent", "Finite");
for(int i=0; i<testNeighbors2.size();i++){
assertEquals(knownNeighbors2.get(i),testNeighbors2.get(i).getState());
}
//test The functions in the Grid Data Array class dimensions
assertEquals(4,thisGridData.getColCount());
assertEquals(4,thisGridData.getRowCount());
//setters
assertEquals(0,thisGridData.getCell(0,0).getState());
thisGridData.setCell(0,0,1);
assertEquals(1,thisGridData.getCell(0,0).getState());
}
@Test
public void testGridModel() throws IOException {
javafxRun(() -> {
try {
test1GameofLifeController.restartSimulationWithNewProp("WaTor/WaTor3.properties");
} catch (IOException e) {
e.printStackTrace();
}
});
GridModel thisGridModel = test1GameofLifeController.getGridOfCells();
assertEquals(0, thisGridModel.getCell(0,0).getState());
assertEquals(1, thisGridModel.getCell(0,1).getState());
assertEquals(0, thisGridModel.getCell(0,2).getState());
assertEquals(0, thisGridModel.getCell(0,3).getState());
assertEquals(0, thisGridModel.getCell(1,0).getState());
assertEquals(2, thisGridModel.getCell(1,1).getState());
assertEquals(0, thisGridModel.getCell(1,2).getState());
assertEquals(0, thisGridModel.getCell(1,3).getState());
assertEquals(2, thisGridModel.getCell(2,0).getState());
assertEquals(0, thisGridModel.getCell(2,1).getState());
assertEquals(2, thisGridModel.getCell(2,2).getState());
assertEquals(1, thisGridModel.getCell(2,3).getState());
assertEquals(1, thisGridModel.getCell(3,0).getState());
assertEquals(0, thisGridModel.getCell(3,1).getState());
assertEquals(0, thisGridModel.getCell(3,2).getState());
assertEquals(0, thisGridModel.getCell(3,3).getState());
javafxRun(() -> test1GameofLifeController.step());
assertEquals(1, thisGridModel.getCell(0,0).getState());
assertEquals(2, thisGridModel.getCell(0,1).getState());
assertEquals(0, thisGridModel.getCell(0,2).getState());
assertEquals(0, thisGridModel.getCell(0,3).getState());
assertEquals(0, thisGridModel.getCell(1,0).getState());
assertEquals(0, thisGridModel.getCell(1,1).getState());
assertEquals(0, thisGridModel.getCell(1,2).getState());
assertEquals(2, thisGridModel.getCell(1,3).getState());
assertEquals(2, thisGridModel.getCell(2,0).getState());
assertEquals(0, thisGridModel.getCell(2,1).getState());
assertEquals(0, thisGridModel.getCell(2,2).getState());
assertEquals(0, thisGridModel.getCell(2,3).getState());
assertEquals(0, thisGridModel.getCell(3,0).getState());
assertEquals(0, thisGridModel.getCell(3,1).getState());
assertEquals(0, thisGridModel.getCell(3,2).getState());
assertEquals(0, thisGridModel.getCell(3,3).getState());
}
@Test
public void testGridView() throws IOException {
javafxRun(() -> {
try {
test1GameofLifeController.restartSimulationWithNewProp("WaTor/WaTor3.properties");
} catch (IOException e) {
e.printStackTrace();
}
});
Paint water = Color.BLUE;
Paint fish = Color.GREEN;
Paint shark = Color.PINK;
GridView thisGridView = test1GameofLifeController.getGridView();
assertEquals(water, thisGridView.getRectangle(0,0).getFill());
assertEquals(fish, thisGridView.getRectangle(0,1).getFill());
assertEquals(water, thisGridView.getRectangle(0,2).getFill());
assertEquals(water, thisGridView.getRectangle(0,3).getFill());
assertEquals(water, thisGridView.getRectangle(1,0).getFill());
assertEquals(shark, thisGridView.getRectangle(1,1).getFill());
assertEquals(water, thisGridView.getRectangle(1,2).getFill());
assertEquals(water, thisGridView.getRectangle(1,3).getFill());
assertEquals(shark, thisGridView.getRectangle(2,0).getFill());
assertEquals(water, thisGridView.getRectangle(2,1).getFill());
assertEquals(shark, thisGridView.getRectangle(2,2).getFill());
assertEquals(fish, thisGridView.getRectangle(2,3).getFill());
assertEquals(fish, thisGridView.getRectangle(3,0).getFill());
assertEquals(water, thisGridView.getRectangle(3,1).getFill());
assertEquals(water, thisGridView.getRectangle(3,2).getFill());
assertEquals(water, thisGridView.getRectangle(3,3).getFill());
javafxRun(() -> test1GameofLifeController.step());
assertEquals(fish, thisGridView.getRectangle(0,0).getFill());
assertEquals(shark, thisGridView.getRectangle(0,1).getFill());
assertEquals(water, thisGridView.getRectangle(0,2).getFill());
assertEquals(water, thisGridView.getRectangle(0,3).getFill());
assertEquals(water, thisGridView.getRectangle(1,0).getFill());
assertEquals(water, thisGridView.getRectangle(1,1).getFill());
assertEquals(water, thisGridView.getRectangle(1,2).getFill());
assertEquals(shark, thisGridView.getRectangle(1,3).getFill());
assertEquals(shark, thisGridView.getRectangle(2,0).getFill());
assertEquals(water, thisGridView.getRectangle(2,1).getFill());
assertEquals(water, thisGridView.getRectangle(2,2).getFill());
assertEquals(water, thisGridView.getRectangle(2,3).getFill());
assertEquals(water, thisGridView.getRectangle(3,0).getFill());
assertEquals(water, thisGridView.getRectangle(3,1).getFill());
assertEquals(water, thisGridView.getRectangle(3,2).getFill());
assertEquals(water, thisGridView.getRectangle(3,3).getFill());
}
}
|
package com.hibernate.model;
import java.util.Date;
public class Employee {
private int id;
private String name;
private String role;
private Date insertTime;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public Date getInsertTime() {
return insertTime;
}
public void setInsertTime(Date insertTime) {
this.insertTime = insertTime;
}
}
|
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.services.resources.account;
import org.jboss.logging.Logger;
import org.jboss.resteasy.spi.HttpRequest;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.keycloak.events.EventBuilder;
import org.keycloak.models.ClientModel;
import org.keycloak.models.Constants;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.services.managers.AppAuthManager;
import org.keycloak.services.managers.Auth;
import org.keycloak.services.managers.AuthenticationManager;
import org.keycloak.theme.Theme;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.util.List;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/
public class AccountLoader {
private static final Logger logger = Logger.getLogger(AccountLoader.class);
public Object getAccountService(KeycloakSession session, EventBuilder event) {
RealmModel realm = session.getContext().getRealm();
ClientModel client = realm.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID);
if (client == null || !client.isEnabled()) {
logger.debug("account management not enabled");
throw new NotFoundException("account management not enabled");
}
HttpRequest request = session.getContext().getContextObject(HttpRequest.class);
HttpHeaders headers = session.getContext().getRequestHeaders();
MediaType content = headers.getMediaType();
List<MediaType> accepts = headers.getAcceptableMediaTypes();
Theme theme = getTheme(session);
boolean deprecatedAccount = isDeprecatedFormsAccountConsole(theme);
if (request.getHttpMethod().equals(HttpMethod.OPTIONS)) {
return new CorsPreflightService(request);
} else if ((accepts.contains(MediaType.APPLICATION_JSON_TYPE) || MediaType.APPLICATION_JSON_TYPE.equals(content)) && !request.getUri().getPath().endsWith("keycloak.json")) {
AuthenticationManager.AuthResult authResult = new AppAuthManager().authenticateBearerToken(session);
if (authResult == null) {
throw new NotAuthorizedException("Bearer token required");
}
Auth auth = new Auth(session.getContext().getRealm(), authResult.getToken(), authResult.getUser(), client, authResult.getSession(), false);
AccountRestService accountRestService = new AccountRestService(session, auth, client, event);
ResteasyProviderFactory.getInstance().injectProperties(accountRestService);
accountRestService.init();
return accountRestService;
} else {
if (deprecatedAccount) {
AccountFormService accountFormService = new AccountFormService(realm, client, event);
ResteasyProviderFactory.getInstance().injectProperties(accountFormService);
accountFormService.init();
return accountFormService;
} else {
AccountConsole console = new AccountConsole(realm, client, theme);
ResteasyProviderFactory.getInstance().injectProperties(console);
console.init();
return console;
}
}
}
private Theme getTheme(KeycloakSession session) {
try {
return session.theme().getTheme(Theme.Type.ACCOUNT);
} catch (IOException e) {
throw new InternalServerErrorException(e);
}
}
private boolean isDeprecatedFormsAccountConsole(Theme theme) {
try {
return Boolean.parseBoolean(theme.getProperties().getProperty("deprecatedMode", "true"));
} catch (IOException e) {
throw new InternalServerErrorException(e);
}
}
}
|
package cn.cerc.jdb.mongo;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import com.mongodb.client.MongoDatabase;
import cn.cerc.jdb.core.IConfig;
public class MongoConnectionTest {
private MongoConnection conn = new MongoConnection();
@Before
public void setUp() throws Exception {
conn.setConfig(new IConfig() {
@Override
public String getProperty(String key, String def) {
if (MongoSession.mgdb_site.equals(key))
return "127.0.0.1:3717";
if (MongoSession.mgdb_password.equals(key))
return "password";
if (MongoSession.mgdb_username.equals(key))
return "root";
if (MongoSession.mgdb_dbname.equals(key))
return "admin";
return null;
}
@Override
public String getProperty(String key) {
return getProperty(key, null);
}
});
}
@Test
@Ignore
public void test() {
conn.init();
MongoSession sess = conn.getSession();
MongoDatabase db = sess.getDatabase();
db.createCollection("temp");
System.err.println(db.getName());
}
}
|
/*
* Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.map.impl.proxy;
import com.hazelcast.aggregation.Aggregator;
import com.hazelcast.config.MapConfig;
import com.hazelcast.core.EntryListener;
import com.hazelcast.core.EntryView;
import com.hazelcast.core.ExecutionCallback;
import com.hazelcast.core.HazelcastException;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.ICompletableFuture;
import com.hazelcast.core.IMap;
import com.hazelcast.core.ManagedContext;
import com.hazelcast.internal.journal.EventJournalInitialSubscriberState;
import com.hazelcast.internal.journal.EventJournalReader;
import com.hazelcast.internal.util.SimpleCompletedFuture;
import com.hazelcast.map.EntryProcessor;
import com.hazelcast.map.MapInterceptor;
import com.hazelcast.map.QueryCache;
import com.hazelcast.map.impl.MapService;
import com.hazelcast.map.impl.SimpleEntryView;
import com.hazelcast.map.impl.iterator.MapPartitionIterator;
import com.hazelcast.map.impl.iterator.MapQueryPartitionIterator;
import com.hazelcast.map.impl.journal.MapEventJournalReadOperation;
import com.hazelcast.map.impl.journal.MapEventJournalSubscribeOperation;
import com.hazelcast.map.impl.query.AggregationResult;
import com.hazelcast.map.impl.query.QueryResult;
import com.hazelcast.map.impl.query.Target;
import com.hazelcast.map.impl.querycache.QueryCacheContext;
import com.hazelcast.map.impl.querycache.subscriber.NodeQueryCacheEndToEndConstructor;
import com.hazelcast.map.impl.querycache.subscriber.QueryCacheEndToEndProvider;
import com.hazelcast.map.impl.querycache.subscriber.QueryCacheRequest;
import com.hazelcast.map.impl.querycache.subscriber.SubscriberContext;
import com.hazelcast.map.journal.EventJournalMapEvent;
import com.hazelcast.map.listener.MapListener;
import com.hazelcast.map.listener.MapPartitionLostListener;
import com.hazelcast.mapreduce.Collator;
import com.hazelcast.mapreduce.CombinerFactory;
import com.hazelcast.mapreduce.Job;
import com.hazelcast.mapreduce.JobTracker;
import com.hazelcast.mapreduce.KeyValueSource;
import com.hazelcast.mapreduce.Mapper;
import com.hazelcast.mapreduce.MappingJob;
import com.hazelcast.mapreduce.ReducerFactory;
import com.hazelcast.mapreduce.ReducingSubmittableJob;
import com.hazelcast.mapreduce.aggregation.Aggregation;
import com.hazelcast.mapreduce.aggregation.Supplier;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.projection.Projection;
import com.hazelcast.query.PagingPredicate;
import com.hazelcast.query.Predicate;
import com.hazelcast.query.TruePredicate;
import com.hazelcast.ringbuffer.ReadResultSet;
import com.hazelcast.spi.InternalCompletableFuture;
import com.hazelcast.spi.NodeEngine;
import com.hazelcast.spi.Operation;
import com.hazelcast.util.CollectionUtil;
import com.hazelcast.util.IterationType;
import com.hazelcast.util.executor.DelegatingFuture;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static com.hazelcast.config.InMemoryFormat.NATIVE;
import static com.hazelcast.internal.cluster.Versions.V3_11;
import static com.hazelcast.map.impl.MapService.SERVICE_NAME;
import static com.hazelcast.map.impl.query.QueryResultUtils.transformToSet;
import static com.hazelcast.map.impl.querycache.subscriber.QueryCacheRequest.newQueryCacheRequest;
import static com.hazelcast.map.impl.recordstore.RecordStore.DEFAULT_MAX_IDLE;
import static com.hazelcast.util.ExceptionUtil.rethrow;
import static com.hazelcast.util.MapUtil.createHashMap;
import static com.hazelcast.util.Preconditions.checkNoNullInside;
import static com.hazelcast.util.Preconditions.checkNotInstanceOf;
import static com.hazelcast.util.Preconditions.checkNotNull;
import static com.hazelcast.util.Preconditions.checkPositive;
import static com.hazelcast.util.Preconditions.checkTrue;
import static com.hazelcast.util.Preconditions.isNotNull;
import static com.hazelcast.util.SetUtil.createHashSet;
import static java.util.Collections.emptyMap;
/**
* Proxy implementation of {@link com.hazelcast.core.IMap} interface.
*
* @param <K> the key type of map.
* @param <V> the value type of map.
*/
@SuppressWarnings("checkstyle:classfanoutcomplexity")
public class MapProxyImpl<K, V> extends MapProxySupport<K, V> implements EventJournalReader<EventJournalMapEvent<K, V>> {
public MapProxyImpl(String name, MapService mapService, NodeEngine nodeEngine, MapConfig mapConfig) {
super(name, mapService, nodeEngine, mapConfig);
}
@Override
public V get(Object key) {
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
return toObject(getInternal(key));
}
@Override
public V put(K key, V value) {
return put(key, value, -1, TimeUnit.MILLISECONDS);
}
@Override
public V put(K key, V value, long ttl, TimeUnit timeunit) {
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED);
Data valueData = toData(value);
Data result = putInternal(key, valueData, ttl, timeunit, DEFAULT_MAX_IDLE, TimeUnit.MILLISECONDS);
return toObject(result);
}
@Override
public V put(K key, V value, long ttl, TimeUnit ttlUnit, long maxIdle, TimeUnit maxIdleUnit) {
if (isClusterVersionLessThan(V3_11)) {
throw new UnsupportedOperationException("put with Max-Idle operation is available "
+ "when cluster version is 3.11 or higher");
}
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED);
Data valueData = toData(value);
Data result = putInternal(key, valueData, ttl, ttlUnit, maxIdle, maxIdleUnit);
return toObject(result);
}
@Override
public boolean tryPut(K key, V value, long timeout, TimeUnit timeunit) {
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED);
Data valueData = toData(value);
return tryPutInternal(key, valueData, timeout, timeunit);
}
@Override
public V putIfAbsent(K key, V value) {
return putIfAbsent(key, value, -1, TimeUnit.MILLISECONDS);
}
@Override
public V putIfAbsent(K key, V value, long ttl, TimeUnit timeunit) {
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED);
Data valueData = toData(value);
Data result = putIfAbsentInternal(key, valueData, ttl, timeunit, DEFAULT_MAX_IDLE, TimeUnit.MILLISECONDS);
return toObject(result);
}
@Override
public V putIfAbsent(K key, V value, long ttl, TimeUnit timeunit, long maxIdle, TimeUnit maxIdleUnit) {
if (isClusterVersionLessThan(V3_11)) {
throw new UnsupportedOperationException("putIfAbsent with Max-Idle operation is available "
+ "when cluster version is 3.11 or higher");
}
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED);
Data valueData = toData(value);
Data result = putIfAbsentInternal(key, valueData, ttl, timeunit, maxIdle, maxIdleUnit);
return toObject(result);
}
@Override
public void putTransient(K key, V value, long ttl, TimeUnit timeunit) {
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED);
Data valueData = toData(value);
putTransientInternal(key, valueData, ttl, timeunit, DEFAULT_MAX_IDLE, TimeUnit.MILLISECONDS);
}
@Override
public void putTransient(K key, V value, long ttl, TimeUnit ttlUnit, long maxIdle, TimeUnit maxIdleUnit) {
if (isClusterVersionLessThan(V3_11)) {
throw new UnsupportedOperationException("putTransient with Max-Idle operation is available "
+ "when cluster version is 3.11 or higher");
}
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED);
Data valueData = toData(value);
putTransientInternal(key, valueData, ttl, ttlUnit, maxIdle, maxIdleUnit);
}
@Override
public boolean replace(K key, V oldValue, V newValue) {
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
checkNotNull(oldValue, NULL_VALUE_IS_NOT_ALLOWED);
checkNotNull(newValue, NULL_VALUE_IS_NOT_ALLOWED);
Data oldValueData = toData(oldValue);
Data newValueData = toData(newValue);
return replaceInternal(key, oldValueData, newValueData);
}
@Override
public V replace(K key, V value) {
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED);
Data valueData = toData(value);
return toObject(replaceInternal(key, valueData));
}
@Override
public void set(K key, V value) {
set(key, value, -1, TimeUnit.MILLISECONDS);
}
@Override
public void set(K key, V value, long ttl, TimeUnit ttlUnit) {
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED);
Data valueData = toData(value);
setInternal(key, valueData, ttl, ttlUnit, DEFAULT_MAX_IDLE, TimeUnit.MILLISECONDS);
}
@Override
public void set(K key, V value, long ttl, TimeUnit ttlUnit, long maxIdle, TimeUnit maxIdleUnit) {
if (isClusterVersionLessThan(V3_11)) {
throw new UnsupportedOperationException("set with Max-Idle operation is available "
+ "when cluster version is 3.11 or higher");
}
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED);
Data valueData = toData(value);
setInternal(key, valueData, ttl, ttlUnit, maxIdle, maxIdleUnit);
}
@Override
public V remove(Object key) {
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
Data result = removeInternal(key);
return toObject(result);
}
@Override
public boolean remove(Object key, Object value) {
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED);
Data valueData = toData(value);
return removeInternal(key, valueData);
}
@Override
public void removeAll(Predicate<K, V> predicate) {
checkNotNull(predicate, "predicate cannot be null");
handleHazelcastInstanceAwareParams(predicate);
removeAllInternal(predicate);
}
@Override
public void delete(Object key) {
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
deleteInternal(key);
}
@Override
public boolean containsKey(Object key) {
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
return containsKeyInternal(key);
}
@Override
public boolean containsValue(Object value) {
checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED);
Data valueData = toData(value);
return containsValueInternal(valueData);
}
@Override
public void lock(K key) {
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
Data keyData = toDataWithStrategy(key);
lockSupport.lock(getNodeEngine(), keyData);
}
@Override
public void lock(Object key, long leaseTime, TimeUnit timeUnit) {
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
checkPositive(leaseTime, "leaseTime should be positive");
Data keyData = toDataWithStrategy(key);
lockSupport.lock(getNodeEngine(), keyData, timeUnit.toMillis(leaseTime));
}
@Override
public void unlock(K key) {
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
Data keyData = toDataWithStrategy(key);
lockSupport.unlock(getNodeEngine(), keyData);
}
@Override
public boolean tryRemove(K key, long timeout, TimeUnit timeunit) {
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
return tryRemoveInternal(key, timeout, timeunit);
}
@Override
public ICompletableFuture<V> getAsync(K key) {
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
return new DelegatingFuture<V>(getAsyncInternal(key), serializationService);
}
@Override
public boolean isLocked(K key) {
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
Data keyData = toDataWithStrategy(key);
return lockSupport.isLocked(getNodeEngine(), keyData);
}
@Override
public ICompletableFuture<V> putAsync(K key, V value) {
return putAsync(key, value, -1, TimeUnit.MILLISECONDS);
}
@Override
public ICompletableFuture<V> putAsync(K key, V value, long ttl, TimeUnit timeunit) {
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED);
Data valueData = toData(value);
return new DelegatingFuture<V>(
putAsyncInternal(key, valueData, ttl, timeunit, DEFAULT_MAX_IDLE, TimeUnit.MILLISECONDS),
serializationService);
}
@Override
public ICompletableFuture<V> putAsync(K key, V value, long ttl, TimeUnit ttlUnit, long maxIdle, TimeUnit maxIdleUnit) {
if (isClusterVersionLessThan(V3_11)) {
throw new UnsupportedOperationException("putAsync with Max-Idle operation is available "
+ "when cluster version is 3.11 or higher");
}
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED);
Data valueData = toData(value);
return new DelegatingFuture<V>(
putAsyncInternal(key, valueData, ttl, ttlUnit, maxIdle, maxIdleUnit),
serializationService);
}
@Override
public ICompletableFuture<Void> setAsync(K key, V value) {
return setAsync(key, value, -1, TimeUnit.MILLISECONDS);
}
@Override
public ICompletableFuture<Void> setAsync(K key, V value, long ttl, TimeUnit timeunit) {
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED);
Data valueData = toData(value);
return new DelegatingFuture<Void>(
setAsyncInternal(key, valueData, ttl, timeunit, DEFAULT_MAX_IDLE, TimeUnit.MILLISECONDS),
serializationService);
}
@Override
public ICompletableFuture<Void> setAsync(K key, V value, long ttl, TimeUnit ttlUnit, long maxIdle, TimeUnit maxIdleUnit) {
if (isClusterVersionLessThan(V3_11)) {
throw new UnsupportedOperationException("setAsync with Max-Idle operation is available "
+ "when cluster version is 3.11 or higher");
}
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED);
Data valueData = toData(value);
return new DelegatingFuture<Void>(
setAsyncInternal(key, valueData, ttl, ttlUnit, maxIdle, maxIdleUnit),
serializationService);
}
@Override
public ICompletableFuture<V> removeAsync(K key) {
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
return new DelegatingFuture<V>(removeAsyncInternal(key), serializationService);
}
@Override
public Map<K, V> getAll(Set<K> keys) {
if (CollectionUtil.isEmpty(keys)) {
return emptyMap();
}
int keysSize = keys.size();
List<Data> dataKeys = new LinkedList<Data>();
List<Object> resultingKeyValuePairs = new ArrayList<Object>(keysSize * 2);
getAllInternal(keys, dataKeys, resultingKeyValuePairs);
Map<K, V> result = createHashMap(keysSize);
for (int i = 0; i < resultingKeyValuePairs.size(); ) {
K key = toObject(resultingKeyValuePairs.get(i++));
V value = toObject(resultingKeyValuePairs.get(i++));
result.put(key, value);
}
return result;
}
@Override
public boolean setTtl(K key, long ttl, TimeUnit timeunit) {
checkNotNull(key);
checkNotNull(timeunit);
return setTtlInternal(key, ttl, timeunit);
}
@Override
public void putAll(Map<? extends K, ? extends V> map) {
checkNotNull(map, "Null argument map is not allowed");
putAllInternal(map);
}
@Override
public boolean tryLock(K key) {
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
Data keyData = toDataWithStrategy(key);
return lockSupport.tryLock(getNodeEngine(), keyData);
}
@Override
public boolean tryLock(K key, long time, TimeUnit timeunit) throws InterruptedException {
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
Data keyData = toDataWithStrategy(key);
return lockSupport.tryLock(getNodeEngine(), keyData, time, timeunit);
}
@Override
public boolean tryLock(K key, long time, TimeUnit timeunit, long leaseTime, TimeUnit leaseTimeUnit)
throws InterruptedException {
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
Data keyData = toDataWithStrategy(key);
return lockSupport.tryLock(getNodeEngine(), keyData, time, timeunit, leaseTime, leaseTimeUnit);
}
@Override
public void forceUnlock(K key) {
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
Data keyData = toDataWithStrategy(key);
lockSupport.forceUnlock(getNodeEngine(), keyData);
}
@Override
public String addInterceptor(MapInterceptor interceptor) {
checkNotNull(interceptor, "Interceptor should not be null!");
handleHazelcastInstanceAwareParams(interceptor);
return addMapInterceptorInternal(interceptor);
}
@Override
public void removeInterceptor(String id) {
checkNotNull(id, "Interceptor ID should not be null!");
removeMapInterceptorInternal(id);
}
@Override
public String addLocalEntryListener(MapListener listener) {
checkNotNull(listener, NULL_LISTENER_IS_NOT_ALLOWED);
handleHazelcastInstanceAwareParams(listener);
return addLocalEntryListenerInternal(listener);
}
@Override
public String addLocalEntryListener(EntryListener listener) {
checkNotNull(listener, NULL_LISTENER_IS_NOT_ALLOWED);
handleHazelcastInstanceAwareParams(listener);
return addLocalEntryListenerInternal(listener);
}
@Override
public String addLocalEntryListener(MapListener listener, Predicate<K, V> predicate, boolean includeValue) {
checkNotNull(listener, NULL_LISTENER_IS_NOT_ALLOWED);
checkNotNull(predicate, NULL_PREDICATE_IS_NOT_ALLOWED);
handleHazelcastInstanceAwareParams(listener, predicate);
return addLocalEntryListenerInternal(listener, predicate, null, includeValue);
}
@Override
public String addLocalEntryListener(EntryListener listener, Predicate<K, V> predicate, boolean includeValue) {
checkNotNull(listener, NULL_LISTENER_IS_NOT_ALLOWED);
checkNotNull(predicate, NULL_PREDICATE_IS_NOT_ALLOWED);
handleHazelcastInstanceAwareParams(listener, predicate);
return addLocalEntryListenerInternal(listener, predicate, null, includeValue);
}
@Override
public String addLocalEntryListener(MapListener listener, Predicate<K, V> predicate, K key, boolean includeValue) {
checkNotNull(listener, NULL_LISTENER_IS_NOT_ALLOWED);
checkNotNull(predicate, NULL_PREDICATE_IS_NOT_ALLOWED);
handleHazelcastInstanceAwareParams(listener, predicate);
return addLocalEntryListenerInternal(listener, predicate, toDataWithStrategy(key), includeValue);
}
@Override
public String addLocalEntryListener(EntryListener listener, Predicate<K, V> predicate, K key, boolean includeValue) {
checkNotNull(listener, NULL_LISTENER_IS_NOT_ALLOWED);
checkNotNull(predicate, NULL_PREDICATE_IS_NOT_ALLOWED);
handleHazelcastInstanceAwareParams(listener, predicate);
return addLocalEntryListenerInternal(listener, predicate, toDataWithStrategy(key), includeValue);
}
@Override
public String addEntryListener(MapListener listener, boolean includeValue) {
checkNotNull(listener, NULL_LISTENER_IS_NOT_ALLOWED);
handleHazelcastInstanceAwareParams(listener);
return addEntryListenerInternal(listener, null, includeValue);
}
@Override
public String addEntryListener(EntryListener listener, boolean includeValue) {
checkNotNull(listener, NULL_LISTENER_IS_NOT_ALLOWED);
handleHazelcastInstanceAwareParams(listener);
return addEntryListenerInternal(listener, null, includeValue);
}
@Override
public String addEntryListener(MapListener listener, K key, boolean includeValue) {
checkNotNull(listener, NULL_LISTENER_IS_NOT_ALLOWED);
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
handleHazelcastInstanceAwareParams(listener);
return addEntryListenerInternal(listener, toDataWithStrategy(key), includeValue);
}
@Override
public String addEntryListener(EntryListener listener, K key, boolean includeValue) {
checkNotNull(listener, NULL_LISTENER_IS_NOT_ALLOWED);
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
handleHazelcastInstanceAwareParams(listener);
return addEntryListenerInternal(listener, toDataWithStrategy(key), includeValue);
}
@Override
public String addEntryListener(MapListener listener, Predicate<K, V> predicate, K key, boolean includeValue) {
checkNotNull(listener, NULL_LISTENER_IS_NOT_ALLOWED);
checkNotNull(predicate, NULL_PREDICATE_IS_NOT_ALLOWED);
handleHazelcastInstanceAwareParams(listener, predicate);
return addEntryListenerInternal(listener, predicate, toDataWithStrategy(key), includeValue);
}
@Override
public String addEntryListener(EntryListener listener, Predicate<K, V> predicate, K key, boolean includeValue) {
checkNotNull(listener, NULL_LISTENER_IS_NOT_ALLOWED);
checkNotNull(predicate, NULL_PREDICATE_IS_NOT_ALLOWED);
handleHazelcastInstanceAwareParams(listener, predicate);
return addEntryListenerInternal(listener, predicate, toDataWithStrategy(key), includeValue);
}
@Override
public String addEntryListener(MapListener listener, Predicate<K, V> predicate, boolean includeValue) {
checkNotNull(listener, NULL_LISTENER_IS_NOT_ALLOWED);
checkNotNull(predicate, NULL_PREDICATE_IS_NOT_ALLOWED);
handleHazelcastInstanceAwareParams(listener, predicate);
return addEntryListenerInternal(listener, predicate, null, includeValue);
}
@Override
public String addEntryListener(EntryListener listener, Predicate<K, V> predicate, boolean includeValue) {
checkNotNull(listener, NULL_LISTENER_IS_NOT_ALLOWED);
checkNotNull(predicate, NULL_PREDICATE_IS_NOT_ALLOWED);
handleHazelcastInstanceAwareParams(listener, predicate);
return addEntryListenerInternal(listener, predicate, null, includeValue);
}
@Override
public boolean removeEntryListener(String id) {
checkNotNull(id, "Listener ID should not be null!");
return removeEntryListenerInternal(id);
}
@Override
public String addPartitionLostListener(MapPartitionLostListener listener) {
checkNotNull(listener, NULL_LISTENER_IS_NOT_ALLOWED);
handleHazelcastInstanceAwareParams(listener);
return addPartitionLostListenerInternal(listener);
}
@Override
public boolean removePartitionLostListener(String id) {
checkNotNull(id, "Listener ID should not be null!");
return removePartitionLostListenerInternal(id);
}
@Override
@SuppressWarnings("unchecked")
public EntryView<K, V> getEntryView(K key) {
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
SimpleEntryView<K, V> entryViewInternal = (SimpleEntryView<K, V>) getEntryViewInternal(toDataWithStrategy(key));
if (entryViewInternal == null) {
return null;
}
Data value = (Data) entryViewInternal.getValue();
entryViewInternal.setKey(key);
entryViewInternal.setValue((V) toObject(value));
return entryViewInternal;
}
@Override
public boolean evict(Object key) {
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
return evictInternal(key);
}
@Override
public void evictAll() {
evictAllInternal();
}
@Override
public void loadAll(boolean replaceExistingValues) {
checkTrue(isMapStoreEnabled(), "First you should configure a map store");
loadAllInternal(replaceExistingValues);
}
@Override
public void loadAll(Set<K> keys, boolean replaceExistingValues) {
checkTrue(isMapStoreEnabled(), "First you should configure a map store");
checkNotNull(keys, NULL_KEYS_ARE_NOT_ALLOWED);
checkNoNullInside(keys, NULL_KEY_IS_NOT_ALLOWED);
loadInternal(keys, null, replaceExistingValues);
}
@Override
public void clear() {
clearInternal();
}
@Override
public Set<K> keySet() {
return keySet(TruePredicate.INSTANCE);
}
@Override
@SuppressWarnings("unchecked")
public Set<K> keySet(Predicate predicate) {
return executePredicate(predicate, IterationType.KEY, true);
}
@Override
public Set<Map.Entry<K, V>> entrySet() {
return entrySet(TruePredicate.INSTANCE);
}
@Override
public Set<Map.Entry<K, V>> entrySet(Predicate predicate) {
return executePredicate(predicate, IterationType.ENTRY, true);
}
@Override
public Collection<V> values() {
return values(TruePredicate.INSTANCE);
}
@Override
@SuppressWarnings("unchecked")
public Collection<V> values(Predicate predicate) {
return executePredicate(predicate, IterationType.VALUE, false);
}
private Set executePredicate(Predicate predicate, IterationType iterationType, boolean uniqueResult) {
checkNotNull(predicate, NULL_PREDICATE_IS_NOT_ALLOWED);
QueryResult result = executeQueryInternal(predicate, iterationType, Target.ALL_NODES);
return transformToSet(serializationService, result, predicate, iterationType, uniqueResult, false);
}
@Override
public Set<K> localKeySet() {
return localKeySet(TruePredicate.INSTANCE);
}
@Override
@SuppressWarnings("unchecked")
public Set<K> localKeySet(Predicate predicate) {
checkNotNull(predicate, NULL_PREDICATE_IS_NOT_ALLOWED);
QueryResult result = executeQueryInternal(predicate, IterationType.KEY, Target.LOCAL_NODE);
return transformToSet(serializationService, result, predicate, IterationType.KEY, false, false);
}
@Override
public Object executeOnKey(K key, EntryProcessor entryProcessor) {
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
handleHazelcastInstanceAwareParams(entryProcessor);
Data result = executeOnKeyInternal(key, entryProcessor);
return toObject(result);
}
@Override
public Map<K, Object> executeOnKeys(Set<K> keys, EntryProcessor entryProcessor) {
try {
return submitToKeys(keys, entryProcessor).get();
} catch (Exception e) {
throw rethrow(e);
}
}
/**
* Async version of {@link #executeOnKeys}.
*/
public ICompletableFuture<Map<K, Object>> submitToKeys(Set<K> keys, EntryProcessor entryProcessor) {
checkNotNull(keys, NULL_KEYS_ARE_NOT_ALLOWED);
if (keys.isEmpty()) {
return new SimpleCompletedFuture<Map<K, Object>>(Collections.<K, Object>emptyMap());
}
handleHazelcastInstanceAwareParams(entryProcessor);
Set<Data> dataKeys = createHashSet(keys.size());
return submitToKeysInternal(keys, dataKeys, entryProcessor);
}
@Override
public void submitToKey(K key, EntryProcessor entryProcessor, ExecutionCallback callback) {
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
handleHazelcastInstanceAwareParams(entryProcessor, callback);
executeOnKeyInternal(key, entryProcessor, callback);
}
@Override
public ICompletableFuture submitToKey(K key, EntryProcessor entryProcessor) {
checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED);
handleHazelcastInstanceAwareParams(entryProcessor);
InternalCompletableFuture future = executeOnKeyInternal(key, entryProcessor, null);
return new DelegatingFuture(future, serializationService);
}
@Override
public Map<K, Object> executeOnEntries(EntryProcessor entryProcessor) {
return executeOnEntries(entryProcessor, TruePredicate.INSTANCE);
}
@Override
public Map<K, Object> executeOnEntries(EntryProcessor entryProcessor, Predicate predicate) {
handleHazelcastInstanceAwareParams(entryProcessor, predicate);
List<Data> result = new ArrayList<Data>();
executeOnEntriesInternal(entryProcessor, predicate, result);
if (result.isEmpty()) {
return emptyMap();
}
Map<K, Object> resultingMap = createHashMap(result.size() / 2);
for (int i = 0; i < result.size(); ) {
Data key = result.get(i++);
Data value = result.get(i++);
resultingMap.put((K) toObject(key), toObject(value));
}
return resultingMap;
}
@Override
public <R> R aggregate(Aggregator<Map.Entry<K, V>, R> aggregator) {
return aggregate(aggregator, TruePredicate.<K, V>truePredicate());
}
@Override
public <R> R aggregate(Aggregator<Map.Entry<K, V>, R> aggregator, Predicate<K, V> predicate) {
checkNotNull(aggregator, NULL_AGGREGATOR_IS_NOT_ALLOWED);
checkNotNull(predicate, NULL_PREDICATE_IS_NOT_ALLOWED);
checkNotPagingPredicate(predicate, "aggregate");
// HazelcastInstanceAware handled by cloning
aggregator = serializationService.toObject(serializationService.toData(aggregator));
AggregationResult result = executeQueryInternal(predicate, aggregator, null, IterationType.ENTRY, Target.ALL_NODES);
return result.<R>getAggregator().aggregate();
}
@Override
public <R> Collection<R> project(Projection<Map.Entry<K, V>, R> projection) {
return project(projection, TruePredicate.INSTANCE);
}
@Override
public <R> Collection<R> project(Projection<Map.Entry<K, V>, R> projection, Predicate<K, V> predicate) {
checkNotNull(projection, NULL_PROJECTION_IS_NOT_ALLOWED);
checkNotNull(predicate, NULL_PREDICATE_IS_NOT_ALLOWED);
checkNotPagingPredicate(predicate, "project");
// HazelcastInstanceAware handled by cloning
projection = serializationService.toObject(serializationService.toData(projection));
QueryResult result = executeQueryInternal(predicate, null, projection, IterationType.VALUE, Target.ALL_NODES);
return transformToSet(serializationService, result, predicate, IterationType.VALUE, false, false);
}
@Override
public <SuppliedValue, Result> Result aggregate(Supplier<K, V, SuppliedValue> supplier,
Aggregation<K, SuppliedValue, Result> aggregation) {
checkTrue(NATIVE != mapConfig.getInMemoryFormat(), "NATIVE storage format is not supported for MapReduce");
HazelcastInstance hazelcastInstance = getNodeEngine().getHazelcastInstance();
JobTracker jobTracker = hazelcastInstance.getJobTracker("hz::aggregation-map-" + getName());
return aggregate(supplier, aggregation, jobTracker);
}
@Override
public <SuppliedValue, Result> Result aggregate(Supplier<K, V, SuppliedValue> supplier,
Aggregation<K, SuppliedValue, Result> aggregation,
JobTracker jobTracker) {
checkTrue(NATIVE != mapConfig.getInMemoryFormat(), "NATIVE storage format is not supported for MapReduce");
try {
isNotNull(jobTracker, "jobTracker");
KeyValueSource<K, V> keyValueSource = KeyValueSource.fromMap(this);
Job<K, V> job = jobTracker.newJob(keyValueSource);
Mapper mapper = aggregation.getMapper(supplier);
CombinerFactory combinerFactory = aggregation.getCombinerFactory();
ReducerFactory reducerFactory = aggregation.getReducerFactory();
Collator collator = aggregation.getCollator();
MappingJob mappingJob = job.mapper(mapper);
ReducingSubmittableJob reducingJob;
if (combinerFactory == null) {
reducingJob = mappingJob.reducer(reducerFactory);
} else {
reducingJob = mappingJob.combiner(combinerFactory).reducer(reducerFactory);
}
ICompletableFuture<Result> future = reducingJob.submit(collator);
return future.get();
} catch (Exception e) {
// TODO: not what we want, because it can lead to wrapping of HazelcastException
throw new HazelcastException(e);
}
}
protected Object invoke(Operation operation, int partitionId) throws Throwable {
Future future = operationService.invokeOnPartition(SERVICE_NAME, operation, partitionId);
Object response = future.get();
Object result = toObject(response);
if (result instanceof Throwable) {
throw (Throwable) result;
}
return result;
}
/**
* Returns an iterator for iterating entries in the {@code partitionId}. If {@code prefetchValues} is
* {@code true}, values will be sent along with the keys and no additional data will be fetched when
* iterating. If {@code false}, only keys will be sent and values will be fetched when calling {@code
* Map.Entry.getValue()} lazily.
* <p>
* The entries are not fetched one-by-one but in batches.
* You may control the size of the batch by changing the {@code fetchSize} parameter.
* A too small {@code fetchSize} can affect performance since more data will have to be sent to and from the partition owner.
* A too high {@code fetchSize} means that more data will be sent which can block other operations from being sent,
* including internal operations.
* The underlying implementation may send more values in one batch than {@code fetchSize} if it needs to get to
* a "safepoint" to resume iteration later.
* <p>
* <b>NOTE</b>
* Iterating the map should be done only when the {@link IMap} is not being
* mutated and the cluster is stable (there are no migrations or membership changes).
* In other cases, the iterator may not return some entries or may return an entry twice.
*
* @param fetchSize the size of the batches which will be sent when iterating the data
* @param partitionId the partition ID which is being iterated
* @param prefetchValues whether to send values along with keys (if {@code true}) or
* to fetch them lazily when iterating (if {@code false})
* @return the iterator for the projected entries
*/
public Iterator<Entry<K, V>> iterator(int fetchSize, int partitionId, boolean prefetchValues) {
return new MapPartitionIterator<K, V>(this, fetchSize, partitionId, prefetchValues);
}
/**
* Returns an iterator for iterating the result of the projection on entries in the {@code partitionId} which
* satisfy the {@code predicate}.
* <p>
* The values are not fetched one-by-one but rather in batches.
* You may control the size of the batch by changing the {@code fetchSize} parameter.
* A too small {@code fetchSize} can affect performance since more data will have to be sent to and from the partition owner.
* A too high {@code fetchSize} means that more data will be sent which can block other operations from being sent,
* including internal operations.
* The underlying implementation may send more values in one batch than {@code fetchSize} if it needs to get to
* a "safepoint" to later resume iteration.
* Predicates of type {@link PagingPredicate} are not supported.
* <p>
* <b>NOTE</b>
* Iterating the map should be done only when the {@link IMap} is not being
* mutated and the cluster is stable (there are no migrations or membership changes).
* In other cases, the iterator may not return some entries or may return an entry twice.
*
* @param fetchSize the size of the batches which will be sent when iterating the data
* @param partitionId the partition ID which is being iterated
* @param projection the projection to apply before returning the value. {@code null} value is not allowed
* @param predicate the predicate which the entries must match. {@code null} value is not allowed
* @param <R> the return type
* @return the iterator for the projected entries
* @throws IllegalArgumentException if the predicate is of type {@link PagingPredicate}
* @since 3.9
*/
public <R> Iterator<R> iterator(int fetchSize, int partitionId, Projection<Map.Entry<K, V>, R> projection,
Predicate<K, V> predicate) {
if (predicate instanceof PagingPredicate) {
throw new IllegalArgumentException("Paging predicate is not allowed when iterating map by query");
}
checkNotNull(projection, NULL_PROJECTION_IS_NOT_ALLOWED);
checkNotNull(predicate, NULL_PREDICATE_IS_NOT_ALLOWED);
// HazelcastInstanceAware handled by cloning
projection = serializationService.toObject(serializationService.toData(projection));
handleHazelcastInstanceAwareParams(predicate);
return new MapQueryPartitionIterator<K, V, R>(this, fetchSize, partitionId, predicate, projection);
}
@Override
public ICompletableFuture<EventJournalInitialSubscriberState> subscribeToEventJournal(int partitionId) {
final MapEventJournalSubscribeOperation op = new MapEventJournalSubscribeOperation(name);
op.setPartitionId(partitionId);
return operationService.invokeOnPartition(op);
}
/**
* {@inheritDoc}
* <p>
* This implementation will skip cloning of the predicate and projection
* for performance reasons. Because of this, the results of the projection
* and predicate should not depend on any state that will be lost while
* cloning. If you wish to get rid of user state, you may clone the predicate
* and projection and keep them cached for all calls to this method to avoid
* the overhead of cloning.
*/
@Override
public <T> ICompletableFuture<ReadResultSet<T>> readFromEventJournal(
long startSequence,
int minSize,
int maxSize,
int partitionId,
com.hazelcast.util.function.Predicate<? super EventJournalMapEvent<K, V>> predicate,
Projection<? super EventJournalMapEvent<K, V>, ? extends T> projection) {
if (maxSize < minSize) {
throw new IllegalArgumentException("maxSize " + maxSize
+ " must be greater or equal to minSize " + minSize);
}
final ManagedContext context = serializationService.getManagedContext();
context.initialize(predicate);
context.initialize(projection);
final MapEventJournalReadOperation<K, V, T> op = new MapEventJournalReadOperation<K, V, T>(
name, startSequence, minSize, maxSize, predicate, projection);
op.setPartitionId(partitionId);
return operationService.invokeOnPartition(op);
}
@Override
public String toString() {
return "IMap{name='" + name + '\'' + '}';
}
@Override
public QueryCache<K, V> getQueryCache(String name) {
checkNotNull(name, "name cannot be null");
return getQueryCacheInternal(name, null, null, null, this);
}
@Override
public QueryCache<K, V> getQueryCache(String name, Predicate<K, V> predicate, boolean includeValue) {
checkNotNull(name, "name cannot be null");
checkNotNull(predicate, "predicate cannot be null");
checkNotInstanceOf(PagingPredicate.class, predicate, "predicate");
handleHazelcastInstanceAwareParams(predicate);
return getQueryCacheInternal(name, null, predicate, includeValue, this);
}
@Override
public QueryCache<K, V> getQueryCache(String name, MapListener listener, Predicate<K, V> predicate, boolean includeValue) {
checkNotNull(name, "name cannot be null");
checkNotNull(predicate, "predicate cannot be null");
checkNotInstanceOf(PagingPredicate.class, predicate, "predicate");
handleHazelcastInstanceAwareParams(listener, predicate);
return getQueryCacheInternal(name, listener, predicate, includeValue, this);
}
private QueryCache<K, V> getQueryCacheInternal(String name, MapListener listener, Predicate<K, V> predicate,
Boolean includeValue, IMap<K, V> map) {
QueryCacheContext queryCacheContext = mapServiceContext.getQueryCacheContext();
QueryCacheRequest request = newQueryCacheRequest()
.forMap(map)
.withCacheName(name)
.withListener(listener)
.withPredicate(predicate)
.withIncludeValue(includeValue)
.withContext(queryCacheContext);
return createQueryCache(request);
}
private QueryCache<K, V> createQueryCache(QueryCacheRequest request) {
QueryCacheContext queryCacheContext = request.getContext();
SubscriberContext subscriberContext = queryCacheContext.getSubscriberContext();
QueryCacheEndToEndProvider queryCacheEndToEndProvider = subscriberContext.getEndToEndQueryCacheProvider();
return queryCacheEndToEndProvider.getOrCreateQueryCache(request.getMapName(), request.getCacheName(),
new NodeQueryCacheEndToEndConstructor(request));
}
private static void checkNotPagingPredicate(Predicate predicate, String method) {
if (predicate instanceof PagingPredicate) {
throw new IllegalArgumentException("PagingPredicate not supported in " + method + " method");
}
}
}
|
/***** BEGIN LICENSE BLOCK *****
* Version: EPL 2.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Eclipse Public
* 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.eclipse.org/legal/epl-v20.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2002 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2002-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2004-2005 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2007 Miguel Covarrubias <mlcovarrubias@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the EPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the EPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby.internal.runtime.methods;
import org.jruby.RubyModule;
import org.jruby.RubyProc;
import org.jruby.runtime.ArgumentDescriptor;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.Helpers;
import org.jruby.runtime.PositionAware;
import org.jruby.runtime.Signature;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
/**
*
* @author jpetersen
*/
public class ProcMethod extends DynamicMethod implements PositionAware, IRMethodArgs {
private RubyProc proc;
/**
* Constructor for ProcMethod.
* @param visibility
*/
public ProcMethod(RubyModule implementationClass, RubyProc proc, Visibility visibility, String name) {
// FIXME: set up a call configuration for this
super(implementationClass, visibility, name);
this.proc = proc;
}
public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule klazz, String name, IRubyObject[] args, Block block) {
return proc.call(context, args, self, klazz, block);
}
public DynamicMethod dup() {
return new ProcMethod(getImplementationClass(), proc, getVisibility(), name);
}
// TODO: Push isSame up to DynamicMethod to simplify general equality
public boolean isSame(DynamicMethod method) {
if (!(method instanceof ProcMethod)) return false;
return ((ProcMethod) method).proc == proc;
}
@Override
public Arity getArity() {
return proc.getBlock().getSignature().arity();
}
public String getFile() {
return proc.getBlock().getBody().getFile();
}
public int getLine() {
return proc.getBlock().getBody().getLine();
}
@Override
public Signature getSignature() {
return proc.getBlock().getBody().getSignature();
}
@Override
public ArgumentDescriptor[] getArgumentDescriptors() {
return proc.getBlock().getBody().getArgumentDescriptors();
}
public RubyProc getProc() {
return proc;
}
}
|
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.customtabs;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowLooper;
import org.chromium.base.Callback;
import org.chromium.base.test.util.Feature;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.testing.local.LocalRobolectricTestRunner;
import java.util.concurrent.TimeUnit;
/**
* Tests for {@link NavigationInfoCaptureTrigger}.
*/
@RunWith(LocalRobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class NavigationInfoCaptureTriggerTest {
@Mock
private Callback<Tab> mDelegate;
private NavigationInfoCaptureTrigger mTrigger;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mTrigger = new NavigationInfoCaptureTrigger(mDelegate);
}
/**
* Tests the normal flow where onload is called, then first meaningful paint happens soon
* after. We want the capture to trigger after first meaningful paint.
*/
@Test
@Feature({"CustomTabs"})
public void testNormalFlow() {
mTrigger.onLoadFinished(null);
// If we run everything on the Looper, the backup onload capture will trigger. Therefore
// run long enough for the primary onload to trigger.
ShadowLooper.idleMainLooper(2, TimeUnit.SECONDS);
verify(mDelegate, times(0)).onResult(any());
mTrigger.onFirstMeaningfulPaint(null);
verifyCaptured(1);
mTrigger.onHide(null);
verifyCaptured(1);
}
/**
* Tests the flow where first meaningful paint is called before onload. The screen should only
* be captured once, after the first meaningful paint and onload.
*/
@Test
@Feature({"CustomTabs"})
public void testDelayedOnload() {
mTrigger.onFirstMeaningfulPaint(null);
verifyCaptured(0);
mTrigger.onLoadFinished(null);
verifyCaptured(1);
mTrigger.onHide(null);
verifyCaptured(1);
}
/**
* Tests the flow where first meaningful paint and onload don't occur and we capture during
* on hide as a backup.
*/
@Test
@Feature({"CustomTabs"})
public void testOnHide() {
mTrigger.onHide(null);
verifyCaptured(1);
}
/**
* Tests that the backup onload trigger works.
*/
@Test
@Feature({"CustomTabs"})
public void testBackupOnload() {
mTrigger.onLoadFinished(null);
ShadowLooper.idleMainLooper(2, TimeUnit.SECONDS);
verify(mDelegate, times(0)).onResult(any());
verifyCaptured(1);
}
/**
* Tests that pending capture tasks are cancelled when the page navigates.
*/
@Test
@Feature({"CustomTabs"})
public void testCancelOnNavigation() {
mTrigger.onLoadFinished(null);
mTrigger.onFirstMeaningfulPaint(null);
mTrigger.onNewNavigation();
verifyCaptured(0);
}
/**
* Tests that navigation resets the state.
*/
@Test
@Feature({"CustomTabs"})
@SuppressWarnings("unchecked")
public void testResetOnNavigation() {
testNormalFlow();
mTrigger.onNewNavigation();
clearInvocations(mDelegate); // Clears the mock so the verifies in the original test work.
testNormalFlow();
mTrigger.onNewNavigation();
clearInvocations(mDelegate);
testDelayedOnload();
}
/**
* Tests that we capture only on the first FMP.
*/
@Test
@Feature({"CustomTabs"})
public void testMultipleFmps() {
mTrigger.onLoadFinished(null);
mTrigger.onFirstMeaningfulPaint(null);
mTrigger.onFirstMeaningfulPaint(null);
verifyCaptured(1);
}
private void verifyCaptured(int times) {
ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
verify(mDelegate, times(times)).onResult(any());
}
}
|
package seedu.expensetracker.logic.parser;
//@@authoer winsonhys
import static seedu.expensetracker.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.expensetracker.logic.parser.CliSyntax.PREFIX_BUDGET;
import static seedu.expensetracker.logic.parser.CliSyntax.PREFIX_CATEGORY;
import static seedu.expensetracker.logic.parser.ParserUtil.arePrefixesPresent;
import seedu.expensetracker.logic.commands.SetCategoryBudgetCommand;
import seedu.expensetracker.logic.parser.exceptions.ParseException;
import seedu.expensetracker.model.budget.CategoryBudget;
/**
* Parses input arguments and creates a new SetCategoryBudgetCommandParser object
*/
public class SetCategoryBudgetCommandParser implements Parser<SetCategoryBudgetCommand> {
/**
* Parses the given {@code String} of arguments in the context of the AddCommand
* and returns an AddCommand object for execution.
* @throws ParseException if the user input does not conform the expected format
*/
public SetCategoryBudgetCommand parse(String args) throws ParseException {
try {
ArgumentMultimap argMultimap =
ArgumentTokenizer.tokenize(args, PREFIX_CATEGORY, PREFIX_BUDGET);
if (!arePrefixesPresent(argMultimap, PREFIX_CATEGORY, PREFIX_BUDGET)
|| !argMultimap.getPreamble().isEmpty()) {
throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT,
SetCategoryBudgetCommand.MESSAGE_USAGE));
}
String categoryName = argMultimap.getValue(PREFIX_CATEGORY).get();
String budget = argMultimap.getValue(PREFIX_BUDGET).get();
return new SetCategoryBudgetCommand(new CategoryBudget(categoryName, budget));
} catch (IllegalArgumentException e) {
throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT,
SetCategoryBudgetCommand.MESSAGE_USAGE));
}
}
}
|
/**
* Copyright (C) 2020 WaveMaker, Inc.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.wavemaker.runtime.security.provider.database.users;
import java.util.List;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
/**
* Created by ArjunSahasranam on 15/3/16.
*/
public interface UserProvider {
UserDetails loadUser(String username);
UserDetails createUserDetails(String username, UserDetails user, List<GrantedAuthority> dbAuths);
}
|
package com.lpoo.fallout.model.battle;
import com.lpoo.fallout.model.wander.Attributes;
import com.lpoo.fallout.model.wander.CharacterInfo;
import com.lpoo.fallout.model.wander.element.Enemy;
import com.lpoo.fallout.model.wander.element.VaultBoy;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class BattleInfoTest {
public BattleInfo info;
public VaultBoy mockedVaultBoy;
public Enemy mockedEnemy;
@BeforeEach
void setUp() {
CharacterInfo mockedVaultBoyInfo = Mockito.mock(CharacterInfo.class);
Mockito.when(mockedVaultBoyInfo.getWeaponDamage()).thenReturn(1);
Mockito.when(mockedVaultBoyInfo.getAttributes()).thenReturn(new Attributes(1, 1, 1, 1));
mockedVaultBoy = Mockito.mock(VaultBoy.class);
Mockito.when(mockedVaultBoy.getLevel()).thenReturn(1);
Mockito.when(mockedVaultBoy.getCharacterInfo()).thenReturn(mockedVaultBoyInfo);
CharacterInfo mockedEnemyInfo = Mockito.mock(CharacterInfo.class);
Mockito.when(mockedEnemyInfo.getAttributes()).thenReturn(new Attributes(1, 1, 1, 1));
mockedEnemy = Mockito.mock(Enemy.class);
Mockito.when(mockedEnemy.getCharacterInfo()).thenReturn(mockedEnemyInfo);
Mockito.when(mockedEnemy.getLevel()).thenReturn(1);
info = new BattleInfo(mockedVaultBoy, mockedEnemy);
}
@Test
void testClassNotCopy() {
BattleStats origAttackerStats = info.getTurn().getAttackerStats();
BattleStats origDefenderStats = info.getTurn().getDefenderStats();
info.changeTurn();
Assertions.assertSame(origAttackerStats, info.getTurn().getDefenderStats());
Assertions.assertSame(origDefenderStats, info.getTurn().getAttackerStats());
}
@Test
void checkSuccessfulEnemyDeath() {
info.getTurn().getDefenderStats().setHealthPoints(0);
Assertions.assertSame(info.checkDeath(), mockedEnemy);
}
@Test
void checkSuccessfulVaultBoyDeath() {
info.getTurn().getAttackerStats().setHealthPoints(0);
Assertions.assertSame(info.checkDeath(), mockedVaultBoy);
}
@Test
void noOneDies() {
Assertions.assertNull(info.checkDeath());
}
@Test
void turnChangeBoolean() {
Assertions.assertTrue(info.isPlayerTurn());
info.changeTurn();
Assertions.assertFalse(info.isPlayerTurn());
}
@Test
void turnChange() {
BattleStats formerAttacker = info.getTurn().getAttackerStats();
BattleStats formerDefender = info.getTurn().getDefenderStats();
info.changeTurn();
Assertions.assertSame(formerAttacker, info.getTurn().getDefenderStats());
Assertions.assertSame(formerDefender, info.getTurn().getAttackerStats());
}
}
|
package com.alibaba.dubbo.loadbalancer;
public class LoadBalancerBuilder {
public static LoadBalancerBuilder newBuilder(String clientName) {
return new LoadBalancerBuilder(clientName);
}
private String clientName;
public LoadBalancerBuilder(String clientName) {
this.clientName = clientName;
}
public LoadBalancer build() {
return new BaseLoadBalancer();
}
}
|
/**
* ${projectname}
* ${projectdescription}
*/
package ${package};
|
/**
*
* Copyright (C) 2011-2017 KSFX. 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 ch.ksfx.web.pages.simulator;
import ch.ksfx.dao.simulation.SimulatedAssetDecisionStrategyTemplateDAO;
import ch.ksfx.dao.simulation.SimulatedTradeDAO;
import ch.ksfx.dao.simulation.SimulationRawDataDAO;
import ch.ksfx.model.simulation.SimulatedAssetDecisionStrategyTemplate;
import ch.ksfx.model.simulation.SimulatedTrade;
import org.apache.commons.lang.time.DateUtils;
import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.annotation.Secured;
import java.util.Date;
@Deprecated //To be removed
@Secured({"ROLE_ADMIN"})
public class SimulationRawDataViewer
{
private Logger logger = LoggerFactory.getLogger(SimulationRawDataViewer.class);
@Inject
private SimulationRawDataDAO simulationRawDataDAO;
@Inject
private SimulatedTradeDAO simulatedTradeDAO;
// @Inject
// private ChartGenerator chartGenerator;
@Inject
private ComponentResources componentResources;
@Inject
private SimulatedAssetDecisionStrategyTemplateDAO simulatedAssetDecisionStrategyTemplateDAO;
@Property
private SimulatedAssetDecisionStrategyTemplate simulatedAssetDecisionStrategyTemplate;
@Property
private SimulatedTrade simulatedTrade;
@Property
@Persist
private Date fromDate;
@Property
@Persist
private Date toDate;
@Persist
private Long oldTradeId;
@Secured({"ROLE_ADMIN"})
public void onActivate(Long simulatedAssetDecisionStrategyTemplateId, Long simulatedTradeId)
{
this.simulatedAssetDecisionStrategyTemplate = simulatedAssetDecisionStrategyTemplateDAO.getSimulatedAssetDecisionStrategyTemplateForId(simulatedAssetDecisionStrategyTemplateId);
this.simulatedTrade = simulatedTradeDAO.getSimulatedTradeForId(simulatedTradeId);
if (oldTradeId == null || !oldTradeId.equals(simulatedTrade.getId())) {
if (simulatedTrade.getSimulatedMarketOrders().get(0).getExecutionDate() != null) {
logger.info("=============== Setting new dates ================ ot " + oldTradeId + " nt " + simulatedTrade.getId());
fromDate = DateUtils.addSeconds(simulatedTrade.getSimulatedMarketOrders().get(0).getExecutionDate(), -10800);
toDate = DateUtils.addSeconds(simulatedTrade.getSimulatedMarketOrders().get(0).getExecutionDate(), 10800);
oldTradeId = simulatedTrade.getId();
}
}
logger.info("Fromdate is now " + fromDate);
logger.info("Todate is now " + toDate);
}
public Long[] onPassivate()
{
Long[] param = new Long[2];
if (simulatedAssetDecisionStrategyTemplate != null) {
param[0] = simulatedAssetDecisionStrategyTemplate.getId();
}
if (simulatedTrade != null) {
param[1] = simulatedTrade.getId();
}
return param;
}
public void onSuccessFromRawDataViewerForm()
{
logger.info("================== Found fromdate " + fromDate);
logger.info("================== Found todate " + toDate);
}
public String getHugeGraphLink()
{
return componentResources.createEventLink("hugeGraph").toURI();
}
public Long getSystemTime()
{
return System.currentTimeMillis();
}
public String getGraphLink()
{
return componentResources.createEventLink("graph",simulatedAssetDecisionStrategyTemplate.getId()).toURI();
}
}
*/
|
/*
* 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.prestosql.sql.planner.iterative.rule;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import io.prestosql.connector.CatalogName;
import io.prestosql.metadata.TableHandle;
import io.prestosql.plugin.tpch.TpchColumnHandle;
import io.prestosql.plugin.tpch.TpchTableHandle;
import io.prestosql.plugin.tpch.TpchTableLayoutHandle;
import io.prestosql.plugin.tpch.TpchTransactionHandle;
import io.prestosql.spi.connector.ColumnHandle;
import io.prestosql.spi.predicate.Domain;
import io.prestosql.spi.predicate.TupleDomain;
import io.prestosql.spi.type.Type;
import io.prestosql.sql.parser.SqlParser;
import io.prestosql.sql.planner.TypeAnalyzer;
import io.prestosql.sql.planner.iterative.rule.test.BaseRuleTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.util.Map;
import java.util.Optional;
import static io.airlift.slice.Slices.utf8Slice;
import static io.prestosql.spi.predicate.Domain.singleValue;
import static io.prestosql.spi.type.BigintType.BIGINT;
import static io.prestosql.spi.type.VarcharType.createVarcharType;
import static io.prestosql.sql.planner.assertions.PlanMatchPattern.constrainedTableScanWithTableLayout;
import static io.prestosql.sql.planner.assertions.PlanMatchPattern.filter;
import static io.prestosql.sql.planner.assertions.PlanMatchPattern.values;
import static io.prestosql.sql.planner.iterative.rule.test.PlanBuilder.expression;
public class TestPushPredicateIntoTableScan
extends BaseRuleTest
{
private PushPredicateIntoTableScan pushPredicateIntoTableScan;
private TableHandle nationTableHandle;
private TableHandle ordersTableHandle;
private CatalogName catalogName;
@BeforeClass
public void setUpBeforeClass()
{
pushPredicateIntoTableScan = new PushPredicateIntoTableScan(tester().getMetadata(), new TypeAnalyzer(new SqlParser(), tester().getMetadata()), true);
catalogName = tester().getCurrentConnectorId();
TpchTableHandle nation = new TpchTableHandle("nation", 1.0);
nationTableHandle = new TableHandle(
catalogName,
nation,
TpchTransactionHandle.INSTANCE,
Optional.of(new TpchTableLayoutHandle(nation, TupleDomain.all())));
TpchTableHandle orders = new TpchTableHandle("orders", 1.0);
ordersTableHandle = new TableHandle(
catalogName,
orders,
TpchTransactionHandle.INSTANCE,
Optional.of(new TpchTableLayoutHandle(orders, TupleDomain.all())));
}
@Test
public void doesNotFireIfNoTableScan()
{
tester().assertThat(pushPredicateIntoTableScan)
.on(p -> p.values(p.symbol("a", BIGINT)))
.doesNotFire();
}
@Test
public void eliminateTableScanWhenNoLayoutExist()
{
tester().assertThat(pushPredicateIntoTableScan)
.on(p -> p.filter(expression("orderstatus = 'G'"),
p.tableScan(
ordersTableHandle,
ImmutableList.of(p.symbol("orderstatus", createVarcharType(1))),
ImmutableMap.of(p.symbol("orderstatus", createVarcharType(1)), new TpchColumnHandle("orderstatus", createVarcharType(1))))))
.matches(values("A"));
}
@Test
public void replaceWithExistsWhenNoLayoutExist()
{
ColumnHandle columnHandle = new TpchColumnHandle("nationkey", BIGINT);
tester().assertThat(pushPredicateIntoTableScan)
.on(p -> p.filter(expression("nationkey = BIGINT '44'"),
p.tableScan(
nationTableHandle,
ImmutableList.of(p.symbol("nationkey", BIGINT)),
ImmutableMap.of(p.symbol("nationkey", BIGINT), columnHandle),
TupleDomain.none())))
.matches(values("A"));
}
@Test
public void doesNotFireIfRuleNotChangePlan()
{
tester().assertThat(pushPredicateIntoTableScan)
.on(p -> p.filter(expression("nationkey % 17 = BIGINT '44' AND nationkey % 15 = BIGINT '43'"),
p.tableScan(
nationTableHandle,
ImmutableList.of(p.symbol("nationkey", BIGINT)),
ImmutableMap.of(p.symbol("nationkey", BIGINT), new TpchColumnHandle("nationkey", BIGINT)),
TupleDomain.all())))
.doesNotFire();
}
@Test
public void ruleAddedTableLayoutToFilterTableScan()
{
Map<String, Domain> filterConstraint = ImmutableMap.<String, Domain>builder()
.put("orderstatus", singleValue(createVarcharType(1), utf8Slice("F")))
.build();
tester().assertThat(pushPredicateIntoTableScan)
.on(p -> p.filter(expression("orderstatus = CAST ('F' AS VARCHAR(1))"),
p.tableScan(
ordersTableHandle,
ImmutableList.of(p.symbol("orderstatus", createVarcharType(1))),
ImmutableMap.of(p.symbol("orderstatus", createVarcharType(1)), new TpchColumnHandle("orderstatus", createVarcharType(1))))))
.matches(
constrainedTableScanWithTableLayout("orders", filterConstraint, ImmutableMap.of("orderstatus", "orderstatus")));
}
@Test
public void ruleAddedNewTableLayoutIfTableScanHasEmptyConstraint()
{
tester().assertThat(pushPredicateIntoTableScan)
.on(p -> p.filter(expression("orderstatus = 'F'"),
p.tableScan(
ordersTableHandle,
ImmutableList.of(p.symbol("orderstatus", createVarcharType(1))),
ImmutableMap.of(p.symbol("orderstatus", createVarcharType(1)), new TpchColumnHandle("orderstatus", createVarcharType(1))))))
.matches(
constrainedTableScanWithTableLayout(
"orders",
ImmutableMap.of("orderstatus", singleValue(createVarcharType(1), utf8Slice("F"))),
ImmutableMap.of("orderstatus", "orderstatus")));
}
@Test
public void ruleWithPushdownableToTableLayoutPredicate()
{
Type orderStatusType = createVarcharType(1);
tester().assertThat(pushPredicateIntoTableScan)
.on(p -> p.filter(expression("orderstatus = 'O'"),
p.tableScan(
ordersTableHandle,
ImmutableList.of(p.symbol("orderstatus", orderStatusType)),
ImmutableMap.of(p.symbol("orderstatus", orderStatusType), new TpchColumnHandle("orderstatus", orderStatusType)))))
.matches(constrainedTableScanWithTableLayout(
"orders",
ImmutableMap.of("orderstatus", singleValue(orderStatusType, utf8Slice("O"))),
ImmutableMap.of("orderstatus", "orderstatus")));
}
@Test
public void nonDeterministicPredicate()
{
Type orderStatusType = createVarcharType(1);
tester().assertThat(pushPredicateIntoTableScan)
.on(p -> p.filter(expression("orderstatus = 'O' AND rand() = 0"),
p.tableScan(
ordersTableHandle,
ImmutableList.of(p.symbol("orderstatus", orderStatusType)),
ImmutableMap.of(p.symbol("orderstatus", orderStatusType), new TpchColumnHandle("orderstatus", orderStatusType)))))
.matches(
filter("rand() = 0",
constrainedTableScanWithTableLayout(
"orders",
ImmutableMap.of("orderstatus", singleValue(orderStatusType, utf8Slice("O"))),
ImmutableMap.of("orderstatus", "orderstatus"))));
}
}
|
package module603packageJava0;
import java.lang.Integer;
public class Foo69 {
Integer int0;
public void foo0() {
new module603packageJava0.Foo68().foo3();
}
public void foo1() {
foo0();
}
public void foo2() {
foo1();
}
public void foo3() {
foo2();
}
}
|
/**
*/
package instance;
import aadl2.PropertyValue;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Reference Value</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link instance.InstanceReferenceValue#getReferencedInstanceObject <em>Referenced Instance Object</em>}</li>
* </ul>
*
* @see instance.InstancePackage#getInstanceReferenceValue()
* @model
* @generated
*/
public interface InstanceReferenceValue extends PropertyValue {
/**
* Returns the value of the '<em><b>Referenced Instance Object</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Referenced Instance Object</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Referenced Instance Object</em>' reference.
* @see #setReferencedInstanceObject(InstanceObject)
* @see instance.InstancePackage#getInstanceReferenceValue_ReferencedInstanceObject()
* @model required="true" ordered="false"
* @generated
*/
InstanceObject getReferencedInstanceObject();
/**
* Sets the value of the '{@link instance.InstanceReferenceValue#getReferencedInstanceObject <em>Referenced Instance Object</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Referenced Instance Object</em>' reference.
* @see #getReferencedInstanceObject()
* @generated
*/
void setReferencedInstanceObject(InstanceObject value);
} // InstanceReferenceValue
|
package tss.tpm;
import tss.*;
import java.util.*;
// -----------This is an auto-generated file: do not edit
//>>>
/** Table 28 lists the architecturally defined handles that cannot be changed. The handles
* include authorization handles, and special handles.
*/
public final class TPM_RH extends TpmEnum<TPM_RH>
{
// Values from enum _N are only intended to be used in case labels of a switch statement using the result of this.asEnum() method as the switch condition.
// However, their Java names are identical to those of the constants defined in this class further below,
// so for any other usage just prepend them with the TPM_RH. qualifier.
public enum _N {
FIRST,
/** Not used1 */
SRK,
/** Handle references the Storage Primary Seed (SPS), the ownerAuth, and the ownerPolicy */
OWNER,
/** Not used1 */
REVOKE,
/** Not used1 */
TRANSPORT,
/** Not used1 */
OPERATOR,
/** Not used1 */
ADMIN,
/** Not used1 */
EK,
/** A handle associated with the null hierarchy, an EmptyAuth authValue, and an Empty
* Policy authPolicy.
*/
NULL,
/** Value reserved to the TPM to indicate a handle location that has not been initialized
* or assigned
*/
UNASSIGNED,
/** Authorization value used to indicate a password authorization session */
PW,
/** References the authorization associated with the dictionary attack lockout reset */
LOCKOUT,
/** References the Endorsement Primary Seed (EPS), endorsementAuth, and endorsementPolicy */
ENDORSEMENT,
/** References the Platform Primary Seed (PPS), platformAuth, and platformPolicy */
PLATFORM,
/** For phEnableNV */
PLATFORM_NV,
/** Start of a range of authorization values that are vendor-specific. A TPM may support
* any of the values in this range as are needed for vendor-specific purposes.
* Disabled if ehEnable is CLEAR.
* NOTE Any includes none.
*/
AUTH_00,
/** End of the range of vendor-specific authorization values. */
AUTH_FF,
/** Start of the range of authenticated timers */
ACT_0,
/** End of the range of authenticated timers */
ACT_F,
/** The top of the reserved handle area
* This is set to allow TPM2_GetCapability() to know where to stop. It may vary as
* implementations add to the permanent handle area.
*/
LAST
}
private static ValueMap<TPM_RH> _ValueMap = new ValueMap<TPM_RH>();
/** These definitions provide mapping of the Java enum constants to their TPM integer values */
public static final TPM_RH
FIRST = new TPM_RH(0x40000000, _N.FIRST),
SRK = new TPM_RH(0x40000000, _N.SRK),
OWNER = new TPM_RH(0x40000001, _N.OWNER),
REVOKE = new TPM_RH(0x40000002, _N.REVOKE),
TRANSPORT = new TPM_RH(0x40000003, _N.TRANSPORT),
OPERATOR = new TPM_RH(0x40000004, _N.OPERATOR),
ADMIN = new TPM_RH(0x40000005, _N.ADMIN),
EK = new TPM_RH(0x40000006, _N.EK),
NULL = new TPM_RH(0x40000007, _N.NULL),
UNASSIGNED = new TPM_RH(0x40000008, _N.UNASSIGNED),
PW = new TPM_RH(0x40000009, _N.PW),
LOCKOUT = new TPM_RH(0x4000000A, _N.LOCKOUT),
ENDORSEMENT = new TPM_RH(0x4000000B, _N.ENDORSEMENT),
PLATFORM = new TPM_RH(0x4000000C, _N.PLATFORM),
PLATFORM_NV = new TPM_RH(0x4000000D, _N.PLATFORM_NV),
AUTH_00 = new TPM_RH(0x40000010, _N.AUTH_00),
AUTH_FF = new TPM_RH(0x4000010F, _N.AUTH_FF),
ACT_0 = new TPM_RH(0x40000110, _N.ACT_0),
ACT_F = new TPM_RH(0x4000011F, _N.ACT_F),
LAST = new TPM_RH(0x4000011F, _N.LAST);
/** @deprecated Use {@link #PW} instead */
@Deprecated
public static final TPM_RH RS_PW = new TPM_RH(PW.toInt(), _N.PW, true);
public TPM_RH () { super(0, _ValueMap); }
public TPM_RH (int value) { super(value, _ValueMap); }
public static TPM_RH fromInt (int value) { return TpmEnum.fromInt(value, _ValueMap, TPM_RH.class); }
public static TPM_RH fromTpm (byte[] buf) { return TpmEnum.fromTpm(buf, _ValueMap, TPM_RH.class); }
public static TPM_RH fromTpm (TpmBuffer buf) { return TpmEnum.fromTpm(buf, _ValueMap, TPM_RH.class); }
public TPM_RH._N asEnum() { return (TPM_RH._N)NameAsEnum; }
public static Collection<TPM_RH> values() { return _ValueMap.values(); }
private TPM_RH (int value, _N nameAsEnum) { super(value, nameAsEnum, _ValueMap); }
private TPM_RH (int value, _N nameAsEnum, boolean noConvFromInt) { super(value, nameAsEnum, null); }
@Override
protected int wireSize() { return 4; }
}
//<<<
|
/*
* Copyright (c) 2018 m2049r
*
* 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.swap.xwpwallet.ledger;
public enum Instruction {
INS_NONE(0x00),
INS_RESET(0x02),
INS_GET_KEY(0x20),
INS_PUT_KEY(0x22),
INS_GET_CHACHA8_PREKEY(0x24),
INS_VERIFY_KEY(0x26),
INS_SECRET_KEY_TO_PUBLIC_KEY(0x30),
INS_GEN_KEY_DERIVATION(0x32),
INS_DERIVATION_TO_SCALAR(0x34),
INS_DERIVE_PUBLIC_KEY(0x36),
INS_DERIVE_SECRET_KEY(0x38),
INS_GEN_KEY_IMAGE(0x3A),
INS_SECRET_KEY_ADD(0x3C),
INS_SECRET_KEY_SUB(0x3E),
INS_GENERATE_KEYPAIR(0x40),
INS_SECRET_SCAL_MUL_KEY(0x42),
INS_SECRET_SCAL_MUL_BASE(0x44),
INS_DERIVE_SUBADDRESS_PUBLIC_KEY(0x46),
INS_GET_SUBADDRESS(0x48),
INS_GET_SUBADDRESS_SPEND_PUBLIC_KEY(0x4A),
INS_GET_SUBADDRESS_SECRET_KEY(0x4C),
INS_OPEN_TX(0x70),
INS_SET_SIGNATURE_MODE(0x72),
INS_GET_ADDITIONAL_KEY(0x74),
INS_STEALTH(0x76),
INS_BLIND(0x78),
INS_UNBLIND(0x7A),
INS_VALIDATE(0x7C),
INS_MLSAG(0x7E),
INS_CLOSE_TX(0x80),
INS_GET_RESPONSE(0xc0),
INS_UNDEFINED(0xff);
public static Instruction fromByte(byte n) {
switch (n & 0xFF) {
case 0x00:
return INS_NONE;
case 0x02:
return INS_RESET;
case 0x20:
return INS_GET_KEY;
case 0x22:
return INS_PUT_KEY;
case 0x24:
return INS_GET_CHACHA8_PREKEY;
case 0x26:
return INS_VERIFY_KEY;
case 0x30:
return INS_SECRET_KEY_TO_PUBLIC_KEY;
case 0x32:
return INS_GEN_KEY_DERIVATION;
case 0x34:
return INS_DERIVATION_TO_SCALAR;
case 0x36:
return INS_DERIVE_PUBLIC_KEY;
case 0x38:
return INS_DERIVE_SECRET_KEY;
case 0x3A:
return INS_GEN_KEY_IMAGE;
case 0x3C:
return INS_SECRET_KEY_ADD;
case 0x3E:
return INS_SECRET_KEY_SUB;
case 0x40:
return INS_GENERATE_KEYPAIR;
case 0x42:
return INS_SECRET_SCAL_MUL_KEY;
case 0x44:
return INS_SECRET_SCAL_MUL_BASE;
case 0x46:
return INS_DERIVE_SUBADDRESS_PUBLIC_KEY;
case 0x48:
return INS_GET_SUBADDRESS;
case 0x4A:
return INS_GET_SUBADDRESS_SPEND_PUBLIC_KEY;
case 0x4C:
return INS_GET_SUBADDRESS_SECRET_KEY;
case 0x70:
return INS_OPEN_TX;
case 0x72:
return INS_SET_SIGNATURE_MODE;
case 0x74:
return INS_GET_ADDITIONAL_KEY;
case 0x76:
return INS_STEALTH;
case 0x78:
return INS_BLIND;
case 0x7A:
return INS_UNBLIND;
case 0x7C:
return INS_VALIDATE;
case 0x7E:
return INS_MLSAG;
case 0x80:
return INS_CLOSE_TX;
case 0xc0:
return INS_GET_RESPONSE;
default:
return INS_UNDEFINED;
}
}
public int getValue() {
return value;
}
public byte getByteValue() {
return (byte) (value & 0xFF);
}
private int value;
Instruction(int value) {
this.value = value;
}
}
|
package com.bretpatterson.schemagen.graphql.annotations;
import graphql.schema.DataFetcher;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Fields annotated with this use the specified data fetcher for retrieval
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface GraphQLDataFetcher {
/**
* A custom datafetcher you would like to use for this field
* @return
*/
Class<? extends DataFetcher> dataFetcher();
}
|
package com.cyc.kb;
/*
* #%L
* KBAPI
* %%
* Copyright (C) 1995 - 2014 Cycorp, Inc
* %%
* This software is the proprietary information of Cycorp, Inc.
* Use is subject to license terms.
* #L%
*/
/**
* An enumeration describing the existential status of a KB entity, and its
* compatibility with a particular semantic object type.
*
* @author nwinant
*/
public enum KBStatus {
EXISTS_AS_TYPE,
EXISTS_WITH_COMPATIBLE_TYPE,
EXISTS_WITH_TYPE_CONFLICT,
DOES_NOT_EXIST;
}
|
package restmule.core.util;
import java.lang.reflect.InvocationTargetException;
import retrofit2.Call;
/**
*
* {@link RetrofitUtil}
* <p>
* @version 1.0.0
*
*/
public class RetrofitUtil {
@SuppressWarnings("unchecked")
public static <R, T> Call<R> getCall(
String methodName,
Class<?>[] types,
Object[] vals,
T client)
throws
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException,
NoSuchMethodException,
SecurityException
{
if (types.length > 0 && types.length == vals.length){
Class<? extends Object> clazz = client.getClass();
return (Call<R>) clazz.getMethod(methodName,types).invoke(client, vals);
}
return null;
}
}
|
/**
* Copyright 2009-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ibatis.type;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @author Clinton Begin
*/
public class StringTypeHandler extends BaseTypeHandler<String> {
@Override
public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType)
throws SQLException {
ps.setString(i, parameter); // ps 设置字符串类型
}
@Override
public String getNullableResult(ResultSet rs, String columnName)
throws SQLException {
return rs.getString(columnName);
}
@Override
public String getNullableResult(ResultSet rs, int columnIndex)
throws SQLException {
return rs.getString(columnIndex);
}
@Override
public String getNullableResult(CallableStatement cs, int columnIndex)
throws SQLException {
return cs.getString(columnIndex);
}
}
|
/*
* Copyright 2017 ~ 2025 the original author or authors. <wanglsir@gmail.com, 983708408@qq.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.wl4g.iam.config.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import static com.wl4g.iam.common.constant.ConfigIAMConstants.KEY_IAM_CONFIG_PREFIX;
/**
* Social networking services configuration
*
* @author wangl.sir
* @version v1.0 2019年1月8日
* @since
*/
@ConfigurationProperties(prefix = KEY_IAM_CONFIG_PREFIX + ".crypto")
public class CryptoProperties {
private int keyPairPools = 64;
private long keyPairExpireMs = 600_000;
public int getKeyPairPools() {
return keyPairPools;
}
public void setKeyPairPools(int keyPairPools) {
this.keyPairPools = keyPairPools;
}
public long getKeyPairExpireMs() {
return keyPairExpireMs;
}
public void setKeyPairExpireMs(long keyPairExpireMs) {
this.keyPairExpireMs = keyPairExpireMs;
}
}
|
/*******************************************************************************
* Copyright 2014 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.video;
import java.io.FileNotFoundException;
import com.badlogic.gdx.files.FileHandle;
class VideoPlayerStub implements VideoPlayer {
@Override public boolean play (FileHandle file) throws FileNotFoundException {
return true;
}
@Override public boolean render () {
return false;
}
@Override public boolean isBuffered () {
return true;
}
@Override public void resize (int width, int height) {
}
@Override public void pause () {
}
@Override public void resume () {
}
@Override public void stop () {
}
@Override public void setOnVideoSizeListener (VideoSizeListener listener) {
}
@Override public void setOnCompletionListener (CompletionListener listener) {
}
@Override public int getVideoWidth () {
return 0;
}
@Override public int getVideoHeight () {
return 0;
}
@Override public boolean isPlaying () {
return false;
}
@Override public void dispose () {
}
}
|
/*
* Copyright (C) 2020 Dremio
*
* 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.projectnessie.jaxrs;
import io.restassured.RestAssured;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.http.ContentType;
import java.net.URI;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.projectnessie.jaxrs.ext.NessieJaxRsExtension;
import org.projectnessie.jaxrs.ext.NessieUri;
import org.projectnessie.server.store.TableCommitMetaStoreWorker;
import org.projectnessie.versioned.persist.adapter.DatabaseAdapter;
import org.projectnessie.versioned.persist.tests.extension.DatabaseAdapterExtension;
import org.projectnessie.versioned.persist.tests.extension.NessieDbAdapter;
@ExtendWith(DatabaseAdapterExtension.class)
abstract class AbstractTestJerseyResteasy extends AbstractResteasyTest {
@NessieDbAdapter(storeWorker = TableCommitMetaStoreWorker.class)
static DatabaseAdapter databaseAdapter;
@RegisterExtension
static NessieJaxRsExtension server = new NessieJaxRsExtension(() -> databaseAdapter);
@BeforeAll
static void setup(@NessieUri URI uri) {
RestAssured.baseURI = uri.toString();
RestAssured.port = uri.getPort();
RestAssured.requestSpecification =
new RequestSpecBuilder()
.setContentType(ContentType.JSON)
.setAccept(ContentType.JSON)
.build();
basePath = "/";
}
}
|
package com.rnredux;
import com.facebook.react.ReactActivity;
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "RNRedux";
}
}
|
/*
* Copyright 2020 Hochschule Luzern - Informatik.
*
* 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 ch.hslu.ad.sw09.buffer;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.Random;
import java.util.concurrent.TimeUnit;
/**
* Demonstration des BoundedBuffers mit n Producer und m Consumer.
*/
public final class DemoBoundedBuffer {
private static final Logger LOG = LogManager.getLogger(DemoBoundedBuffer.class);
/**
* Privater Konstruktor.
*/
private DemoBoundedBuffer() {
}
/**
* Main-Demo.
* @param args not used.
* @throws InterruptedException wenn das warten unterbrochen wird.
*/
public static void main(final String[] args) throws InterruptedException {
final Random random = new Random();
final int nPros = 3;
final Producer[] producers = new Producer[nPros];
final ThreadGroup prosGroup = new ThreadGroup("Producer-Threads");
final int mCons = 2;
final Consumer[] consumers = new Consumer[mCons];
final ThreadGroup consGroup = new ThreadGroup("Consumer-Threads");
final BoundedBufferAdapter<Integer> queue = new BoundedBufferAdapter<>(50);
for (int i = 0; i < nPros; i++) {
producers[i] = new Producer(queue, random.nextInt(10000));
new Thread(prosGroup, producers[i], "Prod " + (char) (i + 65)).start();
}
for (int i = 0; i < mCons; i++) {
consumers[i] = new Consumer(queue);
new Thread(consGroup, consumers[i], "Cons " + (char) (i + 65)).start();
}
while (prosGroup.activeCount() > 0) {
Thread.yield();
}
TimeUnit.MILLISECONDS.sleep(100);
consGroup.interrupt();
int sumPros = 0;
for (int i = 0; i < nPros; i++) {
LOG.info("Prod " + (char) (i + 65) + " = " + producers[i].getSum());
sumPros += producers[i].getSum();
}
int sumCons = 0;
for (int i = 0; i < mCons; i++) {
LOG.info("Cons " + (char) (i + 65) + " = " + consumers[i].getSum());
sumCons += consumers[i].getSum();
}
LOG.info(sumPros + " = " + sumCons);
}
}
|
package com.dashboard.commondashboard;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.data.annotation.Id;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
@RequiredArgsConstructor
public class SchedulerInfo {
@Id
@Getter private final String _id;
@Getter private final String schedulerVersion;
@Getter private final String whenUpdated;
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.runners.gearpump.translators.utils;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import com.google.common.collect.Lists;
import io.gearpump.streaming.dsl.window.impl.Window;
import java.time.Instant;
import java.util.List;
import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
import org.apache.beam.sdk.transforms.windowing.GlobalWindow;
import org.apache.beam.sdk.transforms.windowing.IntervalWindow;
import org.apache.beam.sdk.values.KV;
import org.junit.Test;
/** Tests for {@link TranslatorUtils}. */
public class TranslatorUtilsTest {
private static final List<KV<org.joda.time.Instant, Instant>> TEST_VALUES =
Lists.newArrayList(
KV.of(new org.joda.time.Instant(0), Instant.EPOCH),
KV.of(new org.joda.time.Instant(42), Instant.ofEpochMilli(42)),
KV.of(new org.joda.time.Instant(Long.MIN_VALUE), Instant.ofEpochMilli(Long.MIN_VALUE)),
KV.of(new org.joda.time.Instant(Long.MAX_VALUE), Instant.ofEpochMilli(Long.MAX_VALUE)));
@Test
public void testJodaTimeAndJava8TimeConversion() {
for (KV<org.joda.time.Instant, Instant> kv : TEST_VALUES) {
assertThat(TranslatorUtils.jodaTimeToJava8Time(kv.getKey()), equalTo(kv.getValue()));
assertThat(TranslatorUtils.java8TimeToJodaTime(kv.getValue()), equalTo(kv.getKey()));
}
}
@Test
public void testBoundedWindowToGearpumpWindow() {
assertThat(
TranslatorUtils.boundedWindowToGearpumpWindow(
new IntervalWindow(
new org.joda.time.Instant(0), new org.joda.time.Instant(Long.MAX_VALUE))),
equalTo(Window.apply(Instant.EPOCH, Instant.ofEpochMilli(Long.MAX_VALUE))));
assertThat(
TranslatorUtils.boundedWindowToGearpumpWindow(
new IntervalWindow(
new org.joda.time.Instant(Long.MIN_VALUE),
new org.joda.time.Instant(Long.MAX_VALUE))),
equalTo(
Window.apply(
Instant.ofEpochMilli(Long.MIN_VALUE), Instant.ofEpochMilli(Long.MAX_VALUE))));
BoundedWindow globalWindow = GlobalWindow.INSTANCE;
assertThat(
TranslatorUtils.boundedWindowToGearpumpWindow(globalWindow),
equalTo(
Window.apply(
Instant.ofEpochMilli(BoundedWindow.TIMESTAMP_MIN_VALUE.getMillis()),
Instant.ofEpochMilli(globalWindow.maxTimestamp().getMillis() + 1))));
}
}
|
/*
* Copyright (C) 2021 REALTIMETECH All Rights Reserved
*
* Licensed either under the Apache License, Version 2.0, or (at your option)
* under the terms of the GNU General Public License as published by
* the Free Software Foundation (subject to the "Classpath" exception),
* either version 2, or any later version (collectively, 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
* http://www.gnu.org/licenses/
* http://www.gnu.org/software/classpath/license.html
*
* or as provided in the LICENSE file that accompanied this code.
* 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.realtimetech.opack.transformer;
import com.realtimetech.opack.Opacker;
import com.realtimetech.opack.exception.DeserializeException;
import com.realtimetech.opack.exception.SerializeException;
public interface Transformer {
/**
* Serialize specific value to opack value.
*
* @param value the value to be serialized
* @return opack value
* @throws SerializeException if a problem occurs during serializing
*/
public Object serialize(Opacker opacker, Object value) throws SerializeException;
/**
* Deserialize opack value.
*
* @param value the opack value to be deserialized
* @param goalType the goal type to deserialize
* @return deserialized value
* @throws DeserializeException if a problem occurs during deserializing
*/
public Object deserialize(Opacker opacker, Class<?> goalType, Object value) throws DeserializeException;
}
|
package pro.requena.angularee.web.rest;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
/**
* Base path definition.
*
*/
@ApplicationPath("/rest")
public class JaxRsActivator extends Application {
}
|
package kr.pe.codda.servlet.admin;
import java.io.File;
import java.io.FileOutputStream;
import java.util.logging.Level;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kr.pe.codda.client.AnyProjectConnectionPoolIF;
import kr.pe.codda.client.ConnectionPoolManager;
import kr.pe.codda.common.buildsystem.pathsupporter.WebRootBuildSystemPathSupporter;
import kr.pe.codda.common.config.CoddaConfiguration;
import kr.pe.codda.common.config.CoddaConfigurationManager;
import kr.pe.codda.common.etc.CommonStaticFinalVars;
import kr.pe.codda.common.message.AbstractMessage;
import kr.pe.codda.impl.classloader.ClientMessageCodecManger;
import kr.pe.codda.impl.message.MessageResultRes.MessageResultRes;
import kr.pe.codda.impl.message.TreeSiteMenuReq.TreeSiteMenuReq;
import kr.pe.codda.impl.message.TreeSiteMenuRes.TreeSiteMenuRes;
import kr.pe.codda.weblib.common.AccessedUserInformation;
import kr.pe.codda.weblib.common.WebCommonStaticFinalVars;
import kr.pe.codda.weblib.jdf.AbstractAdminLoginServlet;
import com.google.gson.Gson;
public class UserWebsiteMenuInfoFileUpdaterSvl extends
AbstractAdminLoginServlet {
private static final long serialVersionUID = 654417668900237779L;
/*private String getTabStrings(int tapStep) {
StringBuilder tapStringBuilder = new StringBuilder();
for (int i=0; i < tapStep; i++) {
tapStringBuilder.append("\t");
}
return tapStringBuilder.toString();
}
private String makeWebsiteMenuPartStringUsingMenuList(List<TreeSiteMenuRes.Menu> menuList, int tapStep) {
StringBuilder websiteMenuPartStringBuilder = new StringBuilder();
for (TreeSiteMenuRes.Menu menu : menuList) {
List<TreeSiteMenuRes.Menu> childMenuList = menu.getChildMenuList();
if (null == childMenuList || childMenuList.isEmpty()) {
websiteMenuPartStringBuilder.append(getTabStrings(tapStep));
if (menuGroupURL.equals(menu.getLinkURL())) {
siteNavbarStringBuilder.append("<li class=\"active\">");
} else {
siteNavbarStringBuilder.append("<li>");
}
websiteMenuPartStringBuilder.append("<li>");
websiteMenuPartStringBuilder.append("<a href=\"");
websiteMenuPartStringBuilder.append(menu.getLinkURL());
websiteMenuPartStringBuilder.append("\">");
websiteMenuPartStringBuilder.append(menu.getMenuName());
websiteMenuPartStringBuilder.append("</a></li>");
websiteMenuPartStringBuilder.append(CommonStaticFinalVars.NEWLINE);
} else {
websiteMenuPartStringBuilder.append(getTabStrings(tapStep));
websiteMenuPartStringBuilder.append("<li class=\"dropdown\">");
websiteMenuPartStringBuilder.append(CommonStaticFinalVars.NEWLINE);
websiteMenuPartStringBuilder.append(getTabStrings(tapStep+1));
websiteMenuPartStringBuilder.append("<a class=\"dropdown-toggle\" data-toggle=\"dropdown\" href=\"");
websiteMenuPartStringBuilder.append(menu.getLinkURL());
websiteMenuPartStringBuilder.append("\">");
websiteMenuPartStringBuilder.append(menu.getMenuName());
websiteMenuPartStringBuilder.append("<span class=\"caret\"></span></a>");
websiteMenuPartStringBuilder.append(CommonStaticFinalVars.NEWLINE);
websiteMenuPartStringBuilder.append(getTabStrings(tapStep+1));
websiteMenuPartStringBuilder.append("<ul class=\"dropdown-menu\">");
websiteMenuPartStringBuilder.append(CommonStaticFinalVars.NEWLINE);
websiteMenuPartStringBuilder.append(makeWebsiteMenuPartStringUsingMenuList(childMenuList, tapStep+2));
//siteNavbarStringBuilder.append(CommonStaticFinalVars.NEWLINE);
websiteMenuPartStringBuilder.append(getTabStrings(tapStep+1));
websiteMenuPartStringBuilder.append("</ul>");
websiteMenuPartStringBuilder.append(CommonStaticFinalVars.NEWLINE);
websiteMenuPartStringBuilder.append(getTabStrings(tapStep));
websiteMenuPartStringBuilder.append("</li>");
websiteMenuPartStringBuilder.append(CommonStaticFinalVars.NEWLINE);
}
}
return websiteMenuPartStringBuilder.toString();
}*/
@Override
protected void performTask(HttpServletRequest req, HttpServletResponse res)
throws Exception {
CoddaConfigurationManager coddaConfigurationManager = CoddaConfigurationManager
.getInstance();
CoddaConfiguration runningProjectConfiguration = coddaConfigurationManager
.getRunningProjectConfiguration();
String installedPathString = runningProjectConfiguration
.getInstalledPathString();
String mainProjectName = runningProjectConfiguration
.getMainProjectName();
AnyProjectConnectionPoolIF mainProjectConnectionPool = ConnectionPoolManager
.getInstance().getMainProjectConnectionPool();
TreeSiteMenuReq treeSiteMenuReq = new TreeSiteMenuReq();
AccessedUserInformation accessedUserformation = getAccessedUserInformationFromSession(req);
treeSiteMenuReq.setRequestedUserID(accessedUserformation.getUserID());
TreeSiteMenuRes treeSiteMenuRes = null;
AbstractMessage outputMessage = mainProjectConnectionPool
.sendSyncInputMessage(ClientMessageCodecManger.getInstance(), treeSiteMenuReq);
if (!(outputMessage instanceof TreeSiteMenuRes)) {
if ((outputMessage instanceof MessageResultRes)) {
MessageResultRes messageResultRes = (MessageResultRes) outputMessage;
String errorMessage = "트리형 메뉴 목록 조회가 실패하였습니다";
String debugMessage = messageResultRes.toString();
printErrorMessagePage(req, res, errorMessage, debugMessage);
return;
} else {
String errorMessage = "트리형 메뉴 목록 조회가 실패했습니다";
String debugMessage = new StringBuilder("입력 메시지[")
.append(treeSiteMenuReq.getMessageID())
.append("]에 대한 비 정상 출력 메시지[")
.append(outputMessage.toString()).append("] 도착")
.toString();
log.severe(debugMessage);
printErrorMessagePage(req, res, errorMessage, debugMessage);
return;
}
}
treeSiteMenuRes = (TreeSiteMenuRes) outputMessage;
/*
final int tapStep = 5;
String websiteMenuPartString = makeWebsiteMenuPartStringUsingMenuList(treeSiteMenuRes.getRootMenuList(), tapStep);
*/
Gson gson = new Gson();
String treeSiteMenuResJsonString = gson.toJson(treeSiteMenuRes);
String userWebRootPathString = WebRootBuildSystemPathSupporter.getUserWebRootPathString(installedPathString, mainProjectName);
File watcherFile = new File(new StringBuilder().append(userWebRootPathString)
.append(File.separator)
.append(WebCommonStaticFinalVars.USER_WEBSITE_MENU_INFO_FILE).toString());
if ( watcherFile.exists()) {
if (! watcherFile.isFile()) {
String errorMessage = new StringBuilder().append("the sitemenu part string file[")
.append(watcherFile.getAbsoluteFile())
.append("] is not a regular file").toString();
String debugMessage = null;
log.warning(errorMessage);
printErrorMessagePage(req, res, errorMessage, debugMessage);
return;
}
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(watcherFile, false);
fos.write(treeSiteMenuResJsonString.getBytes(CommonStaticFinalVars.SOURCE_FILE_CHARSET));
} catch(Exception e) {
log.log(Level.WARNING, "'웹사이트 메뉴 파트 문자열 파일' 쓰기 실패", e);
String errorMessage = "'웹사이트 메뉴 파트 문자열 파일' 쓰기 실패";
String debugMessage = e.getMessage();
printErrorMessagePage(req, res, errorMessage, debugMessage);
return;
} finally {
if (null != fos) {
try {
fos.close();
} catch(Exception e1) {
}
}
}
printJspPage(req, res, "/sitemenu/menu/UserWebsiteMenuInfoFileUpdater.jsp");
}
}
|
package com.github.reimu.gobang;
public interface Player {
Point play();
void display(Point p);
}
|
package org.infinispan.commons.jdkspecific;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 11.0
**/
public class ThreadCreator {
public static Thread createThread(ThreadGroup threadGroup, Runnable target, boolean lightweight) {
if (lightweight) {
return Thread.builder().virtual().group(threadGroup).task(target).build();
} else {
return new Thread(threadGroup, target);
}
}
}
|
/*
* #%L
* wcm.io
* %%
* Copyright (C) 2020 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.qa.glnm.hamcrest.element;
import org.hamcrest.Matcher;
import org.openqa.selenium.WebElement;
/**
* Matches {@link org.openqa.selenium.WebElement#getAttribute(String)}
*
* @since 5.0.0
*/
public class ElementAttribute extends WebElementMatcher<String> {
protected ElementAttribute(String name, Matcher<String> matcher) {
super(
name + " attribute",
element -> element.getAttribute(name),
matcher);
}
/**
* <p>elementAttribute.</p>
*
* @param attributeName name of attribute
* @param matcher used to match attribute value
* @return matcher matching element's attribute value
*/
public static Matcher<WebElement> elementAttribute(
String attributeName,
Matcher<String> matcher) {
return new ElementAttribute(attributeName, matcher);
}
}
|
package eventsrc4j.io;
import eventsrc4j.Event;
import eventsrc4j.Fold;
import eventsrc4j.StreamAction;
import fj.data.Option;
import java.util.stream.Stream;
/**
* A stream of events, that can be read.
*
* @param <K> events key type.
* @param <S> sequence used for ordering events in the stream.
* @param <E> concrete domain events type.
*/
public interface EventStream<K, S, E> {
/**
* ReadEventStream the stream of events, in order of sequence, from the underlying data store.
*
* @param <R> the results of the stream fold. Must NOT reference the folded {@link Stream}.
* @param fromSeq The starting sequence to read events from (exclusive). Empty to read from the
* start.
* @param streamFold a fold on the stream of events.
* @return an IO action producing the result of the stream fold. The {@link Stream} is closed and
* unreadable after execution of the action.
*/
<R> IO<R> read(Option<S> fromSeq, Fold<Event<K, S, E>, R> streamFold);
/**
* GetSnapshot the latest event of the stream.
*
* @return an IO action producing the single latest event, if found.
*/
IO<Option<Event<K, S, E>>> latest();
default <R> IO<R> evalAction(StreamAction<K, S, E, R> action) {
return action.eval(StreamIOAlgebra.of(this));
}
}
|
/**
* 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 com.leansoft.luxun.message.compress;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GZIPCompression extends CompressionFacade {
public GZIPCompression(InputStream inputStream, ByteArrayOutputStream outputStream) throws IOException {
super(inputStream != null ? new GZIPInputStream(inputStream) : null, //
outputStream != null ? new GZIPOutputStream(outputStream) : null);
}
}
|
package jetbrains.mps.lang.typesystem.typesystem;
/*Generated by MPS */
import jetbrains.mps.lang.typesystem.runtime.AbstractNonTypesystemRule_Runtime;
import jetbrains.mps.lang.typesystem.runtime.NonTypesystemRule_Runtime;
import org.jetbrains.mps.openapi.model.SNode;
import jetbrains.mps.typesystem.inference.TypeCheckingContext;
import jetbrains.mps.lang.typesystem.runtime.IsApplicableStatus;
import jetbrains.mps.errors.messageTargets.MessageTarget;
import jetbrains.mps.errors.messageTargets.NodeMessageTarget;
import jetbrains.mps.errors.IErrorReporter;
import org.jetbrains.mps.openapi.language.SAbstractConcept;
import org.jetbrains.mps.openapi.language.SConcept;
import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory;
public class check_NodeInferTypeOperation_NonTypesystemRule extends AbstractNonTypesystemRule_Runtime implements NonTypesystemRule_Runtime {
public check_NodeInferTypeOperation_NonTypesystemRule() {
}
public void applyRule(final SNode operation, final TypeCheckingContext typeCheckingContext, IsApplicableStatus status) {
if (!(!(RulesUtil.withinInferenceItem(operation)))) {
final MessageTarget errorTarget = new NodeMessageTarget();
IErrorReporter _reporter_2309309498 = typeCheckingContext.reportTypeError(operation, "don't use infer type operation within inference rules", "r:00000000-0000-4000-0000-011c895902b1(jetbrains.mps.lang.typesystem.typesystem)", "1196099140505", null, errorTarget);
}
}
public SAbstractConcept getApplicableConcept() {
return CONCEPTS.Node_InferTypeOperation$x;
}
public IsApplicableStatus isApplicableAndPattern(SNode argument) {
return new IsApplicableStatus(argument.getConcept().isSubConceptOf(getApplicableConcept()), null);
}
public boolean overrides() {
return false;
}
private static final class CONCEPTS {
/*package*/ static final SConcept Node_InferTypeOperation$x = MetaAdapterFactory.getConcept(0x7a5dda6291404668L, 0xab76d5ed1746f2b2L, 0x584039bf75272c67L, "jetbrains.mps.lang.typesystem.structure.Node_InferTypeOperation");
}
}
|
/*******************************************************************************
* Copyright 2013 Petar Petrov <me@petarpetrov.org>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.petpet.c3po.utils;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import com.petpet.c3po.api.dao.Cache;
import org.apache.log4j.helpers.ISO8601DateFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.petpet.c3po.api.model.Element;
import com.petpet.c3po.api.model.helper.MetadataRecord;
import com.petpet.c3po.api.model.helper.MetadataRecord.Status;
import com.petpet.c3po.api.model.helper.PropertyType;
/**
* The data helper class offers some data manipulation methods.
*
* @author Petar Petrov <me@petarpetrov.org>
*
*/
public final class DataHelper {
/**
* Default logger.
*/
private static final Logger LOG = LoggerFactory.getLogger( DataHelper.class );
/**
* The types of known properties.
*/
private static Properties TYPES;
/**
* Some date patterns used for date parsing.
*/
private static final String[] PATTERNS = { "yyyy:MM:dd HH:mm:ss", "MM/dd/yyyy HH:mm:ss", "dd MMM yyyy HH:mm",
"EEE dd MMM yyyy HH:mm", "EEE, MMM dd, yyyy hh:mm:ss a", "EEE, MMM dd, yyyy hh:mm a", "EEE dd MMM yyyy HH.mm",
"HH:mm MM/dd/yyyy", "yyyyMMddHHmmss", "yyyy-MM-dd'T'HH:mm:ss" };
/**
* Loads the types of known properties into the TYPES {@link Properties}
* object.
*/
public static void init() {
try {
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream( "datatypes.properties" );
TYPES = new Properties();
TYPES.load( in );
in.close();
} catch ( IOException e ) {
e.printStackTrace();
}
}
/**
* Gets the type of the property defined by the given key. If it is not found,
* STRING is returned.
*
* @param key
* the key to look for.
* @return the type of the property.
*/
public static String getPropertyType( String key ) {
return TYPES.getProperty( key, "STRING" );
}
/**
* Removes a trailing zero (.0) from a string.
*
* @param str
* the string to chop.
* @return the string without the trailing .0.
*/
public static String removeTrailingZero( final String str ) {
if ( str != null && str.endsWith( ".0" ) ) {
return str.substring( 0, str.length() - 2 );
}
return str;
}
/**
* Merges the given metadata record within the given element. If a value for
* this record already exists, then a proper merge is done, where Conflicts
* are set if necessary.
*
* @param e
* the element to use for merging.
* @param mr
* the record to merge.
*/
public static void mergeMetadataRecord( Element e, MetadataRecord mr ) {
Cache cache = Configurator.getDefaultConfigurator().getPersistence().getCache();
if ( e == null || mr == null ) {
return;
}
List<MetadataRecord> oldMetadata = e.removeMetadata( mr.getProperty() );
if ( oldMetadata.size() == 0 ) {
e.getMetadata().add( mr );
} else if ( oldMetadata.size() == 1 ) {
MetadataRecord oldMR = oldMetadata.get( 0 );
if ( oldMR.getStatus().equals( Status.CONFLICT.name() ) ) {
for (String val : mr.getValues()) {
String newVal = getTypedValue(cache.getProperty(mr.getProperty()).getType(), val).toString();
if (!oldMR.getValues().contains(newVal)) {
mr.setStatus(Status.CONFLICT.name());
oldMetadata.add(mr);
break;
}
}
} else {
// String oldVal = getTypedValue( cache.getProperty(oldMR.getProperty()).getType(), oldMR.getValue() ).toString(); TODO:fix this
// String newVal = getTypedValue( mr.getProperty().getType(), mr.getValue() ).toString();
// if ( !oldVal.equals( newVal ) ) {
oldMR.setStatus( Status.CONFLICT.name() );
mr.setStatus( Status.CONFLICT.name() );
oldMetadata.add( mr );
// }
}
} else {
boolean exists = false;
for ( MetadataRecord old : oldMetadata ) {
// String oldVal = getTypedValue( old.getProperty().getType(), old.getValue() ).toString(); TODO:fix this
// String newVal = getTypedValue( mr.getProperty().getType(), mr.getValue() ).toString();
// if ( oldVal.equals( newVal ) ) {
exists = true;
// }
}
if ( !exists ) {
mr.setStatus( Status.CONFLICT.name() );
oldMetadata.add( mr );
}
}
e.getMetadata().addAll( oldMetadata );
}
// @Deprecated
// public static BasicDBObject getFilterQuery(Filter filter) {
// PersistenceLayer pl =
// Configurator.getDefaultConfigurator().getPersistence();
// BasicDBObject ref = new BasicDBObject("descriminator",
// filter.getDescriminator());
// ref.put("collection", filter.getCollection());
// DBCursor cursor = pl.find(Constants.TBL_FILTERS, ref);
//
// BasicDBObject query = new BasicDBObject("collection",
// filter.getCollection());
//
// Filter tmp;
// while (cursor.hasNext()) {
// DBObject next = cursor.next();
// tmp = DataHelper.parseFilter(next);
// if (tmp.getValue() != null) {
//
// Property property = pl.getCache().getProperty(tmp.getProperty());
//
// if (tmp.getValue().equals("Unknown")) {
// query.put("metadata." + tmp.getProperty() + ".values", new
// BasicDBObject("$exists", false));
// query.put("metadata." + tmp.getProperty() + ".value", new
// BasicDBObject("$exists", false));
//
// } else if (tmp.getValue().equals("Conflicted")) {
// query.put("metadata." + tmp.getProperty() + ".status",
// MetadataRecord.Status.CONFLICT.toString());
//
// } else if (property.getType().equals(PropertyType.DATE.toString())) {
//
// Calendar cal = Calendar.getInstance();
// cal.set(Integer.parseInt(tmp.getValue()), Calendar.JANUARY, 1);
// Date start = cal.getTime();
// cal.set(Integer.parseInt(tmp.getValue()), Calendar.DECEMBER, 31);
// Date end = cal.getTime();
//
// BasicDBObject date = new BasicDBObject();
// date.put("$lte", end);
// date.put("$gte", start);
//
// query.put("metadata." + tmp.getProperty() + ".value", date);
//
// } else if (property.getType().equals(PropertyType.INTEGER.toString())) {
// String val = tmp.getValue();
// String[] constraints = val.split(" - ");
// String low = constraints[0];
// String high = constraints[1];
//
// BasicDBObject range = new BasicDBObject();
// range.put("$lte", Long.parseLong(high));
// range.put("$gte", Long.parseLong(low));
//
// query.put("metadata." + tmp.getProperty() + ".value", range);
//
// } else {
// query.put("metadata." + tmp.getProperty() + ".value",
// inferValue(tmp.getValue()));
// }
// }
// }
//
// LOG.debug("FILTER QUERY: {}", query.toString());
// return query;
// }
// private static Object inferValue(String value) {
// Object result = value;
// if (value.equalsIgnoreCase("true")) {
// result = new Boolean(true);
// }
//
// if (value.equalsIgnoreCase("false")) {
// result = new Boolean(false);
// }
//
// return result;
// }
/**
* Tries to infer the type of the value based on the property type and
* converts the value. Otherwise it leaves the string representation. This is
* valuable as the underlying persistence layer can store the native type
* instead of strings which makes some aggregation functions easier.
*
* @param t
* the type of the property @see {@link PropertyType}
* @param value
* the value to convert
* @return an object with the specific type, or the original value. If the
* passed value was null, an empty string is returned.
*/
public static Object getTypedValue( String t, String value ) {
if ( value == null ) {
return "";
}
PropertyType type = PropertyType.valueOf( t );
Object result = null;
switch ( type ) {
case STRING:
result = value;
break;
case BOOL:
result = getBooleanValue( value );
break;
case INTEGER:
result = getIntegerValue( value );
break;
case FLOAT:
result = getDoubleValue( value );
break;
case DATE:
result = getDateValue( value );
break;
case ARRAY:
break;
}
return (result == null) ? value : result;
}
/**
* Tries to convert to a date object. First the method tries to match the
* value based on some predefined patterns. If no pattern matches the the
* method checks if the value is a long. If nothing succeeds then null is
* returned.
*
* @param value
* the value to convert
* @return a date if successful, null otherwise.
*/
private static Date getDateValue( String value ) {
LOG.trace( "parsing value {} as date", value );
final SimpleDateFormat fmt = new SimpleDateFormat();
Date result = null;
for ( String p : PATTERNS ) {
fmt.applyPattern( p );
result = parseDate( fmt, value );
if ( result != null ) {
break;
}
}
if ( result == null ) {
LOG.trace( "No pattern matching for value {}, try to parse as long", value );
}
try {
if ( value.length() != 14 ) {
LOG.trace( "value is not 14 characters long, probably a long representation" );
result = new Date( Long.valueOf( value ) );
}
} catch ( NumberFormatException e ) {
LOG.trace( "date is not in long representation, trying pattern matching: {}", e.getMessage() );
}
return result;
}
/**
* Gets a double out of the passed value.
*
* @param value
* the value to convert
* @return null if not a floating point string.
*/
private static Double getDoubleValue( String value ) {
try {
return Double.parseDouble( value );
} catch ( NumberFormatException e ) {
LOG.warn( "Value {} is not an float", value );
return null;
}
}
/**
* Converts to integer.
*
* @param value
* the value to convert.
* @return the integer object or null if not a numeric value.
*/
private static Long getIntegerValue( String value ) {
try {
return Long.parseLong( value );
} catch ( NumberFormatException e ) {
LOG.warn( "Value {} is not an integer", value );
return null;
}
}
/**
* A boolean representation of the passed string. If the string equals one of
* 'yes', 'true' or 'no', 'false' then the value is converted to the
* corresponding boolean. Otherwise null is returned
*
* @param value
* the value to convert
* @return the boolean representation of the value, or null if not a boolean.
*/
private static Boolean getBooleanValue( String value ) {
if ( value.equalsIgnoreCase( "yes" ) || value.equalsIgnoreCase( "true" ) ) {
return new Boolean( true );
} else if ( value.equalsIgnoreCase( "no" ) || value.equalsIgnoreCase( "false" ) ) {
return new Boolean( false );
} else {
LOG.warn( "Value {} is not a boolean", value );
return null;
}
}
/**
* Parses a date with the given dateformat.
*
* @param fmt
* the dateformat object to parse the date with.
* @param d
* the string to parse.
* @return the date or null if parsing was not successful.
*/
private static Date parseDate( DateFormat fmt, String d ) {
try {
return fmt.parse( d );
} catch ( ParseException e ) {
LOG.trace( "date could not be parsed: {}", e.getMessage() );
return null;
}
}
private DataHelper() {
}
}
|
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cache.config;
import org.springframework.beans.factory.config.TypedStringValue;
import org.springframework.beans.factory.parsing.ReaderContext;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.beans.factory.support.ManagedMap;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.cache.interceptor.*;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* {@link org.springframework.beans.factory.xml.BeanDefinitionParser
* BeanDefinitionParser} for the {@code <tx:advice/>} tag.
*
* @author Costin Leau
* @author Phillip Webb
* @author Stephane Nicoll
*/
class CacheAdviceParser extends AbstractSingleBeanDefinitionParser {
private static final String CACHEABLE_ELEMENT = "cacheable";
private static final String CACHE_EVICT_ELEMENT = "cache-evict";
private static final String CACHE_PUT_ELEMENT = "cache-put";
private static final String METHOD_ATTRIBUTE = "method";
private static final String DEFS_ELEMENT = "caching";
private static String getAttributeValue(Element element, String attributeName, String defaultValue) {
String attribute = element.getAttribute(attributeName);
if (StringUtils.hasText(attribute)) {
return attribute.trim();
}
return defaultValue;
}
@Override
protected Class<?> getBeanClass(Element element) {
return CacheInterceptor.class;
}
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
builder.addPropertyReference("cacheManager", CacheNamespaceHandler.extractCacheManager(element));
CacheNamespaceHandler.parseKeyGenerator(element, builder.getBeanDefinition());
List<Element> cacheDefs = DomUtils.getChildElementsByTagName(element, DEFS_ELEMENT);
if (!cacheDefs.isEmpty()) {
// Using attributes source.
List<RootBeanDefinition> attributeSourceDefinitions = parseDefinitionsSources(cacheDefs, parserContext);
builder.addPropertyValue("cacheOperationSources", attributeSourceDefinitions);
} else {
// Assume annotations source.
builder.addPropertyValue("cacheOperationSources",
new RootBeanDefinition("org.springframework.cache.annotation.AnnotationCacheOperationSource"));
}
}
private List<RootBeanDefinition> parseDefinitionsSources(List<Element> definitions, ParserContext parserContext) {
ManagedList<RootBeanDefinition> defs = new ManagedList<>(definitions.size());
// extract default param for the definition
for (Element element : definitions) {
defs.add(parseDefinitionSource(element, parserContext));
}
return defs;
}
private RootBeanDefinition parseDefinitionSource(Element definition, ParserContext parserContext) {
Props prop = new Props(definition);
// add cacheable first
ManagedMap<TypedStringValue, Collection<CacheOperation>> cacheOpMap = new ManagedMap<>();
cacheOpMap.setSource(parserContext.extractSource(definition));
List<Element> cacheableCacheMethods = DomUtils.getChildElementsByTagName(definition, CACHEABLE_ELEMENT);
for (Element opElement : cacheableCacheMethods) {
String name = prop.merge(opElement, parserContext.getReaderContext());
TypedStringValue nameHolder = new TypedStringValue(name);
nameHolder.setSource(parserContext.extractSource(opElement));
CacheableOperation.Builder builder = prop.merge(opElement,
parserContext.getReaderContext(), new CacheableOperation.Builder());
builder.setUnless(getAttributeValue(opElement, "unless", ""));
builder.setSync(Boolean.parseBoolean(getAttributeValue(opElement, "sync", "false")));
Collection<CacheOperation> col = cacheOpMap.get(nameHolder);
if (col == null) {
col = new ArrayList<>(2);
cacheOpMap.put(nameHolder, col);
}
col.add(builder.build());
}
List<Element> evictCacheMethods = DomUtils.getChildElementsByTagName(definition, CACHE_EVICT_ELEMENT);
for (Element opElement : evictCacheMethods) {
String name = prop.merge(opElement, parserContext.getReaderContext());
TypedStringValue nameHolder = new TypedStringValue(name);
nameHolder.setSource(parserContext.extractSource(opElement));
CacheEvictOperation.Builder builder = prop.merge(opElement,
parserContext.getReaderContext(), new CacheEvictOperation.Builder());
String wide = opElement.getAttribute("all-entries");
if (StringUtils.hasText(wide)) {
builder.setCacheWide(Boolean.parseBoolean(wide.trim()));
}
String after = opElement.getAttribute("before-invocation");
if (StringUtils.hasText(after)) {
builder.setBeforeInvocation(Boolean.parseBoolean(after.trim()));
}
Collection<CacheOperation> col = cacheOpMap.get(nameHolder);
if (col == null) {
col = new ArrayList<>(2);
cacheOpMap.put(nameHolder, col);
}
col.add(builder.build());
}
List<Element> putCacheMethods = DomUtils.getChildElementsByTagName(definition, CACHE_PUT_ELEMENT);
for (Element opElement : putCacheMethods) {
String name = prop.merge(opElement, parserContext.getReaderContext());
TypedStringValue nameHolder = new TypedStringValue(name);
nameHolder.setSource(parserContext.extractSource(opElement));
CachePutOperation.Builder builder = prop.merge(opElement,
parserContext.getReaderContext(), new CachePutOperation.Builder());
builder.setUnless(getAttributeValue(opElement, "unless", ""));
Collection<CacheOperation> col = cacheOpMap.get(nameHolder);
if (col == null) {
col = new ArrayList<>(2);
cacheOpMap.put(nameHolder, col);
}
col.add(builder.build());
}
RootBeanDefinition attributeSourceDefinition = new RootBeanDefinition(NameMatchCacheOperationSource.class);
attributeSourceDefinition.setSource(parserContext.extractSource(definition));
attributeSourceDefinition.getPropertyValues().add("nameMap", cacheOpMap);
return attributeSourceDefinition;
}
/**
* Simple, reusable class used for overriding defaults.
*/
private static class Props {
private String key;
private String keyGenerator;
private String cacheManager;
private String condition;
private String method;
@Nullable
private String[] caches;
Props(Element root) {
String defaultCache = root.getAttribute("cache");
this.key = root.getAttribute("key");
this.keyGenerator = root.getAttribute("key-generator");
this.cacheManager = root.getAttribute("cache-manager");
this.condition = root.getAttribute("condition");
this.method = root.getAttribute(METHOD_ATTRIBUTE);
if (StringUtils.hasText(defaultCache)) {
this.caches = StringUtils.commaDelimitedListToStringArray(defaultCache.trim());
}
}
<T extends CacheOperation.Builder> T merge(Element element, ReaderContext readerCtx, T builder) {
String cache = element.getAttribute("cache");
// sanity check
String[] localCaches = this.caches;
if (StringUtils.hasText(cache)) {
localCaches = StringUtils.commaDelimitedListToStringArray(cache.trim());
}
if (localCaches != null) {
builder.setCacheNames(localCaches);
} else {
readerCtx.error("No cache specified for " + element.getNodeName(), element);
}
builder.setKey(getAttributeValue(element, "key", this.key));
builder.setKeyGenerator(getAttributeValue(element, "key-generator", this.keyGenerator));
builder.setCacheManager(getAttributeValue(element, "cache-manager", this.cacheManager));
builder.setCondition(getAttributeValue(element, "condition", this.condition));
if (StringUtils.hasText(builder.getKey()) && StringUtils.hasText(builder.getKeyGenerator())) {
throw new IllegalStateException("Invalid cache advice configuration on '" +
element.toString() + "'. Both 'key' and 'keyGenerator' attributes have been set. " +
"These attributes are mutually exclusive: either set the SpEL expression used to" +
"compute the key at runtime or set the name of the KeyGenerator bean to use.");
}
return builder;
}
@Nullable
String merge(Element element, ReaderContext readerCtx) {
String method = element.getAttribute(METHOD_ATTRIBUTE);
if (StringUtils.hasText(method)) {
return method.trim();
}
if (StringUtils.hasText(this.method)) {
return this.method;
}
readerCtx.error("No method specified for " + element.getNodeName(), element);
return null;
}
}
}
|
package com.raizlabs.android.dbflow.test.list;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import com.raizlabs.android.dbflow.list.FlowCursorList;
import com.raizlabs.android.dbflow.list.FlowQueryList;
import com.raizlabs.android.dbflow.runtime.transaction.TransactionListenerAdapter;
import com.raizlabs.android.dbflow.sql.language.Delete;
import com.raizlabs.android.dbflow.test.FlowTestCase;
import com.raizlabs.android.dbflow.test.utils.GenerationUtils;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertTrue;
/**
* Description:
*/
public class ListTest extends FlowTestCase {
@Test
public void testTableList() {
Delete.table(ListModel.class);
List<ListModel> testModel1s = GenerationUtils.generateRandomModels(ListModel.class, 100);
FlowQueryList<ListModel> flowQueryList = new FlowQueryList<>(ListModel.class);
assertTrue(flowQueryList.size() == 100);
assertTrue(flowQueryList.containsAll(testModel1s));
ListModel model1 = flowQueryList.remove(0);
assertTrue(flowQueryList.size() == 99);
assertTrue(flowQueryList.add(model1));
assertTrue(flowQueryList.size() == 100);
flowQueryList.set(model1);
flowQueryList.clear();
assertTrue(flowQueryList.size() == 0);
}
@Test
public void testTableListEmpty() {
Delete.table(ListModel.class);
FlowQueryList<ListModel> flowQueryList = new FlowQueryList<>(ListModel.class);
ListModel listModel = new ListModel();
listModel.setName("Test");
flowQueryList.add(listModel);
assertTrue(flowQueryList.size() == 1);
Delete.table(ListModel.class);
}
private class TestModelAdapter extends BaseAdapter {
private FlowCursorList<ListModel> mFlowCursorList;
public TestModelAdapter(FlowCursorList<ListModel> flowCursorList) {
mFlowCursorList = flowCursorList;
}
@Override
public int getCount() {
return mFlowCursorList.getCount();
}
@Override
public ListModel getItem(int position) {
return mFlowCursorList.getItem(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return null;
}
}
@Test
public void testCursorList() {
Delete.table(ListModel.class);
final List<ListModel> testModel1s = GenerationUtils.generateRandomModels(ListModel.class, 50);
FlowCursorList<ListModel> flowCursorList = new FlowCursorList<>(true, ListModel.class);
TestModelAdapter modelAdapter = new TestModelAdapter(flowCursorList);
assertTrue(testModel1s.size() == modelAdapter.getCount());
flowCursorList.fetchAll(new TransactionListenerAdapter<List<ListModel>>() {
@Override
public void onResultReceived(List<ListModel> models) {
assertTrue(models.size() == testModel1s.size());
}
});
}
}
|
package com.packtpub.springsecurity.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import javax.persistence.*;
import java.io.Serializable;
import java.security.Principal;
import java.util.Set;
/**
* {@link CalendarUser} is this applications notion of a user. It is good to use your own objects to interact with a
* user especially in large applications. This ensures that as you evolve your security requirements (update Spring
* Security, leverage new Spring Security modules, or even swap out security implementations) you can do so easily.
*
* @author Rob Winch
* @author Mick Knutson
*
*/
@Entity
@Table(name = "calendar_users")
public class CalendarUser implements Principal, Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String firstName;
private String lastName;
private String email;
private String password;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "user_role",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles;
/**
* Gets the email address for this user. When authenticating against this data directly, this is also used as the
* username.
*
* @return
*/
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
/**
* Gets the first name of the user.
*
* @return
*/
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* Gets the id for this user. When creating a new user this should be null, otherwise it will be non-null.
*
* @return
*/
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
/**
* Gets the last name of the user.
*
* @return
*/
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* Gets the password for this user. In some instances, this password is not actually used. For example, when an in
* memory authentication is used the password on the spring security User object is used.
*
* @return
*/
@JsonIgnore
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
/**
* Get the list of Roles for this CalendarUser
* @return
*/
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
// --- convenience methods ---
/**
* Gets the full name in a formatted fashion. Note in a real application a formatter may be more appropriate, but in
* this application simplicity is more important.
*
* @return
*/
@JsonIgnore
public String getName() {
return getEmail();
}
// --- override Object ---
@Override
public int hashCode() {
//return HashCodeBuilder.reflectionHashCode(this);
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
//return EqualsBuilder.reflectionEquals(this, obj);
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CalendarUser other = (CalendarUser) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
private static final long serialVersionUID = 8433999509932007961L;
@Override
public String toString() {
return ReflectionToStringBuilder.toString(this);
}
} // The End...
|
package com.joaogsrocha._SpringREST.payroll;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
class SkinController {
private final SkinRepository repository;
SkinController(SkinRepository repository) {
this.repository = repository;
}
// Aggregate root
// tag::get-aggregate-root[]
@GetMapping("api/skin")
List<Skin> all() {
return repository.findAll();
}
// end::get-aggregate-root[]
@PostMapping("api/skin")
Skin newSkin(@RequestBody Skin newSkin) {
return repository.save(newSkin);
}
// Single item
@GetMapping("api/skin/{id}")
Skin one(@PathVariable Long id) {
return repository.findById(id)
.orElseThrow(() -> new SkinNotFoundException(id));
}
@PutMapping("api/skin/{id}")
Skin replaceSkin(@RequestBody Skin newSkin, @PathVariable Long id) {
return repository.findById(id)
.map(skin -> {
skin.setName(newSkin.getName());
skin.setCondition(newSkin.getCondition());
return repository.save(skin);
})
.orElseGet(() -> {
newSkin.setId(id);
return repository.save(newSkin);
});
}
@DeleteMapping("api/skin/{id}")
void deleteEmployee(@PathVariable Long id) {
repository.deleteById(id);
}
}
|
package com.bjwg.back.model;
import com.bjwg.back.base.Pages;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class InfoExample {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table bjwg_info
*
* @mbggenerated
*/
protected String orderByClause;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table bjwg_info
*
* @mbggenerated
*/
protected boolean distinct;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table bjwg_info
*
* @mbggenerated
*/
protected List<Criteria> oredCriteria;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table bjwg_info
*
* @mbggenerated
*/
protected Pages page;
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table bjwg_info
*
* @mbggenerated
*/
public InfoExample() {
oredCriteria = new ArrayList<Criteria>();
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table bjwg_info
*
* @mbggenerated
*/
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table bjwg_info
*
* @mbggenerated
*/
public String getOrderByClause() {
return orderByClause;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table bjwg_info
*
* @mbggenerated
*/
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table bjwg_info
*
* @mbggenerated
*/
public boolean isDistinct() {
return distinct;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table bjwg_info
*
* @mbggenerated
*/
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table bjwg_info
*
* @mbggenerated
*/
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table bjwg_info
*
* @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 bjwg_info
*
* @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 bjwg_info
*
* @mbggenerated
*/
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table bjwg_info
*
* @mbggenerated
*/
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table bjwg_info
*
* @mbggenerated
*/
public void setPage(Pages page) {
this.page=page;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table bjwg_info
*
* @mbggenerated
*/
public Pages getPage() {
return page;
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table bjwg_info
*
* @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;
}
public void addCriterion(String condition) {
condition = "1=1 "+condition;
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 andInfoIdIsNull() {
addCriterion("t.info_id is null");
return (Criteria) this;
}
public Criteria andInfoIdIsNotNull() {
addCriterion("t.info_id is not null");
return (Criteria) this;
}
public Criteria andInfoIdEqualTo(Long value) {
addCriterion("t.info_id =", value, "infoId");
return (Criteria) this;
}
public Criteria andInfoIdNotEqualTo(Long value) {
addCriterion("t.info_id <>", value, "infoId");
return (Criteria) this;
}
public Criteria andInfoIdGreaterThan(Long value) {
addCriterion("t.info_id >", value, "infoId");
return (Criteria) this;
}
public Criteria andInfoIdGreaterThanOrEqualTo(Long value) {
addCriterion("t.info_id >=", value, "infoId");
return (Criteria) this;
}
public Criteria andInfoIdLessThan(Long value) {
addCriterion("t.info_id <", value, "infoId");
return (Criteria) this;
}
public Criteria andInfoIdLessThanOrEqualTo(Long value) {
addCriterion("t.info_id <=", value, "infoId");
return (Criteria) this;
}
public Criteria andInfoIdIn(List<Long> values) {
addCriterion("t.info_id in", values, "infoId");
return (Criteria) this;
}
public Criteria andInfoIdNotIn(List<Long> values) {
addCriterion("t.info_id not in", values, "infoId");
return (Criteria) this;
}
public Criteria andInfoIdBetween(Long value1, Long value2) {
addCriterion("t.info_id between", value1, value2, "infoId");
return (Criteria) this;
}
public Criteria andInfoIdNotBetween(Long value1, Long value2) {
addCriterion("t.info_id not between", value1, value2, "infoId");
return (Criteria) this;
}
public Criteria andTitleIsNull() {
addCriterion("t.title is null");
return (Criteria) this;
}
public Criteria andTitleIsNotNull() {
addCriterion("t.title is not null");
return (Criteria) this;
}
public Criteria andTitleEqualTo(String value) {
addCriterion("t.title =", value, "title");
return (Criteria) this;
}
public Criteria andTitleNotEqualTo(String value) {
addCriterion("t.title <>", value, "title");
return (Criteria) this;
}
public Criteria andTitleGreaterThan(String value) {
addCriterion("t.title >", value, "title");
return (Criteria) this;
}
public Criteria andTitleGreaterThanOrEqualTo(String value) {
addCriterion("t.title >=", value, "title");
return (Criteria) this;
}
public Criteria andTitleLessThan(String value) {
addCriterion("t.title <", value, "title");
return (Criteria) this;
}
public Criteria andTitleLessThanOrEqualTo(String value) {
addCriterion("t.title <=", value, "title");
return (Criteria) this;
}
public Criteria andTitleLike(String value) {
addCriterion("t.title like", value, "title");
return (Criteria) this;
}
public Criteria andTitleNotLike(String value) {
addCriterion("t.title not like", value, "title");
return (Criteria) this;
}
public Criteria andTitleIn(List<String> values) {
addCriterion("t.title in", values, "title");
return (Criteria) this;
}
public Criteria andTitleNotIn(List<String> values) {
addCriterion("t.title not in", values, "title");
return (Criteria) this;
}
public Criteria andTitleBetween(String value1, String value2) {
addCriterion("t.title between", value1, value2, "title");
return (Criteria) this;
}
public Criteria andTitleNotBetween(String value1, String value2) {
addCriterion("t.title not between", value1, value2, "title");
return (Criteria) this;
}
public Criteria andSummaryIsNull() {
addCriterion("t.summary is null");
return (Criteria) this;
}
public Criteria andSummaryIsNotNull() {
addCriterion("t.summary is not null");
return (Criteria) this;
}
public Criteria andSummaryEqualTo(String value) {
addCriterion("t.summary =", value, "summary");
return (Criteria) this;
}
public Criteria andSummaryNotEqualTo(String value) {
addCriterion("t.summary <>", value, "summary");
return (Criteria) this;
}
public Criteria andSummaryGreaterThan(String value) {
addCriterion("t.summary >", value, "summary");
return (Criteria) this;
}
public Criteria andSummaryGreaterThanOrEqualTo(String value) {
addCriterion("t.summary >=", value, "summary");
return (Criteria) this;
}
public Criteria andSummaryLessThan(String value) {
addCriterion("t.summary <", value, "summary");
return (Criteria) this;
}
public Criteria andSummaryLessThanOrEqualTo(String value) {
addCriterion("t.summary <=", value, "summary");
return (Criteria) this;
}
public Criteria andSummaryLike(String value) {
addCriterion("t.summary like", value, "summary");
return (Criteria) this;
}
public Criteria andSummaryNotLike(String value) {
addCriterion("t.summary not like", value, "summary");
return (Criteria) this;
}
public Criteria andSummaryIn(List<String> values) {
addCriterion("t.summary in", values, "summary");
return (Criteria) this;
}
public Criteria andSummaryNotIn(List<String> values) {
addCriterion("t.summary not in", values, "summary");
return (Criteria) this;
}
public Criteria andSummaryBetween(String value1, String value2) {
addCriterion("t.summary between", value1, value2, "summary");
return (Criteria) this;
}
public Criteria andSummaryNotBetween(String value1, String value2) {
addCriterion("t.summary not between", value1, value2, "summary");
return (Criteria) this;
}
public Criteria andCtimeIsNull() {
addCriterion("t.ctime is null");
return (Criteria) this;
}
public Criteria andCtimeIsNotNull() {
addCriterion("t.ctime is not null");
return (Criteria) this;
}
public Criteria andCtimeEqualTo(Date value) {
addCriterion("t.ctime =", value, "ctime");
return (Criteria) this;
}
public Criteria andCtimeNotEqualTo(Date value) {
addCriterion("t.ctime <>", value, "ctime");
return (Criteria) this;
}
public Criteria andCtimeGreaterThan(Date value) {
addCriterion("t.ctime >", value, "ctime");
return (Criteria) this;
}
public Criteria andCtimeGreaterThanOrEqualTo(Date value) {
addCriterion("t.ctime >=", value, "ctime");
return (Criteria) this;
}
public Criteria andCtimeLessThan(Date value) {
addCriterion("t.ctime <", value, "ctime");
return (Criteria) this;
}
public Criteria andCtimeLessThanOrEqualTo(Date value) {
addCriterion("t.ctime <=", value, "ctime");
return (Criteria) this;
}
public Criteria andCtimeIn(List<Date> values) {
addCriterion("t.ctime in", values, "ctime");
return (Criteria) this;
}
public Criteria andCtimeNotIn(List<Date> values) {
addCriterion("t.ctime not in", values, "ctime");
return (Criteria) this;
}
public Criteria andCtimeBetween(Date value1, Date value2) {
addCriterion("t.ctime between", value1, value2, "ctime");
return (Criteria) this;
}
public Criteria andCtimeNotBetween(Date value1, Date value2) {
addCriterion("t.ctime not between", value1, value2, "ctime");
return (Criteria) this;
}
public Criteria andTypeIsNull() {
addCriterion("t.type is null");
return (Criteria) this;
}
public Criteria andTypeIsNotNull() {
addCriterion("t.type is not null");
return (Criteria) this;
}
public Criteria andTypeEqualTo(Byte value) {
addCriterion("t.type =", value, "type");
return (Criteria) this;
}
public Criteria andTypeNotEqualTo(Byte value) {
addCriterion("t.type <>", value, "type");
return (Criteria) this;
}
public Criteria andTypeGreaterThan(Byte value) {
addCriterion("t.type >", value, "type");
return (Criteria) this;
}
public Criteria andTypeGreaterThanOrEqualTo(Byte value) {
addCriterion("t.type >=", value, "type");
return (Criteria) this;
}
public Criteria andTypeLessThan(Byte value) {
addCriterion("t.type <", value, "type");
return (Criteria) this;
}
public Criteria andTypeLessThanOrEqualTo(Byte value) {
addCriterion("t.type <=", value, "type");
return (Criteria) this;
}
public Criteria andTypeIn(List<Byte> values) {
addCriterion("t.type in", values, "type");
return (Criteria) this;
}
public Criteria andTypeNotIn(List<Byte> values) {
addCriterion("t.type not in", values, "type");
return (Criteria) this;
}
public Criteria andTypeBetween(Byte value1, Byte value2) {
addCriterion("t.type between", value1, value2, "type");
return (Criteria) this;
}
public Criteria andTypeNotBetween(Byte value1, Byte value2) {
addCriterion("t.type not between", value1, value2, "type");
return (Criteria) this;
}
public Criteria andStatusIsNull() {
addCriterion("t.status is null");
return (Criteria) this;
}
public Criteria andStatusIsNotNull() {
addCriterion("t.status is not null");
return (Criteria) this;
}
public Criteria andStatusEqualTo(Byte value) {
addCriterion("t.status =", value, "status");
return (Criteria) this;
}
public Criteria andStatusNotEqualTo(Byte value) {
addCriterion("t.status <>", value, "status");
return (Criteria) this;
}
public Criteria andStatusGreaterThan(Byte value) {
addCriterion("t.status >", value, "status");
return (Criteria) this;
}
public Criteria andStatusGreaterThanOrEqualTo(Byte value) {
addCriterion("t.status >=", value, "status");
return (Criteria) this;
}
public Criteria andStatusLessThan(Byte value) {
addCriterion("t.status <", value, "status");
return (Criteria) this;
}
public Criteria andStatusLessThanOrEqualTo(Byte value) {
addCriterion("t.status <=", value, "status");
return (Criteria) this;
}
public Criteria andStatusIn(List<Byte> values) {
addCriterion("t.status in", values, "status");
return (Criteria) this;
}
public Criteria andStatusNotIn(List<Byte> values) {
addCriterion("t.status not in", values, "status");
return (Criteria) this;
}
public Criteria andStatusBetween(Byte value1, Byte value2) {
addCriterion("t.status between", value1, value2, "status");
return (Criteria) this;
}
public Criteria andStatusNotBetween(Byte value1, Byte value2) {
addCriterion("t.status not between", value1, value2, "status");
return (Criteria) this;
}
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table bjwg_info
*
* @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 bjwg_info
*
* @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);
}
}
}
|
package com.shuflr.interceptor.exceptions;
/**
* Copyright (c) 2013 Carel Vosloo <code@bronzegate.com>
* All rights reserved. No warranty, explicit or implicit, provided.
* Created: 07/08/2013 15:49 by carel
*/
public class AuthenticationRequiredException extends InterceptorException{
public AuthenticationRequiredException(String message) {
super(message);
}
}
|
/*
* Copyright 2013-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.kubernetes.fabric8.config.bootstrap;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.kubernetes.fabric8.config.Application;
import org.springframework.cloud.kubernetes.fabric8.config.Fabric8ConfigMapPropertySourceLocator;
import org.springframework.cloud.kubernetes.fabric8.config.Fabric8SecretsPropertySourceLocator;
import org.springframework.context.ConfigurableApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Application.class)
class Fabric8BootstrapConfigurationNotInsideK8s {
@Autowired
private ConfigurableApplicationContext context;
// tests that @ConditionalOnCloudPlatform(CloudPlatform.KUBERNETES) has the desired
// effect, meaning when it is disabled, no property source bean is present
@Test
void bothMissing() {
assertThat(context.getBeanNamesForType(Fabric8ConfigMapPropertySourceLocator.class)).hasSize(0);
assertThat(context.getBeanNamesForType(Fabric8SecretsPropertySourceLocator.class)).hasSize(0);
}
}
|
/*
* Copyright 2018-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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.vault.config;
import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.vault.authentication.ClientAuthentication;
import org.springframework.vault.authentication.ReactiveSessionManager;
import org.springframework.vault.authentication.SessionManager;
import org.springframework.vault.authentication.VaultTokenSupplier;
import org.springframework.vault.core.ReactiveVaultTemplate;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Unit tests for {@link VaultReactiveBootstrapConfiguration}.
*
* @author Mark Paluch
*/
public class ReactiveVaultBootstrapConfigurationTests {
private ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration(
AutoConfigurations.of(VaultBootstrapConfiguration.class, VaultReactiveBootstrapConfiguration.class));
@Test
public void shouldConfigureWithoutAuthentication() {
this.contextRunner.withPropertyValues("spring.cloud.vault.kv.enabled=false",
"spring.cloud.vault.authentication=NONE", "spring.cloud.bootstrap.enabled=true").run(context -> {
assertThat(context).doesNotHaveBean(SessionManager.class);
assertThat(context).doesNotHaveBean(ClientAuthentication.class);
assertThat(context).doesNotHaveBean(VaultTokenSupplier.class);
assertThat(context).doesNotHaveBean(ReactiveSessionManager.class);
assertThat(context).hasSingleBean(ReactiveVaultTemplate.class);
});
}
}
|
/**
* Copyright 2012-2013 the Semargl contributors. See AUTHORS for more details.
*
* 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.semarglproject.jena.core.sink;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.graph.Triple;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.shared.Lock;
import org.semarglproject.rdf.ParseException;
import org.semarglproject.sink.TripleSink;
/**
* Implementation if {@link TripleSink} which feeds triples from Semargl's pipeline to Jena's {@link Model}.
* <br>
* List of supported options:
* <ul>
* <li>{@link #OUTPUT_MODEL_PROPERTY}</li>
* </ul>
*/
public final class JenaSink extends AbstractJenaSink {
private static final int DEFAULT_BATCH_SIZE = 512;
private final int batchSize;
private Triple[] triples;
private int triplesSize;
private JenaSink(Model model, int batchSize) {
super(model);
this.batchSize = batchSize;
}
/**
* Instantiates sink for specified Jena {@link Model}
* @param model model to sink triples to
* @return new instance of Jena sink
*/
public static TripleSink connect(Model model) {
return new JenaSink(model, DEFAULT_BATCH_SIZE);
}
private void newBatch() {
triples = new Triple[batchSize];
triplesSize = 0;
}
@Override
protected void addTriple(Node subj, Node pred, Node obj) {
triples[triplesSize++] = new Triple(subj, pred, obj);
if (triplesSize == batchSize) {
model.enterCriticalSection(Lock.WRITE);
model.getGraph().getBulkUpdateHandler().add(triples);
model.leaveCriticalSection();
newBatch();
}
}
@Override
public void startStream() throws ParseException {
newBatch();
}
@Override
public void endStream() throws ParseException {
if (triplesSize == 0) {
return;
}
Triple[] dummy = new Triple[triplesSize];
System.arraycopy(triples, 0, dummy, 0, triplesSize);
model.enterCriticalSection(Lock.WRITE);
model.getGraph().getBulkUpdateHandler().add(dummy);
model.leaveCriticalSection();
}
@Override
public void setBaseUri(String baseUri) {
}
}
|
/*
* Copyright (c) 2016-2017, Adam <Adam@sigterm.info>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.mixins;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import javax.inject.Named;
import net.runelite.api.ChatMessageType;
import net.runelite.api.ClanMember;
import net.runelite.api.EnumComposition;
import net.runelite.api.Friend;
import net.runelite.api.GameState;
import net.runelite.api.GrandExchangeOffer;
import net.runelite.api.GraphicsObject;
import net.runelite.api.HashTable;
import net.runelite.api.HintArrowType;
import net.runelite.api.Ignore;
import net.runelite.api.IndexDataBase;
import net.runelite.api.IndexedSprite;
import net.runelite.api.InventoryID;
import net.runelite.api.MenuAction;
import static net.runelite.api.MenuAction.PLAYER_EIGTH_OPTION;
import static net.runelite.api.MenuAction.PLAYER_FIFTH_OPTION;
import static net.runelite.api.MenuAction.PLAYER_FIRST_OPTION;
import static net.runelite.api.MenuAction.PLAYER_FOURTH_OPTION;
import static net.runelite.api.MenuAction.PLAYER_SECOND_OPTION;
import static net.runelite.api.MenuAction.PLAYER_SEVENTH_OPTION;
import static net.runelite.api.MenuAction.PLAYER_SIXTH_OPTION;
import static net.runelite.api.MenuAction.PLAYER_THIRD_OPTION;
import net.runelite.api.MenuEntry;
import net.runelite.api.MessageNode;
import net.runelite.api.NPC;
import net.runelite.api.Node;
import net.runelite.api.PacketBuffer;
import static net.runelite.api.Perspective.LOCAL_TILE_SIZE;
import net.runelite.api.Player;
import net.runelite.api.Point;
import net.runelite.api.Prayer;
import net.runelite.api.Projectile;
import net.runelite.api.Skill;
import net.runelite.api.SpritePixels;
import net.runelite.api.Tile;
import net.runelite.api.VarPlayer;
import net.runelite.api.Varbits;
import net.runelite.api.WidgetNode;
import net.runelite.api.WorldType;
import net.runelite.api.coords.LocalPoint;
import net.runelite.api.coords.WorldPoint;
import net.runelite.api.events.BoostedLevelChanged;
import net.runelite.api.events.CanvasSizeChanged;
import net.runelite.api.events.ChatMessage;
import net.runelite.api.events.ClanChanged;
import net.runelite.api.events.ClientTick;
import net.runelite.api.events.DraggingWidgetChanged;
import net.runelite.api.events.ExperienceChanged;
import net.runelite.api.events.GameStateChanged;
import net.runelite.api.events.GrandExchangeOfferChanged;
import net.runelite.api.events.MenuEntryAdded;
import net.runelite.api.events.MenuOpened;
import net.runelite.api.events.MenuOptionClicked;
import net.runelite.api.events.MenuShouldLeftClick;
import net.runelite.api.events.NpcSpawned;
import net.runelite.api.events.PlayerDespawned;
import net.runelite.api.events.PlayerMenuOptionsChanged;
import net.runelite.api.events.PlayerSpawned;
import net.runelite.api.events.ResizeableChanged;
import net.runelite.api.events.UsernameChanged;
import net.runelite.api.events.VarbitChanged;
import net.runelite.api.events.WidgetLoaded;
import net.runelite.api.hooks.Callbacks;
import net.runelite.api.hooks.DrawCallbacks;
import net.runelite.api.mixins.Copy;
import net.runelite.api.mixins.FieldHook;
import net.runelite.api.mixins.Inject;
import net.runelite.api.mixins.MethodHook;
import net.runelite.api.mixins.Mixin;
import net.runelite.api.mixins.Replace;
import net.runelite.api.mixins.Shadow;
import net.runelite.api.vars.AccountType;
import net.runelite.api.widgets.Widget;
import net.runelite.api.widgets.WidgetInfo;
import net.runelite.api.widgets.WidgetItem;
import net.runelite.api.widgets.WidgetType;
import net.runelite.rs.api.RSChatLineBuffer;
import net.runelite.rs.api.RSClanMemberManager;
import net.runelite.rs.api.RSClient;
import net.runelite.rs.api.RSDeque;
import net.runelite.rs.api.RSEnum;
import net.runelite.rs.api.RSFriendContainer;
import net.runelite.rs.api.RSFriendManager;
import net.runelite.rs.api.RSHashTable;
import net.runelite.rs.api.RSIgnoreContainer;
import net.runelite.rs.api.RSIndexDataBase;
import net.runelite.rs.api.RSIndexedSprite;
import net.runelite.rs.api.RSItem;
import net.runelite.rs.api.RSItemContainer;
import net.runelite.rs.api.RSNPC;
import net.runelite.rs.api.RSName;
import net.runelite.rs.api.RSPlayer;
import net.runelite.rs.api.RSSpritePixels;
import net.runelite.rs.api.RSWidget;
import org.slf4j.Logger;
@Mixin(RSClient.class)
public abstract class RSClientMixin implements RSClient
{
@Shadow("clientInstance")
private static RSClient client;
@Inject
@javax.inject.Inject
private Callbacks callbacks;
@Inject
private DrawCallbacks drawCallbacks;
@Inject
@javax.inject.Inject
@Named("Core Logger")
private Logger logger;
@Inject
private static int tickCount;
@Inject
private static boolean interpolatePlayerAnimations;
@Inject
private static boolean interpolateNpcAnimations;
@Inject
private static boolean interpolateObjectAnimations;
@Inject
private static RSPlayer[] oldPlayers = new RSPlayer[2048];
@Inject
private static int itemPressedDurationBuffer;
@Inject
private static int inventoryDragDelay;
@Inject
private static int oldMenuEntryCount;
@Inject
private static RSItem lastItemDespawn;
@Inject
private boolean gpu;
@Inject
private static boolean oldIsResized;
@Inject
static int skyboxColor;
@Inject
private final Cache<Integer, RSEnum> enumCache = CacheBuilder.newBuilder()
.maximumSize(64)
.build();
@Inject
public RSClientMixin()
{
}
@Inject
@Override
public Callbacks getCallbacks()
{
return callbacks;
}
@Inject
@Override
public DrawCallbacks getDrawCallbacks()
{
return drawCallbacks;
}
@Inject
@Override
public void setDrawCallbacks(DrawCallbacks drawCallbacks)
{
this.drawCallbacks = drawCallbacks;
}
@Inject
@Override
public Logger getLogger()
{
return logger;
}
@Inject
@Override
public boolean isInterpolatePlayerAnimations()
{
return interpolatePlayerAnimations;
}
@Inject
@Override
public void setInterpolatePlayerAnimations(boolean interpolate)
{
interpolatePlayerAnimations = interpolate;
}
@Inject
@Override
public boolean isInterpolateNpcAnimations()
{
return interpolateNpcAnimations;
}
@Inject
@Override
public void setInterpolateNpcAnimations(boolean interpolate)
{
interpolateNpcAnimations = interpolate;
}
@Inject
@Override
public boolean isInterpolateObjectAnimations()
{
return interpolateObjectAnimations;
}
@Inject
@Override
public void setInterpolateObjectAnimations(boolean interpolate)
{
interpolateObjectAnimations = interpolate;
}
@Inject
@Override
public void setInventoryDragDelay(int delay)
{
inventoryDragDelay = delay;
}
@Inject
@Override
public AccountType getAccountType()
{
int varbit = getVar(Varbits.ACCOUNT_TYPE);
switch (varbit)
{
case 1:
return AccountType.IRONMAN;
case 2:
return AccountType.ULTIMATE_IRONMAN;
case 3:
return AccountType.HARDCORE_IRONMAN;
}
return AccountType.NORMAL;
}
@Inject
@Override
public Tile getSelectedSceneTile()
{
int tileX = getSelectedSceneTileX();
int tileY = getSelectedSceneTileY();
if (tileX == -1 || tileY == -1)
{
return null;
}
return getScene().getTiles()[getPlane()][tileX][tileY];
}
@Inject
@Override
public List<Player> getPlayers()
{
int validPlayerIndexes = getPlayerIndexesCount();
int[] playerIndexes = getPlayerIndices();
Player[] cachedPlayers = getCachedPlayers();
List<Player> players = new ArrayList<Player>(validPlayerIndexes);
for (int i = 0; i < validPlayerIndexes; ++i)
{
players.add(cachedPlayers[playerIndexes[i]]);
}
return players;
}
@Inject
@Override
public List<NPC> getNpcs()
{
int validNpcIndexes = getNpcIndexesCount();
int[] npcIndexes = getNpcIndices();
NPC[] cachedNpcs = getCachedNPCs();
List<NPC> npcs = new ArrayList<NPC>(validNpcIndexes);
for (int i = 0; i < validNpcIndexes; ++i)
{
npcs.add(cachedNpcs[npcIndexes[i]]);
}
return npcs;
}
@Inject
@Override
public int getBoostedSkillLevel(Skill skill)
{
int[] boostedLevels = getBoostedSkillLevels();
return boostedLevels[skill.ordinal()];
}
@Inject
@Override
public int getRealSkillLevel(Skill skill)
{
int[] realLevels = getRealSkillLevels();
return realLevels[skill.ordinal()];
}
@Inject
@Override
public int getTotalLevel()
{
int totalLevel = 0;
int[] realLevels = client.getRealSkillLevels();
int lastSkillIdx = Skill.CONSTRUCTION.ordinal();
for (int i = 0; i < realLevels.length; i++)
{
if (i <= lastSkillIdx)
{
totalLevel += realLevels[i];
}
}
return totalLevel;
}
@Inject
@Override
public void addChatMessage(ChatMessageType type, String name, String message, String sender)
{
addChatMessage(type.getType(), name, message, sender);
}
@Inject
@Override
public GameState getGameState()
{
return GameState.of(getRSGameState());
}
@Inject
@Override
public Point getMouseCanvasPosition()
{
return new Point(getMouseX(), getMouseY());
}
@Inject
@Override
public Widget[] getWidgetRoots()
{
int topGroup = getWidgetRoot();
List<Widget> widgets = new ArrayList<Widget>();
for (RSWidget widget : getWidgets()[topGroup])
{
if (widget != null && widget.getRSParentId() == -1)
{
widgets.add(widget);
}
}
return widgets.toArray(new Widget[widgets.size()]);
}
@Inject
@Override
public Widget getWidget(WidgetInfo widget)
{
int groupId = widget.getGroupId();
int childId = widget.getChildId();
return getWidget(groupId, childId);
}
@Inject
@Override
public RSWidget[] getGroup(int groupId)
{
RSWidget[][] widgets = getWidgets();
if (widgets == null || groupId < 0 || groupId >= widgets.length || widgets[groupId] == null)
{
return null;
}
return widgets[groupId];
}
@Inject
@Override
public Widget getWidget(int groupId, int childId)
{
RSWidget[][] widgets = getWidgets();
if (widgets == null || widgets.length <= groupId)
{
return null;
}
RSWidget[] childWidgets = widgets[groupId];
if (childWidgets == null || childWidgets.length <= childId)
{
return null;
}
return childWidgets[childId];
}
@Inject
@Override
public int getVar(VarPlayer varPlayer)
{
int[] varps = getVarps();
return varps[varPlayer.getId()];
}
@Inject
@Override
public int getVarpValue(int[] varps, int varpId)
{
return varps[varpId];
}
@Inject
@Override
public void setVarpValue(int[] varps, int varpId, int value)
{
varps[varpId] = value;
}
@Inject
@Override
public boolean isPrayerActive(Prayer prayer)
{
return getVar(prayer.getVarbit()) == 1;
}
/**
* Returns the local player's current experience in the specified
* {@link Skill}.
*
* @param skill the {@link Skill} to retrieve the experience for
* @return the local player's current experience in the specified
* {@link Skill}, or -1 if the {@link Skill} isn't valid
*/
@Inject
@Override
public int getSkillExperience(Skill skill)
{
int[] experiences = getSkillExperiences();
if (skill == Skill.OVERALL)
{
logger.debug("getSkillExperience called for {}!", skill);
return (int) getOverallExperience();
}
int idx = skill.ordinal();
// I'm not certain exactly how needed this is, but if the Skill enum is updated in the future
// to hold something else that's not reported it'll save us from an ArrayIndexOutOfBoundsException.
if (idx >= experiences.length)
{
return -1;
}
return experiences[idx];
}
@Inject
@Override
public long getOverallExperience()
{
int[] experiences = getSkillExperiences();
long totalExperience = 0L;
for (int experience : experiences)
{
totalExperience += experience;
}
return totalExperience;
}
@Inject
@Override
public void refreshChat()
{
setChatCycle(getCycleCntr());
}
@Inject
@Override
public Widget getViewportWidget()
{
if (isResized())
{
if (getVar(Varbits.SIDE_PANELS) == 1)
{
return getWidget(WidgetInfo.RESIZABLE_VIEWPORT_BOTTOM_LINE);
}
else
{
return getWidget(WidgetInfo.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX);
}
}
return getWidget(WidgetInfo.FIXED_VIEWPORT);
}
@Inject
@Override
public MenuEntry[] getMenuEntries()
{
int count = getMenuOptionCount();
String[] menuOptions = getMenuOptions();
String[] menuTargets = getMenuTargets();
int[] menuIdentifiers = getMenuIdentifiers();
int[] menuTypes = getMenuTypes();
int[] params0 = getMenuActionParams0();
int[] params1 = getMenuActionParams1();
boolean[] leftClick = getMenuForceLeftClick();
MenuEntry[] entries = new MenuEntry[count];
for (int i = 0; i < count; ++i)
{
MenuEntry entry = entries[i] = new MenuEntry();
entry.setOption(menuOptions[i]);
entry.setTarget(menuTargets[i]);
entry.setIdentifier(menuIdentifiers[i]);
entry.setType(menuTypes[i]);
entry.setParam0(params0[i]);
entry.setParam1(params1[i]);
entry.setForceLeftClick(leftClick[i]);
}
return entries;
}
@Inject
@Override
public void setMenuEntries(MenuEntry[] entries)
{
int count = 0;
String[] menuOptions = getMenuOptions();
String[] menuTargets = getMenuTargets();
int[] menuIdentifiers = getMenuIdentifiers();
int[] menuTypes = getMenuTypes();
int[] params0 = getMenuActionParams0();
int[] params1 = getMenuActionParams1();
boolean[] leftClick = getMenuForceLeftClick();
for (MenuEntry entry : entries)
{
menuOptions[count] = entry.getOption();
menuTargets[count] = entry.getTarget();
menuIdentifiers[count] = entry.getIdentifier();
menuTypes[count] = entry.getType();
params0[count] = entry.getParam0();
params1[count] = entry.getParam1();
leftClick[count] = entry.isForceLeftClick();
++count;
}
setMenuOptionCount(count);
oldMenuEntryCount = count;
}
@FieldHook("menuOptionCount")
@Inject
public static void onMenuOptionsChanged(int idx)
{
int oldCount = oldMenuEntryCount;
int newCount = client.getMenuOptionCount();
oldMenuEntryCount = newCount;
if (newCount == oldCount + 1)
{
MenuEntryAdded event = new MenuEntryAdded(
client.getMenuOptions()[newCount - 1],
client.getMenuTargets()[newCount - 1],
client.getMenuTypes()[newCount - 1],
client.getMenuIdentifiers()[newCount - 1],
client.getMenuActionParams0()[newCount - 1],
client.getMenuActionParams1()[newCount - 1]
);
client.getCallbacks().post(event);
}
}
@Inject
@Override
public List<Projectile> getProjectiles()
{
List<Projectile> projectiles = new ArrayList<Projectile>();
RSDeque projectileDeque = this.getProjectilesDeque();
Node head = projectileDeque.getHead();
for (Node node = head.getNext(); node != head; node = node.getNext())
{
projectiles.add((Projectile) node);
}
return projectiles;
}
@Inject
@Override
public List<GraphicsObject> getGraphicsObjects()
{
List<GraphicsObject> graphicsObjects = new ArrayList<GraphicsObject>();
RSDeque graphicsObjectDeque = this.getGraphicsObjectDeque();
Node head = graphicsObjectDeque.getHead();
for (Node node = head.getNext(); node != head; node = node.getNext())
{
graphicsObjects.add((GraphicsObject) node);
}
return graphicsObjects;
}
@Inject
@Override
public void setModIcons(IndexedSprite[] modIcons)
{
setRSModIcons((RSIndexedSprite[]) modIcons);
}
@Inject
@Override
@Nullable
public LocalPoint getLocalDestinationLocation()
{
int sceneX = getDestinationX();
int sceneY = getDestinationY();
if (sceneX != 0 && sceneY != 0)
{
return LocalPoint.fromScene(sceneX, sceneY);
}
return null;
}
@Inject
@Override
public void changeMemoryMode(boolean lowMemory)
{
setLowMemory(lowMemory);
setSceneLowMemory(lowMemory);
setAudioHighMemory(true);
setObjectCompositionLowDetail(lowMemory);
}
@Inject
@Override
public RSItemContainer getItemContainer(InventoryID inventory)
{
RSHashTable itemContainers = getItemContainers();
return (RSItemContainer) itemContainers.get(inventory.getId());
}
@Inject
@Override
public boolean isFriended(String name, boolean mustBeLoggedIn)
{
RSName rsName = createName(name, getLoginType());
return getFriendManager().isFriended(rsName, mustBeLoggedIn);
}
@Inject
@Override
public int getClanChatCount()
{
final RSClanMemberManager clanMemberManager = getClanMemberManager();
return clanMemberManager != null ? clanMemberManager.getCount() : 0;
}
@Inject
@Override
public ClanMember[] getClanMembers()
{
final RSClanMemberManager clanMemberManager = getClanMemberManager();
if (clanMemberManager == null)
{
return null;
}
final int count = clanMemberManager.getCount();
return Arrays.copyOf(clanMemberManager.getNameables(), count);
}
@Inject
@Override
public String getClanOwner()
{
return getClanMemberManager().getClanOwner();
}
@Inject
@Override
public String getClanChatName()
{
return getClanMemberManager().getClanChatName();
}
@Inject
@Override
public Friend[] getFriends()
{
final RSFriendManager friendManager = getFriendManager();
if (friendManager == null)
{
return null;
}
final RSFriendContainer friendContainer = friendManager.getFriendContainer();
if (friendContainer == null)
{
return null;
}
final int count = friendContainer.getCount();
return Arrays.copyOf(friendContainer.getNameables(), count);
}
@Inject
@Override
public int getFriendsCount()
{
final RSFriendManager friendManager = getFriendManager();
if (friendManager == null)
{
return -1;
}
final RSFriendContainer friendContainer = friendManager.getFriendContainer();
if (friendContainer == null)
{
return -1;
}
return friendContainer.getCount();
}
@Inject
@Override
public Ignore[] getIgnores()
{
final RSFriendManager friendManager = getFriendManager();
if (friendManager == null)
{
return null;
}
final RSIgnoreContainer ignoreContainer = friendManager.getIgnoreContainer();
if (ignoreContainer == null)
{
return null;
}
final int count = ignoreContainer.getCount();
return Arrays.copyOf(ignoreContainer.getNameables(), count);
}
@Inject
@Override
public int getIgnoreCount()
{
final RSFriendManager friendManager = getFriendManager();
if (friendManager == null)
{
return -1;
}
final RSIgnoreContainer ignoreContainer = friendManager.getIgnoreContainer();
if (ignoreContainer == null)
{
return -1;
}
return ignoreContainer.getCount();
}
@Inject
@Override
public boolean isClanMember(String name)
{
final RSClanMemberManager clanMemberManager = getClanMemberManager();
return clanMemberManager != null && clanMemberManager.isMember(createName(name, getLoginType()));
}
@FieldHook("draggingWidget")
@Inject
public static void draggingWidgetChanged(int idx)
{
DraggingWidgetChanged draggingWidgetChanged = new DraggingWidgetChanged();
draggingWidgetChanged.setDraggingWidget(client.isDraggingWidget());
client.getCallbacks().post(draggingWidgetChanged);
}
@Inject
@Override
public SpritePixels createItemSprite(int itemId, int quantity, int border, int shadowColor, int stackable, boolean noted, int scale)
{
assert isClientThread();
int zoom = get3dZoom();
set3dZoom(scale);
try
{
return createItemSprite(itemId, quantity, border, shadowColor, stackable, noted);
}
finally
{
set3dZoom(zoom);
}
}
@Copy("runWidgetOnLoadListener")
public static void rs$runWidgetOnLoadListener(int groupId)
{
throw new RuntimeException();
}
@Replace("runWidgetOnLoadListener")
public static void rl$runWidgetOnLoadListener(int groupId)
{
rs$runWidgetOnLoadListener(groupId);
RSWidget[][] widgets = client.getWidgets();
boolean loaded = widgets != null && widgets[groupId] != null;
if (loaded)
{
WidgetLoaded event = new WidgetLoaded();
event.setGroupId(groupId);
client.getCallbacks().post(event);
}
}
@FieldHook("itemPressedDuration")
@Inject
public static void itemPressedDurationChanged(int idx)
{
if (client.getItemPressedDuration() > 0)
{
itemPressedDurationBuffer++;
if (itemPressedDurationBuffer >= inventoryDragDelay)
{
client.setItemPressedDuration(itemPressedDurationBuffer);
}
else
{
client.setItemPressedDuration(0);
}
}
else
{
itemPressedDurationBuffer = 0;
}
}
@FieldHook("skillExperiences")
@Inject
public static void experiencedChanged(int idx)
{
ExperienceChanged experienceChanged = new ExperienceChanged();
Skill[] possibleSkills = Skill.values();
// We subtract one here because 'Overall' isn't considered a skill that's updated.
if (idx < possibleSkills.length - 1)
{
Skill updatedSkill = possibleSkills[idx];
experienceChanged.setSkill(updatedSkill);
client.getCallbacks().post(experienceChanged);
}
}
@FieldHook("boostedSkillLevels")
@Inject
public static void boostedSkillLevelsChanged(int idx)
{
Skill[] skills = Skill.values();
if (idx >= 0 && idx < skills.length - 1)
{
Skill updatedSkill = skills[idx];
BoostedLevelChanged boostedLevelChanged = new BoostedLevelChanged();
boostedLevelChanged.setSkill(updatedSkill);
client.getCallbacks().post(boostedLevelChanged);
}
}
@FieldHook("playerOptions")
@Inject
public static void playerOptionsChanged(int idx)
{
// Reset the menu type
MenuAction[] playerActions = {PLAYER_FIRST_OPTION, PLAYER_SECOND_OPTION, PLAYER_THIRD_OPTION, PLAYER_FOURTH_OPTION,
PLAYER_FIFTH_OPTION, PLAYER_SIXTH_OPTION, PLAYER_SEVENTH_OPTION, PLAYER_EIGTH_OPTION};
if (idx >= 0 && idx < playerActions.length)
{
MenuAction playerAction = playerActions[idx];
client.getPlayerMenuTypes()[idx] = playerAction.getId();
}
PlayerMenuOptionsChanged optionsChanged = new PlayerMenuOptionsChanged();
optionsChanged.setIndex(idx);
client.getCallbacks().post(optionsChanged);
}
@FieldHook("gameState")
@Inject
public static void gameStateChanged(int idx)
{
GameStateChanged gameStateChange = new GameStateChanged();
gameStateChange.setGameState(client.getGameState());
client.getCallbacks().post(gameStateChange);
}
@FieldHook("cachedNPCs")
@Inject
public static void cachedNPCsChanged(int idx)
{
RSNPC[] cachedNPCs = client.getCachedNPCs();
if (idx < 0 || idx >= cachedNPCs.length)
{
return;
}
RSNPC npc = cachedNPCs[idx];
if (npc != null)
{
npc.setIndex(idx);
client.getCallbacks().postDeferred(new NpcSpawned(npc));
}
}
@FieldHook("cachedPlayers")
@Inject
public static void cachedPlayersChanged(int idx)
{
RSPlayer[] cachedPlayers = client.getCachedPlayers();
if (idx < 0 || idx >= cachedPlayers.length)
{
return;
}
RSPlayer player = cachedPlayers[idx];
RSPlayer oldPlayer = oldPlayers[idx];
oldPlayers[idx] = player;
if (oldPlayer != null)
{
client.getCallbacks().post(new PlayerDespawned(oldPlayer));
}
if (player != null)
{
client.getCallbacks().postDeferred(new PlayerSpawned(player));
}
}
@Inject
@FieldHook("grandExchangeOffers")
public static void onGrandExchangeOffersChanged(int idx)
{
if (idx == -1)
{
return;
}
GrandExchangeOffer internalOffer = client.getGrandExchangeOffers()[idx];
if (internalOffer == null)
{
return;
}
GrandExchangeOfferChanged offerChangedEvent = new GrandExchangeOfferChanged();
offerChangedEvent.setOffer(internalOffer);
offerChangedEvent.setSlot(idx);
client.getCallbacks().post(offerChangedEvent);
}
@FieldHook("clientVarps")
@Inject
public static void settingsChanged(int idx)
{
VarbitChanged varbitChanged = new VarbitChanged();
varbitChanged.setIndex(idx);
client.getCallbacks().post(varbitChanged);
}
@FieldHook("isResized")
@Inject
public static void resizeChanged(int idx)
{
//maybe couple with varbitChanged. resizeable may not be a varbit but it would fit with the other client settings.
boolean isResized = client.isResized();
if (oldIsResized != isResized)
{
ResizeableChanged resizeableChanged = new ResizeableChanged();
resizeableChanged.setResized(isResized);
client.getCallbacks().post(resizeableChanged);
oldIsResized = isResized;
}
}
@FieldHook("clanMemberManager")
@Inject
public static void clanMemberManagerChanged(int idx)
{
client.getCallbacks().post(new ClanChanged(client.getClanMemberManager() != null));
}
@FieldHook("canvasWidth")
@Inject
public static void canvasWidthChanged(int idx)
{
client.getCallbacks().post(new CanvasSizeChanged());
}
@FieldHook("canvasHeight")
@Inject
public static void canvasHeightChanged(int idx)
{
client.getCallbacks().post(new CanvasSizeChanged());
}
@Inject
@Override
public boolean hasHintArrow()
{
return client.getHintArrowTargetType() != HintArrowType.NONE.getValue();
}
@Inject
@Override
public HintArrowType getHintArrowType()
{
int type = client.getHintArrowTargetType();
if (type == HintArrowType.NPC.getValue())
{
return HintArrowType.NPC;
}
else if (type == HintArrowType.PLAYER.getValue())
{
return HintArrowType.PLAYER;
}
else if (type == HintArrowType.WORLD_POSITION.getValue())
{
return HintArrowType.WORLD_POSITION;
}
else
{
return HintArrowType.NONE;
}
}
@Inject
@Override
public void clearHintArrow()
{
client.setHintArrowTargetType(HintArrowType.NONE.getValue());
}
@Inject
@Override
public void setHintArrow(NPC npc)
{
client.setHintArrowTargetType(HintArrowType.NPC.getValue());
client.setHintArrowNpcTargetIdx(npc.getIndex());
}
@Inject
@Override
public void setHintArrow(Player player)
{
client.setHintArrowTargetType(HintArrowType.PLAYER.getValue());
client.setHintArrowPlayerTargetIdx(((RSPlayer) player).getPlayerId());
}
@Inject
@Override
public void setHintArrow(WorldPoint point)
{
client.setHintArrowTargetType(HintArrowType.WORLD_POSITION.getValue());
client.setHintArrowX(point.getX());
client.setHintArrowY(point.getY());
// position the arrow in center of the tile
client.setHintArrowOffsetX(LOCAL_TILE_SIZE / 2);
client.setHintArrowOffsetY(LOCAL_TILE_SIZE / 2);
}
@Inject
@Override
public WorldPoint getHintArrowPoint()
{
if (getHintArrowType() == HintArrowType.WORLD_POSITION)
{
int x = client.getHintArrowX();
int y = client.getHintArrowY();
return new WorldPoint(x, y, client.getPlane());
}
return null;
}
@Inject
@Override
public Player getHintArrowPlayer()
{
if (getHintArrowType() == HintArrowType.PLAYER)
{
int idx = client.getHintArrowPlayerTargetIdx();
RSPlayer[] players = client.getCachedPlayers();
if (idx < 0 || idx >= players.length)
{
return null;
}
return players[idx];
}
return null;
}
@Inject
@Override
public NPC getHintArrowNpc()
{
if (getHintArrowType() == HintArrowType.NPC)
{
int idx = client.getHintArrowNpcTargetIdx();
RSNPC[] npcs = client.getCachedNPCs();
if (idx < 0 || idx >= npcs.length)
{
return null;
}
return npcs[idx];
}
return null;
}
@Copy("menuAction")
static void rs$menuAction(int var0, int var1, int var2, int var3, String var4, String var5, int var6, int var7)
{
throw new RuntimeException();
}
@Replace("menuAction")
static void rl$menuAction(int actionParam, int widgetId, int menuAction, int id, String menuOption, String menuTarget, int var6, int var7)
{
/* Along the way, the RuneScape client may change a menuAction by incrementing it with 2000.
* I have no idea why, but it does. Their code contains the same conditional statement.
*/
if (menuAction >= 2000)
{
menuAction -= 2000;
}
final MenuOptionClicked menuOptionClicked = new MenuOptionClicked();
menuOptionClicked.setActionParam(actionParam);
menuOptionClicked.setMenuOption(menuOption);
menuOptionClicked.setMenuTarget(menuTarget);
menuOptionClicked.setMenuAction(MenuAction.of(menuAction));
menuOptionClicked.setId(id);
menuOptionClicked.setWidgetId(widgetId);
client.getCallbacks().post(menuOptionClicked);
if (menuOptionClicked.isConsumed())
{
return;
}
rs$menuAction(actionParam, widgetId, menuAction, id, menuOption, menuTarget, var6, var7);
}
@FieldHook("username")
@Inject
public static void onUsernameChanged(int idx)
{
client.getCallbacks().post(new UsernameChanged());
}
@Override
@Inject
public int getTickCount()
{
return tickCount;
}
@Override
@Inject
public void setTickCount(int tick)
{
tickCount = tick;
}
@Inject
@Override
public EnumSet<WorldType> getWorldType()
{
int flags = getFlags();
return WorldType.fromMask(flags);
}
@Inject
@MethodHook("openMenu")
public void menuOpened(int var1, int var2)
{
final MenuOpened event = new MenuOpened();
event.setMenuEntries(getMenuEntries());
callbacks.post(event);
}
@Inject
@MethodHook("updateNpcs")
public static void updateNpcs(boolean var0, PacketBuffer var1)
{
client.getCallbacks().updateNpcs();
}
@Inject
@MethodHook(value = "addChatMessage", end = true)
public static void onAddChatMessage(int type, String name, String message, String sender)
{
Logger logger = client.getLogger();
if (logger.isDebugEnabled())
{
logger.debug("Chat message type {}: {}", ChatMessageType.of(type), message);
}
// Get the message node which was added
Map<Integer, RSChatLineBuffer> chatLineMap = client.getChatLineMap();
RSChatLineBuffer chatLineBuffer = chatLineMap.get(type);
MessageNode messageNode = chatLineBuffer.getLines()[0];
final ChatMessageType chatMessageType = ChatMessageType.of(type);
final ChatMessage chatMessage = new ChatMessage(messageNode, chatMessageType, name, message, sender, messageNode.getTimestamp());
client.getCallbacks().post(chatMessage);
}
@Inject
@MethodHook("methodDraw")
public void methodDraw(boolean var1)
{
callbacks.clientMainLoop();
}
@MethodHook("renderWidgetLayer")
@Inject
public static void renderWidgetLayer(Widget[] widgets, int parentId, int minX, int minY, int maxX, int maxY, int x, int y, int var8)
{
Callbacks callbacks = client.getCallbacks();
HashTable<WidgetNode> componentTable = client.getComponentTable();
for (Widget rlWidget : widgets)
{
RSWidget widget = (RSWidget) rlWidget;
if (widget == null || widget.getRSParentId() != parentId || widget.isSelfHidden())
{
continue;
}
if (parentId != -1)
{
widget.setRenderParentId(parentId);
}
final int renderX = x + widget.getRelativeX();
final int renderY = y + widget.getRelativeY();
widget.setRenderX(renderX);
widget.setRenderY(renderY);
final int widgetType = widget.getType();
if (widgetType == WidgetType.GRAPHIC && widget.getItemId() != -1)
{
if (renderX >= minX && renderX <= maxX && renderY >= minY && renderY <= maxY)
{
WidgetItem widgetItem = new WidgetItem(widget.getItemId(), widget.getItemQuantity(), -1, widget.getBounds(), widget);
callbacks.drawItem(widget.getItemId(), widgetItem);
}
}
else if (widgetType == WidgetType.INVENTORY)
{
Collection<WidgetItem> widgetItems = widget.getWidgetItems();
for (WidgetItem widgetItem : widgetItems)
{
callbacks.drawItem(widgetItem.getId(), widgetItem);
}
}
WidgetNode childNode = componentTable.get(widget.getId());
if (childNode != null)
{
int widgetId = widget.getId();
int groupId = childNode.getId();
RSWidget[] children = client.getWidgets()[groupId];
for (RSWidget child : children)
{
if (child.getRSParentId() == -1)
{
child.setRenderParentId(widgetId);
}
}
}
}
}
@Inject
@Override
public RSItem getLastItemDespawn()
{
return lastItemDespawn;
}
@Inject
@Override
public void setLastItemDespawn(RSItem lastItemDespawn)
{
RSClientMixin.lastItemDespawn = lastItemDespawn;
}
@Inject
@Override
public boolean isGpu()
{
return gpu;
}
@Inject
@Override
public void setGpu(boolean gpu)
{
this.gpu = gpu;
}
@Inject
@Override
public void queueChangedSkill(Skill skill)
{
int[] skills = client.getChangedSkills();
int count = client.getChangedSkillsCount();
skills[++count - 1 & 31] = skill.ordinal();
client.setChangedSkillsCount(count);
}
@Inject
@Override
public RSSpritePixels[] getSprites(IndexDataBase source, int archiveId, int fileId)
{
RSIndexDataBase rsSource = (RSIndexDataBase) source;
byte[] configData = rsSource.getConfigData(archiveId, fileId);
if (configData == null)
{
return null;
}
decodeSprite(configData);
int indexedSpriteCount = getIndexedSpriteCount();
int maxWidth = getIndexedSpriteWidth();
int maxHeight = getIndexedSpriteHeight();
int[] offsetX = getIndexedSpriteOffsetXs();
int[] offsetY = getIndexedSpriteOffsetYs();
int[] widths = getIndexSpriteWidths();
int[] heights = getIndexedSpriteHeights();
byte[][] spritePixelsArray = getSpritePixels();
int[] indexedSpritePalette = getIndexedSpritePalette();
RSSpritePixels[] array = new RSSpritePixels[indexedSpriteCount];
for (int i = 0; i < indexedSpriteCount; ++i)
{
int width = widths[i];
int height = heights[i];
byte[] pixelArray = spritePixelsArray[i];
int[] pixels = new int[width * height];
RSSpritePixels spritePixels = createSpritePixels(pixels, width, height);
spritePixels.setMaxHeight(maxHeight);
spritePixels.setMaxWidth(maxWidth);
spritePixels.setOffsetX(offsetX[i]);
spritePixels.setOffsetY(offsetY[i]);
for (int j = 0; j < width * height; ++j)
{
pixels[j] = indexedSpritePalette[pixelArray[j] & 0xff];
}
array[i] = spritePixels;
}
setIndexedSpriteOffsetXs(null);
setIndexedSpriteOffsetYs(null);
setIndexSpriteWidths(null);
setIndexedSpriteHeights(null);
setIndexSpritePalette(null);
setSpritePixels(null);
return array;
}
@Inject
@Override
public void setSkyboxColor(int newSkyboxColor)
{
skyboxColor = newSkyboxColor;
}
@Inject
@Override
public int getSkyboxColor()
{
return skyboxColor;
}
@Inject
@FieldHook("cycleCntr")
public static void onCycleCntrChanged(int idx)
{
client.getCallbacks().post(new ClientTick());
}
@Copy("shouldLeftClickOpenMenu")
boolean rs$shouldLeftClickOpenMenu()
{
throw new RuntimeException();
}
@Replace("shouldLeftClickOpenMenu")
boolean rl$shouldLeftClickOpenMenu()
{
if (rs$shouldLeftClickOpenMenu())
{
return true;
}
MenuShouldLeftClick menuShouldLeftClick = new MenuShouldLeftClick();
client.getCallbacks().post(menuShouldLeftClick);
if (menuShouldLeftClick.isForceRightClick())
{
return true;
}
int len = getMenuOptionCount();
if (len > 0)
{
int type = getMenuTypes()[len - 1];
return type == MenuAction.RUNELITE_OVERLAY.getId();
}
return false;
}
@Inject
@Override
public EnumComposition getEnum(int id)
{
assert isClientThread() : "getEnum must be called on client thread";
RSEnum rsEnum = enumCache.getIfPresent(id);
if (rsEnum != null)
{
return rsEnum;
}
rsEnum = getRsEnum(id);
enumCache.put(id, rsEnum);
return rsEnum;
}
@Inject
@Override
public void resetHealthBarCaches()
{
getHealthBarCache().reset();
getHealthBarSpriteCache().reset();
}
}
|
package com.example.schedule_render;
import arez.Disposable;
import arez.annotations.ArezComponent;
import arez.annotations.Feature;
import arez.annotations.SuppressArezWarnings;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.processing.Generated;
import jsinterop.annotations.JsConstructor;
import jsinterop.base.Js;
import jsinterop.base.JsPropertyMap;
import react4j.React;
import react4j.ReactNode;
import react4j.internal.OnComponentWillUnmount;
import react4j.internal.OnShouldComponentUpdate;
import react4j.internal.ViewConstructorFunction;
@SuppressArezWarnings("Arez:UnnecessaryAllowEmpty")
@ArezComponent(
name = "com_example_schedule_render_MultiScheduleRenderComponent",
disposeNotifier = Feature.DISABLE,
sting = Feature.DISABLE,
allowEmpty = true
)
@Generated("react4j.processor.React4jProcessor")
abstract class React4j_MultiScheduleRenderComponent extends MultiScheduleRenderComponent {
@Nonnull
private final react4j.internal.NativeView $$react4j$$_nativeView;
React4j_MultiScheduleRenderComponent(
@Nonnull final react4j.internal.NativeView $$react4j$$_nativeView) {
this.$$react4j$$_nativeView = Objects.requireNonNull( $$react4j$$_nativeView );
}
@Override
void myScheduleRender1() {
$$react4j$$_nativeView.forceUpdate();
}
@Override
void myScheduleRender2() {
$$react4j$$_nativeView.forceUpdate();
}
@Override
void myScheduleRender3() {
$$react4j$$_nativeView.setState( JsPropertyMap.of() );
}
@Override
void myScheduleRender4() {
$$react4j$$_nativeView.setState( JsPropertyMap.of() );
}
@Nonnull
private static ViewConstructorFunction getConstructorFunction() {
final ViewConstructorFunction viewConstructor = NativeView::new;
if ( React.enableViewNames() ) {
Js.asPropertyMap( viewConstructor ).set( "displayName", "MultiScheduleRenderComponent" );
}
return viewConstructor;
}
private boolean $$react4j$$_shouldComponentUpdate(
@Nullable final JsPropertyMap<Object> nextInputs) {
assert null != nextInputs;
return false;
}
private void $$react4j$$_componentWillUnmount() {
((Arez_React4j_MultiScheduleRenderComponent) this).dispose();
}
@Nullable
ReactNode $$react4j$$_render() {
assert Disposable.isNotDisposed( this );
return render();
}
static final class Factory {
@Nonnull
static final ViewConstructorFunction TYPE = getConstructorFunction();
}
private static final class NativeView extends react4j.internal.NativeView implements OnShouldComponentUpdate, OnComponentWillUnmount {
@Nonnull
private final React4j_MultiScheduleRenderComponent $$react4j$$_view;
@JsConstructor
NativeView(@Nullable final JsPropertyMap<Object> inputs) {
super( inputs );
$$react4j$$_view = new Arez_React4j_MultiScheduleRenderComponent( this );
}
@Override
public final boolean shouldComponentUpdate(@Nonnull final JsPropertyMap<Object> nextInputs) {
return $$react4j$$_view.$$react4j$$_shouldComponentUpdate( nextInputs );
}
@Override
public final void componentWillUnmount() {
$$react4j$$_view.$$react4j$$_componentWillUnmount();
}
@Override
@Nullable
public final ReactNode render() {
return $$react4j$$_view.$$react4j$$_render();
}
}
}
|
/*******************************************************************************
* Copyright 2014 Virginia Tech Visionarium
*
* 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 edu.vt.arc.vis.osnap.gui.wizards.statuspanes;
import edu.vt.arc.vis.osnap.gui.wizards.statusobjects.NodeLinkTreeStatus;
import java.util.Observable;
import javafx.scene.text.Text;
/**
* Status pane to show user selections from wizard for this layout
*
* @author Shawn P Neuman
*
*/
public class NodeLinkTreeStatusPane
extends PrefuseTreeStatusPane {
private Text depthSpacing;
private Text depthSpacingTF;
private Text siblingSpacing;
private Text siblingSpacingTF;
private Text subTreeSpacing;
private Text subTreeSpacingTF;
private Text orientation;
private Text orientationTF;
/**
* @param lbl
*/
public NodeLinkTreeStatusPane(String lbl) {
super(lbl, 4);
orientation = new Text("Orientation: ");
orientationTF = new Text();
orientationTF.setStyle("-fx-font-weight: bold");
depthSpacing = new Text("Depth Spacing: ");
depthSpacingTF = new Text();
depthSpacingTF.setStyle("-fx-font-weight: bold");
siblingSpacing = new Text("Space Between Siblings: ");
siblingSpacingTF = new Text();
siblingSpacingTF.setStyle("-fx-font-weight: bold");
subTreeSpacing = new Text("Space Between Neighboring Sub-Trees: ");
subTreeSpacingTF = new Text();
subTreeSpacingTF.setStyle("-fx-font-weight: bold");
getGrid().add(orientation, 0, 3);
getGrid().add(orientationTF, 1, 3);
getGrid().add(depthSpacing, 0, 4);
getGrid().add(depthSpacingTF, 1, 4);
getGrid().add(siblingSpacing, 0, 5);
getGrid().add(siblingSpacingTF, 1, 5);
getGrid().add(subTreeSpacing, 0, 6);
getGrid().add(subTreeSpacingTF, 1, 6);
}
@Override
public void update(Observable changedObject, Object changedProperty) {
super.update(changedObject, changedProperty);
if (changedObject instanceof NodeLinkTreeStatus) {
NodeLinkTreeStatus status = (NodeLinkTreeStatus) changedObject;
if (status.getDepthSpacing() != null) {
depthSpacingTF.setText(status.getDepthSpacing().toString());
}
else {
depthSpacingTF.setText("");
}
if (status.getOrientation() != null) {
orientationTF.setText(status.getOrientation().toString());
}
else {
orientationTF.setText("");
}
if (status.getSpaceBetweenSiblings() != null) {
siblingSpacingTF.setText(status.getSpaceBetweenSiblings()
.toString());
}
else {
siblingSpacingTF.setText("");
}
if (status.getSpaceBetweenNeighboringSubtrees() != null) {
subTreeSpacingTF.setText(status
.getSpaceBetweenNeighboringSubtrees().toString());
}
else {
subTreeSpacingTF.setText("");
}
}
}
}
|
/*
* Copyright 2014-05-20 the original author or authors.
*/
package pl.com.softproject.altkom.hibernate.model;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
/**
*
* @author Adrian Lapierre <adrian@softproject.com.pl>
*/
@Entity
@SuppressWarnings("PersistenceUnitPresent")
public class FormFieldValue extends BaseEntity{
@ManyToOne
@JoinColumn(name = "field_id")
private FormField formField;
private String fieldValue;
@ManyToOne
@JoinColumn(name = "formdata_id")
private FormData formData;
public FormField getFormField() {
return formField;
}
public void setFormField(FormField formField) {
this.formField = formField;
}
public String getFieldValue() {
return fieldValue;
}
public void setFieldValue(String fieldValue) {
this.fieldValue = fieldValue;
}
public FormData getFormData() {
return formData;
}
public void setFormData(FormData formData) {
this.formData = formData;
}
}
|
package msf.fc.rest.ec.node.equipment.data.entity;
import org.apache.commons.lang.builder.ToStringBuilder;
import com.google.gson.annotations.SerializedName;
public class EquipmentQInQEcEntity {
@SerializedName("selectable_by_node")
private Boolean selectableByNode;
@SerializedName("selectable_by_vlan_if")
private Boolean selectableByVlanIf;
public Boolean getSelectableByNode() {
return selectableByNode;
}
public void setSelectableByNode(Boolean selectableByNode) {
this.selectableByNode = selectableByNode;
}
public Boolean getSelectableByVlanIf() {
return selectableByVlanIf;
}
public void setSelectableByVlanIf(Boolean selectableByVlanIf) {
this.selectableByVlanIf = selectableByVlanIf;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
|
package com.guomai.dushuhui.bookshop.adapter;
import android.view.View;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.guomai.dushuhui.R;
import com.guomai.dushuhui.bookshop.model.TestData;
/**
* Created by Administrator on 2018/9/12.
*/
public class ShudanPageAdapter extends BaseQuickAdapter<TestData,BaseViewHolder> {
public ShudanPageAdapter(int layoutResId) {
super(layoutResId);
}
@Override
protected void convert(BaseViewHolder helper, TestData item) {
helper.addOnClickListener(R.id.layout_shudan);
/*if (helper.getAdapterPosition() == 0){
helper.getView(R.id.interval).setVisibility(View.GONE);
}*/
/*ImageView iv_cover = helper.getView(R.id.iv_cover);
final ImageView iv_logo = helper.getView(R.id.iv_logo);
Glide.with(mContext.getApplicationContext()).load(item.roadshowInfo.coverUrl)
.placeholder(R.drawable.ic_logo_default)
.into(iv_cover);
Glide.with(mContext.getApplicationContext()).load(item.companyInfo.logoUrl)
.placeholder(R.drawable.default_image)
.into(new SimpleTarget<GlideDrawable>() {
@Override
public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
iv_logo.setImageDrawable(resource);
}
});
helper.setText(R.id.tv_company,item.companyInfo.title)
.setText(R.id.tv_title,item.roadshowInfo.title)
.setText(R.id.road_start_time, TimeUtil.getDateString(item.roadshowInfo.openTime))
.setText(R.id.road_play_times,String.format("播放%d次",item.roadshowInfo.showUserCount));*/
}
}
|
package com.hybris.hyeclipse.tsv.wizards;
import java.io.File;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
public class RunTSVWizardPage extends WizardPage {
private Text scanDirectoryText;
private Text containerText;
private Text fileText;
public RunTSVWizardPage(ISelection selection) {
super("wizardPage");
setTitle("Run TSV analysis");
setDescription("This wizard runs a TSV analysis and opens the results.");
}
/**
* @see IDialogPage#createControl(Composite)
*/
public void createControl(Composite parent) {
Composite container = new Composite(parent, SWT.NULL);
GridLayout layout = new GridLayout();
container.setLayout(layout);
layout.numColumns = 3;
layout.verticalSpacing = 9;
Label label = new Label(container, SWT.NULL);
label.setText("&Scan directory:");
scanDirectoryText = new Text(container, SWT.BORDER | SWT.SINGLE);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
scanDirectoryText.setLayoutData(gd);
scanDirectoryText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
dialogChanged();
}
});
Button button = new Button(container, SWT.PUSH);
button.setText(" Browse...");
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleBrowseFilesystem();
}
});
dialogChanged();
setControl(container);
}
private void handleBrowseFilesystem() {
DirectoryDialog dialog = new DirectoryDialog(getShell());
dialog.setText("Select the scan directory");
String selectedDir = dialog.open();
if (selectedDir != null && selectedDir.isEmpty() == false) {
scanDirectoryText.setText(selectedDir);
}
}
/**
* Ensures that all fields are set.
*/
private void dialogChanged() {
if (getScanDirectoryName().length() == 0) {
updateStatus("Scan directory must be specified");
return;
}
if (getScanDirectory() == null || !getScanDirectory().exists()) {
updateStatus("Scan directory must exist");
return;
}
updateStatus(null);
}
private void updateStatus(String message) {
setErrorMessage(message);
setPageComplete(message == null);
}
public String getScanDirectoryName() {
return scanDirectoryText.getText();
}
public String getContainerName() {
return containerText.getText();
}
public String getFileName() {
return fileText.getText();
}
public File getScanDirectory() {
String scanDirectory = getScanDirectoryName();
if (scanDirectory != null && scanDirectory.isEmpty() == false) {
return new File(scanDirectory);
}
else {
return null;
}
}
}
|
package starter.search;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import net.serenitybdd.core.steps.UIInteractionSteps;
import net.thucydides.core.annotations.Shared;
import net.thucydides.core.annotations.Step;
import starter.navigation.OnthegoHomepage;
public class Busactions extends UIInteractionSteps{
@Shared
OnthegoHomepage onthegohomepage;
@Step("Fill bus type informations")
public void Fillbustypeinfo(String Bustypename, Integer seatcapacity, Integer standcapacity) {
$(SearchForm.ADMIN_BUSTYPE).click();
onthegohomepage.waitForAngularRequestsToFinish();
$(SearchForm.ADMIN_BUSTYPE_NAME).clear();
$(SearchForm.ADMIN_BUSTYPE_NAME).type(Bustypename);
$(SearchForm.ADMIN_BUSTYPE_SEAT).clear();
$(SearchForm.ADMIN_BUSTYPE_SEAT).type(String.valueOf(seatcapacity));
$(SearchForm.ADMIN_BUSTYPE_STAND).clear();
$(SearchForm.ADMIN_BUSTYPE_STAND).type(String.valueOf(standcapacity));
$(SearchForm.ADMIN_BUSTYPE_ADD).click();
}
@Step("Verify bus type response")
public void Verifybustyperesponse(String message) {
onthegohomepage.waitForAngularRequestsToFinish();
assertThat($(SearchForm.ADMIN_BUSTYPE_ERROR).getText(),equalTo(message));
}
@Step("Fill bus service informations")
public void Fillbusserviceinfo(String busservicename) {
$(SearchForm.ADMIN_BUSSERVICE_TAB).click();
onthegohomepage.waitForAngularRequestsToFinish();
$(SearchForm.ADMIN_BUSSERVICE).click();
onthegohomepage.waitForAngularRequestsToFinish();
$(SearchForm.ADMIN_BUSSERVICE_NAME).clear();
$(SearchForm.ADMIN_BUSSERVICE_NAME).type(busservicename);
$(SearchForm.ADMIN_BUSSERVICE_ADD).click();
}
@Step("Verify bus service response")
public void Verifybusserviceresponse(String message) {
onthegohomepage.waitForAngularRequestsToFinish();
assertThat($(SearchForm.ADMIN_BUSSERVICE_ERROR).getText(),equalTo(message));
}
@Step("Fill bus tap card informations")
public void Fillbustapcardinfo(Integer serviceid, Integer stopid, String Cardnumber) {
$(SearchForm.ADMIN_BUSCHECKIN_TAB).click();
onthegohomepage.waitForAngularRequestsToFinish();
$(SearchForm.ADMIN_BUSCHECKIN).click();
onthegohomepage.waitForAngularRequestsToFinish();
$(SearchForm.ADMIN_BUSTAPCARD_SERVICEID).clear();
$(SearchForm.ADMIN_BUSTAPCARD_SERVICEID).type(String.valueOf(serviceid));
$(SearchForm.ADMIN_BUSTAPCARD_STOPID).clear();
$(SearchForm.ADMIN_BUSTAPCARD_STOPID).type(String.valueOf(stopid));
$(SearchForm.ADMIN_BUSTAPCARD_CARDNUM).clear();
$(SearchForm.ADMIN_BUSTAPCARD_CARDNUM).type(Cardnumber);
}
@Step("User tap in")
public void UserTapin() {
$(SearchForm.ADMIN_BUSCHECKIN_ADD).click();
onthegohomepage.waitForAngularRequestsToFinish();
}
@Step("User tap out")
public void UserTapout() {
$(SearchForm.ADMIN_BUSTAPCARD_TAPIN).click();
onthegohomepage.waitForAngularRequestsToFinish();
$(SearchForm.ADMIN_BUSCHECKIN_ADD).click();
onthegohomepage.waitForAngularRequestsToFinish();
}
@Step("Verify bus service response")
public void Verifybustapresponse(String message) {
onthegohomepage.waitForAngularRequestsToFinish();
assertThat($(SearchForm.ADMIN_BUSTAPCARD_ERROR).getText(),equalTo(message));
}
}
|
/**
* Copyright 2010-2015 Boxfuse 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 org.flywaydb.core.internal.dbsupport.sqlserver;
import org.flywaydb.core.migration.ConcurrentMigrationTestCase;
import org.flywaydb.core.internal.util.jdbc.DriverDataSource;
import org.junit.experimental.categories.Category;
import org.flywaydb.core.DbCategory;
import javax.sql.DataSource;
import java.util.Properties;
/**
* Test to demonstrate the migration functionality using SQL Server with the Microsoft driver.
*/
@Category(DbCategory.SQLServer.class)
public class MsSQLServerConcurrentMigrationMediumTest extends ConcurrentMigrationTestCase {
@Override
protected DataSource createDataSource(Properties customProperties) throws Exception {
String user = customProperties.getProperty("sqlserver.user", "sa");
String password = customProperties.getProperty("sqlserver.password", "flyway");
String url = customProperties.getProperty("sqlserver.ms_url", "jdbc:sqlserver://localhost:1433;databaseName=flyway_db_ms_concurrent");
return new DriverDataSource(Thread.currentThread().getContextClassLoader(), null, url, user, password);
}
}
|
/**
* Copyright (C) 2006-2021 Talend Inc. - www.talend.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.talend.sdk.component.form.internal.converter.impl.schema;
import static java.util.Locale.ROOT;
import static java.util.stream.Collectors.toList;
import java.util.Collection;
import java.util.List;
import java.util.TreeMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import javax.json.bind.Jsonb;
import org.talend.sdk.component.form.internal.converter.PropertyContext;
import org.talend.sdk.component.form.internal.converter.PropertyConverter;
import org.talend.sdk.component.form.internal.converter.impl.JsonSchemaConverter;
import org.talend.sdk.component.form.internal.lang.CompletionStages;
import org.talend.sdk.component.form.model.jsonschema.JsonSchema;
import org.talend.sdk.component.server.front.model.SimplePropertyDefinition;
import lombok.AllArgsConstructor;
@AllArgsConstructor
public class ArrayPropertyConverter implements PropertyConverter {
private final Jsonb jsonb;
private final JsonSchema jsonSchema;
private final Collection<SimplePropertyDefinition> properties;
@Override
public CompletionStage<PropertyContext<?>> convert(final CompletionStage<PropertyContext<?>> cs) {
return cs.thenCompose(context -> {
jsonSchema.setType(context.getProperty().getType().toLowerCase(ROOT));
final String prefix = context.getProperty().getPath() + "[]";
final List<SimplePropertyDefinition> arrayElements =
properties.stream().filter(child -> child.getPath().startsWith(prefix)).collect(toList());
if (arrayElements.stream().anyMatch(e -> e.getPath().startsWith(prefix + '.'))) { // complex object
final JsonSchema items = new JsonSchema();
items.setType("object");
items.setProperties(new TreeMap<>());
jsonSchema.setItems(items);
return CompletableFuture
.allOf(arrayElements
.stream()
.filter(prop -> prop.getPath().startsWith(prefix + '.')
&& prop.getPath().indexOf('.', prefix.length() + 1) < 0)
.map(it -> new PropertyContext(it, context.getRootContext(),
context.getConfiguration()))
.map(CompletionStages::toStage)
.map(e -> new JsonSchemaConverter(jsonb, items, properties).convert(e))
.toArray(CompletableFuture[]::new))
.thenApply(done -> context);
} else if (!arrayElements.isEmpty()) { // primitive
final String type = arrayElements.get(0).getType();
final JsonSchema item = new JsonSchema();
item.setTitle(jsonSchema.getTitle());
item.setType("enum".equalsIgnoreCase(type) ? "string" : type.toLowerCase(ROOT));
jsonSchema.setItems(item);
}
return CompletableFuture.completedFuture(context);
});
}
}
|
/*
* Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License. See accompanying
* LICENSE file.
*/
package com.gemstone.gemfire.internal;
import com.gemstone.gemfire.*;
import com.gemstone.gemfire.internal.shared.Version;
import java.io.*;
/**
* An interface that implements data serialization
* for internal GemFire product classes that have a fixed id.
* The fixed id is used
* to represent the class, on the wire, at serialization time and used
* in a switch statement at deserialization time.
* All the codes should be static final in this class.
* <p> Implementors MUST have a public zero-arg constructor.
*
* <p> Note that this class is for internal use only. Customer classes
* that want to do something similiar should implement a subclass of
* {@link DataSerializer} or {@link Instantiator}.
*
* <p>
* To add a new DataSerializableFixedID do this following:
* <ol>
* <li> Define a constant with an id that is free and put it in
* <code>DataSerializableFixedID</code> as a "public static final byte".
* Make sure and update the "unused" comments to no longer mention your new id.
* If implementing a class used only for tests then there is no need to consume
* a fixed id and you should use {@link #NO_FIXED_ID}. In this case you can skip
* steps 3 and 4.
* <li> Define a method in the class that
* implements <code>DataSerializableFixedID</code>
* named {@link #getDSFID} that returns the constant from step 1.
* <li> Define a private static method in {@link DSFIDFactory} that returns an instance
* of the class from step 2 usually be calling its zero-arg constructor
* and then calling fromData(in).
* See the end of {@link DSFIDFactory} for examples.
* <li> Add a case statement in {@link DSFIDFactory#create} for the constant
* from step 1 that calls the method from step 3.
* <li> Implement {@link #toData} and {@link #fromData} just like you
* would on a <code>DataSerializer</code>. Make sure you follow the javadocs
* for these methods to add support for rolling upgrades.
* </ol>
*
* @see DataSerializer
*
* @author Darrel Schneider
* @since 5.7
*/
public interface DataSerializableFixedID extends SerializationVersions {
// NOTE, codes < -65536 will take 4 bytes to serialize
// NOTE, codes < -128 will take 2 bytes to serialize
/* In the class to be serialized, add
public FOO(DataInput in) throws IOException, ClassNotFoundException {
fromData(in);
}
public int getDSFID() {
return FOO;
}
In DataSerializableFixedId, allocate an ID for the class
public static final byte FOO = -54;
In DSFIDFactory, add a case for the new class
case FOO:
return new FOO(in);
*/
public static final short TX_ROLLBACK_TO_SAVEPOINT_MESSAGE = -142;
public static final short HDFS_GATEWAY_EVENT_IMPL = -141;
public static final short SNAPPY_COMPRESSED_CACHED_DESERIALIZABLE = -140;
/* below were used in 7.0.1 temporarily, but now can be reused from >= v7.1
public static final short REMOTE_PUTALL_MESSAGE = -139;
public static final short PR_PUTALL_MESSAGE = -138;
public static final short PUT_ALL_MESSAGE = -137;
*/
public static final short GATEWAY_EVENT_IMPL = -136;
public static final short GATEWAY_SENDER_EVENT_CALLBACK_ARGUMENT = -135;
public static final short GATEWAY_SENDER_EVENT_IMPL = -134;
public static final short CLIENT_TOMBSTONE_MESSAGE = -133;
public static final short R_REGION_OP_REPLY = -132;
public static final short R_REGION_OP = -131;
public static final short WAIT_FOR_VIEW_INSTALLATION = -130;
public static final short DISPATCHED_AND_CURRENT_EVENTS = -129;
public static final byte DLOCK_QUERY_MESSAGE = -128;
public static final byte DLOCK_QUERY_REPLY = -127;
public static final byte CLIENT_HEALTH_STATS = -126;
public static final byte PR_MANAGE_BACKUP_BUCKET_MESSAGE = -125;
public static final byte PR_MANAGE_BACKUP_BUCKET_REPLY_MESSAGE = -124;
public static final byte SIZED_BASED_LOAD_PROBE = -123;
public static final byte CLIENT_PING_MESSAGE_IMPL = -122;
public static final byte REMOTE_PUTALL_REPLY_MESSAGE = -121;
public static final byte VERSION_TAG = -120;
public static final byte REMOTE_PUTALL_MESSAGE = -119;
public static final byte ADD_CACHESERVER_PROFILE_UPDATE = -118;
public static final byte SERVER_INTEREST_REGISTRATION_MESSAGE = -117;
public static final byte FILTER_PROFILE_UPDATE = -116;
// [sumedh] below two IDs are no longer used in new TX model and will be
// removed at some point after GFXD upmerge
//public static final byte JTA_AFTER_COMPLETION_MESSAGE = -115;
//public static final byte JTA_BEFORE_COMPLETION_MESSAGE = -114;
public static final byte TX_NEW_GII_NODE = -114;
public static final byte INVALIDATE_PARTITIONED_REGION_MESSAGE = -113;
public static final byte TX_REMOTE_COMMIT_MESSAGE = -112;
public static final byte TX_REMOTE_ROLLBACK_MESSAGE = -111;
public static final byte PR_PUTALL_REPLY_MESSAGE = -110;
public static final byte PR_PUTALL_MESSAGE = -109;
public static final byte RESOURCE_PROFILE_MESSAGE = -108;
public static final byte RESOURCE_MANAGER_PROFILE = -107;
public static final byte PR_CREATE_BUCKET_MESSAGE = -106;
public static final byte PR_CREATE_BUCKET_REPLY_MESSAGE = -105;
public static final byte DISTRIBUTED_REGION_FUNCTION_MESSAGE = -104;
public static final byte DISTRIBUTED_REGION_FUNCTION_REPLY_MESSAGE = -103;
public static final byte MEMBER_FUNCTION_MESSAGE = -102;
public static final byte MEMBER_FUNCTION_REPLY_MESSAGE = -101;
public static final byte PARTITION_REGION_CONFIG = -100;
public static final byte PR_FETCH_KEYS_REPLY_MESSAGE = -99;
public static final byte PR_DUMP_B2N_REGION_MSG = -98;
public static final byte PR_DUMP_B2N_REPLY_MESSAGE = -97;
public static final byte PR_INVALIDATE_MESSAGE = -96;
public static final byte PR_INVALIDATE_REPLY_MESSAGE = -95;
public static final byte PR_FUNCTION_MESSAGE = -94;
public static final byte PR_FUNCTION_REPLY_MESSAGE = -93;
public static final byte PROFILES_REPLY_MESSAGE = -92;
public static final byte BRIDGE_SERVER_PROFILE = -91;
public static final byte CONTROLLER_PROFILE = -90;
public static final byte CREATE_REGION_MESSAGE = -89;
public static final byte DESTROY_PARTITIONED_REGION_MESSAGE = -88;
// [sumedh] below two IDs are no longer used in new TX model and will be
// removed at some point
public static final byte COMMIT_PROCESS_QUERY_MESSAGE = -87;
public static final byte COMMIT_PROCESS_QUERY_REPLY_MESSAGE = -86;
public static final byte DESTROY_REGION_WITH_CONTEXT_MESSAGE = -85;
public static final byte PUT_ALL_MESSAGE = -84;
public static final byte CLEAR_REGION_MESSAGE = -83;
public static final byte INVALIDATE_REGION_MESSAGE = -82;
public static final byte SEND_QUEUE_MESSAGE = -81;
public static final byte STATE_MARKER_MESSAGE = -80;
public static final byte STATE_STABILIZATION_MESSAGE = -79;
public static final byte STATE_STABILIZED_MESSAGE = -78;
public static final byte CLIENT_MARKER_MESSAGE_IMPL = -77;
// [sumedh] below three IDs are no longer used in new TX model and will be
// removed at some point
public static final byte TX_LOCK_UPDATE_PARTICIPANTS_MESSAGE = -76;
public static final byte TX_ORIGINATOR_RECOVERY_MESSAGE = -75;
public static final byte TX_ORIGINATOR_RECOVERY_REPLY_MESSAGE = -74;
public static final byte QUEUE_REMOVAL_MESSAGE = -73;
public static final byte DLOCK_RECOVER_GRANTOR_MESSAGE = -72;
public static final byte DLOCK_RECOVER_GRANTOR_REPLY_MESSAGE = -71;
public static final byte NON_GRANTOR_DESTROYED_REPLY_MESSAGE = -70;
public static final byte TOMBSTONE_MESSAGE = -69;
public static final byte IDS_REGISTRATION_MESSAGE = -68;
// [sumedh] below ID is no longer used in new TX model and will be
// removed at some point
public static final byte TX_LOCK_UPDATE_PARTICIPANTS_REPLY_MESSAGE = -67;
public static final byte STREAMING_REPLY_MESSAGE = -66;
public static final byte PREFER_BYTES_CACHED_DESERIALIZABLE = -65;
public static final byte VM_CACHED_DESERIALIZABLE = -64;
public static final byte GATEWAY_EVENT_IMPL_66 = -63;
public static final byte SUSPEND_LOCKING_TOKEN = -62;
public static final byte OBJECT_TYPE_IMPL = -61;
public static final byte STRUCT_TYPE_IMPL = -60;
public static final byte COLLECTION_TYPE_IMPL = -59;
public static final byte TX_LOCK_BATCH = -58;
public static final byte STORE_ALL_CACHED_DESERIALIZABLE = -57;
public static final byte GATEWAY_EVENT_CALLBACK_ARGUMENT = -56;
public static final byte MAP_TYPE_IMPL = -55;
public static final byte LOCATOR_LIST_REQUEST = -54;
public static final byte CLIENT_CONNECTION_REQUEST = -53;
public static final byte QUEUE_CONNECTION_REQUEST = -52;
public static final byte LOCATOR_LIST_RESPONSE = -51;
public static final byte CLIENT_CONNECTION_RESPONSE = -50;
public static final byte QUEUE_CONNECTION_RESPONSE = -49;
public static final byte CLIENT_REPLACEMENT_REQUEST = -48;
public static final byte INTEREST_EVENT_MESSAGE = -47;
public static final byte INTEREST_EVENT_REPLY_MESSAGE = -46;
public static final byte CLIENT_BLACKLIST_MESSAGE = -45;
public static final byte REMOVE_CLIENT_FROM_BLACKLIST_MESSAGE = -44;
public static final byte GET_ALL_SERVERS_REQUEST = -43;
public static final byte GET_ALL_SERVRES_RESPONSE = -42;
// [sumedh] below two IDs are no longer used in new TX model and will be
// removed at some point
public static final byte FIND_REMOTE_TX_REPLY = -41;
public static final byte FIND_REMOTE_TX_MESSAGE = -40;
public static final byte R_REMOTE_COMMIT_REPLY_MESSAGE = -39;
public static final byte R_FETCH_KEYS_REPLY = -38;
public static final byte R_FETCH_KEYS_MESSAGE = -37;
public static final byte R_SIZE_MESSAGE = -36;
public static final byte R_SIZE_REPLY_MESSAGE = -35;
public static final byte R_FETCH_ENTRY_REPLY_MESSAGE = -34;
public static final byte R_FETCH_ENTRY_MESSAGE = -33;
public static final byte R_DESTROY_MESSAGE = -32;
public static final byte R_INVALIDATE_MESSAGE = -31;
public static final byte R_INVALIDATE_REPLY_MESSAGE = -30;
public static final byte R_PUT_MESSAGE = -29;
public static final byte R_PUT_REPLY_MESSAGE = -28;
public static final byte R_CONTAINS_MESSAGE = -27;
public static final byte R_CONTAINS_REPLY_MESSAGE = -26;
public static final byte R_GET_MESSAGE = -24;
public static final byte R_GET_REPLY_MESSAGE = -25;
public static final byte DURABLE_CLIENT_INFO_RESPONSE = -23;
public static final byte DURABLE_CLIENT_INFO_REQUEST = -22;
public static final byte CLIENT_INTEREST_MESSAGE = -21;
/**
* A header byte meaning that the next element in the stream is a type meant
* for GemFireXD.
*/
public static final byte GFXD_TYPE = -20;
/**
* A header byte meaning that the next element in the stream is a DVD object
* used for GemFireXD.
*/
public static final byte GFXD_DVD_OBJECT = -19;
/**
* A header byte meaning that the next element in the stream is a
* GlobalRowLocation object used for GemFireXD.
*/
public static final byte GFXD_GLOBAL_ROWLOC = -18;
/**
* A header byte meaning that the next element in the stream is a GemFireKey
* object used for GemFireXD.
*/
public static final byte GFXD_GEMFIRE_KEY = -17;
/**
* A header byte meaning that the next element in the stream is a
* FormatibleBitSet object in GemFireXD.
*/
public static final byte GFXD_FORMATIBLEBITSET = -16;
/**
* A header byte meaning that the next element in the stream is a
* <code>VMIdProfile</code>.
*/
public static final byte VMID_PROFILE_MESSAGE = -15;
/**
* A header byte meaning that the next element in the stream is a
* <code>PersistentUUIDProfile</code>.
*/
public static final byte PERSISTENT_UUID_PROFILE_MESSAGE = -14;
public static final short TX_REMOTE_COMMIT_PHASE1_MESSAGE = -13;
public static final short TX_BATCH_MESSAGE = -12;
public static final short TX_CLEANUP_ENTRY_MESSAGE = -11;
public static final short TX_BATCH_REPLY_MESSAGE = -10;
// -9..-1 unused
public static final byte ILLEGAL = 0;
// 1..2 unused
public static final byte JGROUPS_VIEW = 1;
public static final byte JGROUPS_JOIN_RESP = 2;
public static final byte PUTALL_VERSIONS_LIST = 3;
public static final byte INITIAL_IMAGE_VERSIONED_OBJECT_LIST = 4;
public static final byte FIND_VERSION_TAG = 5;
public static final byte VERSION_TAG_REPLY = 6;
public static final byte VERSIONED_OBJECT_LIST = 7;
public static final byte ENUM_ID = 8;
public static final byte ENUM_INFO = 9;
/**
* A header byte meaning that the next element in the stream is
* a <code>InitialImageOperation.EventStateMessage</code>.
*/
public static final byte REGION_STATE_MESSAGE = 10;
/** A header byte meaning that the next element in the stream is a
* <code>ClientInstantiatorMessage</code>.
*/
public static final byte CLIENT_INSTANTIATOR_MESSAGE = 11;
/** A header byte meaning that the next element in the stream is a
* <code>InternalInstantiator.RegistrationMessage</code>.
*/
public static final byte REGISTRATION_MESSAGE = 12;
/** A header byte meaning that the next element in the stream is a
* <code>InternalInstantiator.RegistrationContextMessage</code>.
*/
public static final byte REGISTRATION_CONTEXT_MESSAGE = 13;
/** More Query Result Classes */
// PRQueryProcessor.EndOfBucket
public static final byte END_OF_BUCKET = 14;
public static final byte RESULTS_BAG = 15;
public static final byte STRUCT_BAG = 16;
public static final byte BUCKET_PROFILE = 17;
public static final byte PARTITION_PROFILE = 18;
public static final byte ROLE_EVENT = 19;
public static final byte BRIDGE_REGION_EVENT = 20;
public static final byte CONCURRENT_HASH_MAP = 21;
public static final byte FIND_DURABLE_QUEUE = 22;
public static final byte FIND_DURABLE_QUEUE_REPLY = 23;
public static final byte BRIDGE_SERVER_LOAD_MESSAGE = 24;
/** A header byte meaning that the next element in the stream is a
* <code>ObjectPartList</code>.
*/
public static final byte OBJECT_PART_LIST = 25;
public static final byte REGION = 26;
/****** Query Result Classes *******/
public static final byte RESULTS_COLLECTION_WRAPPER = 27;
public static final byte RESULTS_SET = 28;
public static final byte SORTED_RESULT_SET = 29;
public static final byte SORTED_STRUCT_SET = 30;
public static final byte UNDEFINED = 31;
public static final byte STRUCT_IMPL = 32;
public static final byte STRUCT_SET = 33;
/** A header byte meaning that the next element in the stream is a
* <code>ClearRegionWithContextMessage</code>. */
public static final byte CLEAR_REGION_MESSAGE_WITH_CONTEXT = 34;
/** A header byte meaning that the next element in the stream is a
* <code>ClientUpdateMessage</code>. */
public static final byte CLIENT_UPDATE_MESSAGE = 35;
/** A header byte meaning that the next element in the stream is a
* <code>EventID</code>. */
public static final byte EVENT_ID = 36;
public static final byte INTEREST_RESULT_POLICY = 37;
/** A header byte meaning that the next element in the stream is a
* <code>ClientProxyMembershipID</code>. */
public static final byte CLIENT_PROXY_MEMBERSHIPID = 38;
public static final byte PR_BUCKET_BACKUP_MESSAGE = 39;
public static final byte SERVER_BUCKET_PROFILE = 40;
public static final byte PR_BUCKET_PROFILE_UPDATE_MESSAGE = 41;
public static final byte PR_BUCKET_SIZE_MESSAGE = 42;
public static final byte PR_CONTAINS_KEY_VALUE_MESSAGE = 43;
public static final byte PR_DUMP_ALL_PR_CONFIG_MESSAGE = 44;
public static final byte PR_DUMP_BUCKETS_MESSAGE = 45;
public static final byte PR_FETCH_ENTRIES_MESSAGE = 46;
public static final byte PR_FETCH_ENTRY_MESSAGE = 47;
public static final byte PR_FETCH_KEYS_MESSAGE = 48;
public static final byte PR_FLUSH_MESSAGE = 49;
public static final byte PR_IDENTITY_REQUEST_MESSAGE = 50;
public static final byte PR_IDENTITY_UPDATE_MESSAGE = 51;
public static final byte PR_INDEX_CREATION_MSG = 52;
public static final byte PR_MANAGE_BUCKET_MESSAGE = 53;
public static final byte PR_PRIMARY_REQUEST_MESSAGE = 54;
public static final byte PR_PRIMARY_REQUEST_REPLY_MESSAGE = 55;
public static final byte PR_SANITY_CHECK_MESSAGE = 56;
public static final byte PR_PUT_REPLY_MESSAGE = 57;
public static final byte PR_QUERY_MESSAGE = 58;
public static final byte PR_REMOVE_INDEXES_MESSAGE = 59;
public static final byte PR_REMOVE_INDEXES_REPLY_MESSAGE = 60;
public static final byte PR_SIZE_MESSAGE = 61;
public static final byte PR_SIZE_REPLY_MESSAGE = 62;
public static final byte PR_BUCKET_SIZE_REPLY_MESSAGE = 63;
public static final byte PR_CONTAINS_KEY_VALUE_REPLY_MESSAGE = 64;
public static final byte PR_FETCH_ENTRIES_REPLY_MESSAGE = 65;
public static final byte PR_FETCH_ENTRY_REPLY_MESSAGE = 66;
public static final byte PR_IDENTITY_REPLY_MESSAGE = 67;
public static final byte PR_INDEX_CREATION_REPLY_MSG = 68;
public static final byte PR_MANAGE_BUCKET_REPLY_MESSAGE = 69;
/** A header byte meaning that the next element in the stream is a
* <code>IpAddress</code>. */
public static final byte IP_ADDRESS = 70;
/** A header byte meaning that the next element in the stream is a
* <code>UpdateOperation.UpdateMessage</code>. */
public static final byte UPDATE_MESSAGE = 71;
/** A header byte meaning that the next element in the stream is a
* <code>ReplyMessage</code>. */
public static final byte REPLY_MESSAGE = 72;
/** <code>DestroyMessage</code> */
public static final byte PR_DESTROY = 73;
/** A header byte meaning that the next element in the stream is a
* <code>CreateRegionReplyMessage</code>. */
public static final byte CREATE_REGION_REPLY_MESSAGE = 74;
public static final byte QUERY_MESSAGE = 75;
public static final byte RESPONSE_MESSAGE = 76;
public static final byte NET_SEARCH_REQUEST_MESSAGE = 77;
public static final byte NET_SEARCH_REPLY_MESSAGE = 78;
public static final byte NET_LOAD_REQUEST_MESSAGE = 79;
public static final byte NET_LOAD_REPLY_MESSAGE = 80;
public static final byte NET_WRITE_REQUEST_MESSAGE = 81;
public static final byte NET_WRITE_REPLY_MESSAGE = 82;
// DLockRequestProcessor
public static final byte DLOCK_REQUEST_MESSAGE = 83;
public static final byte DLOCK_RESPONSE_MESSAGE = 84;
// DLockReleaseMessage
public static final byte DLOCK_RELEASE_MESSAGE = 85;
/** A header byte meaning that the next element in the stream is a
* <code>SystemMemberCacheMessage</code>. */
//added for feature requests #32887
public static final byte ADMIN_CACHE_EVENT_MESSAGE = 86;
public static final byte CQ_ENTRY_EVENT = 87;
// InitialImageOperation
public static final byte REQUEST_IMAGE_MESSAGE = 88;
public static final byte IMAGE_REPLY_MESSAGE = 89;
public static final byte IMAGE_ENTRY = 90;
// CloseCacheMessage
public static final byte CLOSE_CACHE_MESSAGE = 91;
public static final byte DISTRIBUTED_MEMBER = 92;
/** A header byte meaning that the next element in the stream is a
* <code>UpdateOperation.UpdateWithContextMessage</code>. */
public static final byte UPDATE_WITH_CONTEXT_MESSAGE = 93;
// GrantorRequestProcessor
public static final byte GRANTOR_REQUEST_MESSAGE = 94;
public static final byte GRANTOR_INFO_REPLY_MESSAGE = 95;
// StartupMessage
public static final byte STARTUP_MESSAGE = 96;
// StartupResponseMessage
public static final byte STARTUP_RESPONSE_MESSAGE = 97;
// ShutdownMessage
public static final byte SHUTDOWN_MESSAGE = 98;
// DestroyRegionOperation
public static final byte DESTROY_REGION_MESSAGE = 99;
public static final byte PR_PUT_MESSAGE = 100;
// InvalidateOperation
public static final byte INVALIDATE_MESSAGE = 101;
// DestroyOperation
public static final byte DESTROY_MESSAGE = 102;
// DistributionAdvisor
public static final byte DA_PROFILE = 103;
// CacheDistributionAdvisor
public static final byte CACHE_PROFILE = 104;
// EntryEventImpl
public static final byte ENTRY_EVENT = 105;
// UpdateAttributesProcessor
public static final byte UPDATE_ATTRIBUTES_MESSAGE = 106;
public static final byte PROFILE_REPLY_MESSAGE = 107;
// RegionEventImpl
public static final byte REGION_EVENT = 108;
// TXId
public static final byte TRANSACTION_ID = 109;
// [sumedh] below ID is no longer used in new TX model and will be
// removed at some point
public static final byte TX_COMMIT_MESSAGE = 110;
public static final byte HA_PROFILE = 111;
public static final byte ELDER_INIT_MESSAGE = 112;
public static final byte ELDER_INIT_REPLY_MESSAGE = 113;
public static final byte DEPOSE_GRANTOR_MESSAGE = 114;
/** A header byte meaning that the next element in the stream is a
* <code>HAEventWrapper</code>. */
public static final byte HA_EVENT_WRAPPER = 115;
public static final byte DLOCK_RELEASE_REPLY = 116;
public static final byte DLOCK_REMOTE_TOKEN = 117;
// TXCommitMessage.CommitProcessForTXIdMessage
public static final byte COMMIT_PROCESS_FOR_TXID_MESSAGE = 118;
public static final byte FILTER_PROFILE = 119;
public static final byte PR_GET_MESSAGE = 120;
// [sumedh] below two IDs are no longer used in new TX model and will be
// removed at some point
// TXLockIdImpl
public static final byte TRANSACTION_LOCK_ID = 121;
// TXCommitMessage.CommitProcessForLockIdMessage
public static final byte COMMIT_PROCESS_FOR_LOCKID_MESSAGE = 122;
// NonGrantorDestroyedProcessor.NonGrantorDestroyedMessage (dlock)
public static final byte NON_GRANTOR_DESTROYED_MESSAGE = 123;
// Token.EndOfStream
public static final byte END_OF_STREAM_TOKEN = 124;
/** {@link com.gemstone.gemfire.internal.cache.partitioned.GetMessage.GetReplyMessage} */
public static final byte PR_GET_REPLY_MESSAGE = 125;
/** {@link com.gemstone.gemfire.internal.cache.Node} */
public static final byte PR_NODE = 126;
/** A header byte meaning that the next element in the stream is a
* <code>DestroyOperation.DestroyWithContextMessage</code>. */
public static final byte DESTROY_WITH_CONTEXT_MESSAGE = 127;
// NOTE, CODES > 127 will take two bytes to serialize
public static final short PR_FETCH_PARTITION_DETAILS_MESSAGE = 128;
public static final short PR_FETCH_PARTITION_DETAILS_REPLY = 129;
public static final short PR_DEPOSE_PRIMARY_BUCKET_MESSAGE = 130;
public static final short PR_DEPOSE_PRIMARY_BUCKET_REPLY = 131;
public static final short PR_BECOME_PRIMARY_BUCKET_MESSAGE = 132;
public static final short PR_BECOME_PRIMARY_BUCKET_REPLY = 133;
public static final short PR_REMOVE_BUCKET_MESSAGE = 134;
public static final short PR_REMOVE_BUCKET_REPLY = 135;
public static final short PR_MOVE_BUCKET_MESSAGE = 136;
public static final short PR_MOVE_BUCKET_REPLY = 137;
public static final short TX_MANAGER_REMOVE_TRANSACTIONS = 138;
public static final short REGION_VERSION_VECTOR = 139;
public static final short INVALIDATE_WITH_CONTEXT_MESSAGE = 140;
public static final short TOKEN_INVALID = 141;
public static final short TOKEN_LOCAL_INVALID = 142;
public static final short TOKEN_DESTROYED = 143;
public static final short TOKEN_REMOVED = 144;
public static final short TOKEN_REMOVED2 = 145;
public static final short STARTUP_RESPONSE_WITHVERSION_MESSAGE = 146;
public static final short SHUTDOWN_ALL_GATEWAYHUBS_REQUEST = 147;
public static final short SHUTDOWN_ALL_GATEWAYHUBS_RESPONSE = 148;
public static final short TOKEN_TOMBSTONE = 149;
public static final short PR_DESTROY_REPLY_MESSAGE = 150;
public static final short R_DESTROY_REPLY_MESSAGE = 151;
public static final short CLI_FUNCTION_RESULT = 152;
public static final short JMX_MANAGER_PROFILE = 153;
public static final short JMX_MANAGER_PROFILE_MESSAGE = 154;
public static final short R_FETCH_VERSION_MESSAGE = 155;
public static final short R_FETCH_VERSION_REPLY = 156;
public static final short PR_TOMBSTONE_MESSAGE = 157;
public static final short UPDATE_ENTRY_VERSION_MESSAGE = 158;
public static final short PR_UPDATE_ENTRY_VERSION_MESSAGE = 159;
public static final short SHUTDOWN_ALL_GATEWAYSENDERS_REQUEST = 160;
public static final short SHUTDOWN_ALL_GATEWAYSENDERS_RESPONSE = 161;
public static final short SHUTDOWN_ALL_GATEWAYRECEIVERS_REQUEST = 162;
public static final short SHUTDOWN_ALL_GATEWAYRECEIVERS_RESPONSE = 163;
// 164 unused
//public static final short TX_COMMIT_MESSAGE_701 = 164;
// 165..999 unused
public static final short ADD_HEALTH_LISTENER_REQUEST = 1000;
public static final short ADD_HEALTH_LISTENER_RESPONSE = 1001;
public static final short ADD_STAT_LISTENER_REQUEST = 1002;
public static final short ADD_STAT_LISTENER_RESPONSE = 1003;
public static final short ADMIN_CONSOLE_DISCONNECT_MESSAGE = 1004;
public static final short ADMIN_CONSOLE_MESSAGE = 1005;
public static final short ADMIN_FAILURE_RESPONSE = 1006;
public static final short ALERT_LEVEL_CHANGE_MESSAGE = 1007;
public static final short ALERT_LISTENER_MESSAGE = 1008;
public static final short APP_CACHE_SNAPSHOT_MESSAGE = 1009;
public static final short BRIDGE_SERVER_REQUEST = 1010;
public static final short BRIDGE_SERVER_RESPONSE = 1011;
public static final short CACHE_CONFIG_REQUEST = 1012;
public static final short CACHE_CONFIG_RESPONSE = 1013;
public static final short CACHE_INFO_REQUEST = 1014;
public static final short CACHE_INFO_RESPONSE = 1015;
public static final short CANCELLATION_MESSAGE = 1016;
public static final short CANCEL_STAT_LISTENER_REQUEST = 1017;
public static final short CANCEL_STAT_LISTENER_RESPONSE = 1018;
public static final short DESTROY_ENTRY_MESSAGE = 1019;
public static final short ADMIN_DESTROY_REGION_MESSAGE = 1020;
public static final short FETCH_DIST_LOCK_INFO_REQUEST = 1021;
public static final short FETCH_DIST_LOCK_INFO_RESPONSE = 1022;
public static final short FETCH_HEALTH_DIAGNOSIS_REQUEST = 1023;
public static final short FETCH_HEALTH_DIAGNOSIS_RESPONSE = 1024;
public static final short FETCH_HOST_REQUEST = 1025;
public static final short FETCH_HOST_RESPONSE = 1026;
public static final short FETCH_RESOURCE_ATTRIBUTES_REQUEST = 1027;
public static final short FETCH_RESOURCE_ATTRIBUTES_RESPONSE = 1028;
public static final short FETCH_STATS_REQUEST = 1029;
public static final short FETCH_STATS_RESPONSE = 1030;
public static final short FETCH_SYS_CFG_REQUEST = 1031;
public static final short FETCH_SYS_CFG_RESPONSE = 1032;
public static final short FLUSH_APP_CACHE_SNAPSHOT_MESSAGE = 1033;
public static final short HEALTH_LISTENER_MESSAGE = 1034;
// erstwhile licensing messages but don't reuse IDs below
//public static final short LICENSE_INFO_REQUEST = 1035;
//public static final short LICENSE_INFO_RESPONSE = 1036;
public static final short OBJECT_DETAILS_REQUEST = 1037;
public static final short OBJECT_DETAILS_RESPONSE = 1038;
public static final short OBJECT_NAMES_REQUEST = 1039;
public static final short OBJECT_NAMES_RESPONSE = 1040;
public static final short REGION_ATTRIBUTES_REQUEST = 1041;
public static final short REGION_ATTRIBUTES_RESPONSE = 1042;
public static final short REGION_REQUEST = 1043;
public static final short REGION_RESPONSE = 1044;
public static final short REGION_SIZE_REQUEST = 1045;
public static final short REGION_SIZE_RESPONSE = 1046;
public static final short REGION_STATISTICS_REQUEST = 1047;
public static final short REGION_STATISTICS_RESPONSE = 1048;
public static final short REMOVE_HEALTH_LISTENER_REQUEST = 1049;
public static final short REMOVE_HEALTH_LISTENER_RESPONSE = 1050;
public static final short RESET_HEALTH_STATUS_REQUEST = 1051;
public static final short RESET_HEALTH_STATUS_RESPONSE = 1052;
public static final short ROOT_REGION_REQUEST = 1053;
public static final short ROOT_REGION_RESPONSE = 1054;
public static final short SNAPSHOT_RESULT_MESSAGE = 1055;
public static final short STAT_LISTENER_MESSAGE = 1056;
public static final short STORE_SYS_CFG_REQUEST = 1057;
public static final short STORE_SYS_CFG_RESPONSE = 1058;
public static final short SUB_REGION_REQUEST = 1059;
public static final short SUB_REGION_RESPONSE = 1060;
public static final short TAIL_LOG_REQUEST = 1061;
public static final short TAIL_LOG_RESPONSE = 1062;
public static final short VERSION_INFO_REQUEST = 1063;
public static final short VERSION_INFO_RESPONSE = 1064;
public static final short STAT_ALERTS_MGR_ASSIGN_MESSAGE = 1065;
public static final short UPDATE_ALERTS_DEFN_MESSAGE = 1066;
public static final short REFRESH_MEMBER_SNAP_REQUEST = 1067;
public static final short REFRESH_MEMBER_SNAP_RESPONSE = 1068;
public static final short REGION_SUB_SIZE_REQUEST = 1069;
public static final short REGION_SUB_SIZE_RESPONSE = 1070;
public static final short CHANGE_REFRESH_INT_MESSAGE = 1071;
public static final short ALERTS_NOTIF_MESSAGE = 1072;
public static final short STAT_ALERT_DEFN_NUM_THRESHOLD = 1073;
public static final short STAT_ALERT_DEFN_GAUGE_THRESHOLD = 1074;
public static final short STAT_ALERT_NOTIFICATION = 1075;
public static final short FILTER_INFO_MESSAGE = 1076;
public static final short REQUEST_FILTERINFO_MESSAGE = 1077;
public static final short REQUEST_RVV_MESSAGE = 1078;
public static final short RVV_REPLY_MESSAGE = 1079;
public static final short CLIENT_MEMBERSHIP_MESSAGE = 1080;
// 1,081...1,199 reserved for more admin msgs
public static final short PR_FUNCTION_STREAMING_MESSAGE = 1201;
public static final short MEMBER_FUNCTION_STREAMING_MESSAGE = 1202;
public static final short DR_FUNCTION_STREAMING_MESSAGE = 1203;
public static final short FUNCTION_STREAMING_REPLY_MESSAGE = 1204;
public static final short FUNCTION_STREAMING_ORDERED_REPLY_MESSAGE = 1205;
public static final short REQUEST_SYNC_MESSAGE = 1206;
// 1,209..1,999 unused
public static final short HIGH_PRIORITY_ACKED_MESSAGE = 2000;
public static final short SERIAL_ACKED_MESSAGE = 2001;
public static final short CLIENT_DATASERIALIZER_MESSAGE=2002;
//2003..2099 unused
public static final short PERSISTENT_MEMBERSHIP_VIEW_REQUEST =2100;
public static final short PERSISTENT_MEMBERSHIP_VIEW_REPLY = 2101;
public static final short PERSISTENT_STATE_QUERY_REQUEST = 2102;
public static final short PERSISTENT_STATE_QUERY_REPLY = 2103;
public static final short PREPARE_NEW_PERSISTENT_MEMBER_REQUEST = 2104;
public static final short MISSING_PERSISTENT_IDS_REQUEST = 2105;
public static final short MISSING_PERSISTENT_IDS_RESPONSE = 2106;
public static final short REVOKE_PERSISTENT_ID_REQUEST = 2107;
public static final short REVOKE_PERSISTENT_ID_RESPONSE = 2108;
public static final short REMOVE_PERSISTENT_MEMBER_REQUEST = 2109;
public static final short PERSISTENT_MEMBERSHIP_FLUSH_REQUEST = 2110;
public static final short SHUTDOWN_ALL_REQUEST = 2111;
public static final short SHUTDOWN_ALL_RESPONSE = 2112;
public static final short END_BUCKET_CREATION_MESSAGE = 2113;
public static final short FINISH_BACKUP_REQUEST = 2114;
public static final short FINISH_BACKUP_RESPONSE = 2115;
public static final short PREPARE_BACKUP_REQUEST = 2116;
public static final short PREPARE_BACKUP_RESPONSE = 2117;
public static final short COMPACT_REQUEST = 2118;
public static final short COMPACT_RESPONSE = 2119;
public static final short FLOW_CONTROL_PERMIT_MESSAGE = 2120;
public static final short OBJECT_PART_LIST66 = 2121;
public static final short LINKED_RESULTSET = 2122;
public static final short LINKED_STRUCTSET = 2123;
public static final short PR_ALL_BUCKET_PROFILES_UPDATE_MESSAGE = 2124;
public static final short SERIALIZED_OBJECT_PART_LIST = 2125;
public static final short FLUSH_TO_DISK_REQUEST = 2126;
public static final short FLUSH_TO_DISK_RESPONSE= 2127;
public static final short CHECK_TYPE_REGISTRY_STATE= 2128;
public static final short PREPARE_REVOKE_PERSISTENT_ID_REQUEST = 2129;
public static final short MISSING_PERSISTENT_IDS_RESPONSE_662 = 2130;
public static final short PERSISTENT_VERSION_TAG = 2131;
public static final short PERSISTENT_RVV = 2132;
public static final short DISK_STORE_ID = 2133;
public static final short SNAPSHOT_PACKET = 2134;
public static final short SNAPSHOT_RECORD = 2135;
public static final short FLOW_CONTROL_ACK = 2136;
public static final short FLOW_CONTROL_ABORT = 2137;
public static final short REMOTE_LOCATOR_RESPONSE = 2138;
public static final short LOCATOR_JOIN_MESSAGE = 2139;
public static final short PARALLEL_QUEUE_REMOVAL_MESSAGE = 2140;
// 2141 unused
public static final short REMOTE_LOCATOR_PING_REQUEST = 2142;
public static final short REMOTE_LOCATOR_PING_RESPONSE = 2143;
public static final short GATEWAY_SENDER_PROFILE = 2144;
public static final short REMOTE_LOCATOR_JOIN_REQUEST = 2145;
public static final short REMOTE_LOCATOR_JOIN_RESPONSE = 2146;
public static final short REMOTE_LOCATOR_REQUEST = 2147;
public static final short BATCH_DESTROY_MESSAGE = 2148;
public static final short MANAGER_STARTUP_MESSAGE = 2149;
public static final short JMX_MANAGER_LOCATOR_REQUEST = 2150;
public static final short JMX_MANAGER_LOCATOR_RESPONSE = 2151;
public static final short MGMT_COMPACT_REQUEST = 2152;
public static final short MGMT_COMPACT_RESPONSE = 2153;
public static final short MGMT_FEDERATION_COMPONENT = 2154;
public static final short LOCATOR_STATUS_REQUEST = 2155;
public static final short LOCATOR_STATUS_RESPONSE = 2156;
public static final short RELEASE_CLEAR_LOCK_MESSAGE = 2157;
public static final short NULL_TOKEN = 2158;
public static final short PR_DESTROY_ON_DATA_STORE_MESSAGE = 2159;
public static final short COMMIT_PHASE1_REPLY_MESSAGE = 2160;
public static final short TOBJECTLONGHASHMAP = 2161;
public static final short SERVER_PING_MESSAGE = 2162;
// NOTE, codes > 65535 will take 4 bytes to serialize
/**
* This special code is a way for an implementor if this interface
* to say that it does not have a fixed id.
* In that case its class name is serialized.
* Currently only test classes just return this code.
*/
public static final int NO_FIXED_ID = Integer.MAX_VALUE;
//////////////// END CODES ////////////
/**
* Returns the DataSerializer fixed id for the class that implements this method.
*/
public int getDSFID();
/**
* Writes the state of this object as primitive data to the given
* <code>DataOutput</code>.<br>
* <br>
* Note: For rolling upgrades, if there is a change in the object format from
* previous version, add a new toDataPre_GFE_X_X_X_X() method and add an entry for the
* current {@link Version} in the getSerializationVersions array of the implementing
* class. e.g. if msg format changed in version 75, create toDataPre_GFE_7_5_0_0, add
* Version.GFE_75 to the getSerializationVersions array and copy previous toData contents
* to this newly created toDataPre_GFE_X_X_X_X() method.
* <p>
* For GemFireXD use "GFXD" (or whatever we decide on as a product identifier
* in Version) instead of "GFE" in method names.
* @throws IOException
* A problem occurs while writing to <code>out</code>
*/
public void toData(DataOutput out) throws IOException;
/**
* Reads the state of this object as primitive data from the given
* <code>DataInput</code>. <br>
* <br>
* Note: For rolling upgrades, if there is a change in the object format from
* previous version, add a new fromDataPre_GFE_X_X_X_X() method and add an entry for
* the current {@link Version} in the getSerializationVersions array of the implementing
* class. e.g. if msg format changed in version 75, create fromDataPre_GFE_7_5_0_0, add
* Version.GFE_75 to the getSerializationVersions array and copy previous fromData
* contents to this newly created fromDataPre_GFE_X_X_X_X() method.
* <p>
* For GemFireXD use "GFXD" (or whatever we decide on as a product identifier
* in Version) instead of "GFE" in method names.
*
* @throws IOException
* A problem occurs while reading from <code>in</code>
* @throws ClassNotFoundException
* A class could not be loaded while reading from <code>in</code>
*/
public void fromData(DataInput in) throws IOException, ClassNotFoundException;
}
|
package pl.mjedynak.idea.plugins.builder.factory;
import com.google.common.collect.Lists;
import com.intellij.codeInsight.generation.PsiElementClassMember;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiMethod;
import pl.mjedynak.idea.plugins.builder.psi.BestConstructorSelector;
import pl.mjedynak.idea.plugins.builder.psi.model.PsiFieldsForBuilder;
import pl.mjedynak.idea.plugins.builder.verifier.PsiFieldVerifier;
import java.util.List;
public class PsiFieldsForBuilderFactory {
private PsiFieldVerifier psiFieldVerifier;
private BestConstructorSelector bestConstructorSelector;
public PsiFieldsForBuilderFactory(PsiFieldVerifier psiFieldVerifier, BestConstructorSelector bestConstructorSelector) {
this.psiFieldVerifier = psiFieldVerifier;
this.bestConstructorSelector = bestConstructorSelector;
}
@SuppressWarnings("rawtypes")
public PsiFieldsForBuilder createPsiFieldsForBuilder(List<PsiElementClassMember> psiElementClassMembers, PsiClass psiClass) {
List<PsiField> allSelectedPsiFields = Lists.newArrayList();
List<PsiField> psiFieldsFoundInSetters = Lists.newArrayList();
for (PsiElementClassMember psiElementClassMember : psiElementClassMembers) {
PsiElement psiElement = psiElementClassMember.getPsiElement();
if (psiElement instanceof PsiField) {
allSelectedPsiFields.add((PsiField) psiElement);
if (psiFieldVerifier.isSetInSetterMethod((PsiField) psiElement, psiClass)) {
psiFieldsFoundInSetters.add((PsiField) psiElement);
}
}
}
List<PsiField> psiFieldsToFindInConstructor = allSelectedPsiFields;
List<PsiField> psiFieldsForConstructor = Lists.newArrayList();
PsiMethod bestConstructor = bestConstructorSelector.getBestConstructor(psiFieldsToFindInConstructor, psiClass);
if (bestConstructor != null) {
buildPsiFieldsForConstructor(psiFieldsForConstructor, allSelectedPsiFields, bestConstructor);
}
List<PsiField> psiFieldsForSetters = getSubList(psiFieldsFoundInSetters, psiFieldsForConstructor);
return new PsiFieldsForBuilder(psiFieldsForSetters, psiFieldsForConstructor, allSelectedPsiFields, bestConstructor);
}
private void buildPsiFieldsForConstructor(List<PsiField> psiFieldsForConstructor, List<PsiField> allSelectedPsiFields, PsiMethod bestConstructor) {
for (PsiField selectedPsiField : allSelectedPsiFields) {
if (psiFieldVerifier.checkConstructor(selectedPsiField, bestConstructor)) {
psiFieldsForConstructor.add(selectedPsiField);
}
}
}
private List<PsiField> getSubList(List<PsiField> inputList, List<PsiField> listToRemove) {
List<PsiField> newList = Lists.newArrayList();
for (PsiField inputPsiField : inputList) {
boolean setterMustBeAdded = true;
for (PsiField psiFieldToRemove : listToRemove) {
if (psiFieldToRemove.getName().equals(inputPsiField.getName())) {
setterMustBeAdded = false;
}
}
if (setterMustBeAdded) {
newList.add(inputPsiField);
}
}
return newList;
}
}
|
package org.wso2.carbon.apimgt.rest.api.publisher.dto;
import io.swagger.annotations.*;
import com.fasterxml.jackson.annotation.*;
import javax.validation.constraints.NotNull;
@ApiModel(description = "")
public class WsdlInfoDTO {
@NotNull
private String name = null;
@NotNull
private String id = null;
/**
**/
@ApiModelProperty(required = true, value = "")
@JsonProperty("name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
**/
@ApiModelProperty(required = true, value = "")
@JsonProperty("id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class WsdlInfoDTO {\n");
sb.append(" name: ").append(name).append("\n");
sb.append(" id: ").append(id).append("\n");
sb.append("}\n");
return sb.toString();
}
}
|
/*
*
* Module Name: sln-contracts
* Project: sln
*
* Copyright (c) Element Lab LLC
*
* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
*
*/
package ru.elementlab.sln.contracts;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
/**
* Описывает уровень риска лекарственного взаимодействия.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class InteractionSeverityLevel extends CodedValueWithLevel {
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.braintree;
import java.util.HashMap;
import java.util.Map;
import com.braintreegateway.BraintreeGateway;
import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.component.braintree.internal.BraintreeApiCollection;
import org.apache.camel.component.braintree.internal.BraintreeApiName;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.annotations.Component;
import org.apache.camel.support.component.AbstractApiComponent;
/**
* Represents the component that manages {@link BraintreeEndpoint}.
*/
@Component("braintree")
public class BraintreeComponent extends AbstractApiComponent<BraintreeApiName, BraintreeConfiguration, BraintreeApiCollection> {
@Metadata
private BraintreeConfiguration configuration;
private final Map<String, BraintreeGateway> gateways;
public BraintreeComponent() {
super(BraintreeEndpoint.class, BraintreeApiName.class, BraintreeApiCollection.getCollection());
this.gateways = new HashMap<>();
}
public BraintreeComponent(CamelContext context) {
super(context, BraintreeEndpoint.class, BraintreeApiName.class, BraintreeApiCollection.getCollection());
this.gateways = new HashMap<>();
}
@Override
protected BraintreeApiName getApiName(String apiNameStr) throws IllegalArgumentException {
return BraintreeApiName.fromValue(apiNameStr);
}
@Override
protected Endpoint createEndpoint(String uri, String methodName, BraintreeApiName apiName, BraintreeConfiguration endpointConfiguration) {
endpointConfiguration.setApiName(apiName);
endpointConfiguration.setMethodName(methodName);
this.configuration = endpointConfiguration;
return new BraintreeEndpoint(uri, this, apiName, methodName, endpointConfiguration);
}
public synchronized BraintreeGateway getGateway(BraintreeConfiguration configuration) {
BraintreeGateway gateway;
if (configuration.getAccessToken() != null) {
gateway = gateways.get(configuration.getAccessToken());
if (gateway == null) {
gateway = configuration.newBraintreeGateway();
gateways.put(configuration.getAccessToken(), gateway);
}
} else {
gateway = gateways.get(configuration.getMerchantId());
if (gateway == null) {
gateway = configuration.newBraintreeGateway();
gateways.put(configuration.getMerchantId(), gateway);
}
}
return gateway;
}
}
|
/*
* 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.github.housepower.misc;
import com.github.housepower.client.NativeContext;
import com.github.housepower.settings.SettingKey;
import javax.annotation.Nullable;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class DateTimeUtil {
public static ZoneId chooseTimeZone(NativeContext.ServerContext serverContext) {
return (boolean) serverContext.getConfigure().settings().getOrDefault(SettingKey.use_client_time_zone, false)
? ZoneId.systemDefault() : serverContext.timeZone();
}
public static LocalDateTime convertTimeZone(LocalDateTime localDateTime, ZoneId from, ZoneId to) {
return localDateTime.atZone(from).withZoneSameInstant(to).toLocalDateTime();
}
public static long toEpochMilli(final ZonedDateTime zdt) {
return zdt.toInstant().toEpochMilli();
}
public static long toEpochSecond(final ZonedDateTime zdt) {
return zdt.toInstant().getEpochSecond();
}
public static ZonedDateTime toZonedDateTime(final long seconds, final int nanos, final ZoneId tz) {
Instant i = Instant.ofEpochSecond(seconds, nanos);
return ZonedDateTime.ofInstant(i, tz);
}
public static ZonedDateTime toZonedDateTime(final Timestamp x, final ZoneId tz) {
Instant i = Instant.ofEpochSecond(x.getTime() / 1000, x.getNanos());
return ZonedDateTime.ofInstant(i, tz);
}
public static Timestamp toTimestamp(final ZonedDateTime zdt, @Nullable final ZoneId tz) {
ZonedDateTime _zdt = tz == null ? zdt : zdt.withZoneSameLocal(tz);
return Timestamp.from(_zdt.toInstant());
}
}
|
/*
* 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.aliyuncs.sofa.model.v20190815;
import com.aliyuncs.RpcAcsRequest;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.sofa.Endpoint;
/**
* @author auto create
* @version
*/
public class QueryLinkefabricFabricCloudsystemconfigisopenapiRequest extends RpcAcsRequest<QueryLinkefabricFabricCloudsystemconfigisopenapiResponse> {
private Long envId;
private String appName;
private Long tenantId;
private String projectId;
private String env;
private String strategyName;
private String devStage;
private Boolean isStandard;
public QueryLinkefabricFabricCloudsystemconfigisopenapiRequest() {
super("SOFA", "2019-08-15", "QueryLinkefabricFabricCloudsystemconfigisopenapi", "sofacafedeps");
setMethod(MethodType.POST);
try {
com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap);
com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType);
} catch (Exception e) {}
}
public Long getEnvId() {
return this.envId;
}
public void setEnvId(Long envId) {
this.envId = envId;
if(envId != null){
putBodyParameter("EnvId", envId.toString());
}
}
public String getAppName() {
return this.appName;
}
public void setAppName(String appName) {
this.appName = appName;
if(appName != null){
putBodyParameter("AppName", appName);
}
}
public Long getTenantId() {
return this.tenantId;
}
public void setTenantId(Long tenantId) {
this.tenantId = tenantId;
if(tenantId != null){
putBodyParameter("TenantId", tenantId.toString());
}
}
public String getProjectId() {
return this.projectId;
}
public void setProjectId(String projectId) {
this.projectId = projectId;
if(projectId != null){
putBodyParameter("ProjectId", projectId);
}
}
public String getEnv() {
return this.env;
}
public void setEnv(String env) {
this.env = env;
if(env != null){
putBodyParameter("Env", env);
}
}
public String getStrategyName() {
return this.strategyName;
}
public void setStrategyName(String strategyName) {
this.strategyName = strategyName;
if(strategyName != null){
putBodyParameter("StrategyName", strategyName);
}
}
public String getDevStage() {
return this.devStage;
}
public void setDevStage(String devStage) {
this.devStage = devStage;
if(devStage != null){
putBodyParameter("DevStage", devStage);
}
}
public Boolean getIsStandard() {
return this.isStandard;
}
public void setIsStandard(Boolean isStandard) {
this.isStandard = isStandard;
if(isStandard != null){
putBodyParameter("IsStandard", isStandard.toString());
}
}
@Override
public Class<QueryLinkefabricFabricCloudsystemconfigisopenapiResponse> getResponseClass() {
return QueryLinkefabricFabricCloudsystemconfigisopenapiResponse.class;
}
}
|
/*
* Copyright Terracotta, 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.ehcache.impl.internal.concurrent;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
/**
* @author Ludovic Orban
*/
public class ConcurrentHashMapITest {
private static final int ENTRIES = 10000;
@Test
public void testRandomValuesWithObjects() {
ConcurrentHashMap<Object, KeyHolder<Object>> map = new ConcurrentHashMap<>();
for(int i = 0; i < ENTRIES; i++) {
final Object o = new Object();
map.put(o, new KeyHolder<>(o));
}
assertThings(map);
}
@Test
public void testRandomValuesWithComparable() {
ConcurrentHashMap<Comparable<?>, KeyHolder<Object>> map = new ConcurrentHashMap<>();
for(int i = 0; i < ENTRIES; i++) {
final EvilComparableKey o = new EvilComparableKey(UUID.randomUUID().toString());
map.put(o, new KeyHolder<>(o));
}
assertThings(map);
}
@Test
public void testRandomValues() {
ConcurrentHashMap<Object, KeyHolder<Object>> map = new ConcurrentHashMap<>();
final long seed = System.nanoTime();
System.out.println("SEED: " + seed);
final Random random = new Random(seed);
for(int i = 0; i < ENTRIES; i++) {
final Object o;
switch(i % 4) {
case 0:
final int hashCode = random.nextInt();
o = new Object() {
@Override
public int hashCode() {
return hashCode;
}
};
break;
case 1:
o = new EvilKey(Integer.toString(i));
break;
default:
o = new EvilComparableKey(Integer.toString(i));
}
assertThat(map.put(o, new KeyHolder<>(o)) == null, is(true));
}
for (Object o : map.keySet()) {
assertThat(o.toString(), map.containsKey(o), is(true));
assertThat(o.toString(), map.get(o), notNullValue());
}
assertThings(map);
}
@Test
public void testRandomValuesWithCollisions() {
ConcurrentHashMap<Object, KeyHolder<Object>> map = new ConcurrentHashMap<>();
for(int i = 0; i < ENTRIES; i++) {
final EvilKey o = new EvilKey(UUID.randomUUID().toString());
map.put(o, new KeyHolder<>(o));
}
assertThings(map);
}
@Test
public void testActuallyWorks() throws InterruptedException {
final long top = 100000000;
final String key = "counter";
final ConcurrentHashMap<String, Long> map = new ConcurrentHashMap<>();
map.put(key, 0L);
final Runnable runnable = () -> {
for(Long val = map.get(key); val < top && map.replace(key, val, val + 1); val = map.get(key));
};
Thread[] threads = new Thread[Runtime.getRuntime().availableProcessors() * 2];
for (int i = 0, threadsLength = threads.length; i < threadsLength; ) {
threads[i] = new Thread(runnable);
threads[i].setName("Mutation thread #" + ++i);
threads[i - 1].start();
}
for (Thread thread : threads) {
thread.join();
}
assertThat(map.get(key), is(top));
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void assertThings(final ConcurrentHashMap<?, ?> map) {
assertThat(map.size(), is(ENTRIES));
for(int i = 0; i < 100; i ++) {
final HashSet randomValues = new HashSet(getRandomValues(map));
assertThat(randomValues.size(), is(ENTRIES));
for (Object randomValue : randomValues) {
assertThat(randomValue, instanceOf(KeyHolder.class));
final Object key = ((KeyHolder)randomValue).key;
assertThat("Missing " + key, map.containsKey(key), is(true));
}
}
}
private static List<?> getRandomValues(Map<?, ?> map) {
List<?> values = new ArrayList<Object>(map.values());
Collections.shuffle(values);
return values.subList(0, ENTRIES);
}
static class KeyHolder<K> {
final K key;
KeyHolder(final K key) {
this.key = key;
}
}
static class EvilKey {
final String value;
EvilKey(final String value) {
this.value = value;
}
@Override
public int hashCode() {
return this.value.hashCode() & 1;
}
@Override
public boolean equals(final Object obj) {
return obj != null && obj.getClass() == this.getClass() && ((EvilKey)obj).value.equals(value);
}
@Override
public String toString() {
return this.getClass().getSimpleName() + " { " + value + " }";
}
}
static class EvilComparableKey extends EvilKey implements Comparable<EvilComparableKey> {
EvilComparableKey(final String value) {
super(value);
}
@Override
public int compareTo(final EvilComparableKey o) {
return value.compareTo(o.value);
}
}
}
|
/*
*AVISO LEGAL
© Copyright
*Este programa esta protegido por la ley de derechos de autor.
*La reproduccion o distribucion ilicita de este programa o de cualquiera de
*sus partes esta penado por la ley con severas sanciones civiles y penales,
*y seran objeto de todas las sanciones legales que correspondan.
*Su contenido no puede copiarse para fines comerciales o de otras,
*ni puede mostrarse, incluso en una version modificada, en otros sitios Web.
Solo esta permitido colocar hipervinculos al sitio web.
*/
package com.bydan.erp.puntoventa.business.entity;
import java.io.Serializable;
import java.io.File;
import java.util.Calendar;
import java.sql.Timestamp;
import java.util.Set;
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Date;
import org.hibernate.validator.*;
import com.bydan.framework.erp.business.entity.*;
import com.bydan.framework.erp.business.entity.DatoGeneral;
import com.bydan.framework.erp.business.dataaccess.ConstantesSql;
//import com.bydan.framework.erp.business.entity.Mensajes;
import com.bydan.framework.erp.util.Constantes;
import com.bydan.framework.erp.util.ConstantesValidacion;
//import com.bydan.erp.puntoventa.util.TipoRiesgoChequeConstantesFunciones;
import com.bydan.erp.puntoventa.util.*;
@SuppressWarnings("unused")
public class TipoRiesgoCheque extends GeneralEntitySinIdGenerated implements Serializable ,Cloneable {//TipoRiesgoChequeAdditional,GeneralEntity
private static final long serialVersionUID=1L;
public Object clone() {
return super.clone();
}
protected Long id;
protected Long idOriginal;
protected boolean isNew;
protected boolean isChanged;
protected boolean isDeleted;
protected boolean isSelected;
protected Date versionRow;
protected String sType;
public Long getId() {
return this.id;
}
public void setId(Long newId) {
if(this.id!=newId) {
this.isChanged=true;
}
this.id=newId;
super.setId(newId);
}
public Long getIdOriginal() {
return this.idOriginal;
}
public void setIdOriginal(Long newIdOriginal) {
this.idOriginal=newIdOriginal;
super.setIdOriginal(newIdOriginal);
}
public Date getVersionRow(){
//ESTO SIEMPRE SE EJECUTA CUANDO SE CONSUME EJB
return this.versionRow;
}
public void setVersionRow(Date newVersionRow){
if(this.versionRow!=newVersionRow){
//LE COMENTO PORQUE CUANDO HAGO GET SIEMPRE POR ESTO LE PONE isChanged=true
//this.isChanged=true;
}
this.versionRow=newVersionRow;
super.setVersionRow(newVersionRow);
}
public boolean getIsNew() {
return this.isNew;
}
public void setIsNew(boolean newIsNew) {
this.isNew=newIsNew;
super.setIsNew(newIsNew);
}
public boolean getIsChanged() {
return this.isChanged;
}
public void setIsChanged(boolean newIsChanged) {
this.isChanged=newIsChanged;
super.setIsChanged(newIsChanged);
}
public boolean getIsDeleted() {
return this.isDeleted;
}
public void setIsDeleted(boolean newIsDeleted) {
this.isDeleted=newIsDeleted;
super.setIsDeleted(newIsDeleted);
}
public boolean getIsSelected() {
return this.isSelected;
}
public void setIsSelected(boolean newIsSelected) {
this.isSelected=newIsSelected;
super.setIsSelected(newIsSelected);
}
public String getsType() {
return this.sType;
}
public void setsType(String sType) {
this.sType=sType;
super.setsType(sType);
}
private TipoRiesgoCheque tiporiesgochequeOriginal;
private Map<String, Object> mapTipoRiesgoCheque;
public Map<String, Object> getMapTipoRiesgoCheque() {
return mapTipoRiesgoCheque;
}
public void setMapTipoRiesgoCheque(Map<String, Object> mapTipoRiesgoCheque) {
this.mapTipoRiesgoCheque = mapTipoRiesgoCheque;
}
public void inicializarMapTipoRiesgoCheque() {
this.mapTipoRiesgoCheque = new HashMap<String,Object>();
}
public void setMapTipoRiesgoChequeValue(String sKey,Object oValue) {
this.mapTipoRiesgoCheque.put(sKey, oValue);
}
public Object getMapTipoRiesgoChequeValue(String sKey) {
return this.mapTipoRiesgoCheque.get(sKey);
}
@NotNull(message=ConstantesValidacion.SVALIDACIONNOTNULL)
@Length(min=0,max=100,message=ConstantesValidacion.SVALIDACIONLENGTH)
@NotEmpty(message=ConstantesValidacion.SVALIDACIONNOVACIO)
@Pattern(regex=TipoRiesgoChequeConstantesFunciones.SREGEXNOMBRE,message=TipoRiesgoChequeConstantesFunciones.SMENSAJEREGEXNOMBRE)
private String nombre;
@NotNull(message=ConstantesValidacion.SVALIDACIONNOTNULL)
@Length(min=0,max=150,message=ConstantesValidacion.SVALIDACIONLENGTH)
@Pattern(regex=TipoRiesgoChequeConstantesFunciones.SREGEXDESCRIPCION,message=TipoRiesgoChequeConstantesFunciones.SMENSAJEREGEXDESCRIPCION)
private String descripcion;
public List<FormaPagoPuntoVenta> formapagopuntoventas;
public TipoRiesgoCheque () throws Exception {
super();
this.id=0L;
this.idOriginal=0L;
this.versionRow=new java.sql.Timestamp(Calendar.getInstance().getTime().getTime());//new Date();
this.isNew=true;
this.isChanged=false;
this.isDeleted=false;
this.sType="NONE";
this.tiporiesgochequeOriginal=this;
this.nombre="";
this.descripcion="";
this.formapagopuntoventas=null;
/*PARA REPORTES*/
this.inicializarVariablesParaReporte();
/*PARA REPORTES*/
}
//PARA REPORTES
public TipoRiesgoCheque (Long id,Date versionRow,String nombre,String descripcion) throws Exception {
super();
this.id=id;
this.idOriginal=this.id;
this.versionRow=versionRow;
this.isNew=true;
this.isChanged=false;
this.isDeleted=false;
this.tiporiesgochequeOriginal=this;
this.nombre=nombre;
this.descripcion=descripcion;
/*PARA REPORTES*/
this.inicializarVariablesParaReporte();
/*PARA REPORTES*/
}
//PARA REPORTES
public TipoRiesgoCheque (String nombre,String descripcion) throws Exception {
super();
this.id=0L;
this.idOriginal=0L;
this.versionRow=new Date();
this.isNew=true;
this.isChanged=false;
this.isDeleted=false;
this.tiporiesgochequeOriginal=this;
this.nombre=nombre;
this.descripcion=descripcion;
/*PARA REPORTES*/
this.inicializarVariablesParaReporte();
/*PARA REPORTES*/
}
public boolean equals(Object object) {
boolean equal=false;
TipoRiesgoCheque tiporiesgochequeLocal=null;
if(object!=null) {
tiporiesgochequeLocal=(TipoRiesgoCheque)object;
if(tiporiesgochequeLocal!=null) {
if(this.getId()!=null && tiporiesgochequeLocal.getId()!=null) {
if(this.getId().equals(tiporiesgochequeLocal.getId())) {
equal=true;
}
}
}
}
return equal;
}
public String toString() {
String sDetalle="";
if(!TipoRiesgoChequeConstantesFunciones.CON_DESCRIPCION_DETALLADO) {
sDetalle=TipoRiesgoChequeConstantesFunciones.getTipoRiesgoChequeDescripcion(this);
} else {
sDetalle=TipoRiesgoChequeConstantesFunciones.getTipoRiesgoChequeDescripcionDetallado(this);
}
return sDetalle;
}
public TipoRiesgoCheque getTipoRiesgoChequeOriginal() {
return this.tiporiesgochequeOriginal;
}
public void setTipoRiesgoChequeOriginal(TipoRiesgoCheque tiporiesgocheque) {
try {
this.tiporiesgochequeOriginal=tiporiesgocheque;
} catch(Exception e) {
;
}
}
public String getnombre() {
return this.nombre;
}
public String getdescripcion() {
return this.descripcion;
}
public void setnombre(String newnombre)throws Exception
{
try {
if(this.nombre!=newnombre) {
if(newnombre==null) {
//newnombre="";
if(Constantes.ISDEVELOPING) {
System.out.println("TipoRiesgoCheque:Valor nulo no permitido en columna nombre");
}
}
if(newnombre!=null&&newnombre.length()>100) {
newnombre=newnombre.substring(0,98);
System.out.println("TipoRiesgoCheque:Ha sobrepasado el numero maximo de caracteres permitidos,Maximo=100 en columna nombre");
}
this.nombre=newnombre;
this.setIsChanged(true);
}
} catch(Exception e) {
throw e;
}
}
public void setdescripcion(String newdescripcion)throws Exception
{
try {
if(this.descripcion!=newdescripcion) {
if(newdescripcion==null) {
//newdescripcion="";
if(Constantes.ISDEVELOPING) {
System.out.println("TipoRiesgoCheque:Valor nulo no permitido en columna descripcion");
}
}
if(newdescripcion!=null&&newdescripcion.length()>150) {
newdescripcion=newdescripcion.substring(0,148);
System.out.println("TipoRiesgoCheque:Ha sobrepasado el numero maximo de caracteres permitidos,Maximo=150 en columna descripcion");
}
this.descripcion=newdescripcion;
this.setIsChanged(true);
}
} catch(Exception e) {
throw e;
}
}
public List<FormaPagoPuntoVenta> getFormaPagoPuntoVentas() {
return this.formapagopuntoventas;
}
public void setFormaPagoPuntoVentas(List<FormaPagoPuntoVenta> formapagopuntoventas) {
try {
this.formapagopuntoventas=formapagopuntoventas;
} catch(Exception e) {
;
}
}
/*PARA REPORTES*/
public void inicializarVariablesParaReporte() {
}
Object formapagopuntoventasDescripcionReporte;
public Object getformapagopuntoventasDescripcionReporte() {
return formapagopuntoventasDescripcionReporte;
}
public void setformapagopuntoventasDescripcionReporte(Object formapagopuntoventas) {
try {
this.formapagopuntoventasDescripcionReporte=formapagopuntoventas;
} catch(Exception ex) {
;
}
}
/*PARA REPORTES FIN*/
}
|
/*
* Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.huawei.generator.g2x.po.map.manual;
import com.huawei.generator.g2x.po.map.MethodDesc;
import com.google.gson.annotations.Expose;
import java.util.List;
/**
* ManualField: description of manual-methods, indicating wishhub plugins can not modify them directly.
* Therefore app client developers should change them manually.
* <p>
* including:
* 1. methodName means method name
* 2. desc means details of this method, see {@link MethodDesc}
* 3. paramTypes means canonical types of parameters
* 4. weakTypes means weakTypes for overloaded methods with same size of params,
* we will fulfill with "*" for source code engine. Others will be same with paramTypes
* </p>
* <p>
* Note: for manual field, desc is very important, because it contains the user manual and url to guide
* developers.
* </p>
*
* @since 2019-11-27
*/
public class ManualMethod {
@Expose
private String methodName;
@Expose
private List<String> paramTypes;
@Expose
private List<String> weakTypes;
@Expose
private MethodDesc desc;
public ManualMethod(String methodName, List<String> paramTypes, List<String> weakTypes, MethodDesc desc) {
this.methodName = methodName;
this.paramTypes = paramTypes;
this.weakTypes = weakTypes;
this.desc = desc;
}
public String getMethodName() {
return methodName;
}
public List<String> getParamTypes() {
return paramTypes;
}
public MethodDesc getDesc() {
return desc;
}
public List<String> getWeakTypes() {
return weakTypes;
}
public void setWeakTypes(List<String> weakTypes) {
this.weakTypes = weakTypes;
}
public void setMDesc(MethodDesc desc) {
this.desc = desc;
}
}
|
package com.flying.email.bean;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.LinkedList;
/**
* auth:flying date:2017年7月14日
**/
@SuppressWarnings("serial")
public class SubjectItems implements java.io.Serializable {
private Integer keyId = 0;
private int subjectid = 0;
private int execution = 0;
private String dataparam = "";
private String functionname = "";
private int isforbidden = 0;
private int isdelete = 0;
private Date createTime = new Date(-2209017600000L);
private String modifyUser = "";
private Date modifyTime = new Date(-2209017600000L);
public SubjectItems() {
}
public SubjectItems(int subjectid, int execution, String dataparam, String functionname, int isforbidden,
int isdelete, String modifyUser, Date modifyTime) {
this.subjectid = subjectid;
this.execution = execution;
this.dataparam = dataparam;
this.functionname = functionname;
this.isforbidden = isforbidden;
this.isdelete = isdelete;
this.modifyUser = modifyUser;
this.modifyTime = modifyTime;
}
public SubjectItems(int subjectid, int execution, String dataparam, String functionname, int isforbidden,
int isdelete, Date createTime, String modifyUser, Date modifyTime) {
this.subjectid = subjectid;
this.execution = execution;
this.dataparam = dataparam;
this.functionname = functionname;
this.isforbidden = isforbidden;
this.isdelete = isdelete;
this.createTime = createTime;
this.modifyUser = modifyUser;
this.modifyTime = modifyTime;
}
public Integer getKeyId() {
return this.keyId;
}
public void setKeyId(Integer keyId) {
this.keyId = keyId;
}
public int getSubjectid() {
return this.subjectid;
}
public void setSubjectid(int subjectid) {
this.subjectid = subjectid;
}
public int getExecution() {
return this.execution;
}
public void setExecution(int execution) {
this.execution = execution;
}
public String getDataparam() {
return this.dataparam;
}
public void setDataparam(String dataparam) {
this.dataparam = dataparam;
}
public String getFunctionname() {
return this.functionname;
}
public void setFunctionname(String functionname) {
this.functionname = functionname;
}
public int getIsforbidden() {
return this.isforbidden;
}
public void setIsforbidden(int isforbidden) {
this.isforbidden = isforbidden;
}
public int getIsdelete() {
return this.isdelete;
}
public void setIsdelete(int isdelete) {
this.isdelete = isdelete;
}
public Date getCreateTime() {
return this.createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getModifyUser() {
return this.modifyUser;
}
public void setModifyUser(String modifyUser) {
this.modifyUser = modifyUser;
}
public Date getModifyTime() {
return this.modifyTime;
}
public void setModifyTime(Date modifyTime) {
this.modifyTime = modifyTime;
}
/**
* 将数据结果转化为model
*
* @param resultSet
* @return
*/
public static LinkedList<SubjectItems> TransFormModelList(ResultSet resultSet) {
try {
if (resultSet.wasNull()) {
return null;
} else {
LinkedList<SubjectItems> listsubjectitems = new LinkedList<SubjectItems>();
while (resultSet.next()) {
SubjectItems subjectitems = new SubjectItems();
subjectitems.setKeyId(resultSet.getInt("keyid"));
subjectitems.setSubjectid(resultSet.getInt("subjectid"));
subjectitems.setExecution(resultSet.getInt("execution"));
subjectitems.setDataparam(resultSet.getString("dataparam"));
subjectitems.setFunctionname(resultSet.getString("functionname"));
subjectitems.setIsforbidden(resultSet.getInt("isforbidden"));
subjectitems.setIsdelete(resultSet.getInt("isdelete"));
subjectitems.setCreateTime(resultSet.getTimestamp("createTime"));
subjectitems.setModifyUser(resultSet.getString("modifyUser"));
listsubjectitems.add(subjectitems);
}
return listsubjectitems;
}
} catch (SQLException e) {
return null;
}
}
}
|
/*
* 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.servicecomb.service.center.client;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.servicecomb.http.client.task.AbstractTask;
import org.apache.servicecomb.http.client.task.Task;
import org.apache.servicecomb.service.center.client.DiscoveryEvents.InstanceChangedEvent;
import org.apache.servicecomb.service.center.client.DiscoveryEvents.PullInstanceEvent;
import org.apache.servicecomb.service.center.client.model.FindMicroserviceInstancesResponse;
import org.apache.servicecomb.service.center.client.model.Microservice;
import org.apache.servicecomb.service.center.client.model.MicroserviceInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
public class ServiceCenterDiscovery extends AbstractTask {
private static final String ALL_VERSION = "0+";
private static final long POLL_INTERVAL = 15000;
private boolean started = false;
public static class SubscriptionKey {
final String appId;
final String serviceName;
public SubscriptionKey(String appId, String serviceName) {
this.appId = appId;
this.serviceName = serviceName;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SubscriptionKey that = (SubscriptionKey) o;
return appId.equals(that.appId) &&
serviceName.equals(that.serviceName);
}
@Override
public int hashCode() {
return Objects.hash(appId, serviceName);
}
}
public static class SubscriptionValue {
String revision;
List<MicroserviceInstance> instancesCache;
}
private static final Logger LOGGER = LoggerFactory.getLogger(ServiceCenterRegistration.class);
private final ServiceCenterClient serviceCenterClient;
private final EventBus eventBus;
private String myselfServiceId;
private final Map<SubscriptionKey, SubscriptionValue> instancesCache = new ConcurrentHashMap<>();
private final Map<String, Microservice> microserviceCache = new ConcurrentHashMap<>();
public ServiceCenterDiscovery(ServiceCenterClient serviceCenterClient, EventBus eventBus) {
super("service-center-discovery-task");
this.serviceCenterClient = serviceCenterClient;
this.eventBus = eventBus;
this.eventBus.register(this);
}
public void updateMyselfServiceId(String myselfServiceId) {
this.myselfServiceId = myselfServiceId;
}
public void startDiscovery() {
if (!started) {
started = true;
startTask(new PullInstanceTask());
}
}
public void register(SubscriptionKey subscriptionKey) {
this.instancesCache.computeIfAbsent(subscriptionKey, (key) -> new SubscriptionValue());
pullInstance(subscriptionKey, this.instancesCache.get(subscriptionKey));
}
public List<MicroserviceInstance> getInstanceCache(SubscriptionKey key) {
return this.instancesCache.get(key).instancesCache;
}
public boolean isRegistered(SubscriptionKey key) {
return this.instancesCache.get(key) != null;
}
@Subscribe
public void onPullInstanceEvent(PullInstanceEvent event) {
pullAllInstance();
}
private void pullInstance(SubscriptionKey k, SubscriptionValue v) {
try {
FindMicroserviceInstancesResponse instancesResponse = serviceCenterClient
.findMicroserviceInstance(myselfServiceId, k.appId, k.serviceName, ALL_VERSION, v.revision);
if (instancesResponse.isModified()) {
List<MicroserviceInstance> instances = instancesResponse.getMicroserviceInstancesResponse().getInstances()
== null ? Collections.emptyList() : instancesResponse.getMicroserviceInstancesResponse().getInstances();
setMicroserviceInfo(instances);
LOGGER.info("Instance changed event, "
+ "current: revision={}, instances={}; "
+ "origin: revision={}, instances={}; "
+ "appId={}, serviceName={}",
instancesResponse.getRevision(),
instanceToString(instances),
v.revision,
instanceToString(v.instancesCache),
k.appId,
k.serviceName
);
v.instancesCache = instances;
v.revision = instancesResponse.getRevision();
eventBus.post(new InstanceChangedEvent(k.appId, k.serviceName,
v.instancesCache));
}
} catch (Exception e) {
LOGGER.error("find service {}#{} instance failed.", k.appId, k.serviceName, e);
}
}
private void setMicroserviceInfo(List<MicroserviceInstance> instances) {
instances.forEach(instance -> {
Microservice microservice = microserviceCache
.computeIfAbsent(instance.getServiceId(), id -> {
try {
return serviceCenterClient.getMicroserviceByServiceId(id);
} catch (Exception e) {
LOGGER.error("Find microservice by id={} failed", id, e);
throw e;
}
});
instance.setMicroservice(microservice);
});
}
class PullInstanceTask implements Task {
@Override
public void execute() {
pullAllInstance();
startTask(new BackOffSleepTask(POLL_INTERVAL, new PullInstanceTask()));
}
}
private synchronized void pullAllInstance() {
instancesCache.forEach((k, v) -> {
pullInstance(k, v);
});
}
private static String instanceToString(List<MicroserviceInstance> instances) {
if (instances == null) {
return "";
}
StringBuilder sb = new StringBuilder();
for (MicroserviceInstance instance : instances) {
for (String endpoint : instance.getEndpoints()) {
sb.append(endpoint.length() > 64 ? endpoint.substring(0, 64) : endpoint);
sb.append("|");
}
sb.append(instance.getServiceName());
sb.append("|");
}
sb.append("#");
return sb.toString();
}
}
|
/**
* Copyright 2005-2015 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package io.fabric8.insight.jetty;
import org.eclipse.jetty.http.PathMap;
import org.eclipse.jetty.server.Authentication;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.RequestLog;
import org.eclipse.jetty.server.Response;
import org.eclipse.jetty.util.component.AbstractLifeCycle;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import io.fabric8.insight.storage.StorageService;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
import org.osgi.util.tracker.ServiceTracker;
import java.util.Dictionary;
import java.util.Hashtable;
public class InsightRequestLog extends AbstractLifeCycle implements RequestLog, ManagedService {
private static final Logger LOG = Log.getLogger(InsightRequestLog.class);
private final BundleContext bundleContext;
private final ServiceTracker<StorageService, StorageService> storage;
private final String host = System.getProperty("runtime.id");
private ServiceRegistration<ManagedService> registration;
private Dictionary<String, ?> properties;
private boolean enabled = true;
private String type = "jetty";
private PathMap ignorePathMap;
public InsightRequestLog() {
this.bundleContext = FrameworkUtil.getBundle(getClass()).getBundleContext();
storage = new ServiceTracker<StorageService, StorageService>(bundleContext, StorageService.class, null);
}
@Override
protected void doStart() throws Exception {
Hashtable props = new Hashtable();
props.put(Constants.SERVICE_PID, "io.fabric8.insight.jetty");
this.registration = this.bundleContext.registerService(ManagedService.class, this, props);
this.storage.open();
}
@Override
protected void doStop() throws Exception {
try {
storage.close();
} catch (IllegalStateException e) {
// Ignore, in case, the bundle context is already invalidated
}
this.registration.unregister();
}
@Override
public void updated(Dictionary<String, ?> properties) throws ConfigurationException {
this.properties = properties;
this.enabled = getBoolean("enabled", true);
this.type = getString("type", "jetty");
String ignorePaths = getString("ignorePaths", "");
if (ignorePaths != null && ignorePaths.length() > 0) {
ignorePathMap = new PathMap();
for (String s : ignorePaths.split(",")) {
ignorePathMap.put(s, s);
}
}
else {
ignorePathMap = null;
}
}
private String getString(String name, String def) {
Object v = this.properties != null ? this.properties.get(name) : null;
if (v == null) {
return def;
} else {
return v.toString();
}
}
private boolean getBoolean(String name, boolean def) {
Object v = this.properties != null ? this.properties.get(name) : null;
if (v instanceof Boolean) {
return (Boolean) v;
} else if (v == null) {
return def;
} else {
return Boolean.parseBoolean(v.toString());
}
}
@Override
public void log(Request request, Response response) {
try {
if (!enabled) {
return;
}
StorageService s = storage.getService();
if (s == null) {
return;
}
if (ignorePathMap != null && ignorePathMap.getMatch(request.getRequestURI()) != null)
return;
String output = "{ " +
"\"host\": \"" + host + "\", " +
"\"@timestamp\": \"" + InsightUtils.formatDate(request.getTimeStamp()) + "\", " +
"\"remote\": \"" + request.getRemoteAddr() + "\", " +
"\"user\": \"" + (request.getAuthentication() instanceof Authentication.User ? ((Authentication.User)request.getAuthentication()).getUserIdentity().getUserPrincipal().getName() : "") + "\", " +
"\"method\": \"" + request.getMethod() + "\", " +
"\"uri\": \"" + request.getUri().toString() + "\", " +
"\"protocol\": \"" + request.getProtocol() + "\", " +
"\"status\": \"" + response.getStatus() + "\", " +
"\"responseLength\": \"" + response.getContentCount() + "\" " +
" }";
s.store(type, request.getTimeStamp(), output);
}
catch (Exception e)
{
LOG.warn(e);
}
}
}
|
package com.example.rakesh.myapplication2;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.rakesh.myapplication2", appContext.getPackageName());
}
}
|
package cz.wake.lobby.npc.list;
import cz.wake.lobby.Main;
import cz.wake.lobby.npc.IServerNPC;
import net.jitse.npclib.api.events.NPCInteractEvent;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class Survival_115NPC implements IServerNPC {
@Override
public String getId() {
return "survival";
} // 1.15
@Override
public int getSkinId() {
return 279251979;
}
@Override
public Location getLocation() {
return new Location(Bukkit.getWorld("lobby_4"), 384.5, 75, 204.5, 35, 0);
}
@Override
public List<String> getHologramLines() {
List<String> list = new ArrayList<>();
list.add("§3§lSurvival §e[1.15]");
list.add("§f" + Main.getInstance().getSQL().getOnlinePlayers("survival2") +" §7hráčů");
return list;
}
@Override
public void onClick(Player player, NPCInteractEvent.ClickType clickType) {
Main.getInstance().getCraftBalancerManager().bypassConnect(player, "survival");
}
}
|
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.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.jclouds.vi.reference;
/**
* Configuration properties and constants used in VI connections.
*
* @author Adrian Cole
*/
public interface ViConstants {
public static final String PROPERTY_VI_XML_NAMESPACE = "jclouds.vi.xml.ns";
}
|
package file;
import java.io.Serializable;
public class Hero implements Serializable {
//表示这个类当前的版本,如果有了变化,比如新设计了属性,就应该修改这个版本号
private static final long serialVersionUID = 1L;
public String name;
public float hp;
}
|
package com.github.jinahya.bit.io;
/*-
* #%L
* bit-io
* %%
* Copyright (C) 2014 - 2019 Jinahya, 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.
* #L%
*/
/**
* An abstract class for implementing {@link ByteInput} interface.
*
* @param <T> byte source type parameter
* @author Jin Kwon <jinahya_at_gmail.com>
* @see AbstractByteOutput
*/
abstract class AbstractByteInput<T> implements ByteInput {
// -----------------------------------------------------------------------------------------------------------------
/**
* Creates a new instance with specified byte source.
*
* @param source the underlying byte source from which bytes are read; {@code null} if it is intended to be lazily
* initialized and set.
* @see #getSource()
* @see #setSource(Object)
*/
AbstractByteInput(final T source) {
super();
this.source = source;
}
// -----------------------------------------------------------------------------------------------------------------
/**
* Returns a string representation of the object.
*
* @return a string representation of the object.
*/
@Override
public String toString() {
return super.toString() + "{"
+ "source=" + source
+ "}";
}
// ---------------------------------------------------------------------------------------------------------- source
/**
* Returns the current value of {@code source} attribute.
*
* @return the current value of {@code source} attribute.
*/
protected T getSource() {
return source;
}
/**
* Replaces the current value of {@code source} attribute with given.
*
* @param source new value for {@code source} attribute.
*/
protected void setSource(final T source) {
this.source = source;
}
// -----------------------------------------------------------------------------------------------------------------
/**
* The bytes source from which byte are read.
*/
private T source;
}
|
package com.mark59.datahunter.samples.scripts.jsr223format;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ThreadLocalRandom;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.logging.log4j.Level;
import org.openqa.selenium.By;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.PageLoadStrategy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import com.mark59.core.Outcome;
import com.mark59.core.utils.*;
import com.mark59.dsl.samples.seleniumDSL.core._GenericPage;
import com.mark59.dsl.samples.seleniumDSL.pageElements.*;
import com.mark59.selenium.corejmeterimpl.*;
import com.mark59.selenium.drivers.SeleniumDriverFactory;
// >> --------- COMMENT OUT THE NEXT TWO LINES ---------
public class DataHunterLifecyclePvtScriptJSR223Format {
public static void main(String[] args) throws InterruptedException{
// <<
/**
* Note that in this more advanced example access to the com.mark59.dsl.samples.seleniumDSL.* packages is assumed (from the mark59-dsl-samples project).
* <p>Hint: A quick and dirty way to do this is to copy target jar from the mark59-datahunter-samples project since it contains the sample DSL
* packages, into the lib/ext directory of your JMeter instance.
*
* @author Phil Webb
*/
class ThisScript extends SeleniumAbstractJavaSamplerClient {
final class TestConstants {
public static final String DELETE_MULTIPLE_POLICIES_URL_PATH = "/delete_multiple_policies";
public static final String COUNT_POLICIES_URL_PATH = "/count_policies";
public static final String ADD_POLICY_URL_PATH = "/add_policy";
public static final String PRINT_SELECTED_POLICIES_URL_PATH = "/print_selected_policies";
public static final String COUNT_POLICIES_BREAKDOWN_URL_PATH = "/count_policies_breakdown";
public static final String NEXT_POLICY_URL_PATH = "/next_policy";
public static final String UNUSED = "UNUSED";
public static final String EQUALS = "EQUALS";
public static final String SELECT_MOST_RECENTLY_ADDED = "SELECT_MOST_RECENTLY_ADDED";
}
final class DataHunterInputPages extends _GenericPage {
public DataHunterInputPages(WebDriver driver) {
super(driver);
}
public DropdownList applicationStartsWithOrEquals() {
return new DropdownList(driver, By.id("applicationStartsWithOrEquals"));
}
public InputTextElement identifier() {
return new InputTextElement(driver, By.id("identifier"));
}
public InputTextElement lifecycle() {
return new InputTextElement(driver, By.id("lifecycle"));
}
public DropdownList useability() {
return new DropdownList(driver, By.id("useability"));
}
public InputTextElement otherdata() {
return new InputTextElement(driver, By.id("otherdata"));
}
public InputTextElement epochtime() {
return new InputTextElement(driver, By.id("epochtime"));
}
public DropdownList selectOrder() {
return new DropdownList(driver, By.id("selectOrder"));
}
public SubmitBtn submit() {
return new SubmitBtn(driver, By.id("submit"));
}
}
final class DatatHunterActionPages extends _GenericPage {
public DatatHunterActionPages(WebDriver driver) {
super(driver);
}
public InputTextElement identifier() {
return new InputTextElement(driver, By.id("identifier"));
}
public PageTextElement sql() {
return new PageTextElement(driver, By.id("sql"));
}
public PageTextElement sqlResult() {
return new PageTextElement(driver, By.id("sqlResult"));
}
public PageTextElement rowsAffected() {
return new PageTextElement(driver, By.id("rowsAffected"));
}
public PageTextElement sqlResultText() {
return new PageTextElement(driver, By.id("sqlResultText"));
}
public Link backLink() {
return new Link(driver, "Back");
}
public int getCountForBreakdown(String application, String lifecycle, String useability){ // breakdown result only
PageTextElement countForBreakdownElement = null;
try { countForBreakdownElement = new PageTextElement(driver, By.id((application + "_" + lifecycle + "_" + useability + "_count").replace(" ", "_")));
} catch ( NoSuchElementException e) {return 0; }
int count = Integer.valueOf(countForBreakdownElement.getText());
return count;
}
public HtmlTable printSelectedPoliciesTable() {
return new HtmlTable(driver, "printSelectedPoliciesTable");
}
public String formatResultsMessage(String tag){
return "DataHunter " + sqlResultText().getText() + " at " + tag + ", SQL statement [" + sql().getText() + "]" +
", rows affected [" + rowsAffected().getText() + "], details [" + sqlResultText().getText() + "]";
}
}
@Override
protected Map<String, String> additionalTestParameters() {
Map<String, String> jmeterAdditionalParameters = new LinkedHashMap<String, String>();
jmeterAdditionalParameters.put("DATAHUNTER_URL", "http://localhost:8081/mark59-datahunter");
jmeterAdditionalParameters.put("DATAHUNTER_APPLICATION_ID", "DATAHUNTER_PV_TEST");
jmeterAdditionalParameters.put("FORCE_TXN_FAIL_PERCENT", "20");
jmeterAdditionalParameters.put("USER", "default_user");
jmeterAdditionalParameters.put(SeleniumDriverFactory.DRIVER, "CHROME");
jmeterAdditionalParameters.put(SeleniumDriverFactory.HEADLESS_MODE, String.valueOf(false));
jmeterAdditionalParameters.put(SeleniumDriverFactory.BROWSER_DIMENSIONS, Mark59Constants.DEFAULT_BROWSER_DIMENSIONS);
jmeterAdditionalParameters.put(SeleniumDriverFactory.PAGE_LOAD_STRATEGY, PageLoadStrategy.NONE.toString());
jmeterAdditionalParameters.put(SeleniumDriverFactory.PROXY, "");
jmeterAdditionalParameters.put(SeleniumDriverFactory.ADDITIONAL_OPTIONS, "");
jmeterAdditionalParameters.put(SeleniumDriverFactory.WRITE_FFOX_BROWSER_LOGFILE, String.valueOf(false));
jmeterAdditionalParameters.put(IpUtilities.RESTRICT_TO_ONLY_RUN_ON_IPS_LIST, "");
jmeterAdditionalParameters.put(SeleniumDriverFactory.EMULATE_NETWORK_CONDITIONS, "");
return jmeterAdditionalParameters;
}
@Override
protected void runSeleniumTest(JavaSamplerContext context, JmeterFunctionsForSeleniumScripts jm, WebDriver driver) {
String thread = Thread.currentThread().getName();
String lifecycle = "thread_" + thread;
String dataHunterUrl = context.getParameter("DATAHUNTER_URL");
String application = context.getParameter("DATAHUNTER_APPLICATION_ID");
int forceTxnFailPercent = Integer.valueOf(context.getParameter("FORCE_TXN_FAIL_PERCENT").trim());
String user = context.getParameter("USER");
PrintSomeMsgOnceAtStartUp(dataHunterUrl, driver);
DataHunterInputPages dataHunterInputPages = new DataHunterInputPages(driver);
// delete any existing policies for this application/thread combination
jm.startTransaction("DH_lifecycle_0001_loadInitialPage");
driver.get(dataHunterUrl + TestConstants.DELETE_MULTIPLE_POLICIES_URL_PATH + "?application=" + application);
dataHunterInputPages.lifecycle().waitUntilClickable();
jm.endTransaction("DH_lifecycle_0001_loadInitialPage");
dataHunterInputPages.lifecycle().type(lifecycle);
DatatHunterActionPages resultsPage = new DatatHunterActionPages(driver);
jm.startTransaction("DH_lifecycle_0100_deleteMultiplePolicies");
dataHunterInputPages.submit().submit().waitUntilClickable( resultsPage.backLink() );
waitActionPageCheckSqlOk(new DatatHunterActionPages(driver));
jm.endTransaction("DH_lifecycle_0100_deleteMultiplePolicies");
// add a set of policies
driver.get(dataHunterUrl + TestConstants.ADD_POLICY_URL_PATH + "?application=" + application);
for (int i = 1; i <= 5; i++) {
dataHunterInputPages.identifier().type("TESTID" + i);
dataHunterInputPages.lifecycle().type(lifecycle);
dataHunterInputPages.useability().selectByVisibleText(TestConstants.UNUSED) ;
dataHunterInputPages.otherdata().type(user);
dataHunterInputPages.epochtime().type(Long.toString(System.currentTimeMillis()));
// jm.writeScreenshot("add_policy_TESTID" + i);
jm.startTransaction("DH_lifecycle_0200_addPolicy");
SafeSleep.sleep(200); // Mocking a 200 ms txn delay
dataHunterInputPages.submit().submit().waitUntilClickable( resultsPage.backLink() );
waitActionPageCheckSqlOk(resultsPage);
jm.endTransaction("DH_lifecycle_0200_addPolicy");
resultsPage.backLink().click().waitUntilClickable( dataHunterInputPages.submit() ).thenSleep();
}
// dummy transaction just to test transaction failure behavior
jm.startTransaction("DH_lifecycle_0299_sometimes_I_fail");
int randomNum_1_to_100 = ThreadLocalRandom.current().nextInt(1, 101);
if ( randomNum_1_to_100 >= forceTxnFailPercent ) {
jm.endTransaction("DH_lifecycle_0299_sometimes_I_fail", Outcome.PASS);
} else {
jm.endTransaction("DH_lifecycle_0299_sometimes_I_fail", Outcome.FAIL);
}
driver.get(dataHunterUrl + TestConstants.COUNT_POLICIES_URL_PATH + "?application=" + application);
dataHunterInputPages.useability().selectByVisibleText(TestConstants.UNUSED).thenSleep(); // ** note 2
jm.startTransaction("DH_lifecycle_0300_countUnusedPolicies");
dataHunterInputPages.submit().submit().waitUntilClickable( resultsPage.backLink() );
waitActionPageCheckSqlOk(resultsPage);
jm.endTransaction("DH_lifecycle_0300_countUnusedPolicies");
Long countPolicies = Long.valueOf( resultsPage.rowsAffected().getText());
LOG.debug( "countPolicies : " + countPolicies);
jm.userDataPoint(application + "_Total_Unused_Policy_Count", countPolicies);
// count breakdown (count for unused DATAHUNTER_PV_TEST policies for this thread )
driver.get(dataHunterUrl + TestConstants.COUNT_POLICIES_BREAKDOWN_URL_PATH + "?application=" + application);
dataHunterInputPages.applicationStartsWithOrEquals().selectByVisibleText(TestConstants.EQUALS);
dataHunterInputPages.useability().selectByVisibleText(TestConstants.UNUSED);
jm.startTransaction("DH_lifecycle_0400_countUnusedPoliciesCurrentThread");
dataHunterInputPages.submit().submit();
waitActionPageCheckSqlOk(resultsPage);
jm.endTransaction("DH_lifecycle_0400_countUnusedPoliciesCurrentThread");
// direct access to required row-column table element by computing the id:
int countUsedPoliciesCurrentThread = resultsPage.getCountForBreakdown(application, lifecycle, TestConstants.UNUSED);
LOG.debug( "countUsedPoliciesCurrentThread : " + countUsedPoliciesCurrentThread);
jm.userDataPoint(application + "_This_Thread_Unused_Policy_Count", countUsedPoliciesCurrentThread);
// use next policy
driver.get(dataHunterUrl + TestConstants.NEXT_POLICY_URL_PATH + "?application=" + application + "&pUseOrLookup=use");
dataHunterInputPages.lifecycle().type(lifecycle);
dataHunterInputPages.useability().selectByVisibleText(TestConstants.UNUSED);
dataHunterInputPages.selectOrder().selectByVisibleText(TestConstants.SELECT_MOST_RECENTLY_ADDED);
jm.startTransaction("DH_lifecycle_0500_useNextPolicy");
dataHunterInputPages.submit().submit();
waitActionPageCheckSqlOk(resultsPage);
jm.endTransaction("DH_lifecycle_0500_useNextPolicy");
if (LOG.isDebugEnabled() ) {LOG.debug("useNextPolicy: " + application + "-" + lifecycle + " : " + resultsPage.identifier() ); }
//HTML table demo.
long used=0;
long unused=0;
driver.get(dataHunterUrl + TestConstants.PRINT_SELECTED_POLICIES_URL_PATH + "?application=" + application);
dataHunterInputPages.submit().waitUntilClickable();
jm.startTransaction("DH_lifecycle_0600_displaySelectedPolicies");
dataHunterInputPages.submit().submit();
waitActionPageCheckSqlOk(resultsPage);
// demo how to extract a transaction time from with a running script
org.apache.jmeter.samplers.SampleResult sr_0600 = jm.endTransaction("DH_lifecycle_0600_displaySelectedPolicies");
LOG.debug("Transaction " + sr_0600.getSampleLabel() + " ran at " + sr_0600.getTimeStamp() + " and took " + sr_0600.getTime() + " ms." );
HtmlTable printSelectedPoliciesTable = resultsPage.printSelectedPoliciesTable();
for (HtmlTableRow tableRow : printSelectedPoliciesTable.getHtmlTableRows()) {
if (tableRow.getColumnNumberOfExpectedColumns(4, 8).getText().equals("USED")) used++;
if (tableRow.getColumnNumberOfExpectedColumns(4, 8).getText().equals("UNUSED")) unused++;
}
jm.userDataPoint("USED_count_html_demo", used );
jm.userDataPoint("UNUSED_count_html_demo", unused );
LOG.debug("HTML demo: USED=" + used + ", UNUSED=" + unused);
// delete multiple policies (test cleanup - a duplicate of the initial delete policies transactions)
jm.startTransaction("DH_lifecycle_0099_gotoDeleteMultiplePoliciesUrl");
driver.get(dataHunterUrl + TestConstants.DELETE_MULTIPLE_POLICIES_URL_PATH + "?application=" + application);
dataHunterInputPages.lifecycle().waitUntilClickable();
jm.endTransaction("DH_lifecycle_0099_gotoDeleteMultiplePoliciesUrl");
dataHunterInputPages.lifecycle().type(lifecycle);
jm.startTransaction("DH_lifecycle_0100_deleteMultiplePolicies");
dataHunterInputPages.submit().submit();
waitActionPageCheckSqlOk(new DatatHunterActionPages(driver));
jm.endTransaction("DH_lifecycle_0100_deleteMultiplePolicies");
// jm.writeBufferedArtifacts();
}
private void waitActionPageCheckSqlOk(DatatHunterActionPages resultsPage) {
String sqlResultText = resultsPage.sqlResult().getText();
if (!"PASS".equals(sqlResultText)) {
throw new RuntimeException("SQL issue (" + sqlResultText + ") : " +
resultsPage.formatResultsMessage(resultsPage.getClass().getName()));
}
}
@SuppressWarnings("unchecked")
private synchronized void PrintSomeMsgOnceAtStartUp(String dataHunterUrl, WebDriver driver) {
Properties sysprops = System.getProperties();
if (!"true".equals(sysprops.get("printedOnce")) ) {
LOG.info(" Using DataHunter with Url " + dataHunterUrl + "/mark59-datahunter");
Capabilities caps = ((ChromeDriver)driver).getCapabilities();
LOG.info(" Browser Name and Version : " + caps.getBrowserName() + " " + caps.getBrowserVersion());
if ("chrome".equalsIgnoreCase(caps.getBrowserName()) && caps.getCapability("chrome") != null ){
LOG.info(" Chrome Driver Version : " + ((Map<String, String>)caps.getCapability("chrome")).get("chromedriverVersion"));
}
sysprops.put("printedOnce", "true");
}
}
}
// >> --------- COMMENT OUT THE NEXT THREE LINES --------- (capitalization of the SampleResult variable in the next line is deliberate)
org.apache.jmeter.samplers.SampleResult SampleResult = new org.apache.jmeter.samplers.SampleResult();
SampleResult.sampleStart();
Log4jConfigurationHelper.init(Level.INFO) ;
// <<
org.apache.jmeter.samplers.SampleResult testResults = new ThisScript().runSeleniumTest(KeepBrowserOpen.NEVER);
if (testResults != null) {
for (org.apache.jmeter.samplers.SampleResult subResult : testResults.getSubResults()) {
SampleResult.addSubResult(subResult, false);
}
}
SampleResult.setDataType("PARENT" );
SampleResult.setEndTime(0);
// >> --------- COMMENT OUT THE END BRACES BELOW ---------
}
}
|
package com.yang.design.pattern.structural.bridge;
/**
* Created by geely
*/
public class ICBCBank extends Bank {
public ICBCBank(Account account) {
super(account);
}
@Override
Account openAccount() {
System.out.println("打开中国工商银行账号");
account.openAccount();
return account;
}
}
|
package org.example.spring.data.team;
import org.example.spring.data.AbstractTeamPlayerRepository;
import org.example.spring.model.Team;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;
/**
* This is the Repository interface for the Team objects.
*/
@Repository
public interface TeamRepository extends AbstractTeamPlayerRepository<Team, String> {
/**
* Teams have a unique key, like "PHI" for the Philadelphia Flyers.
* This finds the team associated with the given key.
*
* @param key a unique three letter key for a Team
* @return the Team associated with the given key
*/
Team findByKey(String key);
/**
* Find all Teams by the given Conference.
*
* @param conference the name of the Conference to search for teams by
* @param pageable Gets paging and search information from the parameters
* @return all Teams in the specified Conference
*/
Page<Team> findAllByConference(String conference, Pageable pageable);
/**
* Find all teams by the given Division.
*
* @param division the name of the Division to search for teams by
* @param pageable Gets paging and search information from the parameters
* @return all Teams in the specified Division
*/
Page<Team> findAllByDivision(String division, Pageable pageable);
}
|
/*
* 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.dolphinscheduler.dao.entity;
import org.apache.dolphinscheduler.common.enums.UdfType;
import org.apache.dolphinscheduler.common.utils.JSONUtils;
import org.apache.dolphinscheduler.common.utils.StringUtils;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.KeyDeserializer;
import java.io.IOException;
import java.util.Date;
/**
* udf function
*/
@TableName("t_ds_udfs")
public class UdfFunc {
/**
* id
*/
@TableId(value="id", type=IdType.AUTO)
private int id;
/**
* user id
*/
private int userId;
/**
* udf function name
*/
private String funcName;
/**
* udf class name
*/
private String className;
/**
* udf argument types
*/
private String argTypes;
/**
* udf data base
*/
private String database;
/**
* udf description
*/
private String description;
/**
* resource id
*/
private int resourceId;
/**
* resource name
*/
private String resourceName;
/**
* udf function type: hive / spark
*/
private UdfType type;
/**
* create time
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date createTime;
/**
* update time
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date updateTime;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getFuncName() {
return funcName;
}
public void setFuncName(String funcName) {
this.funcName = funcName;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getArgTypes() {
return argTypes;
}
public void setArgTypes(String argTypes) {
this.argTypes = argTypes;
}
public String getDatabase() {
return database;
}
public void setDatabase(String database) {
this.database = database;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getResourceId() {
return resourceId;
}
public void setResourceId(int resourceId) {
this.resourceId = resourceId;
}
public String getResourceName() {
return resourceName;
}
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
public UdfType getType() {
return type;
}
public void setType(UdfType type) {
this.type = type;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
UdfFunc udfFunc = (UdfFunc) o;
if (id != udfFunc.id) {
return false;
}
return !(funcName != null ? !funcName.equals(udfFunc.funcName) : udfFunc.funcName != null);
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + (funcName != null ? funcName.hashCode() : 0);
return result;
}
@Override
public String toString() {
return JSONUtils.toJsonString(this);
}
public static class UdfFuncDeserializer extends KeyDeserializer {
@Override
public Object deserializeKey(String key, DeserializationContext ctxt) throws IOException {
if (StringUtils.isBlank(key)) {
return null;
}
return JSONUtils.parseObject(key);
}
}
}
|
/**
* Copyright © 2010-2020 Nokia
*
* 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.jsonschema2pojo.util;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;
import java.util.TreeSet;
import org.jsonschema2pojo.exception.GenerationException;
import com.sun.codemodel.JClass;
import com.sun.codemodel.JDefinedClass;
import com.sun.codemodel.JExpr;
import com.sun.codemodel.JFieldVar;
import com.sun.codemodel.JMethod;
import com.sun.codemodel.JMod;
import com.sun.codemodel.JType;
import com.sun.codemodel.JTypeVar;
import com.sun.codemodel.JVar;
public class SerializableHelper {
private static final Comparator<JClass> INTERFACE_COMPARATOR =
new Comparator<JClass>() {
@Override
public int compare(JClass object1, JClass object2) {
if (object1 == null && object2 == null) {
return 0;
}
if (object1 == null) {
return 1;
}
if (object2 == null) {
return -1;
}
final String name1 = object1.fullName();
final String name2 = object2.fullName();
if (name1 == null && name2 == null) {
return 0;
}
if (name1 == null) {
return 1;
}
if (name2 == null) {
return -1;
}
return name1.compareTo(name2);
}
};
private static void processMethodCollectionForSerializableSupport(Iterator<JMethod> methods, DataOutputStream dataOutputStream) throws IOException {
TreeMap<String, JMethod> sortedMethods = new TreeMap<>();
while (methods.hasNext()) {
JMethod method = methods.next();
//Collect non-private methods
if ((method.mods().getValue() & JMod.PRIVATE) != JMod.PRIVATE) {
sortedMethods.put(method.name(), method);
}
}
for (JMethod method : sortedMethods.values()) {
dataOutputStream.writeUTF(method.name());
dataOutputStream.writeInt(method.mods().getValue());
if (method.type() != null) {
dataOutputStream.writeUTF(method.type().fullName());
}
for (JVar param : method.params()) {
dataOutputStream.writeUTF(param.type().fullName());
}
}
}
private static void processDefinedClassForSerializableSupport(JDefinedClass jclass, DataOutputStream dataOutputStream) throws IOException {
dataOutputStream.writeUTF(jclass.fullName());
dataOutputStream.writeInt(jclass.mods().getValue());
for (JTypeVar typeParam : jclass.typeParams()) {
dataOutputStream.writeUTF(typeParam.fullName());
}
//sorted
TreeMap<String, JDefinedClass> sortedClasses = new TreeMap<>();
Iterator<JDefinedClass> classes = jclass.classes();
while (classes.hasNext()) {
JDefinedClass nestedClass = classes.next();
sortedClasses.put(nestedClass.fullName(), nestedClass);
}
for (JDefinedClass nestedClass : sortedClasses.values()) {
processDefinedClassForSerializableSupport(nestedClass, dataOutputStream);
}
//sorted
TreeSet<String> fieldNames = new TreeSet<>(jclass.fields().keySet());
for (String fieldName : fieldNames) {
JFieldVar fieldVar = jclass.fields().get(fieldName);
//non private members
if ((fieldVar.mods().getValue() & JMod.PRIVATE) != JMod.PRIVATE) {
processFieldVarForSerializableSupport(jclass.fields().get(fieldName), dataOutputStream);
}
}
Iterator<JClass> interfaces = jclass._implements();
List<JClass> interfacesList = new ArrayList<>();
while (interfaces.hasNext()) {
JClass aInterface = interfaces.next();
interfacesList.add(aInterface);
}
Collections.sort(interfacesList, INTERFACE_COMPARATOR);
for (JClass aInterface : interfacesList) {
dataOutputStream.writeUTF(aInterface.fullName());
}
//we should probably serialize the parent class too! (but what if it has serialversionUID on it? that would be a field and would affect the serialversionUID!)
if (jclass._extends() != null) {
dataOutputStream.writeUTF(jclass._extends().fullName());
}
processMethodCollectionForSerializableSupport(jclass.methods().iterator(), dataOutputStream);
processMethodCollectionForSerializableSupport(jclass.constructors(), dataOutputStream);
}
private static void processFieldVarForSerializableSupport(JFieldVar fieldVar, DataOutputStream dataOutputStream) throws IOException {
dataOutputStream.writeUTF(fieldVar.name());
dataOutputStream.writeInt(fieldVar.mods().getValue());
JType type = fieldVar.type();
dataOutputStream.writeUTF(type.fullName());
}
public static void addSerializableSupport(JDefinedClass jclass) {
jclass._implements(Serializable.class);
try {
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
final DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);
processDefinedClassForSerializableSupport(jclass, dataOutputStream);
dataOutputStream.flush();
final MessageDigest digest = MessageDigest.getInstance("SHA");
final byte[] digestBytes = digest.digest(byteArrayOutputStream.toByteArray());
long serialVersionUID = 0L;
for (int i = Math.min(digestBytes.length, 8) - 1; i >= 0; i--) {
serialVersionUID = serialVersionUID << 8 | digestBytes[i] & 0xff;
}
JFieldVar serialUIDField = jclass.field(JMod.PRIVATE | JMod.STATIC | JMod.FINAL, long.class, "serialVersionUID");
serialUIDField.init(JExpr.lit(serialVersionUID));
} catch (IOException exception) {
throw new GenerationException("IOException while generating serialversionUID field while adding serializable support to class: " + jclass.fullName(), exception);
} catch (NoSuchAlgorithmException exception) {
throw new GenerationException("SHA algorithm not found when trying to generate serialversionUID field while adding serializable support to class: " + jclass.fullName(), exception);
}
}
}
|
/*
* 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 gobblin.runtime.locks;
import java.io.IOException;
import java.net.URI;
import java.util.Properties;
import java.util.Random;
import java.util.concurrent.TimeoutException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.fs.permission.FsPermission;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import gobblin.configuration.ConfigurationKeys;
import gobblin.runtime.api.JobSpec;
import gobblin.util.HadoopUtils;
/**
* A factory for file-based job locks. All locks are presented as files under a common directory.
* If the directory does not exist, it will be automatically created and removed on close().
*/
public class FileBasedJobLockFactory implements JobLockFactory<FileBasedJobLock> {
/** The URI of the file system with the directory for lock files*/
public static final String FS_URI_CONFIG = "fsURI";
/** The path to the directory for lock files*/
public static final String LOCK_DIR_CONFIG = "lockDir";
static final String DEFAULT_LOCK_DIR_PREFIX = "/tmp/gobblin-job-locks-";
/**
* Default waiting period (5 minutes).
* TODO add configuration support
*/
static final long DEFAULT_WAIT_MS = 300000;
private final FileSystem fs;
private final Path lockFileDir;
private final Logger log;
private final boolean deleteLockDirOnClose;
/** Constructs a new factory
* @throws IOException */
public FileBasedJobLockFactory(FileSystem fs, String lockFileDir, Optional<Logger> log)
throws IOException {
this.fs = fs;
this.lockFileDir = new Path(lockFileDir);
this.log = log.or(LoggerFactory.getLogger(getClass().getName() + "-" + lockFileDir));
this.deleteLockDirOnClose = !this.fs.exists(this.lockFileDir);
if (deleteLockDirOnClose) {
createLockDir(this.fs, this.lockFileDir);
}
}
public FileBasedJobLockFactory(FileSystem fs, String lockFileDir) throws IOException {
this(fs, lockFileDir, Optional.<Logger>absent());
}
/** Create a new instance using the specified factory and hadoop configurations. */
public static FileBasedJobLockFactory create(Config factoryConfig,
Configuration hadoopConf,
Optional<Logger> log)
throws IOException {
FileSystem fs = factoryConfig.hasPath(FS_URI_CONFIG) ?
FileSystem.get(URI.create(factoryConfig.getString(FS_URI_CONFIG)), hadoopConf) :
getDefaultFileSystem(hadoopConf);
String lockFilesDir = factoryConfig.hasPath(LOCK_DIR_CONFIG) ?
factoryConfig.getString(LOCK_DIR_CONFIG) :
getDefaultLockDir(fs, log);
return new FileBasedJobLockFactory(fs, lockFilesDir, log);
}
public static FileSystem getDefaultFileSystem(Configuration hadoopConf) throws IOException {
return FileSystem.getLocal(hadoopConf);
}
public static String getDefaultLockDir(FileSystem fs, Optional<Logger> log) {
Random rng = new Random();
Path dirName;
try
{
do {
dirName = new Path(DEFAULT_LOCK_DIR_PREFIX + rng.nextLong());
} while (fs.exists(dirName));
} catch (IllegalArgumentException | IOException e) {
throw new RuntimeException("Unable to create job lock directory: " + e, e);
}
if (log.isPresent()) {
log.get().info("Created default job lock directory: " + dirName);
}
return dirName.toString();
}
protected static void createLockDir(FileSystem fs, Path dirName) throws IOException {
if (!fs.mkdirs(dirName, getDefaultDirPermissions())) {
throw new RuntimeException("Unable to create job lock directory: " + dirName);
}
}
protected static FsPermission getDefaultDirPermissions() {
return new FsPermission(FsAction.ALL, FsAction.READ_EXECUTE, FsAction.NONE);
}
Path getLockFile(String jobName) {
return new Path(lockFileDir, jobName + FileBasedJobLock.LOCK_FILE_EXTENSION);
}
/**
* Acquire the lock.
*
* @throws JobLockException thrown if the {@link JobLock} fails to be acquired
*/
void lock(Path lockFile) throws JobLockException {
log.debug("Creating lock: {}", lockFile);
try {
if (!this.fs.createNewFile(lockFile)) {
throw new JobLockException("Failed to create lock file " + lockFile.getName());
}
} catch (IOException e) {
throw new JobLockException(e);
}
}
/**
* Release the lock.
*
* @throws JobLockException thrown if the {@link JobLock} fails to be released
*/
void unlock(Path lockFile) throws JobLockException {
log.debug("Removing lock: {}", lockFile);
if (!isLocked(lockFile)) {
return;
}
try {
this.fs.delete(lockFile, false);
} catch (IOException e) {
throw new JobLockException(e);
}
}
/**
* Try locking the lock.
*
* @return <em>true</em> if the lock is successfully locked,
* <em>false</em> if otherwise.
* @throws JobLockException thrown if the {@link JobLock} fails to be acquired
*/
boolean tryLock(Path lockFile) throws JobLockException {
log.debug("Attempting lock: {}", lockFile);
try {
return this.fs.createNewFile(lockFile);
} catch (IOException e) {
throw new JobLockException(e);
}
}
/**
* Check if the lock is locked.
*
* @return if the lock is locked
* @throws JobLockException thrown if checking the status of the {@link JobLock} fails
*/
boolean isLocked(Path lockFile) throws JobLockException {
try {
return this.fs.exists(lockFile);
} catch (IOException e) {
throw new JobLockException(e);
}
}
public static Config getConfigForProperties(Properties properties) {
return ConfigFactory.parseMap(ImmutableMap.<String, Object>builder()
.put(FS_URI_CONFIG, properties.getProperty(ConfigurationKeys.FS_URI_KEY, ConfigurationKeys.LOCAL_FS_URI))
.put(LOCK_DIR_CONFIG, properties.getProperty(FileBasedJobLock.JOB_LOCK_DIR))
.build());
}
public static FileBasedJobLockFactory createForProperties(Properties properties)
throws JobLockException {
try {
FileSystem fs = FileSystem.get(
URI.create(properties.getProperty(ConfigurationKeys.FS_URI_KEY, ConfigurationKeys.LOCAL_FS_URI)),
HadoopUtils.getConfFromProperties(properties));
String lockFileDir = properties.getProperty(FileBasedJobLock.JOB_LOCK_DIR);
return new FileBasedJobLockFactory(fs, lockFileDir);
} catch (IOException e) {
throw new JobLockException(e);
}
}
@Override
public FileBasedJobLock getJobLock(JobSpec jobSpec) throws TimeoutException {
String jobName = getJobName(jobSpec);
return new FileBasedJobLock(jobName, this);
}
@VisibleForTesting
static String getJobName(JobSpec jobSpec) {
return jobSpec.getUri().toString().replaceAll("[/.:]", "_");
}
@VisibleForTesting
FileSystem getFs() {
return fs;
}
@VisibleForTesting
Path getLockFileDir() {
return lockFileDir;
}
@Override
public void close() throws IOException {
if (this.deleteLockDirOnClose) {
this.log.info("Delete auto-created lock directory: {}", getLockFileDir());
if (!this.fs.delete(getLockFileDir(), true)) {
this.log.warn("Failed to delete lock directory: {}", getLockFileDir());
}
}
}
}
|
/*
* Copyright 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.gradle.process.internal.health.memory;
import org.gradle.internal.service.scopes.EventScope;
import org.gradle.internal.service.scopes.Scope.Global;
@EventScope(Global.class)
public interface JvmMemoryStatusListener {
void onJvmMemoryStatus(JvmMemoryStatus jvmMemoryStatus);
}
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 University of Wisconsin Board of Regents
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package edu.wisc.library.ocfl.api.model;
import java.time.OffsetDateTime;
import java.util.Objects;
/**
* Descriptive information about an object version.
*/
public class VersionInfo {
private User user;
private String message;
private OffsetDateTime created;
public VersionInfo() {
this.user = new User();
}
/**
* The user who authored the version
*
* @return user object
*/
public User getUser() {
return user;
}
/**
* Sets the user info
*
* @param name the user's name, required
* @param address a URI that identifies the user, such as email address
* @return this
*/
public VersionInfo setUser(String name, String address) {
this.user = new User()
.setName(name)
.setAddress(address);
return this;
}
/**
* Sets the user info
*
* @param user the user object
* @return this
*/
public VersionInfo setUser(User user) {
this.user = user;
return this;
}
/**
* Description of version changes
*
* @return the version description
*/
public String getMessage() {
return message;
}
/**
* Sets the version description
*
* @param message version description
* @return this
*/
public VersionInfo setMessage(String message) {
this.message = message;
return this;
}
/**
* The timestamp when the version was created
*
* @return version creation timestamp
*/
public OffsetDateTime getCreated() {
return created;
}
/**
* Sets the verison creation timestamp. If this value is not supplied, the current system time will be used instead.
*
* @param created version creation timestamp
* @return this
*/
public VersionInfo setCreated(OffsetDateTime created) {
this.created = created;
return this;
}
@Override
public String toString() {
return "VersionInfo{" +
"user=" + user +
", message='" + message + '\'' +
", created=" + created +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
VersionInfo that = (VersionInfo) o;
return user.equals(that.user) &&
Objects.equals(message, that.message) &&
Objects.equals(created, that.created);
}
@Override
public int hashCode() {
return Objects.hash(user, message, created);
}
}
|
/*
* 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.iotdb.db.engine.merge.recover;
import org.apache.iotdb.db.engine.merge.manage.MergeResource;
import org.apache.iotdb.db.engine.storagegroup.TsFileResource;
import org.apache.iotdb.db.metadata.PartialPath;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
/** MergeLogger records the progress of a merge in file "merge.log" as text lines. */
public class MergeLogger {
public static final String MERGE_LOG_NAME = "merge.log";
static final String STR_SEQ_FILES = "seqFiles";
static final String STR_UNSEQ_FILES = "unseqFiles";
static final String STR_TIMESERIES = "timeseries";
static final String STR_START = "start";
static final String STR_END = "end";
static final String STR_ALL_TS_END = "all ts end";
static final String STR_MERGE_START = "merge start";
static final String STR_MERGE_END = "merge end";
private BufferedWriter logStream;
public MergeLogger(String storageGroupDir) throws IOException {
logStream = new BufferedWriter(new FileWriter(new File(storageGroupDir, MERGE_LOG_NAME), true));
}
public void close() throws IOException {
logStream.close();
}
public void logTSStart(List<PartialPath> paths) throws IOException {
logStream.write(STR_START);
for (PartialPath path : paths) {
logStream.write(" " + path);
}
logStream.newLine();
logStream.flush();
}
public void logFilePosition(File file) throws IOException {
logStream.write(String.format("%s %d", file.getAbsolutePath(), file.length()));
logStream.newLine();
logStream.flush();
}
public void logTSEnd() throws IOException {
logStream.write(STR_END);
logStream.newLine();
logStream.flush();
}
public void logAllTsEnd() throws IOException {
logStream.write(STR_ALL_TS_END);
logStream.newLine();
logStream.flush();
}
public void logFileMergeStart(File file, long position) throws IOException {
logStream.write(String.format("%s %d", file.getAbsolutePath(), position));
logStream.newLine();
logStream.flush();
}
public void logFileMergeEnd() throws IOException {
logStream.write(STR_END);
logStream.newLine();
logStream.flush();
}
public void logMergeEnd() throws IOException {
logStream.write(STR_MERGE_END);
logStream.newLine();
logStream.flush();
}
public void logFiles(MergeResource resource) throws IOException {
logSeqFiles(resource.getSeqFiles());
logUnseqFiles(resource.getUnseqFiles());
}
private void logSeqFiles(List<TsFileResource> seqFiles) throws IOException {
logStream.write(STR_SEQ_FILES);
logStream.newLine();
for (TsFileResource tsFileResource : seqFiles) {
logStream.write(tsFileResource.getTsFile().getAbsolutePath());
logStream.newLine();
}
logStream.flush();
}
private void logUnseqFiles(List<TsFileResource> unseqFiles) throws IOException {
logStream.write(STR_UNSEQ_FILES);
logStream.newLine();
for (TsFileResource tsFileResource : unseqFiles) {
logStream.write(tsFileResource.getTsFile().getAbsolutePath());
logStream.newLine();
}
logStream.flush();
}
public void logMergeStart() throws IOException {
logStream.write(STR_MERGE_START);
logStream.newLine();
logStream.flush();
}
}
|
/*
* 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.jdbi.v3.core.statement;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.jdbi.v3.core.config.JdbiConfig;
/**
* Configuration holder for {@link SqlStatement}s.
*/
public final class SqlStatements implements JdbiConfig<SqlStatements> {
private final Map<String, Object> attributes;
private TemplateEngine templateEngine;
private SqlParser sqlParser;
private TimingCollector timingCollector;
public SqlStatements() {
attributes = new ConcurrentHashMap<>();
templateEngine = new DefinedAttributeTemplateEngine();
sqlParser = new ColonPrefixSqlParser();
timingCollector = TimingCollector.NOP_TIMING_COLLECTOR;
}
private SqlStatements(SqlStatements that) {
this.attributes = new ConcurrentHashMap<>(that.attributes);
this.templateEngine = that.templateEngine;
this.sqlParser = that.sqlParser;
this.timingCollector = that.timingCollector;
}
/**
* Define an attribute for {@link StatementContext} for statements executed by Jdbi.
*
* @param key the key for the attribute
* @param value the value for the attribute
* @return this
*/
public SqlStatements define(String key, Object value) {
attributes.put(key, value);
return this;
}
/**
* Defines attributes for each key/value pair in the Map.
*
* @param values map of attributes to define.
* @return this
*/
public SqlStatements defineMap(final Map<String, ?> values) {
if (values != null) {
attributes.putAll(values);
}
return this;
}
/**
* Obtain the value of an attribute
*
* @param key the name of the attribute
* @return the value of the attribute
*/
public Object getAttribute(String key) {
return attributes.get(key);
}
/**
* Returns the attributes which will be applied to {@link SqlStatement SQL statements} created by Jdbi.
*
* @return the defined attributes.
*/
public Map<String, Object> getAttributes() {
return attributes;
}
/**
* @return the template engine which renders the SQL template prior to
* parsing parameters.
*/
public TemplateEngine getTemplateEngine() {
return templateEngine;
}
/**
* Sets the {@link TemplateEngine} used to render SQL for all
* {@link SqlStatement SQL statements} executed by Jdbi. The default
* engine replaces <code><name></code>-style tokens
* with attributes {@link StatementContext#define(String, Object) defined}
* on the statement context.
*
* @param templateEngine the new template engine.
* @return this
*/
public SqlStatements setTemplateEngine(TemplateEngine templateEngine) {
this.templateEngine = templateEngine;
return this;
}
public SqlParser getSqlParser() {
return sqlParser;
}
/**
* Sets the {@link SqlParser} used to parse parameters in SQL statements
* executed by Jdbi. The default parses colon-prefixed named parameter
* tokens, e.g. <code>:name</code>.
*
* @param sqlParser the new SQL parser.
* @return this
*/
public SqlStatements setSqlParser(SqlParser sqlParser) {
this.sqlParser = sqlParser;
return this;
}
/**
* @return the timing collector
*/
public TimingCollector getTimingCollector() {
return timingCollector;
}
/**
* Sets the {@link TimingCollector} used to collect timing about the {@link SqlStatement SQL statements} executed
* by Jdbi. The default collector does nothing.
*
* @param timingCollector the new timing collector
* @return this
*/
public SqlStatements setTimingCollector(TimingCollector timingCollector) {
this.timingCollector = timingCollector == null ? TimingCollector.NOP_TIMING_COLLECTOR : timingCollector;
return this;
}
@Override
public SqlStatements createCopy() {
return new SqlStatements(this);
}
}
|
//
// Copyright 2009 Robin Komiwes, Bruno Verachten, Christophe Cordenier
//
// 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.wooki.test.unit;
import org.apache.tapestry5.ioc.Messages;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.wooki.services.ServicesMessages;
import com.wooki.services.utils.LastActivityMessages;
/**
* Use this class to implement utility class test.
*
* @author ccordenier
*/
public class UtilityClassTest extends AbstractWookiUnitTestSuite
{
@Test(enabled = true)
public void testLastActivityMessage()
{
Messages messages = this.pageTester.getService(ServicesMessages.class).getMessages();
String message = LastActivityMessages.getActivityPeriod(
System.currentTimeMillis(),
messages);
Assert.assertTrue(message.contains("few seconds"));
message = LastActivityMessages.getActivityPeriod(
System.currentTimeMillis() - 61000,
messages);
Assert.assertTrue(message.contains("minute(s) ago"));
message = LastActivityMessages.getActivityPeriod(
System.currentTimeMillis() - (61 * 60000),
messages);
Assert.assertTrue(message.contains("hour(s) ago"));
message = LastActivityMessages.getActivityPeriod(System.currentTimeMillis()
- (61 * 60000 * 25), messages);
Assert.assertTrue(message.contains("day(s) ago"));
message = LastActivityMessages.getActivityPeriod(System.currentTimeMillis()
- (61 * 60000 * 25 * 5), messages);
Assert.assertTrue(!message.contains("ago"));
}
}
|
package hudson.remoting;
import java.util.List;
/**
* {@link ForkRunner} with an ASCII incompatible encoding.
*/
public class ForkEBCDICRunner extends ForkRunner {
@Override
protected List<String> buildCommandLine() {
List<String> r = super.buildCommandLine();
r.add(0,"-Dfile.encoding=CP037");
return r;
}
@Override
public String getName() {
return "forkEBCDIC";
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.appservice.fluent.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.appservice.models.Channels;
import com.azure.resourcemanager.appservice.models.NotificationLevel;
import com.azure.resourcemanager.appservice.models.ResourceScopeType;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.UUID;
/** Recommendation resource specific properties. */
@Fluent
public final class RecommendationProperties {
@JsonIgnore private final ClientLogger logger = new ClientLogger(RecommendationProperties.class);
/*
* Timestamp when this instance was created.
*/
@JsonProperty(value = "creationTime")
private OffsetDateTime creationTime;
/*
* A GUID value that each recommendation object is associated with.
*/
@JsonProperty(value = "recommendationId")
private UUID recommendationId;
/*
* Full ARM resource ID string that this recommendation object is
* associated with.
*/
@JsonProperty(value = "resourceId")
private String resourceId;
/*
* Name of a resource type this recommendation applies, e.g. Subscription,
* ServerFarm, Site.
*/
@JsonProperty(value = "resourceScope")
private ResourceScopeType resourceScope;
/*
* Unique name of the rule.
*/
@JsonProperty(value = "ruleName")
private String ruleName;
/*
* UI friendly name of the rule (may not be unique).
*/
@JsonProperty(value = "displayName")
private String displayName;
/*
* Recommendation text.
*/
@JsonProperty(value = "message")
private String message;
/*
* Level indicating how critical this recommendation can impact.
*/
@JsonProperty(value = "level")
private NotificationLevel level;
/*
* List of channels that this recommendation can apply.
*/
@JsonProperty(value = "channels")
private Channels channels;
/*
* The list of category tags that this recommendation belongs to.
*/
@JsonProperty(value = "categoryTags", access = JsonProperty.Access.WRITE_ONLY)
private List<String> categoryTags;
/*
* Name of action recommended by this object.
*/
@JsonProperty(value = "actionName")
private String actionName;
/*
* True if this recommendation is still valid (i.e. "actionable"). False if
* it is invalid.
*/
@JsonProperty(value = "enabled")
private Integer enabled;
/*
* The list of states of this recommendation. If it's null then it should
* be considered "Active".
*/
@JsonProperty(value = "states")
private List<String> states;
/*
* The beginning time in UTC of a range that the recommendation refers to.
*/
@JsonProperty(value = "startTime")
private OffsetDateTime startTime;
/*
* The end time in UTC of a range that the recommendation refers to.
*/
@JsonProperty(value = "endTime")
private OffsetDateTime endTime;
/*
* When to notify this recommendation next in UTC. Null means that this
* will never be notified anymore.
*/
@JsonProperty(value = "nextNotificationTime")
private OffsetDateTime nextNotificationTime;
/*
* Date and time in UTC when this notification expires.
*/
@JsonProperty(value = "notificationExpirationTime")
private OffsetDateTime notificationExpirationTime;
/*
* Last timestamp in UTC this instance was actually notified. Null means
* that this recommendation hasn't been notified yet.
*/
@JsonProperty(value = "notifiedTime")
private OffsetDateTime notifiedTime;
/*
* A metric value measured by the rule.
*/
@JsonProperty(value = "score")
private Double score;
/*
* True if this is associated with a dynamically added rule
*/
@JsonProperty(value = "isDynamic")
private Boolean isDynamic;
/*
* Extension name of the portal if exists.
*/
@JsonProperty(value = "extensionName")
private String extensionName;
/*
* Deep link to a blade on the portal.
*/
@JsonProperty(value = "bladeName")
private String bladeName;
/*
* Forward link to an external document associated with the rule.
*/
@JsonProperty(value = "forwardLink")
private String forwardLink;
/**
* Get the creationTime property: Timestamp when this instance was created.
*
* @return the creationTime value.
*/
public OffsetDateTime creationTime() {
return this.creationTime;
}
/**
* Set the creationTime property: Timestamp when this instance was created.
*
* @param creationTime the creationTime value to set.
* @return the RecommendationProperties object itself.
*/
public RecommendationProperties withCreationTime(OffsetDateTime creationTime) {
this.creationTime = creationTime;
return this;
}
/**
* Get the recommendationId property: A GUID value that each recommendation object is associated with.
*
* @return the recommendationId value.
*/
public UUID recommendationId() {
return this.recommendationId;
}
/**
* Set the recommendationId property: A GUID value that each recommendation object is associated with.
*
* @param recommendationId the recommendationId value to set.
* @return the RecommendationProperties object itself.
*/
public RecommendationProperties withRecommendationId(UUID recommendationId) {
this.recommendationId = recommendationId;
return this;
}
/**
* Get the resourceId property: Full ARM resource ID string that this recommendation object is associated with.
*
* @return the resourceId value.
*/
public String resourceId() {
return this.resourceId;
}
/**
* Set the resourceId property: Full ARM resource ID string that this recommendation object is associated with.
*
* @param resourceId the resourceId value to set.
* @return the RecommendationProperties object itself.
*/
public RecommendationProperties withResourceId(String resourceId) {
this.resourceId = resourceId;
return this;
}
/**
* Get the resourceScope property: Name of a resource type this recommendation applies, e.g. Subscription,
* ServerFarm, Site.
*
* @return the resourceScope value.
*/
public ResourceScopeType resourceScope() {
return this.resourceScope;
}
/**
* Set the resourceScope property: Name of a resource type this recommendation applies, e.g. Subscription,
* ServerFarm, Site.
*
* @param resourceScope the resourceScope value to set.
* @return the RecommendationProperties object itself.
*/
public RecommendationProperties withResourceScope(ResourceScopeType resourceScope) {
this.resourceScope = resourceScope;
return this;
}
/**
* Get the ruleName property: Unique name of the rule.
*
* @return the ruleName value.
*/
public String ruleName() {
return this.ruleName;
}
/**
* Set the ruleName property: Unique name of the rule.
*
* @param ruleName the ruleName value to set.
* @return the RecommendationProperties object itself.
*/
public RecommendationProperties withRuleName(String ruleName) {
this.ruleName = ruleName;
return this;
}
/**
* Get the displayName property: UI friendly name of the rule (may not be unique).
*
* @return the displayName value.
*/
public String displayName() {
return this.displayName;
}
/**
* Set the displayName property: UI friendly name of the rule (may not be unique).
*
* @param displayName the displayName value to set.
* @return the RecommendationProperties object itself.
*/
public RecommendationProperties withDisplayName(String displayName) {
this.displayName = displayName;
return this;
}
/**
* Get the message property: Recommendation text.
*
* @return the message value.
*/
public String message() {
return this.message;
}
/**
* Set the message property: Recommendation text.
*
* @param message the message value to set.
* @return the RecommendationProperties object itself.
*/
public RecommendationProperties withMessage(String message) {
this.message = message;
return this;
}
/**
* Get the level property: Level indicating how critical this recommendation can impact.
*
* @return the level value.
*/
public NotificationLevel level() {
return this.level;
}
/**
* Set the level property: Level indicating how critical this recommendation can impact.
*
* @param level the level value to set.
* @return the RecommendationProperties object itself.
*/
public RecommendationProperties withLevel(NotificationLevel level) {
this.level = level;
return this;
}
/**
* Get the channels property: List of channels that this recommendation can apply.
*
* @return the channels value.
*/
public Channels channels() {
return this.channels;
}
/**
* Set the channels property: List of channels that this recommendation can apply.
*
* @param channels the channels value to set.
* @return the RecommendationProperties object itself.
*/
public RecommendationProperties withChannels(Channels channels) {
this.channels = channels;
return this;
}
/**
* Get the categoryTags property: The list of category tags that this recommendation belongs to.
*
* @return the categoryTags value.
*/
public List<String> categoryTags() {
return this.categoryTags;
}
/**
* Get the actionName property: Name of action recommended by this object.
*
* @return the actionName value.
*/
public String actionName() {
return this.actionName;
}
/**
* Set the actionName property: Name of action recommended by this object.
*
* @param actionName the actionName value to set.
* @return the RecommendationProperties object itself.
*/
public RecommendationProperties withActionName(String actionName) {
this.actionName = actionName;
return this;
}
/**
* Get the enabled property: True if this recommendation is still valid (i.e. "actionable"). False if it is invalid.
*
* @return the enabled value.
*/
public Integer enabled() {
return this.enabled;
}
/**
* Set the enabled property: True if this recommendation is still valid (i.e. "actionable"). False if it is invalid.
*
* @param enabled the enabled value to set.
* @return the RecommendationProperties object itself.
*/
public RecommendationProperties withEnabled(Integer enabled) {
this.enabled = enabled;
return this;
}
/**
* Get the states property: The list of states of this recommendation. If it's null then it should be considered
* "Active".
*
* @return the states value.
*/
public List<String> states() {
return this.states;
}
/**
* Set the states property: The list of states of this recommendation. If it's null then it should be considered
* "Active".
*
* @param states the states value to set.
* @return the RecommendationProperties object itself.
*/
public RecommendationProperties withStates(List<String> states) {
this.states = states;
return this;
}
/**
* Get the startTime property: The beginning time in UTC of a range that the recommendation refers to.
*
* @return the startTime value.
*/
public OffsetDateTime startTime() {
return this.startTime;
}
/**
* Set the startTime property: The beginning time in UTC of a range that the recommendation refers to.
*
* @param startTime the startTime value to set.
* @return the RecommendationProperties object itself.
*/
public RecommendationProperties withStartTime(OffsetDateTime startTime) {
this.startTime = startTime;
return this;
}
/**
* Get the endTime property: The end time in UTC of a range that the recommendation refers to.
*
* @return the endTime value.
*/
public OffsetDateTime endTime() {
return this.endTime;
}
/**
* Set the endTime property: The end time in UTC of a range that the recommendation refers to.
*
* @param endTime the endTime value to set.
* @return the RecommendationProperties object itself.
*/
public RecommendationProperties withEndTime(OffsetDateTime endTime) {
this.endTime = endTime;
return this;
}
/**
* Get the nextNotificationTime property: When to notify this recommendation next in UTC. Null means that this will
* never be notified anymore.
*
* @return the nextNotificationTime value.
*/
public OffsetDateTime nextNotificationTime() {
return this.nextNotificationTime;
}
/**
* Set the nextNotificationTime property: When to notify this recommendation next in UTC. Null means that this will
* never be notified anymore.
*
* @param nextNotificationTime the nextNotificationTime value to set.
* @return the RecommendationProperties object itself.
*/
public RecommendationProperties withNextNotificationTime(OffsetDateTime nextNotificationTime) {
this.nextNotificationTime = nextNotificationTime;
return this;
}
/**
* Get the notificationExpirationTime property: Date and time in UTC when this notification expires.
*
* @return the notificationExpirationTime value.
*/
public OffsetDateTime notificationExpirationTime() {
return this.notificationExpirationTime;
}
/**
* Set the notificationExpirationTime property: Date and time in UTC when this notification expires.
*
* @param notificationExpirationTime the notificationExpirationTime value to set.
* @return the RecommendationProperties object itself.
*/
public RecommendationProperties withNotificationExpirationTime(OffsetDateTime notificationExpirationTime) {
this.notificationExpirationTime = notificationExpirationTime;
return this;
}
/**
* Get the notifiedTime property: Last timestamp in UTC this instance was actually notified. Null means that this
* recommendation hasn't been notified yet.
*
* @return the notifiedTime value.
*/
public OffsetDateTime notifiedTime() {
return this.notifiedTime;
}
/**
* Set the notifiedTime property: Last timestamp in UTC this instance was actually notified. Null means that this
* recommendation hasn't been notified yet.
*
* @param notifiedTime the notifiedTime value to set.
* @return the RecommendationProperties object itself.
*/
public RecommendationProperties withNotifiedTime(OffsetDateTime notifiedTime) {
this.notifiedTime = notifiedTime;
return this;
}
/**
* Get the score property: A metric value measured by the rule.
*
* @return the score value.
*/
public Double score() {
return this.score;
}
/**
* Set the score property: A metric value measured by the rule.
*
* @param score the score value to set.
* @return the RecommendationProperties object itself.
*/
public RecommendationProperties withScore(Double score) {
this.score = score;
return this;
}
/**
* Get the isDynamic property: True if this is associated with a dynamically added rule.
*
* @return the isDynamic value.
*/
public Boolean isDynamic() {
return this.isDynamic;
}
/**
* Set the isDynamic property: True if this is associated with a dynamically added rule.
*
* @param isDynamic the isDynamic value to set.
* @return the RecommendationProperties object itself.
*/
public RecommendationProperties withIsDynamic(Boolean isDynamic) {
this.isDynamic = isDynamic;
return this;
}
/**
* Get the extensionName property: Extension name of the portal if exists.
*
* @return the extensionName value.
*/
public String extensionName() {
return this.extensionName;
}
/**
* Set the extensionName property: Extension name of the portal if exists.
*
* @param extensionName the extensionName value to set.
* @return the RecommendationProperties object itself.
*/
public RecommendationProperties withExtensionName(String extensionName) {
this.extensionName = extensionName;
return this;
}
/**
* Get the bladeName property: Deep link to a blade on the portal.
*
* @return the bladeName value.
*/
public String bladeName() {
return this.bladeName;
}
/**
* Set the bladeName property: Deep link to a blade on the portal.
*
* @param bladeName the bladeName value to set.
* @return the RecommendationProperties object itself.
*/
public RecommendationProperties withBladeName(String bladeName) {
this.bladeName = bladeName;
return this;
}
/**
* Get the forwardLink property: Forward link to an external document associated with the rule.
*
* @return the forwardLink value.
*/
public String forwardLink() {
return this.forwardLink;
}
/**
* Set the forwardLink property: Forward link to an external document associated with the rule.
*
* @param forwardLink the forwardLink value to set.
* @return the RecommendationProperties object itself.
*/
public RecommendationProperties withForwardLink(String forwardLink) {
this.forwardLink = forwardLink;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
}
}
|
package com.alipay.api.domain;
import java.util.List;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.internal.mapping.ApiListField;
/**
* 发布物业通知公告
*
* @author auto create
* @since 1.0, 2021-04-09 14:45:37
*/
public class AlipayEcoCplifeNoticePublishModel extends AlipayObject {
private static final long serialVersionUID = 7398594794834491534L;
/**
* 待发布通知的目标物业小区ID列表,使用支付宝平台统一的小区ID编码。
*/
@ApiListField("community_id_set")
@ApiField("string")
private List<String> communityIdSet;
/**
* 待发送的通知内容
*/
@ApiField("notice_details")
private CplifeNoticeDetail noticeDetails;
public List<String> getCommunityIdSet() {
return this.communityIdSet;
}
public void setCommunityIdSet(List<String> communityIdSet) {
this.communityIdSet = communityIdSet;
}
public CplifeNoticeDetail getNoticeDetails() {
return this.noticeDetails;
}
public void setNoticeDetails(CplifeNoticeDetail noticeDetails) {
this.noticeDetails = noticeDetails;
}
}
|
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.redshift.model;
import javax.annotation.Generated;
/**
* <p>
* A specified subnet is already in use by another cluster.
* </p>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class SubnetAlreadyInUseException extends com.amazonaws.services.redshift.model.AmazonRedshiftException {
private static final long serialVersionUID = 1L;
/**
* Constructs a new SubnetAlreadyInUseException with the specified error message.
*
* @param message
* Describes the error encountered.
*/
public SubnetAlreadyInUseException(String message) {
super(message);
}
}
|
/*
* Licensed to the Technische Universität Darmstadt under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The Technische Universität Darmstadt
* 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.
*
* 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.tudarmstadt.ukp.clarin.webanno.api.annotation.feature;
import static de.tudarmstadt.ukp.clarin.webanno.api.annotation.feature.editor.StringFeatureTraits.EditorType.AUTOCOMPLETE;
import static de.tudarmstadt.ukp.clarin.webanno.api.annotation.feature.editor.StringFeatureTraits.EditorType.COMBOBOX;
import static de.tudarmstadt.ukp.clarin.webanno.api.annotation.feature.editor.StringFeatureTraits.EditorType.RADIOGROUP;
import static java.util.Arrays.asList;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import org.apache.uima.cas.CAS;
import org.apache.wicket.MarkupContainer;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.tudarmstadt.ukp.clarin.webanno.api.AnnotationSchemaService;
import de.tudarmstadt.ukp.clarin.webanno.api.annotation.action.AnnotationActionHandler;
import de.tudarmstadt.ukp.clarin.webanno.api.annotation.feature.config.StringFeatureSupportProperties;
import de.tudarmstadt.ukp.clarin.webanno.api.annotation.feature.config.StringFeatureSupportPropertiesImpl;
import de.tudarmstadt.ukp.clarin.webanno.api.annotation.feature.editor.DynamicTextAreaFeatureEditor;
import de.tudarmstadt.ukp.clarin.webanno.api.annotation.feature.editor.FeatureEditor;
import de.tudarmstadt.ukp.clarin.webanno.api.annotation.feature.editor.InputFieldTextFeatureEditor;
import de.tudarmstadt.ukp.clarin.webanno.api.annotation.feature.editor.KendoAutoCompleteTextFeatureEditor;
import de.tudarmstadt.ukp.clarin.webanno.api.annotation.feature.editor.KendoComboboxTextFeatureEditor;
import de.tudarmstadt.ukp.clarin.webanno.api.annotation.feature.editor.RadioGroupStringFeatureEditor;
import de.tudarmstadt.ukp.clarin.webanno.api.annotation.feature.editor.StringFeatureTraits;
import de.tudarmstadt.ukp.clarin.webanno.api.annotation.feature.editor.StringFeatureTraits.EditorType;
import de.tudarmstadt.ukp.clarin.webanno.api.annotation.feature.editor.StringFeatureTraitsEditor;
import de.tudarmstadt.ukp.clarin.webanno.api.annotation.feature.editor.TextAreaFeatureEditor;
import de.tudarmstadt.ukp.clarin.webanno.api.annotation.model.AnnotatorState;
import de.tudarmstadt.ukp.clarin.webanno.api.annotation.model.FeatureState;
import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationFeature;
import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationLayer;
import de.tudarmstadt.ukp.clarin.webanno.model.MultiValueMode;
import de.tudarmstadt.ukp.clarin.webanno.model.Tag;
import de.tudarmstadt.ukp.clarin.webanno.support.JSONUtil;
/**
* <p>
* This class is exposed as a Spring Component via
* {@code AnnotationSchemaServiceAutoConfiguration#stringFeatureSupport}.
* </p>
*/
public class StringFeatureSupport
extends UimaPrimitiveFeatureSupport_ImplBase<StringFeatureTraits>
{
private final Logger log = LoggerFactory.getLogger(getClass());
private List<FeatureType> primitiveTypes;
private final StringFeatureSupportProperties properties;
private final AnnotationSchemaService schemaService;
/*
* Constructor for use in unit tests to avoid having to always instantiate the properties.
*/
public StringFeatureSupport()
{
this(new StringFeatureSupportPropertiesImpl(), null);
}
public StringFeatureSupport(StringFeatureSupportProperties aProperties,
AnnotationSchemaService aSchemaService)
{
properties = aProperties;
schemaService = aSchemaService;
}
@Override
public void afterPropertiesSet() throws Exception
{
primitiveTypes = asList(
new FeatureType(CAS.TYPE_NAME_STRING, "Primitive: String", getId()));
}
@Override
public List<FeatureType> getSupportedFeatureTypes(AnnotationLayer aAnnotationLayer)
{
return Collections.unmodifiableList(primitiveTypes);
}
@Override
public boolean accepts(AnnotationFeature aFeature)
{
return MultiValueMode.NONE.equals(aFeature.getMultiValueMode())
&& CAS.TYPE_NAME_STRING.equals(aFeature.getType());
}
@Override
public void setFeatureValue(CAS aCas, AnnotationFeature aFeature, int aAddress, Object aValue)
{
if (aValue != null && schemaService != null && aFeature.getTagset() != null
&& CAS.TYPE_NAME_STRING.equals(aFeature.getType())
&& !schemaService.existsTag((String) aValue, aFeature.getTagset())) {
if (!aFeature.getTagset().isCreateTag()) {
throw new IllegalArgumentException("[" + aValue
+ "] is not in the tag list. Please choose from the existing tags");
}
else {
Tag selectedTag = new Tag();
selectedTag.setName((String) aValue);
selectedTag.setTagSet(aFeature.getTagset());
schemaService.createTag(selectedTag);
}
}
super.setFeatureValue(aCas, aFeature, aAddress, aValue);
}
@Override
public Panel createTraitsEditor(String aId, IModel<AnnotationFeature> aFeatureModel)
{
AnnotationFeature feature = aFeatureModel.getObject();
if (!accepts(feature)) {
throw unsupportedFeatureTypeException(feature);
}
return new StringFeatureTraitsEditor(aId, this, aFeatureModel);
}
@Override
public FeatureEditor createEditor(String aId, MarkupContainer aOwner,
AnnotationActionHandler aHandler, final IModel<AnnotatorState> aStateModel,
final IModel<FeatureState> aFeatureStateModel)
{
AnnotationFeature feature = aFeatureStateModel.getObject().feature;
if (!accepts(feature)) {
throw unsupportedFeatureTypeException(feature);
}
StringFeatureTraits traits = readTraits(feature);
if (feature.getTagset() == null || traits.isMultipleRows()) {
if (traits.isMultipleRows()) {
// If multiple rows are set use a textarea
if (traits.isDynamicSize()) {
return new DynamicTextAreaFeatureEditor(aId, aOwner, aFeatureStateModel);
}
else {
return new TextAreaFeatureEditor(aId, aOwner, aFeatureStateModel);
}
}
else {
// Otherwise use a simple input field
return new InputFieldTextFeatureEditor(aId, aOwner, aFeatureStateModel, aHandler);
}
}
EditorType editorType = traits.getEditorType();
if (editorType == EditorType.AUTO) {
editorType = autoChooseFeatureEditorWithTagset(aFeatureStateModel);
}
switch (editorType) {
case RADIOGROUP:
return new RadioGroupStringFeatureEditor(aId, aOwner, aFeatureStateModel, aHandler);
case COMBOBOX:
return new KendoComboboxTextFeatureEditor(aId, aOwner, aFeatureStateModel, aHandler);
case AUTOCOMPLETE:
return new KendoAutoCompleteTextFeatureEditor(aId, aOwner, aFeatureStateModel,
properties.getAutoCompleteMaxResults(), aHandler);
default:
throw new IllegalStateException(
"Unknown editor type: [" + traits.getEditorType() + "]");
}
}
private EditorType autoChooseFeatureEditorWithTagset(
final IModel<FeatureState> aFeatureStateModel)
{
FeatureState featureState = aFeatureStateModel.getObject();
// For really small tagsets where tag creation is not supported, use a radio group
if (!featureState.feature.getTagset().isCreateTag()
&& featureState.tagset.size() < properties.getComboBoxThreshold()) {
return RADIOGROUP;
}
// For mid-sized tagsets, use a combobox
if (featureState.tagset.size() < properties.getAutoCompleteThreshold()) {
return COMBOBOX;
}
// For larger ones, use an auto-complete field
return AUTOCOMPLETE;
}
@Override
public StringFeatureTraits readTraits(AnnotationFeature aFeature)
{
StringFeatureTraits traits = null;
try {
traits = JSONUtil.fromJsonString(StringFeatureTraits.class, aFeature.getTraits());
}
catch (IOException e) {
log.error("Unable to read traits", e);
}
if (traits == null) {
traits = new StringFeatureTraits();
}
return traits;
}
@Override
public void writeTraits(AnnotationFeature aFeature, StringFeatureTraits aTraits)
{
try {
aFeature.setTraits(JSONUtil.toJsonString(aTraits));
}
catch (IOException e) {
log.error("Unable to write traits", e);
}
}
@Override
public boolean suppressAutoFocus(AnnotationFeature aFeature)
{
StringFeatureTraits traits = readTraits(aFeature);
return !traits.getKeyBindings().isEmpty();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.