text
stringlengths 7
1.01M
|
|---|
package com.hnj.locationservice.entities;
public class Location {
private double latitude;
private double longitude;
protected Location(){}
public Location(double latitude, double longitude) {
this.latitude = latitude;
this.longitude = longitude;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
}
|
/**
* Alipay.com Inc.
* Copyright (c) 2004-2018 All Rights Reserved.
*/
package com.shinnlove.netty.io.type.pio;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import com.shinnlove.netty.io.type.bio.TimeServerHandler;
/**
* 使用线程池
*
* @author shinnlove.jinsheng
* @version $Id: TimeServer.java, v 0.1 2018-06-29 下午1:29 shinnlove.jinsheng Exp $$
*/
public class TimeServer {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
int port = 8080;
if (args != null && args.length > 0) {
try {
port = Integer.valueOf(args[0]);
} catch (NumberFormatException e) {
// 采用默认值
}
}
ServerSocket server = null;
try {
server = new ServerSocket(port);
System.out.println("The time server is start in port : " + port);
Socket socket = null;
TimeServerHandlerExecutePool singleExecutor = new TimeServerHandlerExecutePool(50,
10000);// 创建IO任务线程池
while (true) {
// 阻塞在accept()
socket = server.accept();
// 使用多线程运行服务端受理到的Socket
singleExecutor.execute(new TimeServerHandler(socket));
}
} finally {
if (server != null) {
System.out.println("The time server close");
server.close();
server = null;
}
}
}
}
|
package com.imooc.flink.basic;
import java.util.Locale;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;
/**
* @author Galaxy
* @since 2022/2/21 0:02
*/
public class BatchWcApp {
public static void main(String[] args) throws Exception {
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
DataSource<String> dataSource = env.readTextFile("data/wc.data");
dataSource.flatMap(new FlatMapFunction<String, String>() {
@Override
public void flatMap(String value, Collector<String> collector) throws Exception {
String[] words = value.split(",");
for (String word : words) {
collector.collect(word.toLowerCase(Locale.ROOT).trim());
}
}
}).filter(new FilterFunction<String>() {
@Override
public boolean filter(String value) throws Exception {
return StringUtils.isNotEmpty(value);
}
}).map(new MapFunction<String, Tuple2<String, Integer>>() {
@Override
public Tuple2<String, Integer> map(String value) throws Exception {
return new Tuple2<>(value, 1);
}
}).groupBy(0).sum(1).print();
}
}
|
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*/
package com.microsoft.azure.toolkit.intellij.function;
import com.intellij.openapi.project.Project;
import com.microsoft.azure.management.appservice.WebAppBase;
import com.microsoft.azure.toolkit.intellij.webapp.WebAppBasePropertyView;
import com.microsoft.azuretools.core.mvp.model.function.AzureFunctionMvpModel;
import com.microsoft.tooling.msservices.serviceexplorer.azure.webapp.base.WebAppBasePropertyViewPresenter;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
public class FunctionAppPropertyView extends WebAppBasePropertyView {
private static final String ID = "com.microsoft.azure.toolkit.intellij.function.FunctionAppPropertyView";
public static WebAppBasePropertyView create(@NotNull final Project project, @NotNull final String sid,
@NotNull final String webAppId) {
final FunctionAppPropertyView view = new FunctionAppPropertyView(project, sid, webAppId);
view.onLoadWebAppProperty(sid, webAppId, null);
return view;
}
protected FunctionAppPropertyView(@NotNull Project project, @NotNull String sid, @NotNull String resId) {
super(project, sid, resId, null);
}
@Override
protected String getId() {
return ID;
}
@Override
protected WebAppBasePropertyViewPresenter createPresenter() {
return new WebAppBasePropertyViewPresenter() {
@Override
protected WebAppBase getWebAppBase(String subscriptionId, String functionAppId, String name) throws IOException {
return AzureFunctionMvpModel.getInstance().getFunctionById(subscriptionId, functionAppId);
}
@Override
protected void updateAppSettings(String subscriptionId, String functionAppId, String name, Map toUpdate, Set toRemove)
throws IOException {
AzureFunctionMvpModel.getInstance().updateWebAppSettings(subscriptionId, functionAppId, toUpdate, toRemove);
}
@Override
protected boolean getPublishingProfile(String subscriptionId, String functionAppId, String name, String filePath)
throws IOException {
return AzureFunctionMvpModel.getInstance().getPublishingProfileXmlWithSecrets(subscriptionId, functionAppId, filePath);
}
};
}
}
|
package meet_eat.server.service;
import meet_eat.data.entity.Entity;
import meet_eat.data.entity.Reportable;
import meet_eat.data.entity.relation.Report;
import meet_eat.data.entity.user.User;
public class ReportServiceTest extends EntityRelationServiceTest<ReportService, Report, User, Entity<?>, String> {
@Override
protected User getSourceEntity() {
return getBasicUserPersistent();
}
@Override
protected Entity<?> getTargetEntity() {
return getBasicUserPersistent();
}
@Override
protected Report createDistinctTestEntity(User source, Entity<?> target) {
return new Report(source, (Entity<?> & Reportable) target, "JUnit Test Report");
}
}
|
package hr.fer.oop.task4;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;
import javax.swing.SwingWorker;
class StringWorker extends SwingWorker<Integer, String> {
private final List<String> slowList;
private final String delimiter;
private Consumer<List<String>> chunksProcessor;
private Consumer<Integer> onDone;
public StringWorker(List<String> slowList, String delimiter, Consumer<List<String>> chunksProcessor,
Consumer<Integer> onDone) {
this.slowList = slowList;
this.delimiter = delimiter;
this.chunksProcessor = chunksProcessor;
this.onDone = onDone;
}
@Override
protected Integer doInBackground() throws Exception {
int count = 0;
for (String item : slowList) {
List<String> splitParts = Arrays.asList(item.split(delimiter));
count += splitParts.size();
// publish intermediate results:
for (String splitPart : splitParts) {
publish(splitPart);
}
}
return count;
}
@Override
protected void process(List<String> chunks) {
chunksProcessor.accept(chunks);
}
@Override
protected void done() {
try {
onDone.accept(get());
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package com.winster.thirdpartyserver.utils;
import org.apache.commons.lang.StringUtils;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
@Component("desencrypt")
public class MyStringEncryptor implements StringEncryptor {
@Resource
private EncryptDecrypt encryptDecrypt;
@Override
public String encrypt(String message) {
if (StringUtils.isNotBlank(message)) {
try {
message = encryptDecrypt.encrypt(message);
} catch (Exception e) {
e.printStackTrace();
}
}
return message;
}
@Override
public String decrypt(String encryptedMessage) {
if (StringUtils.isNotBlank(encryptedMessage)) {
try {
encryptedMessage = encryptDecrypt.decrypt(encryptedMessage);
} catch (Exception e) {
e.printStackTrace();
}
}
return encryptedMessage;
}
}
|
package br.com.mblabs.facebookeasy.app;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import java.util.Arrays;
import java.util.List;
import br.com.mblabs.facebookeasy.FacebookManager;
import br.com.mblabs.facebookeasy.business.FacebookBO;
/**
* A login screen that offers login via email/password.
*/
public class LoginActivity extends AppCompatActivity {
private static final List<String> DUMMY_PERMISSIONS = Arrays.asList("public_profile", "user_likes", "user_birthday", "email");
private FacebookManager mFacebookManager;
/**
* A dummy authentication store containing known user names and passwords.
* TODO: remove after connecting to a real authentication system.
*/
private static final String[] DUMMY_CREDENTIALS = new String[]{"foo@example.com:hello", "bar@example.com:world"};
// UI references.
private View mLoginFormView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFacebookManager = new FacebookManager(this, DUMMY_PERMISSIONS);
setContentView(R.layout.activity_login);
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
private void attemptLogin() {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
showButton(false);
mFacebookManager.connect(new FacebookLoginListener());
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mFacebookManager.onActivityResult(requestCode, resultCode, data);
}
private class FacebookLoginListener implements FacebookBO.AppFacebookLoginListener {
@Override
public void onFacebookSuccess(@NonNull String facebookId, @NonNull String token) {
}
@Override
public void onFacebookError() {
showButton(true);
}
@Override
public void onFacebookCancel() {
showButton(true);
}
}
/**
* Shows the progress UI and hides the login form.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showButton(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mLoginFormView.setVisibility(show ? View.VISIBLE : View.GONE);
}
}
}
|
package tk.slicecollections.maxteer.player.role;
import tk.slicecollections.maxteer.Manager;
import tk.slicecollections.maxteer.database.Database;
import tk.slicecollections.maxteer.database.cache.RoleCache;
import tk.slicecollections.maxteer.utils.StringUtils;
import javax.sql.rowset.CachedRowSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* @author Maxter
*/
public class Role {
private int id;
private String name;
private String prefix;
private String permission;
private boolean alwaysVisible;
private boolean broadcast;
public Role(String name, String prefix, String permission, boolean alwaysVisible, boolean broadcast) {
this.id = ROLES.size();
this.name = StringUtils.formatColors(name);
this.prefix = StringUtils.formatColors(prefix);
this.permission = permission;
this.alwaysVisible = alwaysVisible;
this.broadcast = broadcast;
}
public int getId() {
return this.id;
}
public String getName() {
return this.name;
}
public String getPrefix() {
return this.prefix;
}
public String getPermission() {
return this.permission;
}
public boolean isDefault() {
return this.permission.isEmpty();
}
public boolean isAlwaysVisible() {
return this.alwaysVisible;
}
public boolean isBroadcast() {
return this.broadcast;
}
public boolean has(Object player) {
return this.isDefault() || Manager.hasPermission(player, this.permission);
}
private static final List<Role> ROLES = new ArrayList<>();
public static String getPrefixed(String name) {
return getPrefixed(name, false);
}
public static String getColored(String name) {
return getColored(name, false);
}
public static String getPrefixed(String name, boolean removeFake) {
return getTaggedName(name, false, removeFake);
}
public static String getColored(String name, boolean removeFake) {
return getTaggedName(name, true, removeFake);
}
private static String getTaggedName(String name, boolean onlyColor, boolean removeFake) {
String prefix = "&7";
if (!removeFake && Manager.isFake(name)) {
prefix = Manager.getFakeRole(name).getPrefix();
if (onlyColor) {
prefix = StringUtils.getLastColor(prefix);
}
return prefix + Manager.getFake(name);
}
Object target = Manager.getPlayer(name);
if (target != null) {
prefix = getPlayerRole(target, true).getPrefix();
if (onlyColor) {
prefix = StringUtils.getLastColor(prefix);
}
return prefix + name;
}
String rs = RoleCache.isPresent(name) ? RoleCache.get(name) : Database.getInstance().getRankAndName(name);
if (rs != null) {
prefix = getRoleByName(rs.split(" : ")[0]).getPrefix();
if (onlyColor) {
prefix = StringUtils.getLastColor(prefix);
}
name = rs.split(" : ")[1];
if (!removeFake && Manager.isFake(name)) {
name = Manager.getFake(name);
}
return prefix + name;
}
return prefix + name;
}
public static Role getRoleByName(String name) {
for (Role role : ROLES) {
if (StringUtils.stripColors(role.getName()).equalsIgnoreCase(name)) {
return role;
}
}
return ROLES.get(ROLES.size() - 1);
}
public static Role getRoleByPermission(String permission) {
for (Role role : ROLES) {
if (role.getPermission().equals(permission)) {
return role;
}
}
return null;
}
public static Role getPlayerRole(Object player) {
return getPlayerRole(player, false);
}
public static Role getPlayerRole(Object player, boolean removeFake) {
if (!removeFake && Manager.isFake(Manager.getName(player))) {
return Manager.getFakeRole(Manager.getName(player));
}
for (Role role : ROLES) {
if (role.has(player)) {
return role;
}
}
return getLastRole();
}
public static Role getLastRole() {
return ROLES.get(ROLES.size() - 1);
}
public static List<Role> listRoles() {
return ROLES;
}
}
|
/*
* Copyright (c) 2012 - 2020 Arvato Systems GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.arvatosystems.t9t.bpmn2.be.camunda.listener;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.ExecutionListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.arvatosystems.t9t.bpmn2.be.camunda.utils.MDCHelper;
import de.jpaw.dp.Singleton;
@Singleton
public class InfoLogCurrentLocationListener implements ExecutionListener {
private static final Logger LOGGER = LoggerFactory.getLogger(InfoLogCurrentLocationListener.class);
@Override
public void notify(DelegateExecution execution) throws Exception {
if (!LOGGER.isInfoEnabled()) {
return;
}
try (AutoCloseable mdc = MDCHelper.put(execution)) {
if (EVENTNAME_TAKE.equals(execution.getEventName())) {
LOGGER.info("transition {}", execution.getCurrentTransitionId());
} else {
LOGGER.info("{} activity '{}'", execution.getEventName(), execution.getCurrentActivityName());
}
}
}
}
|
/**
* @author Roberto Maia
* @disciplina NExT - Imersão Java
* @Fundamentos if/else e switch/case
* uri1043 Triângulo
*/
import java.util.Scanner;
public class uri1043 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Double a = input.nextDouble();
Double b = input.nextDouble();
Double c = input.nextDouble();
Double perimetro = 0.0;
Double area = 0.0;
if ( (a + b) > c && (a + c) > b && (c + b) > a) {
perimetro = a + b + c;
System.out.println("Perimetro = " + String.format("%.1f", perimetro).replaceAll(",", "."));
} else {
area = (((a+b) * c) / 2);
System.out.println("Area = " + String.format("%.1f", area).replaceAll(",", "."));
}
input.close();
}
}
|
/**
*
*/
package net.osmand.plus.activities.search;
import java.util.ArrayList;
import java.util.List;
import net.osmand.access.AccessibleToast;
import net.osmand.osm.LatLon;
import net.osmand.plus.NameFinderPoiFilter;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.PoiFilter;
import net.osmand.plus.PoiFiltersHelper;
import net.osmand.plus.R;
import net.osmand.plus.ResourceManager;
import net.osmand.plus.SearchByNameFilter;
import net.osmand.plus.activities.EditPOIFilterActivity;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
/**
* @author Maxim Frolov
*
*/
public class SearchPoiFilterActivity extends ListActivity {
public static final String SEARCH_LAT = SearchActivity.SEARCH_LAT;
public static final String SEARCH_LON = SearchActivity.SEARCH_LON;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.searchpoilist);
// ListActivity has a ListView, which you can get with:
ListView lv = getListView();
// Then you can create a listener like so:
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) {
PoiFilter poi = ((AmenityAdapter) getListAdapter()).getItem(pos);
if(!poi.isStandardFilter() || poi.getFilterId().equals(PoiFilter.CUSTOM_FILTER_ID)) {
showEditActivity(poi);
return true;
}
return false;
}
});
}
@Override
protected void onResume() {
super.onResume();
PoiFiltersHelper poiFilters = ((OsmandApplication)getApplication()).getPoiFilters();
List<PoiFilter> filters = new ArrayList<PoiFilter>(poiFilters.getUserDefinedPoiFilters()) ;
filters.addAll(poiFilters.getOsmDefinedPoiFilters());
filters.add(poiFilters.getNameFinderPOIFilter());
setListAdapter(new AmenityAdapter(filters));
}
private void updateIntentToLaunch(Intent intentToLaunch){
LatLon loc = null;
boolean searchAround = false;
Intent intent = getIntent();
if(intent != null){
double lat = intent.getDoubleExtra(SEARCH_LAT, 0);
double lon = intent.getDoubleExtra(SEARCH_LON, 0);
if(lat != 0 || lon != 0){
loc = new LatLon(lat, lon);
}
}
if (loc == null && getParent() instanceof SearchActivity) {
loc = ((SearchActivity) getParent()).getSearchPoint();
searchAround = ((SearchActivity) getParent()).isSearchAroundCurrentLocation();
}
if (loc == null && !searchAround) {
loc = ((OsmandApplication) getApplication()).getSettings().getLastKnownMapLocation();
}
if(loc != null && !searchAround) {
intentToLaunch.putExtra(SearchActivity.SEARCH_LAT, loc.getLatitude());
intentToLaunch.putExtra(SearchActivity.SEARCH_LON, loc.getLongitude());
}
}
private void showEditActivity(PoiFilter poi) {
Intent newIntent = new Intent(SearchPoiFilterActivity.this, EditPOIFilterActivity.class);
// folder selected
newIntent.putExtra(EditPOIFilterActivity.AMENITY_FILTER, poi.getFilterId());
updateIntentToLaunch(newIntent);
startActivityForResult(newIntent, 0);
}
@Override
public void onListItemClick(ListView parent, View v, int position, long id) {
final PoiFilter filter = ((AmenityAdapter) getListAdapter()).getItem(position);
if (filter.getFilterId().equals(PoiFilter.CUSTOM_FILTER_ID)) {
filter.clearFilter();
showEditActivity(filter);
return;
}
if(!(filter instanceof NameFinderPoiFilter)){
ResourceManager rm = ((OsmandApplication) getApplication()).getResourceManager();
if(!rm.containsAmenityRepositoryToSearch(filter instanceof SearchByNameFilter)){
AccessibleToast.makeText(this, R.string.data_to_search_poi_not_available, Toast.LENGTH_LONG);
return;
}
}
final Intent newIntent = new Intent(SearchPoiFilterActivity.this, SearchPOIActivity.class);
newIntent.putExtra(SearchPOIActivity.AMENITY_FILTER, filter.getFilterId());
updateIntentToLaunch(newIntent);
startActivityForResult(newIntent, 0);
}
class AmenityAdapter extends ArrayAdapter<PoiFilter> {
AmenityAdapter(List<PoiFilter> list) {
super(SearchPoiFilterActivity.this, R.layout.searchpoifolder_list, list);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if(row == null) {
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.searchpoifolder_list, parent, false);
}
TextView label = (TextView) row.findViewById(R.id.folder_label);
ImageView icon = (ImageView) row.findViewById(R.id.folder_icon);
final PoiFilter model = getItem(position);
label.setText(model.getName());
if(model.getFilterId().equals(PoiFilter.CUSTOM_FILTER_ID)) {
icon.setImageResource(android.R.drawable.ic_input_get);
} else if (model.getFilterId().equals(PoiFilter.BY_NAME_FILTER_ID)) {
//label.setTypeface(Typeface.DEFAULT, Typeface.ITALIC);
icon.setImageResource(android.R.drawable.ic_search_category_default);
} else {
// label.setTypeface(Typeface.DEFAULT);
icon.setImageResource(model.isStandardFilter() ? R.drawable.folder : R.drawable.tab_icon_favourite_menu);
}
ImageView editIcon = (ImageView) row.findViewById(R.id.folder_edit_icon);
if (model.isStandardFilter()) {
editIcon.setVisibility(View.GONE);
} else {
editIcon.setVisibility(View.VISIBLE);
}
editIcon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showEditActivity(model);
}
});
return (row);
}
}
}
|
/*
* Copyright 2014-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.dbflute.logic.jdbc.schemadiff;
import java.util.Map;
/**
* @author jflute
* @since 0.9.7.1 (2010/06/06 Sunday)
*/
public class DfForeignKeyDiff extends DfConstraintDiff {
// ===================================================================================
// Attribute
// =========
// -----------------------------------------------------
// Diff Item
// ---------
protected DfNextPreviousDiff _foreignTableDiff;
{
_nextPreviousItemList.add(new NextPreviousHandlerBase() {
public String titleName() {
return "FK Table";
}
public String propertyName() {
return "foreignTableDiff";
}
public DfNextPreviousDiff provide() {
return _foreignTableDiff;
}
public void restore(Map<String, Object> foreignKeyDiffMap) {
_foreignTableDiff = restoreNextPreviousDiff(foreignKeyDiffMap, propertyName());
}
});
}
// ===================================================================================
// Constructor
// ===========
protected DfForeignKeyDiff(String columnName, DfDiffType diffType) {
super(columnName, diffType);
}
protected DfForeignKeyDiff(Map<String, Object> foreignKeyDiffMap) {
super(foreignKeyDiffMap);
}
public static DfForeignKeyDiff createAdded(String constraintName) {
return new DfForeignKeyDiff(constraintName, DfDiffType.ADD);
}
public static DfForeignKeyDiff createChanged(String constraintName) {
return new DfForeignKeyDiff(constraintName, DfDiffType.CHANGE);
}
public static DfForeignKeyDiff createDeleted(String constraintName) {
return new DfForeignKeyDiff(constraintName, DfDiffType.DELETE);
}
public static DfForeignKeyDiff createFromDiffMap(Map<String, Object> columnDiffMap) {
return new DfForeignKeyDiff(columnDiffMap);
}
// ===================================================================================
// Accessor
// ========
// -----------------------------------------------------
// Diff Item
// ---------
public boolean hasForeignTableDiff() {
return _foreignTableDiff != null;
}
public DfNextPreviousDiff getForeignTableDiff() {
return _foreignTableDiff;
}
public void setForeignTableDiff(DfNextPreviousDiff foreignTableDiff) {
_foreignTableDiff = foreignTableDiff;
}
}
|
package com.hyq0719.mktapi.oceanengine.bean.ad;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import lombok.Data;
import java.util.List;
@Data
public class AudienceStruct {
@SerializedName("auto_extend_enabled")
private Long autoExtendEnabled = null;
@SerializedName("interest_tags")
private List<Long> interestTags = null;
@SerializedName("aweme_fan_time_scope")
private String awemeFanTimeScope = null;
@SerializedName("auto_extend_targets")
private List<String> autoExtendTargets = null;
@SerializedName("gender")
private String gender = null;
@SerializedName("city")
private List<Long> city = null;
@SerializedName("filter_own_aweme_fans")
private Long filterOwnAwemeFans = null;
@SerializedName("app_behavior_target")
private String appBehaviorTarget = null;
@SerializedName("ad_tag")
private List<Long> adTag = null;
@SerializedName("device_type")
private List<String> deviceType = null;
@SerializedName("platform")
private List<String> platform = null;
@SerializedName("exclude_flow_package")
private List<Long> excludeFlowPackage = null;
@SerializedName("business_ids")
private List<Long> businessIds = null;
@SerializedName("aweme_fan_behaviors")
private List<String> awemeFanBehaviors = null;
@SerializedName("activate_type")
private List<String> activateType = null;
@SerializedName("launch_price")
private List<Long> launchPrice = null;
@SerializedName("action")
private ActionStruct actionStruct = null;
@SerializedName("retargeting_tags_exclude")
private List<Long> retargetingTagsExclude = null;
@SerializedName("aweme_fan_accounts")
private List<Long> awemeFanAccounts = null;
@SerializedName("interest_categories")
private List<Long> interestCategories = null;
@SerializedName("interest_words")
private List<Long> interestWords = null;
@SerializedName("aweme_fan_categories")
private List<Long> awemeFanCategories = null;
@SerializedName("aweme_fans_numbers")
private List<Long> awemeFansNumbers = null;
@SerializedName("article_category")
private List<String> articleCategory = null;
@SerializedName("ac")
private List<String> ac = null;
@SerializedName("android_osv")
private String androidOsv = null;
@SerializedName("app_ids")
private List<Long> appIds = null;
@SerializedName("flow_package")
private List<Long> flowPackage = null;
@SerializedName("location_type")
private String locationType = null;
@SerializedName("carrier")
private List<String> carrier = null;
@SerializedName("retargeting_tags_include")
private List<Long> retargetingTagsInclude = null;
@SerializedName("superior_popularity_type")
private String superiorPopularityType = null;
@SerializedName("device_brand")
private List<String> deviceBrand = null;
@SerializedName("district")
private String district = null;
@SerializedName("filter_aweme_fans_count")
private Long filterAwemeFansCount = null;
@SerializedName("ios_osv")
private String iosOsv = null;
@SerializedName("app_category")
private List<Long> appCategory = null;
@SerializedName("interest_action_mode")
private String interestActionMode = null;
@SerializedName("age")
private List<String> age = null;
@SerializedName("geolocation")
private List<GeolocationStruct> geolocationStruct = null;
@SerializedName("filter_aweme_abnormal_active")
private Long filterAwemeAbnormalActive = null;
public AudienceStruct autoExtendEnabled(Long autoExtendEnabled) {
this.autoExtendEnabled = autoExtendEnabled;
return this;
}
public AudienceStruct interestTags(List<Long> interestTags) {
this.interestTags = interestTags;
return this;
}
public AudienceStruct awemeFanTimeScope(String awemeFanTimeScope) {
this.awemeFanTimeScope = awemeFanTimeScope;
return this;
}
public AudienceStruct autoExtendTargets(List<String> autoExtendTargets) {
this.autoExtendTargets = autoExtendTargets;
return this;
}
public AudienceStruct gender(String gender) {
this.gender = gender;
return this;
}
public AudienceStruct city(List<Long> city) {
this.city = city;
return this;
}
public AudienceStruct filterOwnAwemeFans(Long filterOwnAwemeFans) {
this.filterOwnAwemeFans = filterOwnAwemeFans;
return this;
}
public AudienceStruct appBehaviorTarget(String appBehaviorTarget) {
this.appBehaviorTarget = appBehaviorTarget;
return this;
}
public AudienceStruct adTag(List<Long> adTag) {
this.adTag = adTag;
return this;
}
public AudienceStruct deviceType(List<String> deviceType) {
this.deviceType = deviceType;
return this;
}
public AudienceStruct platform(List<String> platform) {
this.platform = platform;
return this;
}
public AudienceStruct excludeFlowPackage(List<Long> excludeFlowPackage) {
this.excludeFlowPackage = excludeFlowPackage;
return this;
}
public AudienceStruct businessIds(List<Long> businessIds) {
this.businessIds = businessIds;
return this;
}
public AudienceStruct awemeFanBehaviors(List<String> awemeFanBehaviors) {
this.awemeFanBehaviors = awemeFanBehaviors;
return this;
}
public AudienceStruct activateType(List<String> activateType) {
this.activateType = activateType;
return this;
}
public AudienceStruct launchPrice(List<Long> launchPrice) {
this.launchPrice = launchPrice;
return this;
}
public AudienceStruct action(ActionStruct actionStruct) {
this.actionStruct = actionStruct;
return this;
}
public AudienceStruct retargetingTagsExclude(List<Long> retargetingTagsExclude) {
this.retargetingTagsExclude = retargetingTagsExclude;
return this;
}
public AudienceStruct awemeFanAccounts(List<Long> awemeFanAccounts) {
this.awemeFanAccounts = awemeFanAccounts;
return this;
}
public AudienceStruct interestCategories(List<Long> interestCategories) {
this.interestCategories = interestCategories;
return this;
}
public AudienceStruct interestWords(List<Long> interestWords) {
this.interestWords = interestWords;
return this;
}
public AudienceStruct awemeFanCategories(List<Long> awemeFanCategories) {
this.awemeFanCategories = awemeFanCategories;
return this;
}
public AudienceStruct awemeFansNumbers(List<Long> awemeFansNumbers) {
this.awemeFansNumbers = awemeFansNumbers;
return this;
}
public AudienceStruct articleCategory(List<String> articleCategory) {
this.articleCategory = articleCategory;
return this;
}
public AudienceStruct ac(List<String> ac) {
this.ac = ac;
return this;
}
public AudienceStruct androidOsv(String androidOsv) {
this.androidOsv = androidOsv;
return this;
}
public AudienceStruct appIds(List<Long> appIds) {
this.appIds = appIds;
return this;
}
public AudienceStruct flowPackage(List<Long> flowPackage) {
this.flowPackage = flowPackage;
return this;
}
public AudienceStruct locationType(String locationType) {
this.locationType = locationType;
return this;
}
public AudienceStruct carrier(List<String> carrier) {
this.carrier = carrier;
return this;
}
public AudienceStruct retargetingTagsInclude(List<Long> retargetingTagsInclude) {
this.retargetingTagsInclude = retargetingTagsInclude;
return this;
}
public AudienceStruct superiorPopularityType(String superiorPopularityType) {
this.superiorPopularityType = superiorPopularityType;
return this;
}
public AudienceStruct deviceBrand(List<String> deviceBrand) {
this.deviceBrand = deviceBrand;
return this;
}
public AudienceStruct district(String district) {
this.district = district;
return this;
}
public AudienceStruct filterAwemeFansCount(Long filterAwemeFansCount) {
this.filterAwemeFansCount = filterAwemeFansCount;
return this;
}
public AudienceStruct iosOsv(String iosOsv) {
this.iosOsv = iosOsv;
return this;
}
public AudienceStruct appCategory(List<Long> appCategory) {
this.appCategory = appCategory;
return this;
}
public AudienceStruct interestActionMode(String interestActionMode) {
this.interestActionMode = interestActionMode;
return this;
}
public AudienceStruct age(List<String> age) {
this.age = age;
return this;
}
public AudienceStruct geolocation(List<GeolocationStruct> geolocationStruct) {
this.geolocationStruct = geolocationStruct;
return this;
}
public AudienceStruct filterAwemeAbnormalActive(Long filterAwemeAbnormalActive) {
this.filterAwemeAbnormalActive = filterAwemeAbnormalActive;
return this;
}
@Override
public String toString() {
Gson gson = new Gson();
return gson.toJson(this);
}
/**
* Convert the given object to string with each line indented by 4 spaces (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
package com.michelin.ns4kafka.repositories;
import com.michelin.ns4kafka.models.AccessControlEntry;
import java.util.Collection;
import java.util.Optional;
public interface AccessControlEntryRepository {
Collection<AccessControlEntry> findAll();
Optional<AccessControlEntry> findByName(String namespace, String name);
AccessControlEntry create(AccessControlEntry accessControlEntry);
void delete(AccessControlEntry accessControlEntry);
}
|
package smash.app.tweets.importer;
import junit.framework.TestCase;
import smash.data.tweets.pojo.Tweet;
/**
* Created by Yikai Gong on 10/04/17.
*/
public class TweetsImporterTest extends TestCase {
public static final String dummyTweetStr = "{" +
"\"id_str\":\"508093847138619392\"," +
"\"created_at\":\"Sat Sep 06 03:26:27 +0000 2014\"," +
"\"coordinates\":{" +
"\"type\":\"Point\"," +
"\"coordinates\":[144.97145176999998739,-37.807908040000000938]}," +
"\"text\":\"Beautiful day :)\"," +
"\"user\":{" +
"\"screen_name\":\"khangiie\"}," +
"\"lang\":\"en\"}";
public static final String dummyTweetStr2 = "{\"id_str\":\"" +
"819879957954445312\",\"text\":\"▷ take my gear to discover " +
"something new\uD83C\uDF0C\uD83C\uDF0F\\n\\n#Melbourne \\n#gear" +
" \\n_\\n#Australia #japanese… https://t.co/aMLIYx2NZd\",\"coordinates\"" +
":{\"type\":\"Point\",\"coordinates\":[144.96138889,-37.82055556]}," +
"\"created_at\":\"Fri Jan 13 12:13:09 +0000 2017\",\"user\":{" +
"\"screen_name\":\"MihoHariu\"},\"lang\":\"en\"}";
public static final String expectedJson = "{\"id_str\":\"508093847138619392" +
"\",\"text\":\"Beautiful day :)\",\"coordinates\":{\"type\":\"Point\"" +
",\"coordinates\":[144.97145176999998739,-37.807908040000000938]}," +
"\"created_at\":\"Sat Sep 06 03:26:27 +0000 2014\",\"user\":{\"" +
"screen_name\":\"khangiie\"},\"lang\":\"en\",\"tokens\":[\"beautiful\"," +
"\"day\"],\"sentiment\":1}";
public void testProcessTweet() throws Exception {
Tweet dummy = Tweet.fromJSON(dummyTweetStr);
dummy = TweetsImporter.processTweet(dummy);
System.out.println(dummy.toJSON());
assertEquals(dummy.toJSON(), expectedJson);
Tweet dummy2 = Tweet.fromJSON(dummyTweetStr2);
dummy2 = TweetsImporter.processTweet(dummy2);
System.out.println(dummy2.toJSON());
}
}
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.fresco.vito.core.impl.debug;
import android.graphics.Color;
import android.graphics.Rect;
import com.facebook.common.internal.Supplier;
import com.facebook.fresco.ui.common.ControllerListener2;
import com.facebook.fresco.vito.core.FrescoDrawable2;
import com.facebook.fresco.vito.core.VitoImageRequest;
import com.facebook.fresco.vito.core.impl.VitoUtils;
import com.facebook.infer.annotation.Nullsafe;
import java.util.Locale;
import java.util.Map;
import javax.annotation.Nullable;
@Nullsafe(Nullsafe.Mode.STRICT)
public class DefaultDebugOverlayFactory2 extends BaseDebugOverlayFactory2 {
public DefaultDebugOverlayFactory2(Supplier<Boolean> debugOverlayEnabled) {
super(debugOverlayEnabled);
}
@Override
protected void setData(
DebugOverlayDrawable overlay,
FrescoDrawable2 drawable,
@Nullable ControllerListener2.Extras extras) {
setBasicData(overlay, drawable);
setImageRequestData(overlay, drawable.getImageRequest());
setImageOriginData(overlay, extras);
}
private static void setBasicData(DebugOverlayDrawable overlay, FrescoDrawable2 drawable) {
overlay.addDebugData("ID", VitoUtils.getStringId(drawable.getImageId()));
Rect bounds = drawable.getBounds();
overlay.addDebugData("D", formatDimensions(bounds.width(), bounds.height()));
overlay.addDebugData(
"I", formatDimensions(drawable.getActualImageWidthPx(), drawable.getActualImageHeightPx()));
}
private static void setImageOriginData(
DebugOverlayDrawable overlay, @Nullable ControllerListener2.Extras extras) {
String origin = "unknown";
String originSubcategory = "unknown";
if (extras != null) {
Map<String, Object> originExtras = extras.datasourceExtras;
if (originExtras == null) {
// We did not receive data source extras, so the image did not come from the image pipeline
// but from the bitmap memory cache shortcut
originExtras = extras.shortcutExtras;
}
if (originExtras != null) {
origin = String.valueOf(originExtras.get("origin"));
originSubcategory = String.valueOf(originExtras.get("origin_sub"));
}
}
overlay.addDebugData(
"origin", origin, DebugOverlayImageOriginColor.getImageOriginColor(origin));
overlay.addDebugData("origin_sub", originSubcategory, Color.GRAY);
}
private static void setImageRequestData(
DebugOverlayDrawable overlay, @Nullable VitoImageRequest imageRequest) {
if (imageRequest == null) {
return;
}
overlay.addDebugData(
"scale", String.valueOf(imageRequest.imageOptions.getActualImageScaleType()));
}
protected static String formatDimensions(int width, int height) {
return String.format(Locale.US, "%dx%d", width, height);
}
}
|
package com.example.viewtest;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.media.*;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.ListViewCompat;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ListView listView;
private int index;
private int totalCount;
private ArrayList<Image> images=new ArrayList<Image>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=(ListView)findViewById(R.id.list);
initdata();
ImageAdapter imageAdapter=new ImageAdapter(MainActivity.this,R.layout.item,images);
listView.setAdapter(imageAdapter);
}
private void initdata() {
Context context = MainActivity.this;
ContentResolver contentResolver = context.getContentResolver();
Cursor cursor = contentResolver.query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, null, null, null, null);
totalCount = cursor.getCount();
cursor.moveToFirst();
for (int i = 0; i < totalCount; i++) {
int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.DATA);
String id = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.IMAGE_ID));
String src = cursor.getString(index);
Image image = new Image(src, id);
images.add(image);
index = i;
cursor.moveToNext();
}
}
}
|
package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 申请单进度列表
*
* @author auto create
* @since 1.0, 2018-06-25 14:49:09
*/
public class EcoApplySchedule extends AlipayObject {
private static final long serialVersionUID = 2251319762132891276L;
/**
* 批语
*/
@ApiField("audit_comment")
private String auditComment;
/**
* 审批时间(yyyy-MM-dd HH:mm:ss)
*/
@ApiField("audit_time")
private String auditTime;
/**
* 编辑标识:0-不可编辑,1-可编辑,2-需重新提交。
*/
@ApiField("edit_flag")
private Long editFlag;
/**
* 申请单号
*/
@ApiField("order_no")
private String orderNo;
/**
* 审批顺序
*/
@ApiField("order_num")
private Long orderNum;
/**
* 审批阶段状态编码如(1,2,3)
*/
@ApiField("status")
private String status;
/**
* 审批阶段状态描述(审核中,通过,拒绝)
*/
@ApiField("status_desc")
private String statusDesc;
/**
* 审批阶段编码
*/
@ApiField("step")
private String step;
/**
* 审批阶段描述如:初审,提交材料,市局审批,受理中心
*/
@ApiField("step_desc")
private String stepDesc;
public String getAuditComment() {
return this.auditComment;
}
public void setAuditComment(String auditComment) {
this.auditComment = auditComment;
}
public String getAuditTime() {
return this.auditTime;
}
public void setAuditTime(String auditTime) {
this.auditTime = auditTime;
}
public Long getEditFlag() {
return this.editFlag;
}
public void setEditFlag(Long editFlag) {
this.editFlag = editFlag;
}
public String getOrderNo() {
return this.orderNo;
}
public void setOrderNo(String orderNo) {
this.orderNo = orderNo;
}
public Long getOrderNum() {
return this.orderNum;
}
public void setOrderNum(Long orderNum) {
this.orderNum = orderNum;
}
public String getStatus() {
return this.status;
}
public void setStatus(String status) {
this.status = status;
}
public String getStatusDesc() {
return this.statusDesc;
}
public void setStatusDesc(String statusDesc) {
this.statusDesc = statusDesc;
}
public String getStep() {
return this.step;
}
public void setStep(String step) {
this.step = step;
}
public String getStepDesc() {
return this.stepDesc;
}
public void setStepDesc(String stepDesc) {
this.stepDesc = stepDesc;
}
}
|
package poo.slide8.ClasseAbstrataInterface;
public interface SegundaInterface {
String nome = "Maria";
}
|
/*
Copyright 2015 Google 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.google.security.zynamics.reil.algorithms.mono2.common.instructiongraph.interfaces;
/**
* The IInstructionGraph interface which is to be implemented for a sane implementation of an
* instruction graph.
*/
public interface IInstructionGraph {
/**
* Returns the destination of the instruction graph edge.
*
* @param edge The instruction graph edge where the destination node is determined.
* @return The destination node of the instruction graph edge.
*/
public IInstructionGraphNode getDestination(IInstructionGraphEdge edge);
/**
* Returns the entry node of the instruction graph.
*
* @return The entry node of the instruction graph.
*/
public IInstructionGraphNode getEntryNode();
/**
* Returns the exit node of the instruction graph.
*
* @return The exit node of the instruction graph.
*/
public IInstructionGraphNode getExitNode();
/**
* Returns the incoming edges of an instruction graph node.
*
* @param node The instruction graph node to which the edges point to.
* @return The edges incoming to the the instruction graph node.
*/
public Iterable<IInstructionGraphEdge> getIncomingEdges(IInstructionGraphNode node);
/**
* Returns the outgoing edges of an instruction graph node.
*
* @param node The instruction graph node from which the edges originate.
* @return All edges outgoing from the instruction graph node.
*/
public Iterable<IInstructionGraphEdge> getOutgoingEdges(IInstructionGraphNode node);
/**
* Returns the source node of the instruction graph edge.
*
* @param edge The instruction graph edge where the source node is determined.
* @return The source node of the instruction graph edge.
*/
public IInstructionGraphNode getSource(IInstructionGraphEdge edge);
}
|
package com.xiecc.seeWeather.modules.db;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.xiecc.seeWeather.modules.domain.City;
import com.xiecc.seeWeather.modules.domain.Province;
import java.util.ArrayList;
import java.util.List;
/**
* Created by hugo on 2015/9/30 0030.
* 封装数据库操作
*/
public class WeatherDB {
private Context context;
public WeatherDB(Context context) {
this.context = context;
}
public List<Province> loadProvinces(SQLiteDatabase db) {
List<Province> list = new ArrayList<>();
Cursor cursor = db.query("T_Province", null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
Province province = new Province();
province.setProSort(cursor.getInt(cursor.getColumnIndex("ProSort")));
province.setProName(cursor.getString(cursor.getColumnIndex("ProName")));
list.add(province);
} while (cursor.moveToNext());
}
cursor.close();
return list;
}
public List<City> loadCities(SQLiteDatabase db, int ProID) {
List<City> list = new ArrayList<>();
Cursor cursor = db.query("T_City", null, "ProID = ?", new String[] { String.valueOf(ProID) }, null, null, null);
if (cursor.moveToFirst()) {
do {
City city = new City();
city.setCityName(cursor.getString(cursor.getColumnIndex("CityName")));
city.setProID(ProID);
list.add(city);
} while (cursor.moveToNext());
}
cursor.close();
return list;
}
}
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.versioning;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.test.ElasticsearchIntegrationTest;
import org.junit.Test;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
/**
*
*/
public class ConcurrentDocumentOperationTests extends ElasticsearchIntegrationTest {
@Test
public void concurrentOperationOnSameDocTest() throws Exception {
logger.info("--> create an index with 1 shard and max replicas based on nodes");
assertAcked(prepareCreate("test")
.setSettings(settingsBuilder().put(indexSettings()).put("index.number_of_shards", 1)));
logger.info("execute concurrent updates on the same doc");
int numberOfUpdates = 100;
final AtomicReference<Throwable> failure = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(numberOfUpdates);
for (int i = 0; i < numberOfUpdates; i++) {
client().prepareIndex("test", "type1", "1").setSource("field1", i).execute(new ActionListener<IndexResponse>() {
@Override
public void onResponse(IndexResponse response) {
latch.countDown();
}
@Override
public void onFailure(Throwable e) {
e.printStackTrace();
failure.set(e);
latch.countDown();
}
});
}
latch.await();
assertThat(failure.get(), nullValue());
client().admin().indices().prepareRefresh().execute().actionGet();
logger.info("done indexing, check all have the same field value");
Map masterSource = client().prepareGet("test", "type1", "1").execute().actionGet().getSourceAsMap();
for (int i = 0; i < (immutableCluster().size() * 5); i++) {
assertThat(client().prepareGet("test", "type1", "1").execute().actionGet().getSourceAsMap(), equalTo(masterSource));
}
}
}
|
package unit.com.bitdubai.fermat_cry_plugin.layer.crypto_vault.developer.bitdubai.version_1.structure.CryptoVaultDatabaseFactory;
import com.bitdubai.fermat_api.layer.osa_android.database_system.Database;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseFactory;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTable;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableFactory;
import com.bitdubai.fermat_api.layer.osa_android.database_system.PluginDatabaseSystem;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantCreateDatabaseException;
import com.bitdubai.fermat_cry_plugin.layer.crypto_vault.developer.bitdubai.version_1.structure.CryptoVaultDatabaseFactory;
import junit.framework.TestCase;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.UUID;
import static com.googlecode.catchexception.CatchException.catchException;
import static com.googlecode.catchexception.CatchException.caughtException;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when;
/**
* Created by natalia on 26/08/15.
*/
@RunWith(MockitoJUnitRunner.class)
public class CreateDatabaseTest extends TestCase {
@Mock
private PluginDatabaseSystem mockPluginDatabaseSystem;
@Mock
private Database mockDatabase;
@Mock
private DatabaseFactory mockDatabaseFactory;
@Mock
private DatabaseTable mockTable;
@Mock
private DatabaseTableFactory mockTableFactory;
private UUID testOwnerId;
private String deviceUserPublicKey;
private CryptoVaultDatabaseFactory testDatabaseFactory;
private void setUpIds(){
testOwnerId = UUID.randomUUID();
deviceUserPublicKey = UUID.randomUUID().toString();
}
private void setUpMockitoGeneralRules() throws Exception{
when(mockPluginDatabaseSystem.createDatabase(testOwnerId, deviceUserPublicKey)).thenReturn(mockDatabase);
when(mockDatabase.getDatabaseFactory()).thenReturn(mockDatabaseFactory);
when(mockDatabaseFactory.newTableFactory(anyString())).thenReturn(mockTableFactory);
}
@Before
public void setUp() throws Exception{
setUpIds();
setUpMockitoGeneralRules();
}
@Test
public void CreateDatabase_DatabaseAndTablesProperlyCreated_ReturnsDatabase() throws Exception{
testDatabaseFactory = new CryptoVaultDatabaseFactory();
testDatabaseFactory.setPluginDatabaseSystem(mockPluginDatabaseSystem);
Database checkDatabase = testDatabaseFactory.createDatabase(testOwnerId, deviceUserPublicKey);
assertThat(checkDatabase).isEqualTo(mockDatabase);
}
@Test
public void CreateDatabase_PluginSystemCantCreateDatabase_ThrowsCantCreateDatabaseException() throws Exception{
when(mockPluginDatabaseSystem.createDatabase(testOwnerId, deviceUserPublicKey)).thenThrow(new CantCreateDatabaseException("MOCK", null, null, null));
testDatabaseFactory = new CryptoVaultDatabaseFactory();
testDatabaseFactory.setPluginDatabaseSystem(mockPluginDatabaseSystem);
catchException(testDatabaseFactory).createDatabase(testOwnerId, deviceUserPublicKey);
assertThat(caughtException())
.isNotNull()
.isInstanceOf(CantCreateDatabaseException.class);
}
@Test
public void CreateDatabase_CantCreateTables_ThrowsCantCreateDatabaseException() throws Exception{
when(mockDatabaseFactory.newTableFactory(anyString())).thenReturn(null);
testDatabaseFactory = new CryptoVaultDatabaseFactory();
testDatabaseFactory.setPluginDatabaseSystem(mockPluginDatabaseSystem);
catchException(testDatabaseFactory).createDatabase(testOwnerId, deviceUserPublicKey);
assertThat(caughtException())
.isNotNull()
.isInstanceOf(CantCreateDatabaseException.class);
}
@Test
public void CreateDatabase_ConflictedIdWhenCreatingTables_ThrowsCantCreateDatabaseException() throws Exception{
when(mockDatabaseFactory.newTableFactory(anyString())).thenReturn(null);
testDatabaseFactory = new CryptoVaultDatabaseFactory();
testDatabaseFactory.setPluginDatabaseSystem(mockPluginDatabaseSystem);
catchException(testDatabaseFactory).createDatabase(testOwnerId,deviceUserPublicKey);
assertThat(caughtException())
.isNotNull()
.isInstanceOf(CantCreateDatabaseException.class);
}
@Test
public void CreateDatabase_GeneralExceptionThrown_ThrowsCantCreateDatabaseException() throws Exception{
when(mockDatabase.getDatabaseFactory()).thenReturn(null);
testDatabaseFactory = new CryptoVaultDatabaseFactory();
testDatabaseFactory.setPluginDatabaseSystem(mockPluginDatabaseSystem);
catchException(testDatabaseFactory).createDatabase(testOwnerId, deviceUserPublicKey);
assertThat(caughtException())
.isNotNull()
.isInstanceOf(CantCreateDatabaseException.class);
}
}
|
package com.wonderful.permissionlibrary.annotation;
import android.app.Activity;
/**
* @Author wonderful
* @Date 2020-9-28
* @Description 上下文获取接口
* @Version 1.0
*/
public interface ActivityInterface {
public Activity getActivity();
}
|
//
// ========================================================================
// Copyright (c) 1995-2021 Mort Bay Consulting Pty Ltd and others.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.websocket.jsr356.utils;
import org.eclipse.jetty.websocket.common.util.ReflectUtils;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ReflectUtilsTest
{
public static interface Fruit<T>
{
}
public static interface Color<T>
{
}
public static interface Food<T> extends Fruit<T>
{
}
public abstract static class Apple<T extends Object> implements Fruit<T>, Color<String>
{
}
public abstract static class Cherry<A extends Object, B extends Number> implements Fruit<A>, Color<B>
{
}
public abstract static class Banana implements Fruit<String>, Color<String>
{
}
public static class Washington<Z extends Number, X extends Object> extends Cherry<X, Z>
{
}
public static class Rainier extends Washington<Float, Short>
{
}
public static class Pizza implements Food<Integer>
{
}
public static class Cavendish extends Banana
{
}
public static class GrannySmith extends Apple<Long>
{
}
public static class Pear implements Fruit<String>, Color<Double>
{
}
public static class Kiwi implements Fruit<Character>
{
}
@Test
public void testFindGenericPearFruit()
{
assertFindGenericClass(Pear.class, Fruit.class, String.class);
}
@Test
public void testFindGenericPizzaFruit()
{
assertFindGenericClass(Pizza.class, Fruit.class, Integer.class);
}
@Test
public void testFindGenericKiwiFruit()
{
assertFindGenericClass(Kiwi.class, Fruit.class, Character.class);
}
@Test
public void testFindGenericPearColor()
{
assertFindGenericClass(Pear.class, Color.class, Double.class);
}
@Test
public void testFindGenericGrannySmithFruit()
{
assertFindGenericClass(GrannySmith.class, Fruit.class, Long.class);
}
@Test
public void testFindGenericCavendishFruit()
{
assertFindGenericClass(Cavendish.class, Fruit.class, String.class);
}
@Test
public void testFindGenericRainierFruit()
{
assertFindGenericClass(Rainier.class, Fruit.class, Short.class);
}
@Test
public void testFindGenericWashingtonFruit()
{
// Washington does not have a concrete implementation
// of the Fruit interface, this should return null
Class<?> impl = ReflectUtils.findGenericClassFor(Washington.class, Fruit.class);
assertThat("Washington -> Fruit implementation", impl, nullValue());
}
private void assertFindGenericClass(Class<?> baseClass, Class<?> ifaceClass, Class<?> expectedClass)
{
Class<?> foundClass = ReflectUtils.findGenericClassFor(baseClass, ifaceClass);
String msg = String.format("Expecting %s<%s> found on %s", ifaceClass.getName(), expectedClass.getName(), baseClass.getName());
assertEquals(expectedClass, foundClass, msg);
}
}
|
/*******************************************************************************
* Copyright 2013-2018 QaProSoft (http://www.qaprosoft.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.qaprosoft.carina.core.foundation;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Category;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.Assert;
import org.testng.ITestContext;
import org.testng.ITestNGMethod;
import org.testng.ITestResult;
import org.testng.SkipException;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
import org.testng.xml.XmlTest;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import com.jayway.restassured.RestAssured;
import com.qaprosoft.amazon.AmazonS3Manager;
import com.qaprosoft.carina.core.foundation.api.APIMethodBuilder;
import com.qaprosoft.carina.core.foundation.commons.SpecialKeywords;
import com.qaprosoft.carina.core.foundation.dataprovider.core.DataProviderFactory;
import com.qaprosoft.carina.core.foundation.jira.Jira;
import com.qaprosoft.carina.core.foundation.listeners.AbstractTestListener;
import com.qaprosoft.carina.core.foundation.report.Artifacts;
import com.qaprosoft.carina.core.foundation.report.ReportContext;
import com.qaprosoft.carina.core.foundation.report.TestResultItem;
import com.qaprosoft.carina.core.foundation.report.TestResultType;
import com.qaprosoft.carina.core.foundation.report.email.EmailManager;
import com.qaprosoft.carina.core.foundation.report.email.EmailReportGenerator;
import com.qaprosoft.carina.core.foundation.report.email.EmailReportItemCollector;
import com.qaprosoft.carina.core.foundation.report.testrail.TestRail;
import com.qaprosoft.carina.core.foundation.skip.ExpectedSkipManager;
import com.qaprosoft.carina.core.foundation.utils.Configuration;
import com.qaprosoft.carina.core.foundation.utils.Configuration.DriverMode;
import com.qaprosoft.carina.core.foundation.utils.Configuration.Parameter;
import com.qaprosoft.carina.core.foundation.utils.DateUtils;
import com.qaprosoft.carina.core.foundation.utils.JsonUtils;
import com.qaprosoft.carina.core.foundation.utils.Messager;
import com.qaprosoft.carina.core.foundation.utils.R;
import com.qaprosoft.carina.core.foundation.utils.common.CommonUtils;
import com.qaprosoft.carina.core.foundation.utils.metadata.MetadataCollector;
import com.qaprosoft.carina.core.foundation.utils.metadata.model.ElementsInfo;
import com.qaprosoft.carina.core.foundation.utils.naming.TestNamingUtil;
import com.qaprosoft.carina.core.foundation.utils.resources.I18N;
import com.qaprosoft.carina.core.foundation.utils.resources.L10N;
import com.qaprosoft.carina.core.foundation.utils.resources.L10Nparser;
import com.qaprosoft.carina.core.foundation.webdriver.DriverPool;
import com.qaprosoft.carina.core.foundation.webdriver.core.capability.CapabilitiesLoader;
import com.qaprosoft.carina.core.foundation.webdriver.device.Device;
import com.qaprosoft.carina.core.foundation.webdriver.device.DevicePool;
import com.qaprosoft.hockeyapp.HockeyAppManager;
/*
* AbstractTest - base test for UI and API tests.
*
* @author Alex Khursevich
*/
@Listeners({ AbstractTestListener.class })
public abstract class AbstractTest // extends DriverHelper
{
protected static final Logger LOGGER = Logger.getLogger(AbstractTest.class);
protected APIMethodBuilder apiMethodBuilder;
protected static final long EXPLICIT_TIMEOUT = Configuration.getLong(Parameter.EXPLICIT_TIMEOUT);
protected static final String SUITE_TITLE = "%s%s%s - %s (%s%s)";
protected static final String XML_SUITE_NAME = " (%s)";
protected static ThreadLocal<String> suiteNameAppender = new ThreadLocal<String>();
// 3rd party integrations
protected String browserVersion = "";
protected long startDate;
@BeforeSuite(alwaysRun = true)
public void executeBeforeTestSuite(ITestContext context) {
// Add shutdown hook
Runtime.getRuntime().addShutdownHook(new ShutdownHook());
// Set log4j properties
PropertyConfigurator.configure(ClassLoader.getSystemResource("log4j.properties"));
// Set SoapUI log4j properties
System.setProperty("soapui.log4j.config", "./src/main/resources/soapui-log4j.xml");
try {
Logger root = Logger.getRootLogger();
Enumeration<?> allLoggers = root.getLoggerRepository().getCurrentCategories();
while (allLoggers.hasMoreElements()) {
Category tmpLogger = (Category) allLoggers.nextElement();
if (tmpLogger.getName().equals("com.qaprosoft.carina.core")) {
tmpLogger.setLevel(Level.toLevel(Configuration.get(Parameter.CORE_LOG_LEVEL)));
}
}
} catch (NoSuchMethodError e) {
LOGGER.error("Unable to redefine logger level due to the conflicts between log4j and slf4j!");
}
startDate = new Date().getTime();
LOGGER.info(Configuration.asString());
// Configuration.validateConfiguration();
LOGGER.debug("Default thread_count=" + context.getCurrentXmlTest().getSuite().getThreadCount());
context.getCurrentXmlTest().getSuite().setThreadCount(Configuration.getInt(Parameter.THREAD_COUNT));
LOGGER.debug("Updated thread_count=" + context.getCurrentXmlTest().getSuite().getThreadCount());
// update DataProviderThreadCount if any property is provided otherwise sync with value from suite xml file
int count = Configuration.getInt(Parameter.DATA_PROVIDER_THREAD_COUNT);
if (count > 0) {
LOGGER.debug("Updated 'data_provider_thread_count' from "
+ context.getCurrentXmlTest().getSuite().getDataProviderThreadCount() + " to " + count);
context.getCurrentXmlTest().getSuite().setDataProviderThreadCount(count);
} else {
LOGGER.debug("Synching data_provider_thread_count with values from suite xml file...");
R.CONFIG.put(Parameter.DATA_PROVIDER_THREAD_COUNT.getKey(),
String.valueOf(context.getCurrentXmlTest().getSuite().getDataProviderThreadCount()));
LOGGER.debug("Updated 'data_provider_thread_count': " + Configuration.getInt(Parameter.DATA_PROVIDER_THREAD_COUNT));
}
LOGGER.debug("Default data_provider_thread_count="
+ context.getCurrentXmlTest().getSuite().getDataProviderThreadCount());
LOGGER.debug("Updated data_provider_thread_count="
+ context.getCurrentXmlTest().getSuite().getDataProviderThreadCount());
if (!Configuration.isNull(Parameter.URL)) {
if (!Configuration.get(Parameter.URL).isEmpty()) {
RestAssured.baseURI = Configuration.get(Parameter.URL);
}
}
try {
L10N.init();
} catch (Exception e) {
LOGGER.error("L10N bundle is not initialized successfully!", e);
}
try {
I18N.init();
} catch (Exception e) {
LOGGER.error("I18N bundle is not initialized successfully!", e);
}
try {
L10Nparser.init();
} catch (Exception e) {
LOGGER.error("L10Nparser bundle is not initialized successfully!", e);
}
// TODO: move out from AbstractTest->executeBeforeTestSuite
String customCapabilities = Configuration.get(Parameter.CUSTOM_CAPABILITIES);
if (!customCapabilities.isEmpty()) {
// redefine core CONFIG properties using custom capabilities file
new CapabilitiesLoader().loadCapabilities(customCapabilities);
}
String extraCapabilities = Configuration.get(Parameter.EXTRA_CAPABILITIES);
if (!extraCapabilities.isEmpty()) {
// redefine core CONFIG properties using extra capabilities file
new CapabilitiesLoader().loadCapabilities(extraCapabilities);
}
try {
TestRail.updateBeforeSuite(context, this.getClass().getName(), getTitle(context));
} catch (Exception e) {
LOGGER.error("TestRail is not initialized successfully!", e);
}
updateAppPath();
}
@BeforeClass(alwaysRun = true)
public void executeBeforeTestClass(ITestContext context) throws Throwable {
// do nothing for now
}
@AfterClass(alwaysRun = true)
public void executeAfterTestClass(ITestContext context) throws Throwable {
if (Configuration.getDriverMode() == DriverMode.CLASS_MODE) {
LOGGER.debug("Deinitialize driver(s) in UITest->AfterClass.");
quitDrivers();
}
}
@BeforeMethod(alwaysRun = true)
public void executeBeforeTestMethod(XmlTest xmlTest, Method testMethod, ITestContext context) throws Throwable {
// handle expected skip
if (ExpectedSkipManager.getInstance().isSkip(testMethod, context)) {
skipExecution("Based on rule listed above");
}
// do nothing for now
apiMethodBuilder = new APIMethodBuilder();
}
@AfterMethod(alwaysRun = true)
public void executeAfterTestMethod(ITestResult result) {
try {
if (apiMethodBuilder != null) {
apiMethodBuilder.close();
}
DriverMode driverMode = Configuration.getDriverMode();
if (driverMode == DriverMode.METHOD_MODE) {
LOGGER.debug("Deinitialize driver(s) in @AfterMethod.");
quitDrivers();
}
// TODO: improve later removing duplicates with AbstractTestListener
// handle Zafira already passed exception for re-run and do nothing. maybe return should be enough
if (result.getThrowable() != null && result.getThrowable().getMessage() != null
&& result.getThrowable().getMessage().startsWith(SpecialKeywords.ALREADY_PASSED)) {
// [VD] it is prohibited to release TestInfoByThread in this place.!
return;
}
// handle AbstractTest->SkipExecution
if (result.getThrowable() != null && result.getThrowable().getMessage() != null
&& result.getThrowable().getMessage().startsWith(SpecialKeywords.SKIP_EXECUTION)) {
// [VD] it is prohibited to release TestInfoByThread in this place.!
return;
}
List<String> tickets = Jira.getTickets(result);
result.setAttribute(SpecialKeywords.JIRA_TICKET, tickets);
Jira.updateAfterTest(result);
// we shouldn't deregister info here as all retries will not work
// TestNamingUtil.releaseZafiraTest();
// clear jira tickets to be sure that next test is not affected.
Jira.clearTickets();
Artifacts.clearArtifacts();
} catch (Exception e) {
LOGGER.error("Exception in AbstractTest->executeAfterTestMethod: " + e.getMessage());
e.printStackTrace();
}
}
@AfterSuite(alwaysRun = true)
public void executeAfterTestSuite(ITestContext context) {
try {
if (Configuration.getDriverMode() == DriverMode.SUITE_MODE) {
LOGGER.debug("Deinitialize driver(s) in UITest->AfterSuite.");
quitDrivers();
}
ReportContext.removeTempDir(); // clean temp artifacts directory
//HtmlReportGenerator.generate(ReportContext.getBaseDir().getAbsolutePath());
String browser = getBrowser();
String deviceName = getDeviceName();
// String suiteName = getSuiteName(context);
String title = getTitle(context);
TestResultType testResult = EmailReportGenerator.getSuiteResult(EmailReportItemCollector.getTestResults());
String status = testResult.getName();
title = status + ": " + title;
String env = "";
if (!Configuration.isNull(Parameter.ENV)) {
env = Configuration.get(Parameter.ENV);
}
if (!Configuration.get(Parameter.URL).isEmpty()) {
env += " - <a href='" + Configuration.get(Parameter.URL) + "'>" + Configuration.get(Parameter.URL) + "</a>";
}
ReportContext.getTempDir().delete();
// Update JIRA
Jira.updateAfterSuite(context, EmailReportItemCollector.getTestResults());
// generate and send email report by Zafira to test group of people
String emailList = Configuration.get(Parameter.EMAIL_LIST);
String failureEmailList = Configuration.get(Parameter.FAILURE_EMAIL_LIST);
String senderEmail = Configuration.get(Parameter.SENDER_EMAIL);
String senderPassword = Configuration.get(Parameter.SENDER_PASSWORD);
// Generate and send email report using regular method
EmailReportGenerator report = new EmailReportGenerator(title, env,
Configuration.get(Parameter.APP_VERSION), deviceName,
browser, DateUtils.now(), DateUtils.timeDiff(startDate),
EmailReportItemCollector.getTestResults(),
EmailReportItemCollector.getCreatedItems());
String emailContent = report.getEmailBody();
if (!R.ZAFIRA.getBoolean("zafira_enabled")) {
// Do not send email if run is running with enabled Zafira
EmailManager.send(title, emailContent,
emailList,
senderEmail,
senderPassword);
if (testResult.equals(TestResultType.FAIL) && !failureEmailList.isEmpty()) {
EmailManager.send(title, emailContent,
failureEmailList,
senderEmail,
senderPassword);
}
}
// Store emailable report under emailable-report.html
ReportContext.generateHtmlReport(emailContent);
printExecutionSummary(EmailReportItemCollector.getTestResults());
LOGGER.debug("Generating email report...");
TestResultType suiteResult = EmailReportGenerator.getSuiteResult(EmailReportItemCollector.getTestResults());
switch (suiteResult) {
case SKIP_ALL:
Assert.fail("All tests were skipped! Analyze logs to determine possible configuration issues.");
break;
case SKIP_ALL_ALREADY_PASSED:
LOGGER.info("Nothing was executed in rerun mode because all tests already passed and registered in Zafira Repoting Service!");
break;
default:
// do nothing
}
LOGGER.debug("Finish email report generation.");
} catch (Exception e) {
LOGGER.error("Exception in AbstractTest->executeAfterSuite: " + e.getMessage());
e.printStackTrace();
}
}
// TODO: remove this private method
private String getDeviceName() {
String deviceName = "Desktop";
if (!DevicePool.getDevice().isNull()) {
// Samsung - Android 4.4.2; iPhone - iOS 7
Device device = DevicePool.getDevice();
String deviceTemplate = "%s - %s %s";
deviceName = String.format(deviceTemplate, device.getName(), device.getOs(), device.getOsVersion());
}
return deviceName;
}
protected String getBrowser() {
String browser = "";
if (!Configuration.get(Parameter.BROWSER).isEmpty()) {
browser = Configuration.get(Parameter.BROWSER);
}
if (!browserVersion.isEmpty()) {
browser = browser + " " + browserVersion;
}
return browser;
}
protected String getTitle(ITestContext context) {
String browser = getBrowser();
if (!browser.isEmpty()) {
browser = " " + browser; // insert the space before
}
String device = getDeviceName();
String env = !Configuration.isNull(Parameter.ENV) ? Configuration.get(Parameter.ENV) : Configuration.get(Parameter.URL);
String title = "";
String app_version = "";
if (!Configuration.get(Parameter.APP_VERSION).isEmpty()) {
// if nothing is specified then title will contain nothing
app_version = Configuration.get(Parameter.APP_VERSION) + " - ";
}
String suiteName = getSuiteName(context);
String xmlFile = getSuiteFileName(context);
title = String.format(SUITE_TITLE, app_version, suiteName, String.format(XML_SUITE_NAME, xmlFile), env, device, browser);
return title;
}
private String getSuiteFileName(ITestContext context) {
// TODO: investigate why we need such method and suite file name at all
String fileName = context.getSuite().getXmlSuite().getFileName();
if (fileName == null) {
fileName = "undefined";
}
LOGGER.debug("Full suite file name: " + fileName);
if (fileName.contains("\\")) {
fileName = fileName.replaceAll("\\\\", "/");
}
fileName = StringUtils.substringAfterLast(fileName, "/");
LOGGER.debug("Short suite file name: " + fileName);
return fileName;
}
protected String getSuiteName(ITestContext context) {
String suiteName = "";
if (context.getSuite().getXmlSuite() != null && !"Default suite".equals(context.getSuite().getXmlSuite().getName())) {
suiteName = Configuration.get(Parameter.SUITE_NAME).isEmpty() ? context.getSuite().getXmlSuite().getName()
: Configuration.get(Parameter.SUITE_NAME);
} else {
suiteName = Configuration.get(Parameter.SUITE_NAME).isEmpty() ? R.EMAIL.get("title") : Configuration.get(Parameter.SUITE_NAME);
}
String appender = getSuiteNameAppender();
if (appender != null && !appender.isEmpty()) {
suiteName = suiteName + " - " + appender;
}
return suiteName;
}
protected void setSuiteNameAppender(String appender) {
suiteNameAppender.set(appender);
}
protected String getSuiteNameAppender() {
return suiteNameAppender.get();
}
private void printExecutionSummary(List<TestResultItem> tris) {
Messager.INROMATION
.info("**************** Test execution summary ****************");
int num = 1;
for (TestResultItem tri : tris) {
String failReason = tri.getFailReason();
if (failReason == null) {
failReason = "";
}
if (!tri.isConfig() && !failReason.contains(SpecialKeywords.ALREADY_PASSED)
&& !failReason.contains(SpecialKeywords.SKIP_EXECUTION)) {
String reportLinks = !StringUtils.isEmpty(tri.getLinkToScreenshots())
? "screenshots=" + tri.getLinkToScreenshots() + " | "
: "";
reportLinks += !StringUtils.isEmpty(tri.getLinkToLog()) ? "log=" + tri.getLinkToLog() : "";
Messager.TEST_RESULT.info(String.valueOf(num++), tri.getTest(), tri.getResult().toString(),
reportLinks);
}
}
}
/**
* Redefine Jira tickets from test.
*
* @param tickets to set
*/
@Deprecated
protected void setJiraTicket(String... tickets) {
List<String> jiraTickets = new ArrayList<String>();
for (String ticket : tickets) {
jiraTickets.add(ticket);
}
Jira.setTickets(jiraTickets);
}
/**
* Redefine TestRails cases from test.
*
* @param cases to set
*/
protected void setTestRailCase(String... cases) {
TestRail.setCasesID(cases);
}
@DataProvider(name = "DataProvider", parallel = true)
public Object[][] createData(final ITestNGMethod testMethod, ITestContext context) {
Annotation[] annotations = testMethod.getConstructorOrMethod().getMethod().getDeclaredAnnotations();
Object[][] objects = DataProviderFactory.getNeedRerunDataProvider(annotations, context, testMethod);
return objects;
}
@DataProvider(name = "SingleDataProvider")
public Object[][] createDataSingleThread(final ITestNGMethod testMethod,
ITestContext context) {
Annotation[] annotations = testMethod.getConstructorOrMethod().getMethod().getDeclaredAnnotations();
Object[][] objects = DataProviderFactory.getNeedRerunDataProvider(annotations, context, testMethod);
return objects;
}
/**
* Pause for specified timeout.
*
* @param timeout in seconds.
*/
public void pause(long timeout) {
CommonUtils.pause(timeout);
}
public void pause(Double timeout) {
CommonUtils.pause(timeout);
}
protected void putS3Artifact(String key, String path) {
AmazonS3Manager.getInstance().put(Configuration.get(Parameter.S3_BUCKET_NAME), key, path);
}
protected S3Object getS3Artifact(String bucket, String key) {
return AmazonS3Manager.getInstance().get(Configuration.get(Parameter.S3_BUCKET_NAME), key);
}
protected S3Object getS3Artifact(String key) {
return getS3Artifact(Configuration.get(Parameter.S3_BUCKET_NAME), key);
}
private void updateAppPath() {
try {
if (!Configuration.get(Parameter.ACCESS_KEY_ID).isEmpty()) {
updateS3AppPath();
}
} catch (Exception e) {
LOGGER.error("AWS S3 manager exception detected!", e);
}
try {
if (!Configuration.get(Parameter.HOCKEYAPP_TOKEN).isEmpty()) {
updateHockeyAppPath();
}
} catch (Exception e) {
LOGGER.error("HockeyApp manager exception detected!", e);
}
}
/**
* Method to update MOBILE_APP path in case if apk is located in Hockey App.
*/
private void updateHockeyAppPath() {
// hockeyapp://appName/platformName/buildType/version
Pattern HOCKEYAPP_PATTERN = Pattern
.compile("hockeyapp:\\/\\/([a-zA-Z-0-9][^\\/]*)\\/([a-zA-Z-0-9][^\\/]*)\\/([a-zA-Z-0-9][^\\/]*)\\/([a-zA-Z-0-9][^\\/]*)");
String mobileAppPath = Configuration.getMobileApp();
Matcher matcher = HOCKEYAPP_PATTERN.matcher(mobileAppPath);
LOGGER.info("Analyzing if mobile_app is located on HockeyApp...");
if (matcher.find()) {
LOGGER.info("app artifact is located on HockeyApp...");
String appName = matcher.group(1);
String platformName = matcher.group(2);
String buildType = matcher.group(3);
String version = matcher.group(4);
String hockeyAppLocalStorage = Configuration.get(Parameter.HOCKEYAPP_LOCAL_STORAGE);
// download file from HockeyApp to local storage
File file = HockeyAppManager.getInstance().getBuild(hockeyAppLocalStorage, appName, platformName, buildType, version);
Configuration.setMobileApp(file.getAbsolutePath());
LOGGER.info("Updated mobile app: " + Configuration.getMobileApp());
// try to redefine app_version if it's value is latest or empty
String appVersion = Configuration.get(Parameter.APP_VERSION);
if (appVersion.equals("latest") || appVersion.isEmpty()) {
R.CONFIG.put(Parameter.APP_VERSION.getKey(), file.getName());
}
}
}
/**
* Method to update MOBILE_APP path in case if apk is located in s3 bucket.
*/
private void updateS3AppPath() {
Pattern S3_BUCKET_PATTERN = Pattern.compile("s3:\\/\\/([a-zA-Z-0-9][^\\/]*)\\/(.*)");
// get app path to be sure that we need(do not need) to download app from s3 bucket
String mobileAppPath = Configuration.getMobileApp();
Matcher matcher = S3_BUCKET_PATTERN.matcher(mobileAppPath);
LOGGER.info("Analyzing if mobile app is located on S3...");
if (matcher.find()) {
LOGGER.info("app artifact is located on s3...");
String bucketName = matcher.group(1);
String key = matcher.group(2);
Pattern pattern = Pattern.compile(key);
// analyze if we have any pattern inside mobile_app to make extra
// search in AWS
int position = key.indexOf(".*");
if (position > 0) {
// /android/develop/dfgdfg.*/Mapmyrun.apk
int slashPosition = key.substring(0, position).lastIndexOf("/");
if (slashPosition > 0) {
key = key.substring(0, slashPosition);
S3ObjectSummary lastBuild = AmazonS3Manager.getInstance().getLatestBuildArtifact(bucketName, key,
pattern);
key = lastBuild.getKey();
}
}
S3Object objBuild = AmazonS3Manager.getInstance().get(bucketName, key);
String s3LocalStorage = Configuration.get(Parameter.S3_LOCAL_STORAGE);
// download file from AWS to local storage
String fileName = s3LocalStorage + "/" + StringUtils.substringAfterLast(objBuild.getKey(), "/");
File file = new File(fileName);
// verify maybe requested artifact with the same size was already
// download
if (file.exists() && file.length() == objBuild.getObjectMetadata().getContentLength()) {
LOGGER.info("build artifact with the same size already downloaded: " + file.getAbsolutePath());
} else {
LOGGER.info(String.format("Following data was extracted: bucket: %s, key: %s, local file: %s",
bucketName, key, file.getAbsolutePath()));
AmazonS3Manager.getInstance().download(bucketName, key, new File(fileName));
}
Configuration.setMobileApp(file.getAbsolutePath());
// try to redefine app_version if it's value is latest or empty
String appVersion = Configuration.get(Parameter.APP_VERSION);
if (appVersion.equals("latest") || appVersion.isEmpty()) {
R.CONFIG.put(Parameter.APP_VERSION.getKey(), file.getName());
}
}
}
protected void setBug(String id) {
String test = TestNamingUtil.getTestNameByThread();
TestNamingUtil.associateBug(test, id);
}
protected void skipExecution(String message) {
throw new SkipException(SpecialKeywords.SKIP_EXECUTION + ": " + message);
}
// --------------------------------------------------------------------------
// Web Drivers
// --------------------------------------------------------------------------
protected WebDriver getDriver() {
return getDriver(DriverPool.DEFAULT);
}
protected WebDriver getDriver(String name) {
WebDriver drv = DriverPool.getDriver(name);
if (drv == null) {
Assert.fail("Unable to find driver by name: " + name);
}
return drv;
//return castDriver(drv);
}
protected WebDriver getDriver(String name, DesiredCapabilities capabilities, String seleniumHost) {
WebDriver drv = DriverPool.getDriver(name, capabilities, seleniumHost);
if (drv == null) {
Assert.fail("Unable to find driver by name: " + name);
}
return drv;
//return castDriver(drv);
}
/* private WebDriver castDriver(WebDriver drv) {
if (drv instanceof EventFiringWebDriver) {
return ((EventFiringWebDriver) drv).getWrappedDriver();
} else {
return drv;
}
}*/
protected static void quitDrivers() {
DriverPool.quitDrivers();
}
public static class ShutdownHook extends Thread {
private static final Logger LOGGER = Logger.getLogger(ShutdownHook.class);
private void generateMetadata() {
Map<String, ElementsInfo> allData = MetadataCollector.getAllCollectedData();
if (allData.size() > 0) {
LOGGER.debug("Generating collected metadada start...");
}
for (String key : allData.keySet()) {
LOGGER.debug("Creating... medata for '" + key + "' object...");
File file = new File(ReportContext.getArtifactsFolder().getAbsolutePath() + "/metadata/" + key.hashCode() + ".json");
PrintWriter out = null;
try {
out = new PrintWriter(file);
out.append(JsonUtils.toJson(MetadataCollector.getAllCollectedData().get(key)));
out.flush();
} catch (FileNotFoundException e) {
LOGGER.error("Unable to write metadata to json file: " + file.getAbsolutePath(), e);
} finally {
out.close();
}
LOGGER.debug("Created medata for '" + key + "' object...");
}
if (allData.size() > 0) {
LOGGER.debug("Generating collected metadada finish...");
}
}
@Override
public void run() {
LOGGER.debug("Running shutdown hook");
generateMetadata();
}
}
}
|
package com.medusa.gruul.account.api.conf;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author whh
* @description
* @data: 2019/11/26
*/
@Component
@ConfigurationProperties(prefix = "info")
@Data
public class MiniInfoProperty {
/**
* appId
*/
private String appId;
/**
* secret
*/
private String secret;
}
|
/*
* Copyright (c) 2009, GoodData Corporation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of conditions and
* the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of the GoodData Corporation nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.snaplogic.snap.gooddata;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Map.Entry;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.snaplogic.cc.Capabilities;
import org.snaplogic.cc.Capability;
import org.snaplogic.cc.InputView;
import org.snaplogic.cc.OutputView;
import org.snaplogic.cc.prop.SimpleProp;
import org.snaplogic.cc.prop.SimpleProp.SimplePropType;
import org.snaplogic.common.ComponentResourceErr;
import org.snaplogic.common.Field;
import org.snaplogic.common.Record;
import org.snaplogic.common.exceptions.SnapComponentException;
import org.snaplogic.log.Log;
import org.snaplogic.snapi.PropertyConstraint;
import org.snaplogic.snapi.ResDef;
import org.snaplogic.snapi.PropertyConstraint.Type;
import org.snaplogic.util.ConvertUtils;
import com.gooddata.connector.CsvConnector;
import com.gooddata.exception.GdcProjectAccessException;
import com.gooddata.exception.GdcRestApiException;
import com.gooddata.exception.GdcUploadErrorException;
import com.gooddata.exception.HttpMethodException;
import com.gooddata.integration.rest.GdcRESTApiWrapper;
import com.gooddata.integration.rest.configuration.NamePasswordConfiguration;
import com.gooddata.modeling.model.SourceSchema;
import com.gooddata.processor.CliParams;
import com.gooddata.processor.Command;
import com.gooddata.processor.ProcessingContext;
import com.gooddata.util.FileUtil;
public class GoodDataPutSli extends AbstractGoodDataComponent {
private static final String ALL_SNAPSHOTS = "All Snapshots";
private static final String LAST_SNAPSHOT = "Last Snapshot";
@Override
public String getDescription() {
return getLabel() + ". Uploads data into GoodData.";
}
@Override
public Capabilities getCapabilities() {
return new Capabilities() {
/**
*
*/
private static final long serialVersionUID = 3848994857590856035L;
{
put(Capability.INPUT_VIEW_LOWER_LIMIT, 1);
put(Capability.INPUT_VIEW_UPPER_LIMIT, 100);
put(Capability.OUTPUT_VIEW_LOWER_LIMIT, 0);
put(Capability.OUTPUT_VIEW_UPPER_LIMIT, 0);
}
};
}
@Override
public String getLabel() {
return "GoodData Upload (Java)";
}
private static final String DLI_MANIFEST_FILENAME = "upload_info.json";
private static final String DLI_ARCHIVE_SUFFIX = ".zip";
public static final String PROP_PROJECT_NAME = "project_name";
public static final String PROP_PROJECT_ID = "project_id";
public static final String PROP_DLI = "dli";
public static final String PROP_INCREMENTAL = "overwrite";
private static final String PROP_TRANSFER_SNAPSHOTS = "transfer_snapshots";
private static final String PROP_WAIT_FINISH = "wait_finish";
public static final String PROP_SOURCE_SCHEMA = "put_comp_source_schema";
@Override
public String getAPIVersion() {
return "1.0";
}
@Override
public String getComponentVersion() {
return "1.0";
}
private PropertyConstraint projNameLovConstraint = new PropertyConstraint(Type.UNMODIFIABLE, true);
private PropertyConstraint projIdLovConstraint = new PropertyConstraint(Type.UNMODIFIABLE, true);
private SimpleProp projNameProp = new SimpleProp("Project Name", SimplePropType.SnapString, "Project name",
projNameLovConstraint, true);
private SimpleProp projIdProp = new SimpleProp("Project Id", SimplePropType.SnapString, "Project id",
projIdLovConstraint, true);
private PropertyConstraint dlisLovConstraint = new PropertyConstraint(Type.UNMODIFIABLE, true);
private SimpleProp dliProp = new SimpleProp("SLI", SimplePropType.SnapString, "Data Loading Interface",
dlisLovConstraint, true);
@Override
public void createResourceTemplate() {
super.createResourceTemplate();
setPropertyDef(PROP_PROJECT_NAME, projNameProp);
setPropertyDef(PROP_PROJECT_ID, projIdProp);
setPropertyDef(PROP_DLI, dliProp);
setPropertyDef(PROP_INCREMENTAL, new SimpleProp("Incremental", SimplePropType.SnapBoolean,
"Append if true, replace if false", true));
setPropertyValue(PROP_INCREMENTAL, false);
setPropertyDef(PROP_WAIT_FINISH, new SimpleProp("Wait for Finish", SimplePropType.SnapBoolean,
"waits for the server-side processing", true));
setPropertyValue(PROP_WAIT_FINISH, true);
PropertyConstraint transferSnapshotConstrain = new PropertyConstraint(Type.LOV, new String[] { LAST_SNAPSHOT,
ALL_SNAPSHOTS });
SimpleProp transferSnProp = new SimpleProp("Transfer Snapshots", SimplePropType.SnapString,
"Snapshots to transfer to GoodData", transferSnapshotConstrain, true);
setPropertyDef(PROP_TRANSFER_SNAPSHOTS, transferSnProp);
setPropertyValue(PROP_TRANSFER_SNAPSHOTS, LAST_SNAPSHOT);
setPropertyDef(PROP_SOURCE_SCHEMA, new SimpleProp("XML Schema", SimplePropType.SnapString, "",
new PropertyConstraint(Type.HIDDEN, true), true));
setPropertyValue(PROP_SOURCE_SCHEMA, "");
}
@Override
public void validate(ComponentResourceErr err) {
GdcRESTApiWrapper restApi = login(err);
if (restApi == null) {
return;
}
String curProjName = (String) getPropertyValue(PROP_PROJECT_NAME);
try {
if (curProjName != null && restApi.getProjectByName(curProjName) == null) {
err
.getPropertyErr(PROP_PROJECT_NAME)
.setMessage(
"Project '"
+ curProjName
+ "' does not exist for this account. Use auto-fill to populate this property with a list of eligible projects.");
}
} catch (HttpMethodException hme) {
elog(hme);
err.setMessage("Error occurred validating project name: " + hme.getMessage());
}
// TODO check that view matches the metadata
catch (GdcProjectAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void suggestResourceValues(ComponentResourceErr err) {
info("Auto-Fill for GoodDataSnap started, but nothing will be done, there's nothing to auto-guess");
super.suggestResourceValues(err);
}
// TODO
// this pattern should also be used in other places where
// writes to intermediate file or db are done
// even better to keep them in a StringBuffer-like object, not a list
// (so writes are in one swoop) but StringBuffer doesn't seem to have
// a clear() method, or maybe it's just late in the day
protected final int getRecordBufSize() {
if (Log.isLevelDebug()) {
return 16;
} else {
return 1024 * 10;
}
}
protected Map<String, File> stageInputsAsCsv(Map<String, InputView> inputs, boolean createHeader,
boolean useFieldDescForHeader, File tmpDir) {
List<InputView> activeInputViews = new ArrayList<InputView>();
activeInputViews.addAll(inputs.values());
if (activeInputViews.size() == 0) {
throw new SnapComponentException("Not enough input views available");
}
Map<String, File> viewToCsvFile = new HashMap<String, File>();
Map<String, BufferedWriter> viewToCsvWriter = new HashMap<String, BufferedWriter>();
// TODO
Map<String, List<String>> bufferedRecords = new HashMap<String, List<String>>();
try {
while (activeInputViews.size() > 0) {
Collection<InputView> viewsWithData = selectInputView(activeInputViews);
Collection<InputView> finishedViewList = new ArrayList<InputView>();
// Get the records from all the views that currently have data
for (InputView view : viewsWithData) {
String viewName = view.getName();
File csvFile = viewToCsvFile.get(viewName);
// csvFile.deleteOnExit();
BufferedWriter csvWriter = viewToCsvWriter.get(viewName);
if (csvFile == null) {
csvFile = new File(tmpDir, viewName + ".csv");
info("Creating stage CSV file: " + csvFile.getAbsolutePath());
csvWriter = FileUtil.createBufferedUtf8Writer(csvFile);
viewToCsvFile.put(viewName, csvFile);
viewToCsvWriter.put(viewName, csvWriter);
}
Record record = view.readRecord();
if (record == null) {
// We get null as a record, if the view is closing on
// the other side. We are keeping track of those that
// have
// closed in this round, and create a reverse sorted
// list of their indices in the active_input_view list.
// We can't just simply erase them right now out of the
// list since that would screw up our iteration over the
// list.
finishedViewList.add(view);
continue;
}
List<String> curBuffer = bufferedRecords.get(viewName);
if (curBuffer == null) {
curBuffer = new ArrayList<String>(getRecordBufSize());
bufferedRecords.put(viewName, curBuffer);
if (createHeader) {
// No buffer yet created, so write a header
String header = "";
boolean first = true;
for (Field field : view.getFields()) {
if (first) {
first = false;
} else {
header += ",";
}
if (useFieldDescForHeader) {
header += "\"" + field.getDescription() + "\"";
} else {
header += "\"" + field.getName() + "\"";
}
}
curBuffer.add(header);
}
}
String curLine = "";
boolean first = true;
for (Field field : view.getFields()) {
Object val = record.get(field.getName());
String stringVal = null;
if (val == null) {
stringVal = "";
} else if (val instanceof String) {
stringVal = val.toString();
stringVal = stringVal.replace('"', '\"');
} else if (val instanceof BigDecimal) {
stringVal = val.toString();
} else if (val instanceof Timestamp) {
stringVal = ISO_DATE_FORMAT.print(new DateTime((Timestamp) val));
}
if (first) {
first = false;
} else {
curLine += ",";
}
curLine += "\"" + stringVal + "\"";
}
curBuffer.add(curLine);
if (curBuffer.size() > getRecordBufSize()) {
debug("Writing " + curBuffer.size() + " lines to " + csvFile);
for (String line : curBuffer) {
csvWriter.write(line);
csvWriter.write(System.getProperty("line.separator"));
}
csvWriter.flush();
curBuffer.clear();
}
}
// Any views that have finished in the last round?
for (InputView view : finishedViewList) {
// Now we can delete them (starting from the back) from the
// list of active views.
activeInputViews.remove(view);
}
}
// Write out the buffers
for (String viewName : bufferedRecords.keySet()) {
List<String> curBuffer = bufferedRecords.get(viewName);
File csvFile = viewToCsvFile.get(viewName);
BufferedWriter csvWriter = viewToCsvWriter.get(viewName);
if (curBuffer.size() > 0) {
debug("Writing " + curBuffer.size() + " lines to " + csvFile);
for (String line : curBuffer) {
csvWriter.write(line);
csvWriter.write(System.getProperty("line.separator"));
}
csvWriter.flush();
csvWriter.close();
curBuffer.clear();
}
}
return viewToCsvFile;
} catch (IOException ioe) {
// TODO be more graceful here
elog(ioe);
throw new SnapComponentException(ioe);
}
}
public static final DateTimeFormatter ISO_DATE_FORMAT = DateTimeFormat.forPattern(ConvertUtils.DATE_FORMAT_3);
@Override
public void execute(Map<String, InputView> inputViews, Map<String, OutputView> outputViews) {
info("Staged CSVs will be uploaded to GoodData. Logging in...");
//First we need connection to GoodData
ResDef gdConnection = getConnectionReference(null);
NamePasswordConfiguration httpConfiguration = GoodDataConnection.getHttpConfiguration(gdConnection);
NamePasswordConfiguration ftpConfiguration = GoodDataConnection.getFtpConfiguration(gdConnection);
// And extract its parameters
CliParams cliParams = new CliParams();
cliParams.setHttpConfig(httpConfiguration);
cliParams.setFtpConfig(ftpConfiguration);
// All the properties set by the wizard and the user...
String projectName = (String) getPropertyValue(PROP_PROJECT_NAME);
String projectId = getStringPropertyValue(PROP_PROJECT_ID);
String dliName = (String) getPropertyValue(PROP_DLI);
String transferSnapshots = getStringPropertyValue(PROP_TRANSFER_SNAPSHOTS);
Boolean incremental = (Boolean) getPropertyValue(PROP_INCREMENTAL);
boolean waitForFinish = getBooleanPropertyValue(PROP_WAIT_FINISH);
String sourceSchemaString = getStringPropertyValue(PROP_SOURCE_SCHEMA);
// Properties for GdcDI Commands
Properties props = new Properties();
props.setProperty("incremental", incremental.toString());
props.setProperty("waitForFinish", new Boolean(waitForFinish).toString());
// SourceSchema was serialized into string by the wizard, let's get it
SourceSchema sourceSchema;
try {
sourceSchema = SourceSchema.createSchema(new ByteArrayInputStream(sourceSchemaString.getBytes()));
} catch (IOException e) {
elog(e);
throw new SnapComponentException(e);
}
if (projectId == null || dliName == null)
throw new SnapComponentException("Project or SLI is not specified!");
info("Integration starting for project ID " + projectId);
Map<String, File> stagedCSVs = null;
String archivePath = null;
try {
// Transform data flowing into our input view into CSV file
File tmpDir = FileUtil.createTempDir();
stagedCSVs = stageInputsAsCsv(inputViews, false, false, tmpDir);
if (stagedCSVs.size() == 1) {
// One file - exactly what's expected
// setup CSV connector
CsvConnector csvConnector = CsvConnector.createConnector();
csvConnector.setSchema(sourceSchema);
csvConnector.setDataFile(stagedCSVs.entrySet().iterator().next().getValue());
// Setup processing context
ProcessingContext context = new ProcessingContext();
context.setConnector(csvConnector);
context.setProjectId(projectId);
// Finally, do the job
if (transferSnapshots.equals(LAST_SNAPSHOT)) {
Command cmd = new Command("TransferLastSnapshot");
cmd.setParameters(props);
csvConnector.processCommand(cmd, cliParams, context);
} else if (transferSnapshots.equals(ALL_SNAPSHOTS)) {
Command cmd = new Command("TransferAllSnapshots");
cmd.setParameters(props);
csvConnector.processCommand(cmd, cliParams, context);
}
} else {
error("Unexpected number of staged files: " + stagedCSVs.size());
throw new SnapComponentException("Unexpected number of staged files: " + stagedCSVs.size());
}
info("Data for project " + projectId + " updated");
} catch (HttpMethodException e) {
elog(e);
throw new SnapComponentException(e);
} catch (GdcProjectAccessException e) {
elog(e);
throw new SnapComponentException(e);
} catch (IOException e) {
elog(e);
throw new SnapComponentException(e);
} catch (GdcUploadErrorException e) {
elog(e);
throw new SnapComponentException(e);
} catch (GdcRestApiException e) {
elog(e);
throw new SnapComponentException(e);
} finally {
// cleanup
info("Cleaning-up staging CSV files and uploaded archive...");
if (stagedCSVs != null) {
for (Entry<String, File> file : stagedCSVs.entrySet()) {
file.getValue().delete();
}
}
if (archivePath != null) {
new File(archivePath).delete();
}
info("Clean-up done");
}
}
}
|
/*******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.job.entries.ftpdelete;
import static org.pentaho.di.job.entry.validator.AndValidator.putValidators;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.andValidator;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.fileExistsValidator;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.notBlankValidator;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.notNullValidator;
import java.io.File;
import java.net.InetAddress;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.pentaho.di.cluster.SlaveServer;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.RowMetaAndData;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.encryption.Encr;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.entries.ftpsget.FTPSConnection;
import org.pentaho.di.job.entries.sftp.SFTPClient;
import org.pentaho.di.job.entry.JobEntryBase;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.resource.ResourceEntry;
import org.pentaho.di.resource.ResourceEntry.ResourceType;
import org.pentaho.di.resource.ResourceReference;
import org.pentaho.metastore.api.IMetaStore;
import org.w3c.dom.Node;
import com.enterprisedt.net.ftp.FTPClient;
import com.enterprisedt.net.ftp.FTPConnectMode;
import com.enterprisedt.net.ftp.FTPException;
import com.trilead.ssh2.Connection;
import com.trilead.ssh2.HTTPProxyData;
import com.trilead.ssh2.SFTPv3Client;
import com.trilead.ssh2.SFTPv3DirectoryEntry;
/**
* This defines an FTP job entry.
*
* @author Matt
* @since 05-11-2003
*
*/
public class JobEntryFTPDelete extends JobEntryBase implements Cloneable, JobEntryInterface {
private static Class<?> PKG = JobEntryFTPDelete.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private String serverName;
private String port;
private String userName;
private String password;
private String ftpDirectory;
private String wildcard;
private int timeout;
private boolean activeConnection;
private boolean publicpublickey;
private String keyFilename;
private String keyFilePass;
private boolean useproxy;
private String proxyHost;
private String proxyPort; /* string to allow variable substitution */
private String proxyUsername;
private String proxyPassword;
private String socksProxyHost;
private String socksProxyPort;
private String socksProxyUsername;
private String socksProxyPassword;
private String protocol;
public static final String PROTOCOL_FTP = "FTP";
public static final String PROTOCOL_FTPS = "FTPS";
public static final String PROTOCOL_SFTP = "SFTP";
public static final String PROTOCOL_SSH = "SSH";
public String SUCCESS_IF_AT_LEAST_X_FILES_DOWNLOADED = "success_when_at_least";
public String SUCCESS_IF_ERRORS_LESS = "success_if_errors_less";
public String SUCCESS_IF_ALL_FILES_DOWNLOADED = "success_is_all_files_downloaded";
private String nr_limit_success;
private String success_condition;
private boolean copyprevious;
private int FTPSConnectionType;
long NrErrors = 0;
long NrfilesDeleted = 0;
boolean successConditionBroken = false;
String targetFilename = null;
int limitFiles = 0;
FTPClient ftpclient = null;
FTPSConnection ftpsclient = null;
SFTPClient sftpclient = null;
SFTPv3Client sshclient = null;
public JobEntryFTPDelete(String n) {
super(n, "");
copyprevious = false;
protocol = PROTOCOL_FTP;
port = "21";
socksProxyPort = "1080";
nr_limit_success = "10";
success_condition = SUCCESS_IF_ALL_FILES_DOWNLOADED;
publicpublickey = false;
keyFilename = null;
keyFilePass = null;
serverName = null;
FTPSConnectionType = FTPSConnection.CONNECTION_TYPE_FTP;
setID(-1L);
}
public JobEntryFTPDelete() {
this("");
}
public Object clone() {
JobEntryFTPDelete je = (JobEntryFTPDelete) super.clone();
return je;
}
public String getXML() {
StringBuffer retval = new StringBuffer(128);
retval.append(super.getXML());
retval.append(" ").append(XMLHandler.addTagValue("protocol", protocol));
retval.append(" ").append(XMLHandler.addTagValue("servername", serverName));
retval.append(" ").append(XMLHandler.addTagValue("port", port));
retval.append(" ").append(XMLHandler.addTagValue("username", userName));
retval.append(" ").append(
XMLHandler.addTagValue("password", Encr.encryptPasswordIfNotUsingVariables(getPassword())));
retval.append(" ").append(XMLHandler.addTagValue("ftpdirectory", ftpDirectory));
retval.append(" ").append(XMLHandler.addTagValue("wildcard", wildcard));
retval.append(" ").append(XMLHandler.addTagValue("timeout", timeout));
retval.append(" ").append(XMLHandler.addTagValue("active", activeConnection));
retval.append(" ").append(XMLHandler.addTagValue("useproxy", useproxy));
retval.append(" ").append(XMLHandler.addTagValue("proxy_host", proxyHost));
retval.append(" ").append(XMLHandler.addTagValue("proxy_port", proxyPort));
retval.append(" ").append(XMLHandler.addTagValue("proxy_username", proxyUsername));
retval
.append(" ").append(XMLHandler.addTagValue("proxy_password", Encr.encryptPasswordIfNotUsingVariables(proxyPassword)));
retval.append(" ").append(XMLHandler.addTagValue("publicpublickey", publicpublickey));
retval.append(" ").append(XMLHandler.addTagValue("keyfilename", keyFilename));
retval.append(" ").append(XMLHandler.addTagValue("keyfilepass", keyFilePass));
retval.append(" ").append(XMLHandler.addTagValue("nr_limit_success", nr_limit_success));
retval.append(" ").append(XMLHandler.addTagValue("success_condition", success_condition));
retval.append(" ").append(XMLHandler.addTagValue("copyprevious", copyprevious));
retval.append(" ").append(
XMLHandler.addTagValue("ftps_connection_type", FTPSConnection.getConnectionTypeCode(FTPSConnectionType)));
retval.append(" ").append(XMLHandler.addTagValue("socksproxy_host", socksProxyHost));
retval.append(" ").append(XMLHandler.addTagValue("socksproxy_port", socksProxyPort));
retval.append(" ").append(XMLHandler.addTagValue("socksproxy_username", socksProxyUsername));
retval
.append(" ").append(XMLHandler.addTagValue("socksproxy_password", Encr.encryptPasswordIfNotUsingVariables(getSocksProxyPassword())));
return retval.toString();
}
public void loadXML(Node entrynode, List<DatabaseMeta> databases, List<SlaveServer> slaveServers, Repository rep, IMetaStore metaStore)
throws KettleXMLException {
try {
super.loadXML(entrynode, databases, slaveServers);
protocol = XMLHandler.getTagValue(entrynode, "protocol");
port = XMLHandler.getTagValue(entrynode, "port");
serverName = XMLHandler.getTagValue(entrynode, "servername");
userName = XMLHandler.getTagValue(entrynode, "username");
password = Encr.decryptPasswordOptionallyEncrypted(XMLHandler.getTagValue(entrynode, "password"));
ftpDirectory = XMLHandler.getTagValue(entrynode, "ftpdirectory");
wildcard = XMLHandler.getTagValue(entrynode, "wildcard");
timeout = Const.toInt(XMLHandler.getTagValue(entrynode, "timeout"), 10000);
activeConnection = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "active"));
useproxy = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "useproxy"));
proxyHost = XMLHandler.getTagValue(entrynode, "proxy_host");
proxyPort = XMLHandler.getTagValue(entrynode, "proxy_port");
proxyUsername = XMLHandler.getTagValue(entrynode, "proxy_username");
proxyPassword = Encr.decryptPasswordOptionallyEncrypted(XMLHandler.getTagValue(entrynode, "proxy_password"));
publicpublickey = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "publicpublickey"));
keyFilename = XMLHandler.getTagValue(entrynode, "keyfilename");
keyFilePass = XMLHandler.getTagValue(entrynode, "keyfilepass");
nr_limit_success = XMLHandler.getTagValue(entrynode, "nr_limit_success");
success_condition = XMLHandler.getTagValue(entrynode, "success_condition");
copyprevious = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "copyprevious"));
FTPSConnectionType = FTPSConnection.getConnectionTypeByCode(Const.NVL(
XMLHandler.getTagValue(entrynode, "ftps_connection_type"), ""));
socksProxyHost = XMLHandler.getTagValue(entrynode, "socksproxy_host");
socksProxyPort = XMLHandler.getTagValue(entrynode, "socksproxy_port");
socksProxyUsername = XMLHandler.getTagValue(entrynode, "socksproxy_username");
socksProxyPassword = Encr.decryptPasswordOptionallyEncrypted(XMLHandler.getTagValue(entrynode,
"socksproxy_password"));
} catch (KettleXMLException xe) {
throw new KettleXMLException("Unable to load job entry of type 'ftp' from XML node", xe);
}
}
public void loadRep(Repository rep, IMetaStore metaStore, ObjectId id_jobentry, List<DatabaseMeta> databases, List<SlaveServer> slaveServers)
throws KettleException {
try {
protocol = rep.getJobEntryAttributeString(id_jobentry, "protocol");
port = rep.getJobEntryAttributeString(id_jobentry, "port");
serverName = rep.getJobEntryAttributeString(id_jobentry, "servername");
userName = rep.getJobEntryAttributeString(id_jobentry, "username");
password = Encr.decryptPasswordOptionallyEncrypted(rep.getJobEntryAttributeString(id_jobentry, "password"));
ftpDirectory = rep.getJobEntryAttributeString(id_jobentry, "ftpdirectory");
wildcard = rep.getJobEntryAttributeString(id_jobentry, "wildcard");
timeout = (int) rep.getJobEntryAttributeInteger(id_jobentry, "timeout");
activeConnection = rep.getJobEntryAttributeBoolean(id_jobentry, "active");
copyprevious = rep.getJobEntryAttributeBoolean(id_jobentry, "copyprevious");
useproxy = rep.getJobEntryAttributeBoolean(id_jobentry, "useproxy");
proxyHost = rep.getJobEntryAttributeString(id_jobentry, "proxy_host");
proxyPort = rep.getJobEntryAttributeString(id_jobentry, "proxy_port");
proxyUsername = rep.getJobEntryAttributeString(id_jobentry, "proxy_username");
proxyPassword = Encr.decryptPasswordOptionallyEncrypted(rep.getJobEntryAttributeString(id_jobentry,
"proxy_password"));
publicpublickey = rep.getJobEntryAttributeBoolean(id_jobentry, "publicpublickey");
keyFilename = rep.getJobEntryAttributeString(id_jobentry, "keyfilename");
keyFilePass = rep.getJobEntryAttributeString(id_jobentry, "keyfilepass");
nr_limit_success = rep.getJobEntryAttributeString(id_jobentry, "nr_limit_success");
success_condition = rep.getJobEntryAttributeString(id_jobentry, "success_condition");
FTPSConnectionType = FTPSConnection.getConnectionTypeByCode(Const.NVL(
rep.getJobEntryAttributeString(id_jobentry, "ftps_connection_type"), ""));
socksProxyHost = rep.getJobEntryAttributeString(id_jobentry, "socksproxy_host");
socksProxyPort = rep.getJobEntryAttributeString(id_jobentry, "socksproxy_port");
socksProxyUsername = rep.getJobEntryAttributeString(id_jobentry, "socksproxy_username");
socksProxyPassword = Encr.decryptPasswordOptionallyEncrypted(rep.getJobEntryAttributeString(id_jobentry,
"socksproxy_password"));
} catch (KettleException dbe) {
throw new KettleException("Unable to load job entry of type 'ftp' from the repository for id_jobentry="
+ id_jobentry, dbe);
}
}
public void saveRep(Repository rep, IMetaStore metaStore, ObjectId id_job) throws KettleException {
try {
rep.saveJobEntryAttribute(id_job, getObjectId(), "protocol", protocol);
rep.saveJobEntryAttribute(id_job, getObjectId(), "port", port);
rep.saveJobEntryAttribute(id_job, getObjectId(), "servername", serverName);
rep.saveJobEntryAttribute(id_job, getObjectId(), "username", userName);
rep.saveJobEntryAttribute(id_job, getObjectId(), "password", Encr.encryptPasswordIfNotUsingVariables(password));
rep.saveJobEntryAttribute(id_job, getObjectId(), "ftpdirectory", ftpDirectory);
rep.saveJobEntryAttribute(id_job, getObjectId(), "wildcard", wildcard);
rep.saveJobEntryAttribute(id_job, getObjectId(), "timeout", timeout);
rep.saveJobEntryAttribute(id_job, getObjectId(), "active", activeConnection);
rep.saveJobEntryAttribute(id_job, getObjectId(), "copyprevious", copyprevious);
rep.saveJobEntryAttribute(id_job, getObjectId(), "useproxy", useproxy);
rep.saveJobEntryAttribute(id_job, getObjectId(), "publicpublickey", publicpublickey);
rep.saveJobEntryAttribute(id_job, getObjectId(), "keyfilename", keyFilename);
rep.saveJobEntryAttribute(id_job, getObjectId(), "keyfilepass", keyFilePass);
rep.saveJobEntryAttribute(id_job, getObjectId(), "proxy_host", proxyHost);
rep.saveJobEntryAttribute(id_job, getObjectId(), "proxy_port", proxyPort);
rep.saveJobEntryAttribute(id_job, getObjectId(), "proxy_username", proxyUsername);
rep.saveJobEntryAttribute(id_job, getObjectId(),
"proxy_password", Encr.encryptPasswordIfNotUsingVariables(proxyPassword));
rep.saveJobEntryAttribute(id_job, getObjectId(), "nr_limit_success", nr_limit_success);
rep.saveJobEntryAttribute(id_job, getObjectId(), "success_condition", success_condition);
rep.saveJobEntryAttribute(id_job, getObjectId(), "ftps_connection_type",
FTPSConnection.getConnectionType(FTPSConnectionType));
rep.saveJobEntryAttribute(id_job, getObjectId(), "socksproxy_host", socksProxyHost);
rep.saveJobEntryAttribute(id_job, getObjectId(), "socksproxy_port", socksProxyPort);
rep.saveJobEntryAttribute(id_job, getObjectId(), "socksproxy_username", socksProxyUsername);
rep.saveJobEntryAttribute(id_job, getObjectId(),
"socksproxy_password", Encr.encryptPasswordIfNotUsingVariables(socksProxyPassword));
} catch (KettleDatabaseException dbe) {
throw new KettleException("Unable to save job entry of type 'ftp' to the repository for id_job=" + id_job, dbe);
}
}
private boolean getStatus() {
boolean retval = false;
if ((NrErrors == 0 && getSuccessCondition().equals(SUCCESS_IF_ALL_FILES_DOWNLOADED))
|| (NrfilesDeleted >= limitFiles && getSuccessCondition().equals(SUCCESS_IF_AT_LEAST_X_FILES_DOWNLOADED))
|| (NrErrors <= limitFiles && getSuccessCondition().equals(SUCCESS_IF_ERRORS_LESS))) {
retval = true;
}
return retval;
}
public boolean isCopyPrevious() {
return copyprevious;
}
public void setCopyPrevious(boolean copyprevious) {
this.copyprevious = copyprevious;
}
/**
* @param publickey The publicpublickey to set.
*/
public void setUsePublicKey(boolean publickey) {
this.publicpublickey = publickey;
}
/**
* @return Returns the use public key.
*/
public boolean isUsePublicKey() {
return publicpublickey;
}
/**
* @param keyfilename The key filename to set.
*/
public void setKeyFilename(String keyfilename) {
this.keyFilename = keyfilename;
}
/**
* @return Returns the key filename.
*/
public String getKeyFilename() {
return keyFilename;
}
/**
* @param keyFilePass The key file pass to set.
*/
public void setKeyFilePass(String keyFilePass) {
this.keyFilePass = keyFilePass;
}
/**
* @return Returns the key file pass.
*/
public String getKeyFilePass() {
return keyFilePass;
}
/**
* @return the connection type
*/
public int getFTPSConnectionType() {
return FTPSConnectionType;
}
/**
* @param connectionType the connectionType to set
*/
public void setFTPSConnectionType(int type) {
FTPSConnectionType = type;
}
public void setLimitSuccess(String nr_limit_successin) {
this.nr_limit_success = nr_limit_successin;
}
public String getLimitSuccess() {
return nr_limit_success;
}
public void setSuccessCondition(String success_condition) {
this.success_condition = success_condition;
}
public String getSuccessCondition() {
return success_condition;
}
/**
* @return Returns the directory.
*/
public String getFtpDirectory() {
return ftpDirectory;
}
/**
* @param directory The directory to set.
*/
public void setFtpDirectory(String directory) {
this.ftpDirectory = directory;
}
/**
* @return Returns the password.
*/
public String getPassword() {
return password;
}
/**
* @param password The password to set.
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @return Returns the serverName.
*/
public String getServerName() {
return serverName;
}
/**
* @param serverName The serverName to set.
*/
public void setServerName(String serverName) {
this.serverName = serverName;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public String getProtocol() {
return protocol;
}
/**
* @return Returns the userName.
*/
public String getUserName() {
return userName;
}
/**
* @param userName The userName to set.
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* @return Returns the wildcard.
*/
public String getWildcard() {
return wildcard;
}
/**
* @param wildcard The wildcard to set.
*/
public void setWildcard(String wildcard) {
this.wildcard = wildcard;
}
/**
* @param timeout The timeout to set.
*/
public void setTimeout(int timeout) {
this.timeout = timeout;
}
/**
* @return Returns the timeout.
*/
public int getTimeout() {
return timeout;
}
/**
* @return Returns the hostname of the ftp-proxy.
*/
public String getProxyHost() {
return proxyHost;
}
/**
* @param proxyHost The hostname of the proxy.
*/
public void setProxyHost(String proxyHost) {
this.proxyHost = proxyHost;
}
public boolean isUseProxy() {
return useproxy;
}
public void setUseProxy(boolean useproxy) {
this.useproxy = useproxy;
}
/**
* @return Returns the password which is used to authenticate at the proxy.
*/
public String getProxyPassword() {
return proxyPassword;
}
/**
* @param proxyPassword The password which is used to authenticate at the proxy.
*/
public void setProxyPassword(String proxyPassword) {
this.proxyPassword = proxyPassword;
}
/**
* @return Returns the port of the ftp.
*/
public String getPort() {
return port;
}
/**
* @param proxyPort The port of the ftp.
*/
public void setPort(String port) {
this.port = port;
}
/**
* @return Returns the port of the ftp-proxy.
*/
public String getProxyPort() {
return proxyPort;
}
/**
* @param proxyPort The port of the ftp-proxy.
*/
public void setProxyPort(String proxyPort) {
this.proxyPort = proxyPort;
}
/**
* @return Returns the username which is used to authenticate at the proxy.
*/
public String getProxyUsername() {
return proxyUsername;
}
/**
* @param proxyUsername The username which is used to authenticate at the proxy.
*/
public void setProxyUsername(String proxyUsername) {
this.proxyUsername = proxyUsername;
}
@SuppressWarnings("unchecked")
// Needed for the Vector coming from sshclient.ls()
public Result execute(Result previousResult, int nr) {
log.logBasic(BaseMessages.getString(PKG, "JobEntryFTPDelete.Started", serverName));
RowMetaAndData resultRow = null;
Result result = previousResult;
List<RowMetaAndData> rows = result.getRows();
result.setResult(false);
NrErrors = 0;
NrfilesDeleted = 0;
successConditionBroken = false;
HashSet<String> list_previous_files = new HashSet<String>();
// Here let's put some controls before stating the job
String realservername = environmentSubstitute(serverName);
String realserverpassword = Encr.decryptPasswordOptionallyEncrypted(environmentSubstitute(password));
String realFtpDirectory = environmentSubstitute(ftpDirectory);
int realserverport = Const.toInt(environmentSubstitute(port), 0);
String realUsername = environmentSubstitute(userName);
String realPassword = Encr.decryptPasswordOptionallyEncrypted(environmentSubstitute(password));
String realproxyhost = environmentSubstitute(proxyHost);
String realproxyusername = environmentSubstitute(proxyUsername);
String realproxypassword = environmentSubstitute(proxyPassword);
int realproxyport = Const.toInt(environmentSubstitute(proxyPort), 0);
String realkeyFilename = environmentSubstitute(keyFilename);
String realkeyPass = environmentSubstitute(keyFilePass);
// PDI The following is used to apply a path for SSH because the SFTPv3Client doesn't let us specify/change dirs
String sourceFolder = "";
if (isDetailed())
logDetailed(BaseMessages.getString(PKG, "JobEntryFTPDelete.Start"));
if (copyprevious && rows.size() == 0) {
if (isDetailed())
logDetailed(BaseMessages.getString(PKG, "JobEntryFTPDelete.ArgsFromPreviousNothing"));
result.setResult(true);
return result;
}
try {
// Get all the files in the current directory...
String[] filelist = null;
if (protocol.equals(PROTOCOL_FTP)) {
// If socks proxy server was provided
if (!Const.isEmpty(socksProxyHost)) {
if (!Const.isEmpty(socksProxyPort)) {
FTPClient.initSOCKS(environmentSubstitute(socksProxyPort), environmentSubstitute(socksProxyHost));
} else {
throw new FTPException(BaseMessages.getString(PKG, "JobEntryFTPDelete.SocksProxy.PortMissingException",
environmentSubstitute(socksProxyHost), getName()));
}
// then if we have authentication information
if (!Const.isEmpty(socksProxyUsername) && !Const.isEmpty(socksProxyPassword)) {
FTPClient.initSOCKSAuthentication(environmentSubstitute(socksProxyUsername),
environmentSubstitute(socksProxyPassword));
} else if (!Const.isEmpty(socksProxyUsername) && Const.isEmpty(socksProxyPassword)
|| Const.isEmpty(socksProxyUsername) && !Const.isEmpty(socksProxyPassword)) {
// we have a username without a password or vica versa
throw new FTPException(BaseMessages.getString(PKG, "JobEntryFTPDelete.SocksProxy.IncompleteCredentials",
environmentSubstitute(socksProxyHost), getName()));
}
}
// establish the connection
FTPConnect(realservername, realUsername, realPassword, realserverport, realFtpDirectory, realproxyhost,
realproxyusername, realproxypassword, realproxyport, timeout);
filelist = ftpclient.dir();
// Some FTP servers return a message saying no files found as a string in the filenlist
// e.g. Solaris 8
// CHECK THIS !!!
if (filelist.length == 1) {
String translatedWildcard = environmentSubstitute(wildcard);
if (!Const.isEmpty(translatedWildcard)) {
if (filelist[0].startsWith(translatedWildcard)) {
throw new FTPException(filelist[0]);
}
}
}
} else if (protocol.equals(PROTOCOL_FTPS)) {
// establish the secure connection
FTPSConnect(realservername, realUsername, realserverport, realPassword, realFtpDirectory, timeout);
// Get all the files in the current directory...
filelist = ftpsclient.getFileNames();
} else if (protocol.equals(PROTOCOL_SFTP)) {
// establish the secure connection
SFTPConnect(realservername, realUsername, realserverport, realPassword, realFtpDirectory);
// Get all the files in the current directory...
filelist = sftpclient.dir();
} else if (protocol.equals(PROTOCOL_SSH)) {
// establish the secure connection
SSHConnect(realservername, realserverpassword, realserverport, realUsername, realPassword, realproxyhost,
realproxyusername, realproxypassword, realproxyport, realkeyFilename, realkeyPass);
sourceFolder = ".";
if (realFtpDirectory != null)
sourceFolder = realFtpDirectory + "/";
else
sourceFolder = "./";
// NOTE: Source of the unchecked warning suppression for the declaration of this method.
Vector<SFTPv3DirectoryEntry> vfilelist = sshclient.ls(sourceFolder);
if (vfilelist != null) {
// Make one pass through the vfilelist to get an accurate count
// Using the two-pass method with arrays is faster than using ArrayList
int fileCount = 0;
Iterator<SFTPv3DirectoryEntry> iterator = vfilelist.iterator();
while (iterator.hasNext()) {
SFTPv3DirectoryEntry dirEntry = iterator.next();
if (dirEntry != null && !dirEntry.filename.equals(".") && !dirEntry.filename.equals("..")
&& !isDirectory(sshclient, sourceFolder + dirEntry.filename)) {
fileCount++;
}
}
// Now that we have the correct count, create and fill in the array
filelist = new String[fileCount];
iterator = vfilelist.iterator();
int i = 0;
while (iterator.hasNext()) {
SFTPv3DirectoryEntry dirEntry = iterator.next();
if (dirEntry != null && !dirEntry.filename.equals(".") && !dirEntry.filename.equals("..")
&& !isDirectory(sshclient, sourceFolder + dirEntry.filename)) {
filelist[i] = dirEntry.filename;
i++;
}
}
}
}
if (isDetailed())
logDetailed("JobEntryFTPDelete.FoundNFiles", String.valueOf(filelist.length));
int found = filelist == null ? 0 : filelist.length;
if (found == 0) {
result.setResult(true);
return result;
}
Pattern pattern = null;
if (copyprevious) {
// Copy the input row to the (command line) arguments
for (int iteration = 0; iteration < rows.size(); iteration++) {
resultRow = rows.get(iteration);
// Get file names
String file_previous = resultRow.getString(0, null);
if (!Const.isEmpty(file_previous)) {
list_previous_files.add(file_previous);
}
}
} else {
if (!Const.isEmpty(wildcard)) {
String realWildcard = environmentSubstitute(wildcard);
pattern = Pattern.compile(realWildcard);
}
}
if (!getSuccessCondition().equals(SUCCESS_IF_ALL_FILES_DOWNLOADED))
limitFiles = Const.toInt(environmentSubstitute(getLimitSuccess()), 10);
// Get the files in the list...
for (int i = 0; i < filelist.length && !parentJob.isStopped(); i++) {
if (successConditionBroken)
throw new Exception(BaseMessages.getString(PKG, "JobEntryFTPDelete.SuccesConditionBroken"));
boolean getIt = false;
if (isDebug())
logDebug(BaseMessages.getString(PKG, "JobEntryFTPDelete.AnalysingFile", filelist[i]));
try {
// First see if the file matches the regular expression!
if (copyprevious) {
if (list_previous_files.contains(filelist[i]))
getIt = true;
} else {
if (pattern != null) {
Matcher matcher = pattern.matcher(filelist[i]);
getIt = matcher.matches();
}
}
if (getIt) {
// Delete file
if (protocol.equals(PROTOCOL_FTP)) {
ftpclient.delete(filelist[i]);
}
if (protocol.equals(PROTOCOL_FTPS)) {
System.out.println("---------------" + filelist[i]);
ftpsclient.deleteFile(filelist[i]);
} else if (protocol.equals(PROTOCOL_SFTP)) {
sftpclient.delete(filelist[i]);
} else if (protocol.equals(PROTOCOL_SSH)) {
sshclient.rm(sourceFolder + filelist[i]);
}
if (isDetailed())
logDetailed("JobEntryFTPDelete.RemotefileDeleted", filelist[i]);
updateDeletedFiles();
}
} catch (Exception e) {
// Update errors number
updateErrors();
logError(BaseMessages.getString(PKG, "JobFTP.UnexpectedError", e.getMessage()));
if (successConditionBroken)
throw new Exception(BaseMessages.getString(PKG, "JobEntryFTPDelete.SuccesConditionBroken"));
}
} // end for
} catch (Exception e) {
updateErrors();
logError(BaseMessages.getString(PKG, "JobEntryFTPDelete.ErrorGetting", e.getMessage()));
logError(Const.getStackTracker(e));
} finally {
if (ftpclient != null && ftpclient.connected()) {
try {
ftpclient.quit();
ftpclient = null;
} catch (Exception e) {
logError(BaseMessages.getString(PKG, "JobEntryFTPDelete.ErrorQuitting", e.getMessage()));
}
}
if (ftpsclient != null) {
try {
ftpsclient.disconnect();
} catch (Exception e) {
logError(BaseMessages.getString(PKG, "JobEntryFTPDelete.ErrorQuitting", e.getMessage()));
}
}
if (sftpclient != null) {
try {
sftpclient.disconnect();
sftpclient = null;
} catch (Exception e) {
logError(BaseMessages.getString(PKG, "JobEntryFTPDelete.ErrorQuitting", e.getMessage()));
}
}
if (sshclient != null) {
try {
sshclient.close();
sshclient = null;
} catch (Exception e) {
logError(BaseMessages.getString(PKG, "JobEntryFTPDelete.ErrorQuitting", e.getMessage()));
}
}
FTPClient.clearSOCKS();
}
result.setResult(!successConditionBroken);
result.setNrFilesRetrieved(NrfilesDeleted);
result.setNrErrors(NrErrors);
return result;
}
/**
* Checks if file is a directory
*
* @param sftpClient
* @param filename
* @return true, if filename is a directory
*/
public boolean isDirectory(SFTPv3Client sftpClient, String filename) {
try {
return sftpClient.stat(filename).isDirectory();
} catch (Exception e) {
}
return false;
}
private void SSHConnect(String realservername, String realserverpassword, int realserverport, String realUsername,
String realPassword, String realproxyhost, String realproxyusername, String realproxypassword, int realproxyport,
String realkeyFilename, String realkeyPass) throws Exception {
/* Create a connection instance */
Connection conn = new Connection(realservername, realserverport);
/* We want to connect through a HTTP proxy */
if (useproxy) {
conn.setProxyData(new HTTPProxyData(realproxyhost, realproxyport));
/* Now connect */
// if the proxy requires basic authentication:
if (!Const.isEmpty(realproxyusername) || !Const.isEmpty(realproxypassword)) {
conn.setProxyData(new HTTPProxyData(realproxyhost, realproxyport, realproxyusername, realproxypassword));
}
}
if (timeout > 0) {
// Use timeout
conn.connect(null, 0, timeout * 1000);
} else {
// Cache Host Key
conn.connect();
}
// Authenticate
boolean isAuthenticated = false;
if (publicpublickey) {
isAuthenticated = conn.authenticateWithPublicKey(realUsername, new File(realkeyFilename), realkeyPass);
} else {
isAuthenticated = conn.authenticateWithPassword(realUsername, realserverpassword);
}
if (!isAuthenticated)
throw new Exception("Can not connect to ");
sshclient = new SFTPv3Client(conn);
}
private void SFTPConnect(String realservername, String realusername, int realport, String realpassword,
String realFTPDirectory) throws Exception {
// Create sftp client to host ...
sftpclient = new SFTPClient(InetAddress.getByName(realservername), realport, realusername);
//if(isDetailed()) logDetailed("Opened SFTP connection to server ["+realServerName+"] on port ["+realServerPort+"] with username ["+realUsername+"]");
// login to ftp host ...
sftpclient.login(realpassword);
// move to spool dir ...
if (!Const.isEmpty(realFTPDirectory)) {
sftpclient.chdir(realFTPDirectory);
if (isDetailed())
logDetailed("Changed to directory [" + realFTPDirectory + "]");
}
}
private void FTPSConnect(String realservername, String realusername, int realport, String realpassword,
String realFTPDirectory, int realtimeout) throws Exception {
// Create ftps client to host ...
ftpsclient = new FTPSConnection(getFTPSConnectionType(), realservername, realport, realusername, realpassword);
if (!Const.isEmpty(proxyHost)) {
String realProxy_host = environmentSubstitute(proxyHost);
String realProxy_username = environmentSubstitute(proxyUsername);
String realProxy_password = environmentSubstitute(proxyPassword);
ftpsclient.setProxyHost(realProxy_host);
if (!Const.isEmpty(realProxy_username)) {
ftpsclient.setProxyUser(realProxy_username);
}
if (!Const.isEmpty(realProxy_password)) {
ftpsclient.setProxyPassword(realProxy_password);
}
if (isDetailed())
logDetailed(BaseMessages.getString(PKG, "JobEntryFTPDelete.OpenedProxyConnectionOn", realProxy_host));
int proxyport = Const.toInt(environmentSubstitute(proxyPort), 21);
if (proxyport != 0) {
ftpsclient.setProxyPort(proxyport);
}
} else {
if (isDetailed())
logDetailed(BaseMessages.getString(PKG, "JobEntryFTPDelete.OpenedConnectionTo", realservername));
}
// set activeConnection connectmode ...
if (activeConnection) {
ftpsclient.setPassiveMode(false);
if (isDetailed())
logDetailed(BaseMessages.getString(PKG, "JobEntryFTPDelete.SetActive"));
} else {
ftpsclient.setPassiveMode(true);
if (isDetailed())
logDetailed(BaseMessages.getString(PKG, "JobEntryFTPDelete.SetPassive"));
}
// Set the timeout
ftpsclient.setTimeOut(realtimeout);
if (isDetailed())
logDetailed(BaseMessages.getString(PKG, "JobEntryFTPDelete.SetTimeout", String.valueOf(realtimeout)));
// now connect
ftpsclient.connect();
// move to spool dir ...
if (!Const.isEmpty(realFTPDirectory)) {
ftpsclient.changeDirectory(realFTPDirectory);
if (isDetailed())
logDetailed("Changed to directory [" + realFTPDirectory + "]");
}
}
private void FTPConnect(String realServername, String realusername, String realpassword, int realport,
String realFtpDirectory, String realProxyhost, String realproxyusername, String realproxypassword,
int realproxyport, int realtimeout) throws Exception {
// Create ftp client to host:port ...
ftpclient = new FTPClient();
ftpclient.setRemoteAddr(InetAddress.getByName(realServername));
if (realport != 0)
ftpclient.setRemotePort(realport);
if (!Const.isEmpty(realProxyhost)) {
ftpclient.setRemoteAddr(InetAddress.getByName(realProxyhost));
if (isDetailed())
logDetailed(BaseMessages.getString(PKG, "JobEntryFTPDelete.OpenedProxyConnectionOn", realProxyhost));
// FIXME: Proper default port for proxy
if (realproxyport != 0) {
ftpclient.setRemotePort(realproxyport);
}
} else {
ftpclient.setRemoteAddr(InetAddress.getByName(realServername));
if (isDetailed())
logDetailed(BaseMessages.getString(PKG, "JobEntryFTPDelete.OpenedConnectionTo", realServername));
}
// set activeConnection connectmode ...
if (activeConnection) {
ftpclient.setConnectMode(FTPConnectMode.ACTIVE);
if (isDetailed())
logDetailed(BaseMessages.getString(PKG, "JobEntryFTPDelete.SetActive"));
} else {
ftpclient.setConnectMode(FTPConnectMode.PASV);
if (isDetailed())
logDetailed(BaseMessages.getString(PKG, "JobEntryFTPDelete.SetPassive"));
}
// Set the timeout
ftpclient.setTimeout(realtimeout);
if (isDetailed())
logDetailed(BaseMessages.getString(PKG, "JobEntryFTPDelete.SetTimeout", String.valueOf(realtimeout)));
// login to ftp host ...
ftpclient.connect();
String realUsername = realusername + (!Const.isEmpty(realProxyhost) ? "@" + realServername : "")
+ (!Const.isEmpty(realproxyusername) ? " " + realproxyusername : "");
String realPassword = realpassword + (!Const.isEmpty(realproxypassword) ? " " + realproxypassword : "");
ftpclient.login(realUsername, realPassword);
// Remove password from logging, you don't know where it ends up.
if (isDetailed())
logDetailed(BaseMessages.getString(PKG, "JobEntryFTPDelete.LoggedIn", realUsername));
// move to spool dir ...
if (!Const.isEmpty(realFtpDirectory)) {
ftpclient.chdir(realFtpDirectory);
if (isDetailed())
logDetailed(BaseMessages.getString(PKG, "JobEntryFTPDelete.ChangedDir", realFtpDirectory));
}
}
private void updateErrors() {
NrErrors++;
if (!getStatus()) {
// Success condition was broken
successConditionBroken = true;
}
}
private void updateDeletedFiles() {
NrfilesDeleted++;
}
public boolean evaluates() {
return true;
}
/**
* @return the activeConnection
*/
public boolean isActiveConnection() {
return activeConnection;
}
/**
* @param activeConnection the activeConnection to set
*/
public void setActiveConnection(boolean passive) {
this.activeConnection = passive;
}
public void check(List<CheckResultInterface> remarks, JobMeta jobMeta, VariableSpace space, Repository repository, IMetaStore metaStore) {
andValidator().validate(this, "serverName", remarks, putValidators(notBlankValidator()));
andValidator()
.validate(this, "targetDirectory", remarks, putValidators(notBlankValidator(), fileExistsValidator()));
andValidator().validate(this, "userName", remarks, putValidators(notBlankValidator()));
andValidator().validate(this, "password", remarks, putValidators(notNullValidator()));
}
public List<ResourceReference> getResourceDependencies(JobMeta jobMeta) {
List<ResourceReference> references = super.getResourceDependencies(jobMeta);
if (!Const.isEmpty(serverName)) {
String realServername = jobMeta.environmentSubstitute(serverName);
ResourceReference reference = new ResourceReference(this);
reference.getEntries().add(new ResourceEntry(realServername, ResourceType.SERVER));
references.add(reference);
}
return references;
}
/**
* @return Socks proxy host
*/
public String getSocksProxyHost() {
return this.socksProxyHost;
}
/**
* @return Socks proxy port
*/
public String getSocksProxyPort() {
return this.socksProxyPort;
}
/**
* @return Socks proxy username
*/
public String getSocksProxyUsername() {
return this.socksProxyUsername;
}
/**
* @return Socks proxy username
*/
public String getSocksProxyPassword() {
return this.socksProxyPassword;
}
/**
* @return Sets socks proxy host
*/
public void setSocksProxyHost(String socksProxyHost) {
this.socksProxyHost = socksProxyHost;
}
/**
* @return Sets socks proxy port
*/
public void setSocksProxyPort(String socksProxyPort) {
this.socksProxyPort = socksProxyPort;
}
/**
* @return Sets socks proxy username
*/
public void setSocksProxyUsername(String socksProxyUsername) {
this.socksProxyUsername = socksProxyUsername;
}
/**
* @return Sets socks proxy username
*/
public void setSocksProxyPassword(String socksProxyPassword) {
this.socksProxyPassword = socksProxyPassword;
}
}
|
// Copyright (c) 2009 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.sdk.internal.v8native.value;
import java.util.ArrayList;
import java.util.List;
import org.chromium.sdk.FunctionScopeExtension;
import org.chromium.sdk.JsArray;
import org.chromium.sdk.JsFunction;
import org.chromium.sdk.JsScope;
import org.chromium.sdk.JsVariable;
import org.chromium.sdk.Script;
import org.chromium.sdk.TextStreamPosition;
import org.chromium.sdk.internal.v8native.DebugSession;
import org.chromium.sdk.internal.v8native.protocol.input.ScopeRef;
import org.chromium.sdk.internal.v8native.protocol.input.data.FunctionValueHandle;
import org.chromium.sdk.util.MethodIsBlockingException;
/**
* Generic implementation of {@link JsFunction}.
*/
public class JsFunctionImpl extends JsObjectBase<JsObjectBase.BasicPropertyData>
implements JsFunction {
private volatile TextStreamPosition openParenPosition = null;
JsFunctionImpl(ValueLoader valueLoader, ValueMirror valueState) {
super(valueLoader, valueState);
}
@Override
public Script getScript() throws MethodIsBlockingException {
final FunctionValueHandle functionValueHandle = getAdditionalPropertyData();
Long scriptId = functionValueHandle.scriptId();
if (scriptId == null) {
return null;
}
DebugSession debugSession = getInternalContext().getDebugSession();
return debugSession.getScriptManager().findById(scriptId);
}
private List<? extends JsScope> getVariableScopes() {
List<ScopeRef> rawScopes = getAdditionalPropertyData().scopes();
List<JsScopeImpl<?>> result = new ArrayList<JsScopeImpl<?>>(rawScopes.size());
for (ScopeRef scopeRef : rawScopes) {
result.add(JsScopeImpl.create(JsScopeImpl.Host.create(JsFunctionImpl.this), scopeRef));
}
return result;
}
@Override
public TextStreamPosition getOpenParenPosition() throws MethodIsBlockingException {
if (openParenPosition == null) {
final FunctionValueHandle functionValueHandle = getAdditionalPropertyData();
openParenPosition = new TextStreamPosition() {
@Override public int getOffset() {
return castLongToInt(functionValueHandle.position(), NO_POSITION);
}
@Override public int getLine() {
return castLongToInt(functionValueHandle.line(), NO_POSITION);
}
@Override public int getColumn() {
return castLongToInt(functionValueHandle.column(), NO_POSITION);
}
private int castLongToInt(Long objValue, int defaultValue) {
if (objValue == null) {
return defaultValue;
} else {
return objValue.intValue();
}
}
};
}
return openParenPosition;
}
private FunctionValueHandle getAdditionalPropertyData() throws MethodIsBlockingException {
SubpropertiesMirror subpropertiesMirror = getBasicPropertyData(false).getSubpropertiesMirror();
return (FunctionValueHandle) subpropertiesMirror.getAdditionalPropertyData();
}
@Override
public JsArray asArray() {
return null;
}
@Override
public JsFunction asFunction() {
return this;
}
@Override
protected BasicPropertyData wrapBasicData(BasicPropertyData basicPropertyData) {
return basicPropertyData;
}
@Override
protected BasicPropertyData unwrapBasicData(BasicPropertyData additionalPropertyStore) {
return additionalPropertyStore;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append("[JsFunction: type=").append(getType());
try {
for (JsVariable prop : getProperties()) {
result.append(',').append(prop);
}
} catch (MethodIsBlockingException e) {
return "[JsObject: Exception in retrieving data]";
}
result.append(']');
return result.toString();
}
public static final FunctionScopeExtension FUNCTION_SCOPE_EXTENSION =
new FunctionScopeExtension() {
@Override
public List<? extends JsScope> getScopes(JsFunction function)
throws MethodIsBlockingException {
JsFunctionImpl functionImpl = (JsFunctionImpl) function;
return functionImpl.getVariableScopes();
}
};
}
|
/**
* .java
* 类名:
*
* ver 变更日 变更人 变更内容
* ──────────────────────────────────
* V1.0 2014-8-12 lzy 初始生成
*
* Copyright 2014 浙江科技学院肉制品供应链跟踪与质量溯源系统项目小组
*/
package utils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* 通过传入Bean的名称,返回相应的对象
* @author lzy
* @version Ver1.0 2014-8-12
* @date(开发日期) 2014-8-12上午11:45:09
*/
public class SpringBeans {
public static String BEANSXML="spring/beans.xml";
public static Object getBeans(String BeansName){
Object obj = null;
ApplicationContext ctx = new ClassPathXmlApplicationContext(BEANSXML);
obj = ctx.getBean(BeansName);
return obj;
}
public static ApplicationContext getAppContext(){
return new ClassPathXmlApplicationContext(BEANSXML);
}
}
|
package q11191;
public class Greeting
{
public static void main(String[] args)
{
System.out.println("Hello "+args[0]+"!");
}
}
|
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~ Copyright 2017 Adobe Systems Incorporated
~
~ 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.adobe.cq.wcm.core.components.internal.servlets;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.metatype.annotations.AttributeDefinition;
import org.osgi.service.metatype.annotations.Designate;
import org.osgi.service.metatype.annotations.ObjectClassDefinition;
import com.adobe.cq.wcm.core.components.internal.form.FormConstants;
import com.day.cq.wcm.foundation.forms.FormStructureHelperFactory;
import com.day.cq.wcm.foundation.forms.FormsHandlingServletHelper;
import com.day.cq.wcm.foundation.security.SaferSlingPostValidator;
/**
* This form handling servlet accepts POSTs to a form container
* but only if the selector "form" and the extension "html" is used.
*/
@SuppressWarnings("serial")
@Component(
service = {Servlet.class, Filter.class},
configurationPid = "com.adobe.cq.wcm.core.components.commons.forms.impl.CoreFormsHandlingServlet",
property = {
"sling.servlet.resourceTypes=" + FormConstants.RT_CORE_FORM_CONTAINER_V1,
"sling.servlet.resourceTypes=" + FormConstants.RT_CORE_FORM_CONTAINER_V2,
"sling.servlet.methods=POST",
"sling.servlet.selectors=" + CoreFormHandlingServlet.SELECTOR,
"sling.servlet.extensions=" + CoreFormHandlingServlet.EXTENSION,
"sling.filter.scope=request",
"service.ranking:Integer=610",
}
)
@Designate(
ocd = CoreFormHandlingServlet.Configuration.class
)
public class CoreFormHandlingServlet
extends SlingAllMethodsServlet
implements Filter {
@ObjectClassDefinition(
name = "Core Form Handling Servlet",
description = "Accepts posting to a form container component and performs validations"
)
@interface Configuration {
@AttributeDefinition(
name = "Parameter Name Whitelist",
description = "List of name expressions that will pass request validation. A validation error will occur " +
"if any posted parameters are not in the whitelist and not defined on the form."
) String[] name_whitelist() default {};
@AttributeDefinition(
name = "Allow Expressoins",
description = "Evaluate expressions on form submissions."
) boolean allow_expressions() default true;
}
static final String SELECTOR = "form";
static final String EXTENSION = "html";
private static final Boolean PROP_ALLOW_EXPRESSION_DEFAULT = true;
private String[] dataNameWhitelist;
private FormsHandlingServletHelper formsHandlingServletHelper;
private boolean allowExpressions;
@Reference
private SaferSlingPostValidator validator;
@Reference
private FormStructureHelperFactory formStructureHelperFactory;
@Activate
protected void activate(Configuration configuration) {
dataNameWhitelist = PropertiesUtil.toStringArray(configuration.name_whitelist());
allowExpressions = PropertiesUtil.toBoolean(configuration.allow_expressions(), PROP_ALLOW_EXPRESSION_DEFAULT);
formsHandlingServletHelper = new FormsHandlingServletHelper(dataNameWhitelist, validator, FormConstants.RT_ALL_CORE_FORM_CONTAINER,
allowExpressions, formStructureHelperFactory);
}
/**
* @see org.apache.sling.api.servlets.SlingAllMethodsServlet#doPost(org.apache.sling.api.SlingHttpServletRequest, org.apache.sling.api.SlingHttpServletResponse)
*/
protected void doPost(SlingHttpServletRequest request,
final SlingHttpServletResponse response)
throws ServletException, IOException {
formsHandlingServletHelper.doPost(request, response);
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(final ServletRequest request,
final ServletResponse response,
final FilterChain chain)
throws IOException, ServletException {
formsHandlingServletHelper.handleFilter(request, response, chain, EXTENSION, SELECTOR);
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(final FilterConfig config) throws ServletException {
// nothing to do!
}
}
|
package com.siiconcatel.taskling.core.blocks.common;
public enum BlockExecutionStatus {
NotDefined(0),
NotStarted(1),
Started(2),
Completed(3),
Failed(4);
private int numVal;
BlockExecutionStatus(int numVal) {
this.numVal = numVal;
}
public int getNumVal() {
return numVal;
}
}
|
/*
* Copyright The Stargate 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 io.stargate.graphql.fetchers;
import com.datastax.oss.driver.api.querybuilder.SchemaBuilder;
import com.datastax.oss.driver.api.querybuilder.schema.AlterTableAddColumnEnd;
import com.datastax.oss.driver.api.querybuilder.schema.AlterTableStart;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import io.stargate.auth.AuthenticationService;
import io.stargate.auth.StoredCredentials;
import io.stargate.db.ClientState;
import io.stargate.db.Persistence;
import io.stargate.db.QueryState;
import io.stargate.db.datastore.DataStore;
import io.stargate.db.datastore.ResultSet;
import io.stargate.graphql.graphqlservlet.HTTPAwareContextImpl;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
public class AlterTableAddFetcher
implements io.stargate.graphql.fetchers.SchemaFetcher, DataFetcher {
private final Persistence persistence;
private AuthenticationService authenticationService;
public AlterTableAddFetcher(
Persistence persistence, AuthenticationService authenticationService) {
this.persistence = persistence;
this.authenticationService = authenticationService;
}
@Override
public Object get(DataFetchingEnvironment environment) throws Exception {
HTTPAwareContextImpl httpAwareContext = environment.getContext();
String token = httpAwareContext.getAuthToken();
StoredCredentials storedCredentials = authenticationService.validateToken(token);
ClientState clientState = persistence.newClientState(storedCredentials.getRoleName());
QueryState queryState = persistence.newQueryState(clientState);
DataStore dataStore = persistence.newDataStore(queryState, null);
CompletableFuture<ResultSet> resultSetSingle = dataStore.query(getQuery(environment));
resultSetSingle.get();
return true;
}
public String getQuery(DataFetchingEnvironment dataFetchingEnvironment) {
AlterTableStart start =
SchemaBuilder.alterTable(
(String) dataFetchingEnvironment.getArgument("keyspaceName"),
(String) dataFetchingEnvironment.getArgument("tableName"));
List<Map<String, Object>> toAdd = dataFetchingEnvironment.getArgument("toAdd");
if (toAdd.isEmpty()) {
// TODO see if we can enforce that through the schema instead
throw new IllegalArgumentException("toAdd must contain at least one element");
}
AlterTableAddColumnEnd table = null;
for (Map<String, Object> column : toAdd) {
if (table != null) {
table = table.addColumn((String) column.get("name"), decodeType(column.get("type")));
} else {
table = start.addColumn((String) column.get("name"), decodeType(column.get("type")));
}
}
return table.build().getQuery();
}
}
|
package com.vladmihalcea.hibernate.type.basic;
import com.vladmihalcea.hibernate.type.AbstractHibernateType;
import com.vladmihalcea.hibernate.type.basic.internal.YearMonthTypeDescriptor;
import com.vladmihalcea.hibernate.type.util.Configuration;
import org.hibernate.type.descriptor.sql.DateTypeDescriptor;
import java.time.YearMonth;
/**
* Maps a Java {@link java.time.YearMonth} object to a {@code DATE} column type.
* <p>
* For more details about how to use it, check out <a href="https://vladmihalcea.com/java-yearmonth-jpa-hibernate/">this article</a> on <a href="https://vladmihalcea.com/">vladmihalcea.com</a>.
*
* @author Vlad Mihalcea
*/
public class YearMonthDateType
extends AbstractHibernateType<YearMonth> {
public static final YearMonthDateType INSTANCE = new YearMonthDateType();
public YearMonthDateType() {
super(
DateTypeDescriptor.INSTANCE,
YearMonthTypeDescriptor.INSTANCE
);
}
public YearMonthDateType(Configuration configuration) {
super(
DateTypeDescriptor.INSTANCE,
YearMonthTypeDescriptor.INSTANCE,
configuration
);
}
public YearMonthDateType(org.hibernate.type.spi.TypeBootstrapContext typeBootstrapContext) {
this(new Configuration(typeBootstrapContext.getConfigurationSettings()));
}
public String getName() {
return "yearmonth-date";
}
@Override
protected boolean registerUnderJavaType() {
return true;
}
}
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.hc.core5.reactor;
import static org.mockito.Mockito.mock;
import org.junit.jupiter.api.Test;
public class IOWorkersTest {
@Test
public void testIndexOverflow() {
final SingleCoreIOReactor reactor = new SingleCoreIOReactor(null, mock(IOEventHandlerFactory.class), IOReactorConfig.DEFAULT, null, null, null);
final IOWorkers.Selector selector = IOWorkers.newSelector(new SingleCoreIOReactor[]{reactor, reactor, reactor});
for (long i = Integer.MAX_VALUE - 10; i < (long) Integer.MAX_VALUE + 10; i++) {
selector.next();
}
}
}
|
package nl.maastrichtuniversity.networklibrary.cyneo4j.internal.serviceprovider.sync;
import nl.maastrichtuniversity.networklibrary.cyneo4j.internal.serviceprovider.Neo4jRESTServer;
import nl.maastrichtuniversity.networklibrary.cyneo4j.internal.serviceprovider.general.ReturnCodeResponseHandler;
import nl.maastrichtuniversity.networklibrary.cyneo4j.internal.utils.CyUtils;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;
import org.cytoscape.model.CyEdge;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.model.CyNode;
import org.cytoscape.model.CyTable;
import org.cytoscape.work.AbstractTask;
import org.cytoscape.work.TaskMonitor;
import javax.swing.*;
import java.io.IOException;
public class SyncUpTask extends AbstractTask {
private boolean wipeRemote;
private String cypherURL;
private CyNetwork currNet;
private Neo4jRESTServer server;
public SyncUpTask(Neo4jRESTServer server, boolean wipeRemote, String cypherURL, CyNetwork currNet){
this.wipeRemote = wipeRemote;
this.cypherURL = cypherURL;
this.currNet = currNet;
this.server = server;
}
@Override
public void run(TaskMonitor taskMonitor) throws Exception {
CyNetwork currNet = getCurrentNetwork();
if(currNet == null){
JOptionPane.showMessageDialog(null, "No network selected!");
System.out.println("no network selected!");
return;
}
taskMonitor.setTitle("Synchronizing UP to the Server");
double progress = 0.0;
try {
boolean wiped = false;
if(wipeRemote){
taskMonitor.setStatusMessage("wiping remote network");
String wipeQuery = "{ \"query\" : \"MATCH (n) OPTIONAL MATCH (n)-[r]-() DELETE n,r\",\"params\" : {}}";
progress = 0.1;
taskMonitor.setProgress(progress);
// System.out.println(wipeQuery);
wiped = Request.Post(getCypherURL())
.addHeader("Authorization", server.getBasic64AuthInfo())
.bodyString(wipeQuery, ContentType.APPLICATION_JSON)
.execute().handleResponse(new ReturnCodeResponseHandler());
}
if(wiped == wipeRemote){
CyTable defNodeTab = currNet.getDefaultNodeTable();
if(defNodeTab.getColumn("neoid") == null){
defNodeTab.createColumn("neoid", Long.class, false);
}
double steps = currNet.getNodeList().size() + currNet.getEdgeList().size();
double stepSize = 0.9 / steps;
taskMonitor.setStatusMessage("uploading nodes");
for(CyNode node : currNet.getNodeList()){
String params = CyUtils.convertCyAttributesToJson(node, defNodeTab);
String cypher = "{ \"query\" : \"CREATE (n { props }) return id(n)\", \"params\" : { \"props\" : [ "+ params +" ] } }";
Long neoid = Request.Post(getCypherURL())
.addHeader("Authorization", server.getBasic64AuthInfo())
.bodyString(cypher, ContentType.APPLICATION_JSON)
.execute().handleResponse(new CreateIdReturnResponseHandler());
defNodeTab.getRow(node.getSUID()).set("neoid", neoid);
progress = progress + stepSize;
taskMonitor.setProgress(progress);
}
CyTable defEdgeTab = currNet.getDefaultEdgeTable();
if(defEdgeTab.getColumn("neoid") == null){
defEdgeTab.createColumn("neoid", Long.class, false);
}
for(CyEdge edge : currNet.getEdgeList()){
taskMonitor.setStatusMessage("uploading edges");
String from = edge.getSource().getSUID().toString();
String to = edge.getTarget().getSUID().toString();
String rparams = CyUtils.convertCyAttributesToJson(edge, defEdgeTab);
String rtype = defEdgeTab.getRow(edge.getSUID()).get(CyEdge.INTERACTION, String.class);
String cypher = "{\"query\" : \"MATCH (from { SUID: {fname}}),(to { SUID: {tname}}) CREATE (from)-[r:"+rtype+" { rprops } ]->(to) return id(r)\", \"params\" : { \"fname\" : "+from+", \"tname\" : "+to+", \"rprops\" : "+ rparams +" }}";
Long neoid = Request.Post(getCypherURL())
.addHeader("Authorization", server.getBasic64AuthInfo())
.bodyString(cypher, ContentType.APPLICATION_JSON)
.execute().handleResponse(new CreateIdReturnResponseHandler());
defEdgeTab.getRow(edge.getSUID()).set("neoid", neoid);
progress = progress + stepSize;
taskMonitor.setProgress(progress);
}
} else {
System.out.println("could not wipe the instance! aborting syncUp");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
protected CyNetwork getCurrentNetwork() {
return currNet;
}
protected String getCypherURL() {
return cypherURL;
}
protected boolean isWipeRemote() {
return wipeRemote;
}
protected void setWipeRemote(boolean wipeRemote) {
this.wipeRemote = wipeRemote;
}
}
|
/*
* Copyright RestClientGenerator
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.github.raphasil.generator.client.rest.core.model;
import java.util.Map;
import java.util.Set;
import lombok.Builder;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* @author Raphael Nascimento
*/
@Getter
@Builder
@RequiredArgsConstructor
public class Options {
private static final String SUPPRESS_GENERATOR_TIMESTAMP = "restClientGenerator.suppressGeneratorTimestamp";
private static final String SUPPRESS_GENERATOR_COMMENT = "restClientGenerator.suppressGeneratorComment";
private static final String VERBOSE = "restClientGenerator.verbose";
private static final String COMPILE_ARG_FORMAT = "-A%s=%s";
private final boolean suppressGeneratorTimestamp;
private final boolean suppressGeneratorComment;
private final String logLevel;
public static Options of(final Map<String, String> options) {
return Options.builder()
.suppressGeneratorComment(Boolean.parseBoolean(options.get(SUPPRESS_GENERATOR_COMMENT)))
.suppressGeneratorTimestamp(Boolean.parseBoolean(options.get(SUPPRESS_GENERATOR_TIMESTAMP)))
.logLevel(options.getOrDefault(VERBOSE, "warn"))
.build();
}
public static Set<String> supportedOptions() {
return Set.of(SUPPRESS_GENERATOR_TIMESTAMP, SUPPRESS_GENERATOR_COMMENT, VERBOSE);
}
public Iterable<String> toCompileArgs() {
return Set.of(String.format(COMPILE_ARG_FORMAT, SUPPRESS_GENERATOR_TIMESTAMP, suppressGeneratorTimestamp),
String.format(COMPILE_ARG_FORMAT, SUPPRESS_GENERATOR_COMMENT, suppressGeneratorComment),
String.format(COMPILE_ARG_FORMAT, VERBOSE, logLevel));
}
}
|
package com.jpa;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class HintPassDistinctThroughApplication {
@Autowired
private TennisArenaService tennisArenaService;
public static void main(String[] args) {
SpringApplication.run(HintPassDistinctThroughApplication.class, args);
}
@Bean
public ApplicationRunner init() {
return args -> {
tennisArenaService.fetchDistinctTournamentsWithDuplicates();
tennisArenaService.fetchDistinctTournamentsWithoutHint();
tennisArenaService.fetchDistinctTournamentsWithHint();
};
}
}
|
public class RouletteTester {
public static void main(String[] args) {
RoulettePlayer simulator = new RoulettePlayer();
for (int i = 0; i < 100000; i++) {
simulator.visitCasino(100, 200);
}
System.out.println("Probability of success: " + simulator.getWinProbability() + "%");
}
}
|
/**
* Copyright (c) 2019. Qubole 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. See accompanying LICENSE file.
*/
package com.qubole.rubix.core;
import com.google.common.annotations.VisibleForTesting;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import static com.google.common.base.Preconditions.checkState;
/**
* Created by stagra on 4/1/16.
* <p>
* One ReadRequestChain contains ReadRequests for same buffer
*
* ReadRequestChain works with `long` type, even though reads on input streams are limited by the capacity of `int`, in order
* to be generic and be useful in more cases than just reads on input streams. One such use case is of parallel warmup where
* reads are accumulated and merged for a period of time which can lead to reads of much bigger size than Integer.MAX_SIZE
*/
public abstract class ReadRequestChain implements Callable<Long>
{
List<ReadRequest> readRequests = new ArrayList<ReadRequest>();
ReadRequest lastRequest;
boolean isLocked;
boolean cancelled;
private long maxReadRequestSize;
protected final int generationNumber;
protected String threadName;
protected long requests;
private static final Log log = LogFactory.getLog(ReadRequestChain.class);
public ReadRequestChain(int generationNumber)
{
this(generationNumber, Long.MAX_VALUE);
}
// Caller responsible to keep maxReadRequestSize block aligned
public ReadRequestChain(int generationNumber, long maxReadRequestSize)
{
super();
this.generationNumber = generationNumber;
this.maxReadRequestSize = maxReadRequestSize;
this.threadName = Thread.currentThread().getName();
}
@VisibleForTesting
public void setMaxReadRequestSize(long maxReadRequestSize)
{
this.maxReadRequestSize = maxReadRequestSize;
}
// Should be added in forward seek fashion for better performance
public void addReadRequest(ReadRequest readRequest)
{
checkState(!isLocked, "Adding request to a locked chain");
if (lastRequest == null) {
lastRequest = readRequest;
}
else {
// since one chain contains request of same buffer, we can collate
if (lastRequest.getBackendReadEnd() == readRequest.getBackendReadStart()) {
// Since the ReadRequests coming in are for same buffer, can merge the two
lastRequest.setBackendReadEnd(readRequest.getBackendReadEnd());
lastRequest.setActualReadEnd(readRequest.getActualReadEnd());
}
else {
addRequest(lastRequest);
lastRequest = readRequest;
}
}
requests++;
}
private void addRequest(ReadRequest readRequest)
{
long backendReadLength = readRequest.getBackendReadLength();
if (backendReadLength <= maxReadRequestSize) {
addRequestToQueue(readRequest);
return;
}
long backendReadStart = 0;
long actualReadStart = readRequest.getActualReadStart();
while (backendReadStart < backendReadLength) {
long backendReadEnd = backendReadStart + Math.min(maxReadRequestSize, backendReadLength - backendReadStart);
ReadRequest chunkedRequest = new ReadRequest(
backendReadStart,
backendReadEnd,
actualReadStart,
Math.min(readRequest.getActualReadEnd(), backendReadEnd),
readRequest.getDestBuffer(),
readRequest.getDestBufferOffset() + Math.toIntExact(actualReadStart - readRequest.getActualReadStart()),
readRequest.getBackendFileSize());
addRequestToQueue(chunkedRequest);
backendReadStart = backendReadEnd;
actualReadStart = backendReadStart;
}
}
private void addRequestToQueue(ReadRequest readRequest)
{
readRequests.add(readRequest);
log.debug(String.format("Added ReadRequest: [%d, %d, %d, %d, %d]", readRequest.getBackendReadStart(), readRequest.getBackendReadEnd(), readRequest.getActualReadStart(), readRequest.getActualReadEnd(), readRequest.getDestBufferOffset()));
}
public void lock()
{
isLocked = true;
if (lastRequest != null) {
addRequest(lastRequest);
lastRequest = null;
}
}
public List<ReadRequest> getReadRequests()
{
return readRequests;
}
public abstract ReadRequestChainStats getStats();
/*
* This method is used called to update the cache status after read has been done
*/
public void updateCacheStatus(String remotePath, long fileSize, long lastModified, int blockSize, Configuration conf)
{
// no-op by default
}
public void cancel()
{
cancelled = true;
}
protected void propagateCancel(String className)
throws IOException
{
throw new CancelledException(className + " Cancelled");
}
protected class CancelledException
extends IOException
{
public CancelledException(String message)
{
super(message);
}
}
protected class InvalidationRequiredException
extends IOException
{
public InvalidationRequiredException(String message)
{
super(message);
}
}
public boolean isCancelled()
{
return cancelled;
}
public boolean isLocked()
{
return isLocked;
}
}
|
/*
* Copyright (c) 2016 United States Government as represented by the Administrator of the
* National Aeronautics and Space Administration. All Rights Reserved.
*/
package gov.nasa.worldwind;
import androidx.annotation.NonNull;
import gov.nasa.worldwind.geom.Position;
import gov.nasa.worldwind.layer.Layer;
import gov.nasa.worldwind.render.Color;
import gov.nasa.worldwind.render.Renderable;
import gov.nasa.worldwind.util.Logger;
public class PickedObject {
protected boolean isOnTop;
protected int identifier;
protected Object userObject;
protected Layer layer;
protected Position terrainPosition;
protected PickedObject() {
}
public static PickedObject fromRenderable(int identifier, Renderable renderable, Layer layer) {
if (renderable == null) {
throw new IllegalArgumentException(
Logger.logMessage(Logger.ERROR, "PickedObject", "fromRenderable", "missingRenderable"));
}
if (layer == null) {
throw new IllegalArgumentException(
Logger.logMessage(Logger.ERROR, "PickedObject", "fromRenderable", "missingLayer"));
}
PickedObject po = new PickedObject();
po.identifier = identifier;
po.userObject = (renderable.getPickDelegate() != null) ? renderable.getPickDelegate() : renderable;
po.layer = layer;
return po;
}
public static PickedObject fromTerrain(int identifier, Position position) {
if (position == null) {
throw new IllegalArgumentException(
Logger.logMessage(Logger.ERROR, "PickedObject", "fromTerrain", "missingPosition"));
}
Position positionCopy = new Position(position);
PickedObject po = new PickedObject();
po.identifier = identifier;
po.userObject = positionCopy;
po.terrainPosition = positionCopy;
return po;
}
public static Color identifierToUniqueColor(int identifier, Color result) {
if (result == null) {
throw new IllegalArgumentException(
Logger.logMessage(Logger.ERROR, "PickedObject", "identifierToUniqueColor", "missingResult"));
}
int r8 = (identifier >> 16) & 0xFF;
int g8 = (identifier >> 8) & 0xFF;
int b8 = (identifier) & 0xFF;
result.red = r8 / (float) 0xFF;
result.green = g8 / (float) 0xFF;
result.blue = b8 / (float) 0xFF;
result.alpha = 1;
return result;
}
public static int uniqueColorToIdentifier(Color color) {
if (color == null) {
throw new IllegalArgumentException(
Logger.logMessage(Logger.ERROR, "PickedObject", "uniqueColorToIdentifier", "missingColor"));
}
int r8 = Math.round(color.red * 0xFF);
int g8 = Math.round(color.green * 0xFF);
int b8 = Math.round(color.blue * 0xFF);
return (r8 << 16) | (g8 << 8) | (b8);
}
@NonNull
@Override
public String toString() {
return "PickedObject{" +
"isOnTop=" + this.isOnTop +
", identifier=" + this.identifier +
", userObject=" + this.userObject +
", layer=" + this.layer +
", terrainPosition=" + this.terrainPosition +
'}';
}
public boolean isOnTop() {
return this.isOnTop;
}
protected void markOnTop() {
this.isOnTop = true;
}
public int getIdentifier() {
return this.identifier;
}
public Object getUserObject() {
return this.userObject;
}
public Layer getLayer() {
return this.layer;
}
public boolean isTerrain() {
return this.terrainPosition != null;
}
public Position getTerrainPosition() {
return this.terrainPosition;
}
}
|
package com.semmle.js.extractor;
import com.semmle.js.extractor.trapcache.CachingTrapWriter;
import com.semmle.js.extractor.trapcache.ITrapCache;
import com.semmle.util.data.StringUtil;
import com.semmle.util.exception.Exceptions;
import com.semmle.util.extraction.ExtractorOutputConfig;
import com.semmle.util.files.FileUtil;
import com.semmle.util.io.WholeIO;
import com.semmle.util.trap.TrapWriter;
import com.semmle.util.trap.TrapWriter.Label;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.regex.Pattern;
/**
* The file extractor extracts a single file and handles source archive population and TRAP caching;
* it delegates to the appropriate {@link IExtractor} for extracting the contents of the file.
*/
public class FileExtractor {
/**
* Pattern to use on the shebang line of a script to identify whether it is a Node.js script.
*
* <p>There are many different ways of invoking the Node.js interpreter (directly, through {@code
* env}, with or without flags, with or without modified environment, etc.), so we simply look for
* the word {@code "node"} or {@code "nodejs"}.
*/
private static final Pattern NODE_INVOCATION = Pattern.compile("\\bnode(js)?\\b");
/** A pattern that matches strings starting with `{ "...":`, suggesting JSON data. */
public static final Pattern JSON_OBJECT_START =
Pattern.compile("^(?s)\\s*\\{\\s*\"([^\"]|\\\\.)*\"\\s*:.*");
/** The charset for decoding UTF-8 strings. */
private static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
/** Information about supported file types. */
public static enum FileType {
HTML(".htm", ".html", ".xhtm", ".xhtml", ".vue") {
@Override
public IExtractor mkExtractor(ExtractorConfig config, ExtractorState state) {
return new HTMLExtractor(config);
}
@Override
public String toString() {
return "html";
}
},
JS(".js", ".jsx", ".mjs", ".es6", ".es") {
@Override
public IExtractor mkExtractor(ExtractorConfig config, ExtractorState state) {
return new ScriptExtractor(config);
}
@Override
protected boolean contains(File f, String lcExt, ExtractorConfig config) {
if (super.contains(f, lcExt, config)) return true;
// detect Node.js scripts that are meant to be run from
// the command line and do not have a `.js` extension
if (f.isFile() && lcExt.isEmpty()) {
try (BufferedReader br = new BufferedReader(new FileReader(f))) {
String firstLine = br.readLine();
// do a cheap check first
if (firstLine != null && firstLine.startsWith("#!")) {
// now do the slightly more expensive one
return NODE_INVOCATION.matcher(firstLine).find();
}
} catch (IOException e) {
Exceptions.ignore(e, "We simply skip this file.");
}
}
return false;
}
@Override
public String toString() {
return "javascript";
}
},
JSON(".json") {
@Override
public IExtractor mkExtractor(ExtractorConfig config, ExtractorState state) {
return new JSONExtractor(config);
}
@Override
protected boolean contains(File f, String lcExt, ExtractorConfig config) {
if (super.contains(f, lcExt, config)) return true;
// detect JSON-encoded configuration files whose name starts with `.` and ends with `rc`
// (e.g., `.eslintrc` or `.babelrc`)
if (f.isFile() && f.getName().matches("\\..*rc")) {
try (BufferedReader br = new BufferedReader(new FileReader(f))) {
// check whether the first two non-empty lines look like the start of a JSON object
// (two lines because the opening brace is usually on a line by itself)
StringBuilder firstTwoLines = new StringBuilder();
for (int i = 0; i < 2; ) {
String nextLine = br.readLine();
if (nextLine == null) break;
nextLine = nextLine.trim();
if (!nextLine.isEmpty()) {
firstTwoLines.append(nextLine);
++i;
}
}
return JSON_OBJECT_START.matcher(firstTwoLines).matches();
} catch (IOException e) {
Exceptions.ignore(e, "We simply skip this file.");
}
}
return false;
}
@Override
public String toString() {
return "json";
}
},
TYPESCRIPT(".ts", ".tsx") {
@Override
protected boolean contains(File f, String lcExt, ExtractorConfig config) {
if (config.getTypeScriptMode() == TypeScriptMode.NONE) return false;
// Read the beginning of the file to guess the file type.
if (hasBadFileHeader(f, lcExt, config)) {
return false;
}
return super.contains(f, lcExt, config);
}
/** Number of bytes to read from the beginning of a ".ts" file for sniffing its file type. */
private static final int fileHeaderSize = 128;
private boolean hasBadFileHeader(File f, String lcExt, ExtractorConfig config) {
if (!".ts".equals(lcExt)) {
return false;
}
try (FileInputStream fis = new FileInputStream(f)) {
byte[] bytes = new byte[fileHeaderSize];
int length = fis.read(bytes);
// Avoid invalid or unprintable UTF-8 files.
if (config.getDefaultEncoding().equals("UTF-8") && hasUnprintableUtf8(bytes, length)) {
return true;
}
// Avoid trying to extract XML files.
if (isXml(bytes, length)) return true;
// Avoid files with an unrecognized shebang header.
if (hasUnrecognizedShebang(bytes, length)) {
return true;
}
return false;
} catch (IOException e) {
Exceptions.ignore(e, "Let extractor handle this one.");
}
return false;
}
/** Returns the index after the initial BOM, if any, otherwise 0. */
private int skipBOM(byte[] bytes, int length) {
if (length >= 2
&& (bytes[0] == (byte) 0xfe && bytes[1] == (byte) 0xff
|| bytes[0] == (byte) 0xff && bytes[1] == (byte) 0xfe)) {
return 2;
} else {
return 0;
}
}
private boolean isXml(byte[] bytes, int length) {
int startIndex = skipBOM(bytes, length);
// Check for `<` encoded in Ascii/UTF-8 or litte-endian UTF-16.
if (startIndex < length && bytes[startIndex] == '<') {
return true;
}
// Check for `<` encoded in big-endian UTF-16
if (startIndex + 1 < length && bytes[startIndex] == 0 && bytes[startIndex + 1] == '<') {
return true;
}
return false;
}
/**
* Returns true if the byte sequence contains invalid UTF-8 or unprintable ASCII characters.
*/
private boolean hasUnprintableUtf8(byte[] bytes, int length) {
// Constants for bytes with N high-order 1-bits.
// They are typed as `int` as the subsequent byte-to-int promotion would
// otherwise fill the high-order `int` bits with 1s.
final int high1 = 0b10000000;
final int high2 = 0b11000000;
final int high3 = 0b11100000;
final int high4 = 0b11110000;
final int high5 = 0b11111000;
int startIndex = skipBOM(bytes, length);
for (int i = startIndex; i < length; ++i) {
int b = bytes[i];
if ((b & high1) == 0) { // 0xxxxxxx is an ASCII character
// ASCII values 0-31 are unprintable, except 9-13 are whitespace.
// 127 is the unprintable DEL character.
if (b <= 8 || 14 <= b && b <= 31 || b == 127) {
return true;
}
} else {
// Check for malformed UTF-8 multibyte code point
int trailingBytes = 0;
if ((b & high3) == high2) {
trailingBytes = 1; // 110xxxxx 10xxxxxx
} else if ((b & high4) == high3) {
trailingBytes = 2; // 1110xxxx 10xxxxxx 10xxxxxx
} else if ((b & high5) == high4) {
trailingBytes = 3; // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
} else {
return true; // 10xxxxxx and 11111xxx are not valid here.
}
// Trailing bytes must be of form 10xxxxxx
while (trailingBytes > 0) {
++i;
--trailingBytes;
if (i >= length) {
return false;
}
if ((bytes[i] & high2) != high1) {
return true;
}
}
}
}
return false;
}
/**
* Returns true if the byte sequence starts with a shebang line that is not recognized as a
* JavaScript interpreter.
*/
private boolean hasUnrecognizedShebang(byte[] bytes, int length) {
// Shebangs preceded by a BOM aren't recognized in UNIX, but the BOM might only
// be present in the source file, to be stripped out in the build process.
int startIndex = skipBOM(bytes, length);
if (startIndex + 2 >= length) return false;
if (bytes[startIndex] != '#' || bytes[startIndex + 1] != '!') {
return false;
}
int endOfLine = -1;
for (int i = startIndex; i < length; ++i) {
if (bytes[i] == '\r' || bytes[i] == '\n') {
endOfLine = i;
break;
}
}
if (endOfLine == -1) {
// The shebang is either very long or there are no other lines in the file.
// Treat this as unrecognized.
return true;
}
// Extract the shebang text
int startOfText = startIndex + "#!".length();
int lengthOfText = endOfLine - startOfText;
String text = new String(bytes, startOfText, lengthOfText, UTF8_CHARSET);
// Check if the shebang is a recognized JavaScript intepreter.
return !NODE_INVOCATION.matcher(text).find();
}
@Override
public IExtractor mkExtractor(ExtractorConfig config, ExtractorState state) {
return new TypeScriptExtractor(config, state.getTypeScriptParser());
}
@Override
public String toString() {
return "typescript";
}
@Override
public boolean isTrapCachingAllowed() {
return false; // Type information cannot be cached per-file.
}
},
YAML(".raml", ".yaml", ".yml") {
@Override
public IExtractor mkExtractor(ExtractorConfig config, ExtractorState state) {
return new YAMLExtractor(config);
}
@Override
public String toString() {
return "yaml";
}
};
/** The file extensions (lower-case, including leading dot) corresponding to this file type. */
private final Set<String> extensions = new LinkedHashSet<String>();
private FileType(String... extensions) {
for (String extension : extensions) this.extensions.add(extension);
}
public Set<String> getExtensions() {
return extensions;
}
/** Construct an extractor for this file type with the appropriate configuration settings. */
public abstract IExtractor mkExtractor(ExtractorConfig config, ExtractorState state);
/** Determine the {@link FileType} for a given file. */
public static FileType forFile(File f, ExtractorConfig config) {
String lcExt = StringUtil.lc(FileUtil.extension(f));
for (FileType tp : values()) if (tp.contains(f, lcExt, config)) return tp;
return null;
}
/** Determine the {@link FileType} for a given file based on its extension only. */
public static FileType forFileExtension(File f) {
String lcExt = StringUtil.lc(FileUtil.extension(f));
for (FileType tp : values())
if (tp.getExtensions().contains(lcExt)) {
return tp;
}
return null;
}
/**
* Is the given file of this type?
*
* <p>For convenience, the lower-case file extension is also passed as an argument.
*/
protected boolean contains(File f, String lcExt, ExtractorConfig config) {
return extensions.contains(lcExt);
}
/**
* Can we cache the TRAP output of this file?
*
* <p>Caching is disabled for TypeScript files as they depend on type information from other
* files.
*/
public boolean isTrapCachingAllowed() {
return true;
}
/** The names of all defined {@linkplain FileType}s. */
public static final Set<String> allNames = new LinkedHashSet<String>();
static {
for (FileType ft : FileType.values()) allNames.add(ft.name());
}
}
private final ExtractorConfig config;
private final ExtractorOutputConfig outputConfig;
private final ITrapCache trapCache;
public FileExtractor(
ExtractorConfig config, ExtractorOutputConfig outputConfig, ITrapCache trapCache) {
this.config = config;
this.outputConfig = outputConfig;
this.trapCache = trapCache;
}
public ExtractorConfig getConfig() {
return config;
}
public boolean supports(File f) {
return config.hasFileType() || FileType.forFile(f, config) != null;
}
/**
* @return the number of lines of code extracted, or {@code null} if the file was cached
*/
public Integer extract(File f, ExtractorState state) throws IOException {
// populate source archive
String source = new WholeIO(config.getDefaultEncoding()).strictread(f);
outputConfig.getSourceArchive().add(f, source);
// extract language-independent bits
TrapWriter trapwriter = outputConfig.getTrapWriterFactory().mkTrapWriter(f);
Label fileLabel = trapwriter.populateFile(f);
LocationManager locationManager = new LocationManager(f, trapwriter, fileLabel);
locationManager.emitFileLocation(fileLabel, 0, 0, 0, 0);
// now extract the contents
return extractContents(f, fileLabel, source, locationManager, state);
}
/**
* Extract the contents of a file, potentially making use of cached information.
*
* <p>TRAP files can be logically split into two parts: a location-dependent prelude containing
* all the `files`, `folders` and `containerparent` tuples, and a content-dependent main part
* containing all the rest, which does not depend on the source file location at all. Locations in
* the main part do, of course, refer to the source file's ID, but they do so via its symbolic
* label, which is always #10000.
*
* <p>We only cache the content-dependent part, which makes up the bulk of the TRAP file anyway.
* The location-dependent part is emitted from scratch every time by the {@link #extract(File,
* ExtractorState)} method above.
*
* <p>In order to keep labels in the main part independent of the file's location, we bump the
* TRAP label counter to a known value (currently 20000) after the location-dependent part has
* been emitted. If the counter should already be larger than that (which is theoretically
* possible with insanely deeply nested directories), we have to skip caching.
*
* <p>Also note that we support extraction with TRAP writer factories that are not file-backed;
* obviously, no caching is done in that scenario.
*/
private Integer extractContents(
File f, Label fileLabel, String source, LocationManager locationManager, ExtractorState state)
throws IOException {
TrapWriter trapwriter = locationManager.getTrapWriter();
FileType fileType = getFileType(f);
File cacheFile = null, // the cache file for this extraction
resultFile = null; // the final result TRAP file for this extraction
// check whether we can perform caching
if (bumpIdCounter(trapwriter) && fileType.isTrapCachingAllowed()) {
resultFile = outputConfig.getTrapWriterFactory().getTrapFileFor(f);
if (resultFile != null) cacheFile = trapCache.lookup(source, config, fileType);
}
if (cacheFile != null) {
FileUtil.close(trapwriter);
if (cacheFile.exists()) {
FileUtil.append(cacheFile, resultFile);
return null;
}
// not in the cache yet, so use a caching TRAP writer to
// put the data into the cache and append it to the result file
trapwriter = new CachingTrapWriter(cacheFile, resultFile);
bumpIdCounter(trapwriter);
// re-initialise the location manager, since it keeps a reference to the TRAP writer
locationManager = new LocationManager(f, trapwriter, locationManager.getFileLabel());
}
// now do the extraction itself
boolean successful = false;
try {
IExtractor extractor = fileType.mkExtractor(config, state);
TextualExtractor textualExtractor =
new TextualExtractor(trapwriter, locationManager, source, config.getExtractLines());
LoCInfo loc = extractor.extract(textualExtractor);
int numLines = textualExtractor.getNumLines();
int linesOfCode = loc.getLinesOfCode(), linesOfComments = loc.getLinesOfComments();
trapwriter.addTuple("numlines", fileLabel, numLines, linesOfCode, linesOfComments);
trapwriter.addTuple("filetype", fileLabel, fileType.toString());
successful = true;
return linesOfCode;
} finally {
if (!successful && trapwriter instanceof CachingTrapWriter)
((CachingTrapWriter) trapwriter).discard();
FileUtil.close(trapwriter);
}
}
public FileType getFileType(File f) {
return config.hasFileType()
? FileType.valueOf(config.getFileType())
: FileType.forFile(f, config);
}
/**
* Bump trap ID counter to separate path-dependent and path-independent parts of the TRAP file.
*
* @return true if the counter was successfully bumped
*/
public boolean bumpIdCounter(TrapWriter trapwriter) {
return trapwriter.bumpIdCount(20000);
}
}
|
/**
* Copyright (C) 2012-2020 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 ninja.template.directives;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;
import ninja.Context;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
/**
*
* @author svenkubiak
*
*/
@SuppressWarnings("rawtypes")
public class TemplateEngineFreemarkerAuthenticityTokenDirective implements TemplateDirectiveModel {
private Context context;
public TemplateEngineFreemarkerAuthenticityTokenDirective(Context context) {
this.context = context;
}
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
if (!params.isEmpty()) {
throw new TemplateException("This directive doesn't allow parameters.", env);
}
if (loopVars.length != 0) {
throw new TemplateException("This directive doesn't allow loop variables.", env);
}
Writer out = env.getOut();
out.append(this.context.getSession().getAuthenticityToken());
}
}
|
package com.hys.exam.model;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
public class CvLive implements Serializable {
/**
* boy
*/
private static final long serialVersionUID = 4599448644515104811L;
private Long id;
private String class_no;
private String class_name;
private String number;
private String teacher_token;
private String assistant_token;
private String student_token;
private String studentClient_token;
private Date start_date;
private Date invalid_date;
private String teacher_join_url;
private String student_join_url;
private Integer is_web_join;
private Integer is_client_join;
private Integer scene;
private Long cv_id;
private Integer course_make_type;
private Date create_date;
private Date modify_date;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getClass_no() {
return class_no;
}
public void setClass_no(String class_no) {
this.class_no = class_no;
}
public String getClass_name() {
return class_name;
}
public void setClass_name(String class_name) {
this.class_name = class_name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getTeacher_token() {
return teacher_token;
}
public void setTeacher_token(String teacher_token) {
this.teacher_token = teacher_token;
}
public String getAssistant_token() {
return assistant_token;
}
public void setAssistant_token(String assistant_token) {
this.assistant_token = assistant_token;
}
public String getStudent_token() {
return student_token;
}
public void setStudent_token(String student_token) {
this.student_token = student_token;
}
public String getStudentClient_token() {
return studentClient_token;
}
public void setStudentClient_token(String studentClient_token) {
this.studentClient_token = studentClient_token;
}
public Date getStart_date() {
return start_date;
}
public void setStart_date(Date start_date) {
this.start_date = start_date;
}
public Date getInvalid_date() {
return invalid_date;
}
public void setInvalid_date(Date invalid_date) {
this.invalid_date = invalid_date;
}
public String getTeacher_join_url() {
return teacher_join_url;
}
public void setTeacher_join_url(String teacher_join_url) {
this.teacher_join_url = teacher_join_url;
}
public String getStudent_join_url() {
return student_join_url;
}
public void setStudent_join_url(String student_join_url) {
this.student_join_url = student_join_url;
}
public Integer getIs_web_join() {
return is_web_join;
}
public void setIs_web_join(Integer is_web_join) {
this.is_web_join = is_web_join;
}
public Integer getIs_client_join() {
return is_client_join;
}
public void setIs_client_join(Integer is_client_join) {
this.is_client_join = is_client_join;
}
public Integer getScene() {
return scene;
}
public void setScene(Integer scene) {
this.scene = scene;
}
public Long getCv_id() {
return cv_id;
}
public void setCv_id(Long cv_id) {
this.cv_id = cv_id;
}
public Date getCreate_date() {
return create_date;
}
public void setCreate_date(Date create_date) {
this.create_date = create_date;
}
public Date getModify_date() {
return modify_date;
}
public void setModify_date(Date modify_date) {
this.modify_date = modify_date;
}
public Integer getCourse_make_type() {
return course_make_type;
}
public void setCourse_make_type(Integer course_make_type) {
this.course_make_type = course_make_type;
}
}
|
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.automl;
// [START automl_language_entity_extraction_list_model_evaluations]
// [START automl_language_sentiment_analysis_list_model_evaluations]
// [START automl_language_text_classification_list_model_evaluations]
// [START automl_translate_list_model_evaluations]
// [START automl_vision_classification_list_model_evaluations]
// [START automl_vision_object_detection_list_model_evaluations]
import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.ListModelEvaluationsRequest;
import com.google.cloud.automl.v1.ModelEvaluation;
import com.google.cloud.automl.v1.ModelName;
import java.io.IOException;
class ListModelEvaluations {
public static void main(String[] args) throws IOException {
// TODO(developer): Replace these variables before running the sample.
String projectId = "YOUR_PROJECT_ID";
String modelId = "YOUR_MODEL_ID";
listModelEvaluations(projectId, modelId);
}
// List model evaluations
static void listModelEvaluations(String projectId, String modelId) throws IOException {
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
// the "close" method on the client to safely clean up any remaining background resources.
try (AutoMlClient client = AutoMlClient.create()) {
// Get the full path of the model.
ModelName modelFullId = ModelName.of(projectId, "us-central1", modelId);
ListModelEvaluationsRequest modelEvaluationsrequest =
ListModelEvaluationsRequest.newBuilder().setParent(modelFullId.toString()).build();
// List all the model evaluations in the model by applying filter.
System.out.println("List of model evaluations:");
for (ModelEvaluation modelEvaluation :
client.listModelEvaluations(modelEvaluationsrequest).iterateAll()) {
System.out.format("Model Evaluation Name: %s\n", modelEvaluation.getName());
System.out.format("Model Annotation Spec Id: %s", modelEvaluation.getAnnotationSpecId());
System.out.println("Create Time:");
System.out.format("\tseconds: %s\n", modelEvaluation.getCreateTime().getSeconds());
System.out.format("\tnanos: %s", modelEvaluation.getCreateTime().getNanos() / 1e9);
System.out.format(
"Evalution Example Count: %d\n", modelEvaluation.getEvaluatedExampleCount());
// [END automl_language_sentiment_analysis_list_model_evaluations]
// [END automl_language_text_classification_list_model_evaluations]
// [END automl_translate_list_model_evaluations]
// [END automl_vision_classification_list_model_evaluations]
// [END automl_vision_object_detection_list_model_evaluations]
System.out.format(
"Entity Extraction Model Evaluation Metrics: %s\n",
modelEvaluation.getTextExtractionEvaluationMetrics());
// [END automl_language_entity_extraction_list_model_evaluations]
// [START automl_language_sentiment_analysis_list_model_evaluations]
System.out.format(
"Sentiment Analysis Model Evaluation Metrics: %s\n",
modelEvaluation.getTextSentimentEvaluationMetrics());
// [END automl_language_sentiment_analysis_list_model_evaluations]
// [START automl_language_text_classification_list_model_evaluations]
// [START automl_vision_classification_list_model_evaluations]
System.out.format(
"Classification Model Evaluation Metrics: %s\n",
modelEvaluation.getClassificationEvaluationMetrics());
// [END automl_language_text_classification_list_model_evaluations]
// [END automl_vision_classification_list_model_evaluations]
// [START automl_translate_list_model_evaluations]
System.out.format(
"Translate Model Evaluation Metrics: %s\n",
modelEvaluation.getTranslationEvaluationMetrics());
// [END automl_translate_list_model_evaluations]
// [START automl_vision_object_detection_list_model_evaluations]
System.out.format(
"Object Detection Model Evaluation Metrics: %s\n",
modelEvaluation.getImageObjectDetectionEvaluationMetrics());
// [START automl_language_entity_extraction_list_model_evaluations]
// [START automl_language_sentiment_analysis_list_model_evaluations]
// [START automl_language_text_classification_list_model_evaluations]
// [START automl_translate_list_model_evaluations]
// [START automl_vision_classification_list_model_evaluations]
}
}
}
}
// [END automl_language_entity_extraction_list_model_evaluations]
// [END automl_language_sentiment_analysis_list_model_evaluations]
// [END automl_language_text_classification_list_model_evaluations]
// [END automl_translate_list_model_evaluations]
// [END automl_vision_classification_list_model_evaluations]
// [END automl_vision_object_detection_list_model_evaluations]
|
/*
* Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.graalvm.compiler.asm.amd64;
public class AMD64AsmOptions {
public static final boolean UseNormalNop = false;
public static final boolean UseAddressNop = true;
public static final boolean UseIncDec = true;
public static final boolean UseXmmLoadAndClearUpper = true;
public static final boolean UseXmmRegToRegMoveAll = true;
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.namenode;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.PrivilegedExceptionAction;
import javax.net.SocketFactory;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.MD5MD5CRC32FileChecksum;
import org.apache.hadoop.hdfs.DFSClient;
import org.apache.hadoop.hdfs.protocol.ClientProtocol;
import org.apache.hadoop.hdfs.protocol.DatanodeID;
import org.apache.hadoop.hdfs.server.common.HdfsConstants;
import org.apache.hadoop.hdfs.server.common.JspHelper;
import org.apache.hadoop.hdfs.server.datanode.DataNode;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.HdfsConfiguration;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.security.UserGroupInformation;
import org.znerd.xmlenc.XMLOutputter;
/** Servlets for file checksum */
@InterfaceAudience.Private
public class FileChecksumServlets {
/** Redirect file checksum queries to an appropriate datanode. */
@InterfaceAudience.Private
public static class RedirectServlet extends DfsServlet {
/** For java.io.Serializable */
private static final long serialVersionUID = 1L;
/** {@inheritDoc} */
public void doGet(HttpServletRequest request, HttpServletResponse response
) throws ServletException, IOException {
final ServletContext context = getServletContext();
final Configuration conf =
(Configuration) context.getAttribute(JspHelper.CURRENT_CONF);
final UserGroupInformation ugi = getUGI(request, conf);
final NameNode namenode = (NameNode)context.getAttribute("name.node");
final DatanodeID datanode = namenode.getNamesystem().getRandomDatanode();
try {
final URI uri = createRedirectUri("/getFileChecksum", ugi, datanode,
request, namenode);
response.sendRedirect(uri.toURL().toString());
} catch(URISyntaxException e) {
throw new ServletException(e);
//response.getWriter().println(e.toString());
} catch (IOException e) {
response.sendError(400, e.getMessage());
}
}
}
/** Get FileChecksum */
@InterfaceAudience.Private
public static class GetServlet extends DfsServlet {
/** For java.io.Serializable */
private static final long serialVersionUID = 1L;
/** {@inheritDoc} */
public void doGet(HttpServletRequest request, HttpServletResponse response
) throws ServletException, IOException {
final PrintWriter out = response.getWriter();
final String filename = getFilename(request, response);
final XMLOutputter xml = new XMLOutputter(out, "UTF-8");
xml.declaration();
final Configuration conf = new HdfsConfiguration(DataNode.getDataNode().getConf());
final int socketTimeout = conf.getInt(DFSConfigKeys.DFS_CLIENT_SOCKET_TIMEOUT_KEY, HdfsConstants.READ_TIMEOUT);
final SocketFactory socketFactory = NetUtils.getSocketFactory(conf, ClientProtocol.class);
try {
ClientProtocol nnproxy = getUGI(request, conf).doAs
(new PrivilegedExceptionAction<ClientProtocol>() {
@Override
public ClientProtocol run() throws IOException {
return DFSClient.createNamenode(conf);
}
});
final MD5MD5CRC32FileChecksum checksum = DFSClient.getFileChecksum(
filename, nnproxy, socketFactory, socketTimeout);
MD5MD5CRC32FileChecksum.write(xml, checksum);
} catch(IOException ioe) {
writeXml(ioe, filename, xml);
} catch (InterruptedException e) {
writeXml(e, filename, xml);
}
xml.endDocument();
}
}
}
|
/**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.financial.security.option;
import java.util.Map;
import org.joda.beans.Bean;
import org.joda.beans.BeanBuilder;
import org.joda.beans.BeanDefinition;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaProperty;
import org.joda.beans.Property;
import org.joda.beans.PropertyDefinition;
import org.joda.beans.impl.direct.DirectBeanBuilder;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;
import org.threeten.bp.ZonedDateTime;
/**
* The extreme spread payoff style.
*/
@BeanDefinition
public class ExtremeSpreadPayoffStyle extends PayoffStyle {
/** Serialization version. */
private static final long serialVersionUID = 1L;
/**
* The period end.
*/
@PropertyDefinition(validate = "notNull")
private ZonedDateTime _periodEnd;
/**
* The reverse flag.
*/
@PropertyDefinition
private boolean _reverse;
/**
* Creates an instance.
*/
private ExtremeSpreadPayoffStyle() {
}
/**
* Creates an instance.
*
* @param periodEnd the period end, not null
* @param reverse whether the style is reversed
*/
public ExtremeSpreadPayoffStyle(final ZonedDateTime periodEnd, final boolean reverse) {
setPeriodEnd(periodEnd);
setReverse(reverse);
}
//-------------------------------------------------------------------------
@Override
public <T> T accept(final PayoffStyleVisitor<T> visitor) {
return visitor.visitExtremeSpreadPayoffStyle(this);
}
//------------------------- AUTOGENERATED START -------------------------
///CLOVER:OFF
/**
* The meta-bean for {@code ExtremeSpreadPayoffStyle}.
* @return the meta-bean, not null
*/
public static ExtremeSpreadPayoffStyle.Meta meta() {
return ExtremeSpreadPayoffStyle.Meta.INSTANCE;
}
static {
JodaBeanUtils.registerMetaBean(ExtremeSpreadPayoffStyle.Meta.INSTANCE);
}
@Override
public ExtremeSpreadPayoffStyle.Meta metaBean() {
return ExtremeSpreadPayoffStyle.Meta.INSTANCE;
}
//-----------------------------------------------------------------------
/**
* Gets the period end.
* @return the value of the property, not null
*/
public ZonedDateTime getPeriodEnd() {
return _periodEnd;
}
/**
* Sets the period end.
* @param periodEnd the new value of the property, not null
*/
public void setPeriodEnd(ZonedDateTime periodEnd) {
JodaBeanUtils.notNull(periodEnd, "periodEnd");
this._periodEnd = periodEnd;
}
/**
* Gets the the {@code periodEnd} property.
* @return the property, not null
*/
public final Property<ZonedDateTime> periodEnd() {
return metaBean().periodEnd().createProperty(this);
}
//-----------------------------------------------------------------------
/**
* Gets the reverse flag.
* @return the value of the property
*/
public boolean isReverse() {
return _reverse;
}
/**
* Sets the reverse flag.
* @param reverse the new value of the property
*/
public void setReverse(boolean reverse) {
this._reverse = reverse;
}
/**
* Gets the the {@code reverse} property.
* @return the property, not null
*/
public final Property<Boolean> reverse() {
return metaBean().reverse().createProperty(this);
}
//-----------------------------------------------------------------------
@Override
public ExtremeSpreadPayoffStyle clone() {
return JodaBeanUtils.cloneAlways(this);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj != null && obj.getClass() == this.getClass()) {
ExtremeSpreadPayoffStyle other = (ExtremeSpreadPayoffStyle) obj;
return JodaBeanUtils.equal(getPeriodEnd(), other.getPeriodEnd()) &&
(isReverse() == other.isReverse()) &&
super.equals(obj);
}
return false;
}
@Override
public int hashCode() {
int hash = 7;
hash = hash * 31 + JodaBeanUtils.hashCode(getPeriodEnd());
hash = hash * 31 + JodaBeanUtils.hashCode(isReverse());
return hash ^ super.hashCode();
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder(96);
buf.append("ExtremeSpreadPayoffStyle{");
int len = buf.length();
toString(buf);
if (buf.length() > len) {
buf.setLength(buf.length() - 2);
}
buf.append('}');
return buf.toString();
}
@Override
protected void toString(StringBuilder buf) {
super.toString(buf);
buf.append("periodEnd").append('=').append(JodaBeanUtils.toString(getPeriodEnd())).append(',').append(' ');
buf.append("reverse").append('=').append(JodaBeanUtils.toString(isReverse())).append(',').append(' ');
}
//-----------------------------------------------------------------------
/**
* The meta-bean for {@code ExtremeSpreadPayoffStyle}.
*/
public static class Meta extends PayoffStyle.Meta {
/**
* The singleton instance of the meta-bean.
*/
static final Meta INSTANCE = new Meta();
/**
* The meta-property for the {@code periodEnd} property.
*/
private final MetaProperty<ZonedDateTime> _periodEnd = DirectMetaProperty.ofReadWrite(
this, "periodEnd", ExtremeSpreadPayoffStyle.class, ZonedDateTime.class);
/**
* The meta-property for the {@code reverse} property.
*/
private final MetaProperty<Boolean> _reverse = DirectMetaProperty.ofReadWrite(
this, "reverse", ExtremeSpreadPayoffStyle.class, Boolean.TYPE);
/**
* The meta-properties.
*/
private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap(
this, (DirectMetaPropertyMap) super.metaPropertyMap(),
"periodEnd",
"reverse");
/**
* Restricted constructor.
*/
protected Meta() {
}
@Override
protected MetaProperty<?> metaPropertyGet(String propertyName) {
switch (propertyName.hashCode()) {
case 566572890: // periodEnd
return _periodEnd;
case 1099846370: // reverse
return _reverse;
}
return super.metaPropertyGet(propertyName);
}
@Override
public BeanBuilder<? extends ExtremeSpreadPayoffStyle> builder() {
return new DirectBeanBuilder<ExtremeSpreadPayoffStyle>(new ExtremeSpreadPayoffStyle());
}
@Override
public Class<? extends ExtremeSpreadPayoffStyle> beanType() {
return ExtremeSpreadPayoffStyle.class;
}
@Override
public Map<String, MetaProperty<?>> metaPropertyMap() {
return _metaPropertyMap$;
}
//-----------------------------------------------------------------------
/**
* The meta-property for the {@code periodEnd} property.
* @return the meta-property, not null
*/
public final MetaProperty<ZonedDateTime> periodEnd() {
return _periodEnd;
}
/**
* The meta-property for the {@code reverse} property.
* @return the meta-property, not null
*/
public final MetaProperty<Boolean> reverse() {
return _reverse;
}
//-----------------------------------------------------------------------
@Override
protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
switch (propertyName.hashCode()) {
case 566572890: // periodEnd
return ((ExtremeSpreadPayoffStyle) bean).getPeriodEnd();
case 1099846370: // reverse
return ((ExtremeSpreadPayoffStyle) bean).isReverse();
}
return super.propertyGet(bean, propertyName, quiet);
}
@Override
protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
switch (propertyName.hashCode()) {
case 566572890: // periodEnd
((ExtremeSpreadPayoffStyle) bean).setPeriodEnd((ZonedDateTime) newValue);
return;
case 1099846370: // reverse
((ExtremeSpreadPayoffStyle) bean).setReverse((Boolean) newValue);
return;
}
super.propertySet(bean, propertyName, newValue, quiet);
}
@Override
protected void validate(Bean bean) {
JodaBeanUtils.notNull(((ExtremeSpreadPayoffStyle) bean)._periodEnd, "periodEnd");
super.validate(bean);
}
}
///CLOVER:ON
//-------------------------- AUTOGENERATED END --------------------------
}
|
//package edu.gemini.spModel.gemini.bhros.test;
//
//import edu.gemini.spModel.gemini.bhros.BHROSParams;
//import edu.gemini.spModel.gemini.bhros.InstBHROS;
//import edu.gemini.spModel.gemini.bhros.ech.HROSHardwareConstants;
//import edu.gemini.spModel.pio.ParamSet;
//import edu.gemini.spModel.pio.PioFactory;
//import edu.gemini.spModel.pio.xml.PioXmlFactory;
//
//import java.io.ByteArrayInputStream;
//import java.io.ByteArrayOutputStream;
//import java.io.IOException;
//import java.io.ObjectInputStream;
//import java.io.ObjectOutputStream;
//import java.lang.reflect.Method;
//import java.util.ArrayList;
//import java.util.Collection;
////$Id: InstBHROSTest.java 7077 2006-05-26 19:56:48Z anunez $
//
//import junit.framework.TestCase;
//
//public class InstBHROSTest extends TestCase {
//
// private static void assertEquals(double a, double b) {
// assertEquals(a, b, 0.0001);
// }
//
// public void testEchelleDefaults() {
// InstBHROS bhros = new InstBHROS();
// assertEquals(bhros.getCentralWavelength(), 0.4334);
// assertEquals(bhros.getEchelleALT(), -56.988739);
// assertEquals(bhros.getEchelleAz(), 0.277674);
// assertEquals(bhros.getGoniAng(), -10.1180084);
// }
//
// public void testCCDDefaults() {
// InstBHROS bhros = new InstBHROS();
// assertEquals(bhros.getCCDCentreX(), 0.0);
// assertEquals(bhros.getCCDCentreY(), HROSHardwareConstants.BLUE_YCENTRE);
// assertEquals(bhros.getCCDAmplifiers(), BHROSParams.CCDReadoutPorts.DEFAULT);
// assertEquals(bhros.getCCDGain(), BHROSParams.CCDGain.DEFAULT);
// assertEquals(bhros.getCCDSpeed(), BHROSParams.CCDSpeed.DEFAULT);
// assertEquals(bhros.getCCDXBinning(), BHROSParams.CCDXBinning.DEFAULT);
// assertEquals(bhros.getCCDYBinning(), BHROSParams.CCDYBinning.DEFAULT);
// }
//
// public void testOtherDefaults() {
// InstBHROS bhros = new InstBHROS();
// assertEquals(bhros.getEntranceFibre(), BHROSParams.EntranceFibre.DEFAULT);
//// assertEquals(bhros.getExposureMeterFilter(), BHROSParams.ExposureMeterFilter.DEFAULT);
// assertEquals(bhros.getHartmannFlap(), BHROSParams.HartmannFlap.DEFAULT);
// assertEquals(bhros.getISSPort(), BHROSParams.ISSPort.DEFAULT);
// assertEquals(bhros.getPostSlitFilter(), BHROSParams.PostSlitFilter.DEFAULT);
// assertEquals(bhros.getROI(), BHROSParams.ROI.DEFAULT);
// }
//
// public void testEchelleUpdating() throws IOException, ClassNotFoundException {
// InstBHROS bhros = new InstBHROS();
//
// // Set the wavelength and make sure everything adjusts.
// bhros.setCentralWavelength(0.700);
// assertEquals(bhros.getEchelleALT(), -56.6204);
// assertEquals(bhros.getEchelleAz(), 1.2478);
// assertEquals(bhros.getGoniAng(), -5.6265);
//
// // Ditto with position.
// bhros.setCCDCentreX(1.08);
// bhros.setCCDCentreY(-15.04);
// assertEquals(bhros.getEchelleALT(), -56.6006);
// assertEquals(bhros.getEchelleAz(), 1.2650);
// assertEquals(bhros.getGoniAng(), -5.6996);
//
// // Make sure these values come back when we serialize.
// bhros = (InstBHROS) serializeDeserialize(bhros);
// assertEquals(bhros.getEchelleALT(), -56.6006);
// assertEquals(bhros.getEchelleAz(), 1.2650);
// assertEquals(bhros.getGoniAng(), -5.6996);
//
// }
//
// public void testProperties() throws Exception {
// InstBHROS bhros = new InstBHROS();
//
// // Enumerated Types
// testProperty(bhros, "CCDReadoutPorts", BHROSParams.CCDReadoutPorts.values());
// testProperty(bhros, "CCDGain", BHROSParams.CCDGain.values());
// testProperty(bhros, "CCDSpeed", BHROSParams.CCDSpeed.values());
// testProperty(bhros, "CCDXBinning", BHROSParams.CCDXBinning.values());
// testProperty(bhros, "CCDYBinning", BHROSParams.CCDYBinning.values());
// testProperty(bhros, "EntranceFibre", BHROSParams.EntranceFibre.values());
//// testProperty(bhros, "ExposureMeterFilter", BHROSParams.ExposureMeterFilter.class, BHROSParams.ExposureMeterFilter.TYPES);
// testProperty(bhros, "HartmannFlap", BHROSParams.HartmannFlap.values());
// testProperty(bhros, "ISSPort", BHROSParams.ISSPort.values());
// testProperty(bhros, "ROI", BHROSParams.ROI.values());
//
// // Doubles
// testProperty(bhros, "CentralWavelength", new double[] {0.4, 0.6, 0.9});
// testProperty(bhros, "CCDCentreX", new double[] {-5, 0, 5});
// testProperty(bhros, "CCDCentreY", new double[] {-5, -1});
//
// }
//
// /**
// * Test to see that simple set/get works, as well as serialization of the property,
// * persistence to/from a ParamSet.
// */
// private void testProperty(InstBHROS target, String propName, Class type, Collection values) throws Exception {
//
// String propertyName = Character.toUpperCase(propName.charAt(0)) + "";
// if (propName.length() > 1) {
// propertyName += propName.substring(1);
// }
// Method get = target.getClass().getMethod("get" + propertyName);
// Method set = target.getClass().getMethod("set" + propertyName, type);
// for (Object val : values) {
// // Simple get/set
// set.invoke(target, val);
// assertEquals(get.invoke(target, new Object[0]), val);
//
// // Serialize, deserialize, then test property again
// Object deserializedTarget = serializeDeserialize(target);
// assertEquals(get.invoke(deserializedTarget, new Object[0]), val);
//
// // Target and deserializedTarget should be equal() now.
// assertEquals(target, deserializedTarget);
//
// // Swizzle to ParamSet, then back
// PioFactory factory = new PioXmlFactory();
// ParamSet ps = target.getParamSet(factory);
// InstBHROS newInstance = new InstBHROS();
// newInstance.setParamSet(ps);
// assertEquals(get.invoke(newInstance, new Object[0]), val);
//
// // Target and deserializedTarget should be equal() now.
// assertEquals(target, newInstance);
// }
// }
//
// private void testProperty(InstBHROS target, String propName, double[] values) throws Exception {
// Collection<Double> vals = new ArrayList<Double>(values.length);
// for (double value : values) vals.add(value);
// testProperty(target, propName, Double.TYPE, vals);
// }
//
// private void testProperty(InstBHROS target, String propName, Object[] values) throws Exception {
// Collection<Object> vals = new ArrayList<Object>(values.length);
// if (values.length <= 0) throw new Exception("Collection has zero elements!");
// Class type = values[0].getClass();
// for (Object value : values) {
// vals.add(value);
// }
//
// testProperty(target, propName, type , vals);
// }
//
// private Object serializeDeserialize(Object o) throws IOException, ClassNotFoundException {
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// ObjectOutputStream oos = new ObjectOutputStream(baos);
// oos.writeObject(o);
// ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
// ObjectInputStream ois = new ObjectInputStream(bais);
// return ois.readObject();
// }
//
//}
|
package nachos.network;
import nachos.machine.*;
import nachos.threads.*;
/**
* A collection of message queues, one for each local port. A
* <tt>PostOffice</tt> interacts directly with the network hardware. Because
* of the network hardware, we are guaranteed that messages will never be
* corrupted, but they might get lost.
*
* <p>
* The post office uses a "postal worker" thread to wait for messages to arrive
* from the network and to place them in the appropriate queues. This cannot
* be done in the receive interrupt handler because each queue (implemented
* with a <tt>SynchList</tt>) is protected by a lock.
*/
public class PostOffice {
/**
* Allocate a new post office, using an array of <tt>SynchList</tt>s.
* Register the interrupt handlers with the network hardware and start the
* "postal worker" thread.
*/
public PostOffice() {
messageReceived = new Semaphore(0);
messageSent = new Semaphore(0);
sendLock = new Lock();
queues = new SynchList[MailMessage.portLimit];
for (int i=0; i<queues.length; i++)
queues[i] = new SynchList();
Runnable receiveHandler = new Runnable() {
public void run() { receiveInterrupt(); }
};
Runnable sendHandler = new Runnable() {
public void run() { sendInterrupt(); }
};
Machine.networkLink().setInterruptHandlers(receiveHandler,
sendHandler);
KThread t = new KThread(new Runnable() {
public void run() { postalDelivery(); }
});
t.fork();
}
/**
* Retrieve a message on the specified port, waiting if necessary.
*
* @param port the port on which to wait for a message.
*
* @return the message received.
*/
public MailMessage receive(int port) {
Lib.assertTrue(port >= 0 && port < queues.length);
Lib.debug(dbgNet, "waiting for mail on port " + port);
MailMessage mail = (MailMessage) queues[port].removeFirst();
if (Lib.test(dbgNet))
System.out.println("got mail on port " + port + ": " + mail);
return mail;
}
/**
* Wait for incoming messages, and then put them in the correct mailbox.
*/
private void postalDelivery() {
while (true) {
messageReceived.P();
Packet p = Machine.networkLink().receive();
MailMessage mail;
try {
mail = new MailMessage(p);
}
catch (MalformedPacketException e) {
continue;
}
if (Lib.test(dbgNet))
System.out.println("delivering mail to port " + mail.dstPort
+ ": " + mail);
// atomically add message to the mailbox and wake a waiting thread
queues[mail.dstPort].add(mail);
}
}
/**
* Called when a packet has arrived and can be dequeued from the network
* link.
*/
private void receiveInterrupt() {
messageReceived.V();
}
/**
* Send a message to a mailbox on a remote machine.
*/
public void send(MailMessage mail) {
if (Lib.test(dbgNet))
System.out.println("sending mail: " + mail);
sendLock.acquire();
Machine.networkLink().send(mail.packet);
messageSent.P();
sendLock.release();
}
/**
* Called when a packet has been sent and another can be queued to the
* network link. Note that this is called even if the previous packet was
* dropped.
*/
private void sendInterrupt() {
messageSent.V();
}
private SynchList[] queues;
private Semaphore messageReceived; // V'd when a message can be dequeued
private Semaphore messageSent; // V'd when a message can be queued
private Lock sendLock;
private static final char dbgNet = 'n';
}
|
package com.evolved.automata.parser.math;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Vector;
import com.evolved.automata.parser.StringDistribution;
import com.evolved.automata.parser.math.ExpressionFactory.OperatorDefinition;
import com.evolved.automata.parser.math.ExpressionFactory.TokenResult;
public class ReferenceExpressionPreProcessor implements ExpressionFactory.ExpressionPreProcesssor
{
protected StringDistribution _operatorMatcher;
protected Vector<HashSet<String>> operators;
protected HashSet<String> totalOperators;
protected HashSet<String> infixOperators;
protected HashSet<String> prefixOperators;
protected HashSet<String> postfixOperators;
protected HashMap<String, HashSet<String>> operatorTypes;
protected HashMap<String, String> canonicalOperatorMap;
public ReferenceExpressionPreProcessor()
{
canonicalOperatorMap = new HashMap<String, String>();
// Define operator groups
infixOperators = new HashSet<String>();
infixOperators.add("+");
infixOperators.add("-");
infixOperators.add("*");
infixOperators.add("/");
infixOperators.add("^");
infixOperators.add(",");
canonicalOperatorMap.put("+", "+");
canonicalOperatorMap.put("-", "-");
canonicalOperatorMap.put("*", "*");
canonicalOperatorMap.put("/", "/");
prefixOperators = new HashSet<String>();
prefixOperators.add("sq");
prefixOperators.add("sin");
prefixOperators.add("cos");
canonicalOperatorMap.put("sq", "sq");
canonicalOperatorMap.put("sin", "sin");
canonicalOperatorMap.put("cos", "cos");
postfixOperators = new HashSet<String>();
// Define operator precedence
operators = new Vector<HashSet<String>>();
HashSet<String> ops = new HashSet<String>();
// Add lowest precedent
ops.add(",");
canonicalOperatorMap.put(",", ",");
operators.add(ops);
ops = new HashSet<String>();
// Add lowest precedent
ops.add("+");
ops.add("-");
operators.add(ops);
ops = new HashSet<String>();
ops.add("*");
ops.add("/");
operators.add(ops);
ops = new HashSet<String>();
ops.add("^");
ops.add("sq");
ops.add("sin");
ops.add("cos");
canonicalOperatorMap.put("^", "^");
operators.add(ops);
ops = new HashSet<String>();
ops.add("(");
ops.add(")");
operators.add(ops);
canonicalOperatorMap.put(")", ")");
canonicalOperatorMap.put("(", "(");
totalOperators = new HashSet<String>();
totalOperators.addAll(ops);
totalOperators.addAll(infixOperators);
totalOperators.addAll(prefixOperators);
totalOperators.addAll(postfixOperators);
_operatorMatcher = new StringDistribution();
for (String op:totalOperators)
{
_operatorMatcher.addString(op);
}
operatorTypes = new HashMap<String, HashSet<String>>();
operatorTypes.put("infixOperators", infixOperators);
operatorTypes.put("prefixOperators", prefixOperators);
operatorTypes.put("postfixOperators", postfixOperators);
}
@Override
public TokenResult[] tokenize(String expression) {
expression = expression.trim();
int i = 0;
StringBuilder token = new StringBuilder();
LinkedList<TokenResult> tokens = new LinkedList<TokenResult>();
Integer[] ends;
while (i<expression.length())
{
ends = _operatorMatcher.matchString(i, expression);
if (ends!=null)
{
if (token.length()>0)
tokens.add(new TokenResult(true, token.toString()));
tokens.add(new TokenResult(false, canonicalOperatorMap.get(expression.substring(i, ends[0]))));
i = ends[0];
token = new StringBuilder();
}
else
{
token.append(expression.charAt(i));
i++;
}
}
if (token.length()>0)
tokens.add(new TokenResult(true, token.toString()));
return tokens.toArray(new TokenResult[0]);
}
@Override
public Argument[] argumentParser(TokenResult[] tokenizedAlgebraicExpression, HashMap<String, Argument> vars)
{
Argument[] args = new Argument[tokenizedAlgebraicExpression.length];
for (int i=0;i<args.length;i++)
{
if (tokenizedAlgebraicExpression[i].preParsed!=null)
args[i] = tokenizedAlgebraicExpression[i].preParsed;
else if (vars!=null && vars.containsKey(tokenizedAlgebraicExpression[i].value))
{
args[i] = new VariableArgument(tokenizedAlgebraicExpression[i].value, vars);
}
else if (tokenizedAlgebraicExpression[i].OPERANDP)
args[i] = parseOperand(tokenizedAlgebraicExpression[i].value);
else
args[i] = parseOperator(tokenizedAlgebraicExpression[i].value);
}
return args;
}
@Override
public OperatorDefinition getOperatorDefinition() {
return new OperatorDefinition()
{
@Override
public HashSet<String> getInfixOperators() {
return infixOperators;
}
@Override
public HashSet<String> getPrefixOperators() {
return prefixOperators;
}
@Override
public HashSet<String> getPostfixOperators() {
return postfixOperators;
}
@Override
public Vector<HashSet<String>> getOperatorPrecedence() {
return operators;
}
@Override
public HashSet<String> getTotalOperators() {
return totalOperators;
}
};
}
@Override
public Argument parseOperator(String opToken) {
if (infixOperators.contains(opToken))
{
return new BinaryOperator(opToken);
}
else if (prefixOperators.contains(opToken))
{
return new Function(opToken);
}
return null;
}
@Override
public Argument parseOperand(String argToken) {
return new SimpleDoubleArgument(Double.parseDouble(argToken));
}
}
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.ml;
import org.elasticsearch.client.Validatable;
import org.elasticsearch.client.ml.job.config.Job;
import org.elasticsearch.client.ml.job.util.PageParams;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.xcontent.ObjectParser;
import org.elasticsearch.common.xcontent.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.Objects;
/**
* A request to retrieve records of a given job
*/
public class GetRecordsRequest implements ToXContentObject, Validatable {
public static final ParseField EXCLUDE_INTERIM = new ParseField("exclude_interim");
public static final ParseField START = new ParseField("start");
public static final ParseField END = new ParseField("end");
public static final ParseField RECORD_SCORE = new ParseField("record_score");
public static final ParseField SORT = new ParseField("sort");
public static final ParseField DESCENDING = new ParseField("desc");
public static final ObjectParser<GetRecordsRequest, Void> PARSER = new ObjectParser<>("get_records_request", GetRecordsRequest::new);
static {
PARSER.declareString((request, jobId) -> request.jobId = jobId, Job.ID);
PARSER.declareBoolean(GetRecordsRequest::setExcludeInterim, EXCLUDE_INTERIM);
PARSER.declareStringOrNull(GetRecordsRequest::setStart, START);
PARSER.declareStringOrNull(GetRecordsRequest::setEnd, END);
PARSER.declareObject(GetRecordsRequest::setPageParams, PageParams.PARSER, PageParams.PAGE);
PARSER.declareDouble(GetRecordsRequest::setRecordScore, RECORD_SCORE);
PARSER.declareString(GetRecordsRequest::setSort, SORT);
PARSER.declareBoolean(GetRecordsRequest::setDescending, DESCENDING);
}
private String jobId;
private Boolean excludeInterim;
private String start;
private String end;
private PageParams pageParams;
private Double recordScore;
private String sort;
private Boolean descending;
private GetRecordsRequest() {}
/**
* Constructs a request to retrieve records of a given job
* @param jobId id of the job to retrieve records of
*/
public GetRecordsRequest(String jobId) {
this.jobId = Objects.requireNonNull(jobId);
}
public String getJobId() {
return jobId;
}
public Boolean getExcludeInterim() {
return excludeInterim;
}
/**
* Sets the value of "exclude_interim".
* When {@code true}, interim records will be filtered out.
* @param excludeInterim value of "exclude_interim" to be set
*/
public void setExcludeInterim(Boolean excludeInterim) {
this.excludeInterim = excludeInterim;
}
public String getStart() {
return start;
}
/**
* Sets the value of "start" which is a timestamp.
* Only records whose timestamp is on or after the "start" value will be returned.
* @param start String representation of a timestamp; may be an epoch seconds, epoch millis or an ISO string
*/
public void setStart(String start) {
this.start = start;
}
public String getEnd() {
return end;
}
/**
* Sets the value of "end" which is a timestamp.
* Only records whose timestamp is before the "end" value will be returned.
* @param end String representation of a timestamp; may be an epoch seconds, epoch millis or an ISO string
*/
public void setEnd(String end) {
this.end = end;
}
public PageParams getPageParams() {
return pageParams;
}
/**
* Sets the paging parameters
* @param pageParams The paging parameters
*/
public void setPageParams(PageParams pageParams) {
this.pageParams = pageParams;
}
public Double getRecordScore() {
return recordScore;
}
/**
* Sets the value of "record_score".
* Only records with "record_score" equal or greater will be returned.
* @param recordScore value of "record_score".
*/
public void setRecordScore(Double recordScore) {
this.recordScore = recordScore;
}
public String getSort() {
return sort;
}
/**
* Sets the value of "sort".
* Specifies the record field to sort on.
* @param sort value of "sort".
*/
public void setSort(String sort) {
this.sort = sort;
}
public Boolean getDescending() {
return descending;
}
/**
* Sets the value of "desc".
* Specifies the sorting order.
* @param descending value of "desc"
*/
public void setDescending(Boolean descending) {
this.descending = descending;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(Job.ID.getPreferredName(), jobId);
if (excludeInterim != null) {
builder.field(EXCLUDE_INTERIM.getPreferredName(), excludeInterim);
}
if (start != null) {
builder.field(START.getPreferredName(), start);
}
if (end != null) {
builder.field(END.getPreferredName(), end);
}
if (pageParams != null) {
builder.field(PageParams.PAGE.getPreferredName(), pageParams);
}
if (recordScore != null) {
builder.field(RECORD_SCORE.getPreferredName(), recordScore);
}
if (sort != null) {
builder.field(SORT.getPreferredName(), sort);
}
if (descending != null) {
builder.field(DESCENDING.getPreferredName(), descending);
}
builder.endObject();
return builder;
}
@Override
public int hashCode() {
return Objects.hash(jobId, excludeInterim, recordScore, pageParams, start, end, sort, descending);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
GetRecordsRequest other = (GetRecordsRequest) obj;
return Objects.equals(jobId, other.jobId) &&
Objects.equals(excludeInterim, other.excludeInterim) &&
Objects.equals(recordScore, other.recordScore) &&
Objects.equals(pageParams, other.pageParams) &&
Objects.equals(start, other.start) &&
Objects.equals(end, other.end) &&
Objects.equals(sort, other.sort) &&
Objects.equals(descending, other.descending);
}
}
|
package com.yveshe.restful;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class LoginController {
@RequestMapping(value = "/login")
public String showLoginForm(HttpServletRequest req, Model model) {
String exceptionClassName = (String) req.getAttribute("shiroLoginFailure");
String error = null;
if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
error = "用户名/密码错误";
} else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
error = "用户名/密码错误";
} else if (exceptionClassName != null) {
error = "其他错误:" + exceptionClassName;
}
model.addAttribute("error", error);
return "login";
}
}
|
package engine.components;
public abstract class AbstractComponent<T> implements Component<T> {
private final ComponentType type;
public AbstractComponent(ComponentType type) {
this.type = type;
}
@Override
public ComponentType getType() {
return type;
}
@Override
public String toString() {
return type.toString();
}
}
|
/**
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright 2012-2015 the original author or authors.
*/
package org.assertj.core.internal.objects;
import static org.assertj.core.error.ShouldNotBeIn.shouldNotBeIn;
import static org.assertj.core.test.ErrorMessages.*;
import static org.assertj.core.test.ObjectArrays.emptyArray;
import static org.assertj.core.test.TestData.someInfo;
import static org.assertj.core.test.TestFailures.failBecauseExpectedAssertionErrorWasNotThrown;
import static org.assertj.core.util.Arrays.array;
import static org.assertj.core.util.FailureMessages.actualIsNull;
import static org.mockito.Mockito.verify;
import org.assertj.core.api.AssertionInfo;
import org.assertj.core.internal.Objects;
import org.assertj.core.internal.ObjectsBaseTest;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Tests for <code>{@link Objects#assertIsNotIn(AssertionInfo, Object, Object[])}</code>.
*
* @author Joel Costigliola
* @author Alex Ruiz
* @author Yvonne Wang
*/
public class Objects_assertIsNotIn_with_array_Test extends ObjectsBaseTest {
private static String[] values;
@BeforeClass
public static void setUpOnce() {
values = array("Yoda", "Leia");
}
@Test
public void should_throw_error_if_array_is_null() {
thrown.expectNullPointerException(arrayIsNull());
Object[] array = null;
objects.assertIsNotIn(someInfo(), "Yoda", array);
}
@Test
public void should_throw_error_if_array_is_empty() {
thrown.expectIllegalArgumentException(arrayIsEmpty());
objects.assertIsNotIn(someInfo(), "Yoda", emptyArray());
}
@Test
public void should_pass_if_actual_is_in_not_array() {
objects.assertIsNotIn(someInfo(), "Luke", values);
}
@Test
public void should_fail_if_actual_is_null() {
thrown.expectAssertionError(actualIsNull());
objects.assertIsNotIn(someInfo(), null, values);
}
@Test
public void should_fail_if_actual_is_not_in_array() {
AssertionInfo info = someInfo();
try {
objects.assertIsNotIn(info, "Yoda", values);
} catch (AssertionError e) {
verify(failures).failure(info, shouldNotBeIn("Yoda", values));
return;
}
failBecauseExpectedAssertionErrorWasNotThrown();
}
@Test
public void should_pass_if_actual_is_in_not_array_according_to_custom_comparison_strategy() {
objectsWithCustomComparisonStrategy.assertIsNotIn(someInfo(), "Luke", values);
}
@Test
public void should_fail_if_actual_is_not_in_array_according_to_custom_comparison_strategy() {
AssertionInfo info = someInfo();
try {
objectsWithCustomComparisonStrategy.assertIsNotIn(info, "YODA", values);
} catch (AssertionError e) {
verify(failures).failure(info, shouldNotBeIn("YODA", values, customComparisonStrategy));
return;
}
failBecauseExpectedAssertionErrorWasNotThrown();
}
}
|
package resonant.lib.prefab.damage;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.potion.Potion;
import net.minecraft.util.DamageSource;
import resonant.api.armor.IInsulatedArmor;
import resonant.lib.prefab.CustomDamageSource;
import resonant.lib.prefab.potion.CustomPotionEffect;
import universalelectricity.api.UniversalElectricity;
import universalelectricity.api.electricity.IElectricalNetwork;
/** Electrical based damage source
*
* @author Darkguardsman */
public class ElectricalDamage extends CustomDamageSource
{
public ElectricalDamage(Object source)
{
super("electrocution");
this.setDamageBypassesArmor();
this.setDifficultyScaled();
}
/** Handles wire or machine based electrocution
*
* @param entity - entity to electrocute
* @param network - network to calculate damage from, and drain energy from */
public static void handleElectrocution(Entity entity, IElectricalNetwork network)
{
handleElectrocution(entity, null, network);
}
/** Handles wire or machine based electrocution
*
* @param entity - entity to electrocute
* @param source - source of the damage, can be null *
* @param network - network to calculate damage from, and drain energy from */
public static void handleElectrocution(Entity entity, Object source, IElectricalNetwork network)
{
handleElectrocution(entity, source, network, 1);
}
/** Handles wire or machine based electrocution
*
* @param entity - entity to electrocute
* @param source - source of the damage, can be null *
* @param network - network to calculate damage from, and drain energy from
* @param percent - percent of damage to apply 1 = 100% */
public static void handleElectrocution(Entity entity, Object source, IElectricalNetwork network, float percent)
{
if (network != null && network.getRequest() > 0 && network.getBuffer() > 0 && network.getVoltage() != 0)
{
electrocuteEntity(entity, source, network.getVoltage(), percent);
network.setBuffer(Math.max(0, network.getBuffer() - network.getVoltage() * 10));
}
}
/** Electrocutes an entity, takes into account several different conditions when applying damage
*
* @param entity - entity to electrocute
* @param voltage - voltage level being used
* @return damage applied to the entity */
public static float electrocuteEntity(Entity entity, Object source, long voltage, float percent)
{
if (entity instanceof EntityLivingBase)
{
/* Damage is percent based of default voltage, this prevents insta-killing entities */
float damage = Math.abs(voltage / UniversalElectricity.DEFAULT_VOLTAGE) * percent;
DamageSource sourceDamage = new ElectricalDamage(source);
damage = handleArmorReduction(entity, sourceDamage, voltage, damage);
/* No damage no method calls */
if (damage > 0)
{
entity.attackEntityFrom(sourceDamage, Math.min(damage, 15));
if (entity instanceof EntityLivingBase && damage >= 2)
{
((EntityLivingBase) entity).addPotionEffect(new CustomPotionEffect(Potion.confusion.id, (int) ((voltage / 120) * 20), 1));
((EntityLivingBase) entity).addPotionEffect(new CustomPotionEffect(Potion.weakness.id, (int) ((voltage / 120) * 20), 1));
((EntityLivingBase) entity).addPotionEffect(new CustomPotionEffect(Potion.digSlowdown.id, (int) ((voltage / 120) * 20), 1));
}
}
return damage >= 0 ? damage : 0;
}
return 0;
}
//TODO turn this into an armor handler
public static float handleArmorReduction(Entity entity, DamageSource source, long voltage, float damage)
{
//TODO add support for normal mobs
if (entity instanceof EntityPlayer)
{
EntityPlayer entityPlayer = (EntityPlayer) entity;
/** Average damage when the player wears a full armor set */
float averageDamage = 0;
/** Damage to be applied */
float appliedDamage = damage;
/** Is the character wearing a full suit of the same armor */
boolean fullSuit = true;
boolean hadArmor = false;
/* Check for full suit of protected armor */
for (int armorSlot = 0; armorSlot < entityPlayer.inventory.armorInventory.length; armorSlot++)
{
if (entityPlayer.inventory.armorInventory[armorSlot] != null)
{
if (entityPlayer.inventory.armorInventory[armorSlot].getItem() instanceof IInsulatedArmor)
{
IInsulatedArmor insulatedArmor = (IInsulatedArmor) entityPlayer.inventory.armorInventory[armorSlot].getItem();
float d = insulatedArmor.onEletricalDamage(entityPlayer.inventory.armorInventory[armorSlot], (EntityLivingBase) entity, source, voltage, damage);
hadArmor = true;
if (insulatedArmor.areAllPartsNeeded(entityPlayer.inventory.armorInventory[armorSlot], (EntityLivingBase) entity, source, "Electrical", voltage))
{
averageDamage += d;
if (armorSlot > 0)
{
if (!insulatedArmor.isPartOfSet(entityPlayer.inventory.armorInventory[armorSlot], entityPlayer.inventory.armorInventory[armorSlot - 1]))
fullSuit = false;
}
}
else
{
appliedDamage = d;
fullSuit = false;
}
}
else
{
fullSuit = false;
}
}
}
if (fullSuit && hadArmor)
{
return averageDamage > 0 ? averageDamage / 4 : 0;
}
else
{
return appliedDamage;
}
}
return damage;
}
}
|
package org.eclipse.aether.util.repository;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import static org.junit.Assert.*;
import org.eclipse.aether.DefaultRepositorySystemSession;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.repository.Authentication;
import org.eclipse.aether.repository.AuthenticationContext;
import org.eclipse.aether.repository.AuthenticationDigest;
import org.eclipse.aether.repository.RemoteRepository;
import org.junit.Test;
public class SecretAuthenticationTest
{
private RepositorySystemSession newSession()
{
return new DefaultRepositorySystemSession();
}
private RemoteRepository newRepo( Authentication auth )
{
return new RemoteRepository.Builder( "test", "default", "http://localhost" ).setAuthentication( auth ).build();
}
private AuthenticationContext newContext( Authentication auth )
{
return AuthenticationContext.forRepository( newSession(), newRepo( auth ) );
}
private String newDigest( Authentication auth )
{
return AuthenticationDigest.forRepository( newSession(), newRepo( auth ) );
}
@Test
public void testConstructor_CopyChars()
{
char[] value = { 'v', 'a', 'l' };
new SecretAuthentication( "key", value );
assertArrayEquals( new char[] { 'v', 'a', 'l' }, value );
}
@Test
public void testFill()
{
Authentication auth = new SecretAuthentication( "key", "value" );
AuthenticationContext context = newContext( auth );
assertNull( context.get( "another-key" ) );
assertEquals( "value", context.get( "key" ) );
}
@Test
public void testDigest()
{
Authentication auth1 = new SecretAuthentication( "key", "value" );
Authentication auth2 = new SecretAuthentication( "key", "value" );
String digest1 = newDigest( auth1 );
String digest2 = newDigest( auth2 );
assertEquals( digest1, digest2 );
Authentication auth3 = new SecretAuthentication( "key", "Value" );
String digest3 = newDigest( auth3 );
assertNotEquals( digest3, digest1 );
Authentication auth4 = new SecretAuthentication( "Key", "value" );
String digest4 = newDigest( auth4 );
assertNotEquals( digest4, digest1 );
}
@Test
public void testEquals()
{
Authentication auth1 = new SecretAuthentication( "key", "value" );
Authentication auth2 = new SecretAuthentication( "key", "value" );
Authentication auth3 = new SecretAuthentication( "key", "Value" );
assertEquals( auth1, auth2 );
assertNotEquals( auth1, auth3 );
assertNotEquals( null, auth1 );
}
@Test
public void testHashCode()
{
Authentication auth1 = new SecretAuthentication( "key", "value" );
Authentication auth2 = new SecretAuthentication( "key", "value" );
assertEquals( auth1.hashCode(), auth2.hashCode() );
}
}
|
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2018 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.checks.design;
import static com.puppycrawl.tools.checkstyle.checks.design.FinalClassCheck.MSG_KEY;
import static org.junit.Assert.assertArrayEquals;
import org.junit.Assert;
import org.junit.Test;
import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport;
import com.puppycrawl.tools.checkstyle.DefaultConfiguration;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
public class FinalClassCheckTest
extends AbstractModuleTestSupport {
@Override
protected String getPackageLocation() {
return "com/puppycrawl/tools/checkstyle/checks/design/finalclass";
}
@Test
public void testGetRequiredTokens() {
final FinalClassCheck checkObj = new FinalClassCheck();
final int[] expected = {TokenTypes.CLASS_DEF, TokenTypes.CTOR_DEF, TokenTypes.PACKAGE_DEF};
assertArrayEquals("Default required tokens are invalid",
expected, checkObj.getRequiredTokens());
}
@Test
public void testFinalClass() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(FinalClassCheck.class);
final String[] expected = {
"7: " + getCheckMessage(MSG_KEY, "InputFinalClass"),
"15: " + getCheckMessage(MSG_KEY, "test4"),
"113: " + getCheckMessage(MSG_KEY, "someinnerClass"),
};
verify(checkConfig, getPath("InputFinalClass.java"), expected);
}
@Test
public void testClassWithPrivateCtorAndNestedExtendingSubclass() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(FinalClassCheck.class);
final String[] expected = {
"16: " + getCheckMessage(MSG_KEY, "C"),
};
verify(checkConfig,
getNonCompilablePath(
"InputFinalClassClassWithPrivateCtorWithNestedExtendingClass.java"),
expected);
}
@Test
public void testClassWithPrivateCtorAndNestedExtendingSubclassWithoutPackage()
throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(FinalClassCheck.class);
final String[] expected = {
"8: " + getCheckMessage(MSG_KEY, "C"),
};
verify(checkConfig,
getNonCompilablePath(
"InputFinalClassClassWithPrivateCtorWithNestedExtendingClassWithoutPackage.java"),
expected);
}
@Test
public void testImproperToken() {
final FinalClassCheck finalClassCheck = new FinalClassCheck();
final DetailAST badAst = new DetailAST();
final int unsupportedTokenByCheck = TokenTypes.EOF;
badAst.setType(unsupportedTokenByCheck);
try {
finalClassCheck.visitToken(badAst);
Assert.fail("IllegalStateException is expected");
}
catch (IllegalStateException ex) {
// it is OK
}
}
@Test
public void testGetAcceptableTokens() {
final FinalClassCheck obj = new FinalClassCheck();
final int[] expected = {TokenTypes.CLASS_DEF, TokenTypes.CTOR_DEF, TokenTypes.PACKAGE_DEF};
assertArrayEquals("Default acceptable tokens are invalid",
expected, obj.getAcceptableTokens());
}
}
|
// Template Source: BaseEntity.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.models;
import com.microsoft.graph.serializer.ISerializer;
import com.microsoft.graph.serializer.IJsonBackedObject;
import com.microsoft.graph.serializer.AdditionalDataManager;
import java.util.EnumSet;
import com.microsoft.graph.http.BaseCollectionPage;
import com.microsoft.graph.models.RankedEmailAddress;
import com.microsoft.graph.models.Phone;
import com.microsoft.graph.models.Location;
import com.microsoft.graph.models.PersonDataSource;
import com.microsoft.graph.models.Website;
import com.microsoft.graph.models.Entity;
import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Person.
*/
public class Person extends Entity implements IJsonBackedObject {
/**
* The Birthday.
* The person's birthday.
*/
@SerializedName(value = "birthday", alternate = {"Birthday"})
@Expose
@Nullable
public String birthday;
/**
* The Company Name.
* The name of the person's company.
*/
@SerializedName(value = "companyName", alternate = {"CompanyName"})
@Expose
@Nullable
public String companyName;
/**
* The Department.
* The person's department.
*/
@SerializedName(value = "department", alternate = {"Department"})
@Expose
@Nullable
public String department;
/**
* The Display Name.
* The person's display name.
*/
@SerializedName(value = "displayName", alternate = {"DisplayName"})
@Expose
@Nullable
public String displayName;
/**
* The Email Addresses.
* The person's email addresses.
*/
@SerializedName(value = "emailAddresses", alternate = {"EmailAddresses"})
@Expose
@Nullable
public java.util.List<RankedEmailAddress> emailAddresses;
/**
* The Given Name.
* The person's given name.
*/
@SerializedName(value = "givenName", alternate = {"GivenName"})
@Expose
@Nullable
public String givenName;
/**
* The Is Favorite.
* true if the user has flagged this person as a favorite.
*/
@SerializedName(value = "isFavorite", alternate = {"IsFavorite"})
@Expose
@Nullable
public Boolean isFavorite;
/**
* The Mailbox Type.
* The type of mailbox that is represented by the person's email address.
*/
@SerializedName(value = "mailboxType", alternate = {"MailboxType"})
@Expose
@Nullable
public String mailboxType;
/**
* The Office Location.
* The location of the person's office.
*/
@SerializedName(value = "officeLocation", alternate = {"OfficeLocation"})
@Expose
@Nullable
public String officeLocation;
/**
* The Person Notes.
* Free-form notes that the user has taken about this person.
*/
@SerializedName(value = "personNotes", alternate = {"PersonNotes"})
@Expose
@Nullable
public String personNotes;
/**
* The Person Type.
* The type of person.
*/
@SerializedName(value = "personType", alternate = {"PersonType"})
@Expose
@Nullable
public String personType;
/**
* The Phones.
* The person's phone numbers.
*/
@SerializedName(value = "phones", alternate = {"Phones"})
@Expose
@Nullable
public java.util.List<Phone> phones;
/**
* The Postal Addresses.
* The person's addresses.
*/
@SerializedName(value = "postalAddresses", alternate = {"PostalAddresses"})
@Expose
@Nullable
public java.util.List<Location> postalAddresses;
/**
* The Profession.
* The person's profession.
*/
@SerializedName(value = "profession", alternate = {"Profession"})
@Expose
@Nullable
public String profession;
/**
* The Sources.
* The sources the user data comes from, for example Directory or Outlook Contacts.
*/
@SerializedName(value = "sources", alternate = {"Sources"})
@Expose
@Nullable
public java.util.List<PersonDataSource> sources;
/**
* The Surname.
* The person's surname.
*/
@SerializedName(value = "surname", alternate = {"Surname"})
@Expose
@Nullable
public String surname;
/**
* The Title.
* The person's title.
*/
@SerializedName(value = "title", alternate = {"Title"})
@Expose
@Nullable
public String title;
/**
* The User Principal Name.
* The user principal name (UPN) of the person. The UPN is an Internet-style login name for the person based on the Internet standard RFC 822. By convention, this should map to the person's email name. The general format is alias@domain.
*/
@SerializedName(value = "userPrincipalName", alternate = {"UserPrincipalName"})
@Expose
@Nullable
public String userPrincipalName;
/**
* The Websites.
* The person's websites.
*/
@SerializedName(value = "websites", alternate = {"Websites"})
@Expose
@Nullable
public java.util.List<Website> websites;
/**
* The Yomi Company.
* The phonetic Japanese name of the person's company.
*/
@SerializedName(value = "yomiCompany", alternate = {"YomiCompany"})
@Expose
@Nullable
public String yomiCompany;
/**
* Sets the raw JSON object
*
* @param serializer the serializer
* @param json the JSON object to set this object to
*/
public void setRawObject(@Nonnull final ISerializer serializer, @Nonnull final JsonObject json) {
}
}
|
package fr.adrienbrault.idea.symfony2plugin.stubs.indexes;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiRecursiveElementWalkingVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.indexing.*;
import com.intellij.util.io.DataExternalizer;
import com.intellij.util.io.EnumeratorStringDescriptor;
import com.intellij.util.io.KeyDescriptor;
import com.jetbrains.twig.TwigFile;
import com.jetbrains.twig.TwigFileType;
import com.jetbrains.twig.elements.TwigCompositeElement;
import com.jetbrains.twig.elements.TwigElementTypes;
import com.jetbrains.twig.elements.TwigExtendsTag;
import fr.adrienbrault.idea.symfony2plugin.stubs.indexes.externalizer.StringSetDataExternalizer;
import fr.adrienbrault.idea.symfony2plugin.templating.TwigPattern;
import fr.adrienbrault.idea.symfony2plugin.templating.dict.TwigBlock;
import fr.adrienbrault.idea.symfony2plugin.templating.util.TwigUtil;
import fr.adrienbrault.idea.symfony2plugin.util.PsiElementUtils;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class TwigBlockIndexExtension extends FileBasedIndexExtension<String, Set<String>> {
public static final ID<String, Set<String>> KEY = ID.create("fr.adrienbrault.idea.symfony2plugin.twig_block_names");
private final KeyDescriptor<String> KEY_DESCRIPTOR = new EnumeratorStringDescriptor();
private static final StringSetDataExternalizer DATA_EXTERNALIZER = new StringSetDataExternalizer();
@NotNull
@Override
public DataIndexer<String, Set<String>, FileContent> getIndexer() {
return fileContent -> {
Map<String, Set<String>> blocks = new HashMap<>();
PsiFile psiFile = fileContent.getPsiFile();
if(psiFile instanceof TwigFile) {
for (TwigBlock twigBlock : TwigUtil.getBlocksInFile((TwigFile) psiFile)) {
// we only index file scope
// {% embed 'foo.html.twig' %}{% block foo %}{% endembed %}
PsiElement embedStatement = PsiElementUtils.getParentOfType(twigBlock.getTarget(), TwigElementTypes.EMBED_STATEMENT);
if(embedStatement == null) {
blocks.putIfAbsent("block", new HashSet<>());
blocks.get("block").add(twigBlock.getName());
}
}
for(TwigExtendsTag extendsTag : PsiTreeUtil.getChildrenOfTypeAsList(psiFile, TwigExtendsTag.class)) {
for (String templateName : TwigUtil.getTwigExtendsTagTemplates(extendsTag)) {
blocks.putIfAbsent("extends", new HashSet<>());
blocks.get("extends").add(TwigUtil.normalizeTemplateName(templateName));
}
}
for(TwigCompositeElement twigCompositeElement: PsiTreeUtil.getChildrenOfTypeAsList(psiFile, TwigCompositeElement.class)) {
if(twigCompositeElement.getNode().getElementType() == TwigElementTypes.TAG) {
twigCompositeElement.acceptChildren(new PsiRecursiveElementWalkingVisitor() {
@Override
public void visitElement(PsiElement element) {
if(TwigPattern.getTwigTagUseNamePattern().accepts(element) && PsiElementUtils.getParentOfType(element, TwigElementTypes.EMBED_STATEMENT) == null) {
String templateName = TwigUtil.normalizeTemplateName(PsiElementUtils.trimQuote(element.getText()));
if(StringUtils.isNotBlank(templateName)) {
blocks.putIfAbsent("use", new HashSet<>());
blocks.get("use").add(templateName);
}
}
super.visitElement(element);
}
});
}
}
}
return blocks;
};
}
@NotNull
@Override
public ID<String, Set<String>> getName() {
return KEY;
}
@NotNull
@Override
public KeyDescriptor<String> getKeyDescriptor() {
return KEY_DESCRIPTOR;
}
@NotNull
@Override
public DataExternalizer<Set<String>> getValueExternalizer() {
return DATA_EXTERNALIZER;
}
@Override
public int getVersion() {
return 2;
}
@NotNull
@Override
public FileBasedIndex.InputFilter getInputFilter() {
return file -> file.getFileType() == TwigFileType.INSTANCE;
}
@Override
public boolean dependsOnFileContent() {
return true;
}
}
|
package com.jn.langx.test.util.charset;
import com.jn.langx.util.collection.Collects;
import com.jn.langx.util.function.Consumer;
import com.jn.langx.util.io.Charsets;
import org.junit.Test;
public class Utf8Tests {
@Test
public void test() {
String v = "-1=-1";
byte[] bytes = v.getBytes(Charsets.UTF_8);
Collects.forEach(bytes, new Consumer<Byte>() {
@Override
public void accept(Byte aByte) {
System.out.print(aByte+" ");
}
});
}
}
|
package uk.gov.dwp.dataworks.provider.standalone;
import org.junit.Assert;
import org.junit.Test;
import uk.gov.dwp.dataworks.dto.DecryptDataKeyResponse;
import uk.gov.dwp.dataworks.dto.GenerateDataKeyResponse;
public class StandaloneDataKeyDecryptionProviderTest {
private final StandaloneCurrentKeyIdProvider currentKeyIdProvider = new StandaloneCurrentKeyIdProvider();
private final StandaloneDataKeyGeneratorProvider generatorProvider = new StandaloneDataKeyGeneratorProvider();
private final StandaloneDataKeyDecryptionProvider decryptionProvider = new StandaloneDataKeyDecryptionProvider();
@Test
public void canDecryptKeys(){
// Create key
GenerateDataKeyResponse keys = generatorProvider.generateDataKey(currentKeyIdProvider.getKeyId());
// Decrypt key
DecryptDataKeyResponse decrypted = decryptionProvider.decryptDataKey(
keys.dataKeyEncryptionKeyId,
keys.ciphertextDataKey);
// What went in, must come out
Assert.assertEquals(keys.plaintextDataKey, decrypted.plaintextDataKey);
}
}
|
package edu.cmu.cs.cs214.hw5.framework;
import java.util.ArrayList;
import java.util.List;
import edu.cmu.cs.cs214.hw5.plugin.*;
import twitter4j.*;
/**
* The framework is responsible to write the main method, plugin
* developers can simply write their plugins implementing the
* Plugin interface, then register their plugins below.
* @author Hingon Miu & Raymond Xia
*/
public class main {
/**
* @param args
*/
public static void main(String[] args) {
Framework framework = new Framework();
// register plugins below (at most 10 plugins registered)
framework.registerPlugin(new SamplePlugin());
framework.registerPlugin(new SamplePlugin());
framework.registerPlugin(new SamplePlugin());
framework.registerPlugin(new SamplePlugin());
framework.registerPlugin(new SamplePlugin());
framework.confirmPlugins(); // signifies that all plugins are registered
}
}
|
package aima.test.core.unit.learning.knowledge;
import aima.core.learning.knowledge.KnowledgeLearningProblemFactory;
import aima.core.learning.knowledge.LogicalExample;
import aima.core.learning.knowledge.MinimalConsistentDet;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
/**
* @author samagra
*/
public class MinimalConsistentDetTest {
@Test
public void minimalConsistentDetTest(){
HashSet<String> setOfString = new HashSet<>(Arrays.asList("Mass","Temperature","Material","Size"));
List<LogicalExample> examples = KnowledgeLearningProblemFactory.getConductanceMeasurementProblem();
MinimalConsistentDet algo = new MinimalConsistentDet();
Assert.assertTrue(algo.minimalConsistentDet(examples, setOfString).
containsAll(Arrays.asList("Temperature","Material")));
Assert.assertEquals(2,algo.minimalConsistentDet(examples,setOfString).size());
}
}
|
/*
* Copyright 2013-2018 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.mturk.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.mturk.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* ListQualificationRequestsRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ListQualificationRequestsRequestMarshaller {
private static final MarshallingInfo<String> QUALIFICATIONTYPEID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("QualificationTypeId").build();
private static final MarshallingInfo<String> NEXTTOKEN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("NextToken").build();
private static final MarshallingInfo<Integer> MAXRESULTS_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("MaxResults").build();
private static final ListQualificationRequestsRequestMarshaller instance = new ListQualificationRequestsRequestMarshaller();
public static ListQualificationRequestsRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(ListQualificationRequestsRequest listQualificationRequestsRequest, ProtocolMarshaller protocolMarshaller) {
if (listQualificationRequestsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listQualificationRequestsRequest.getQualificationTypeId(), QUALIFICATIONTYPEID_BINDING);
protocolMarshaller.marshall(listQualificationRequestsRequest.getNextToken(), NEXTTOKEN_BINDING);
protocolMarshaller.marshall(listQualificationRequestsRequest.getMaxResults(), MAXRESULTS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
package com.byteowls.gradle.tasks;
import org.gradle.api.DefaultTask;
import org.gradle.api.internal.tasks.options.OptionValidationException;
import org.gradle.api.tasks.TaskAction;
import org.gradle.api.tasks.options.Option;
import org.jasypt.util.text.BasicTextEncryptor;
import org.jasypt.util.text.StrongTextEncryptor;
import org.jasypt.util.text.TextEncryptor;
/**
* @author m.oberwasserlechner@byteowls.com
*/
public abstract class PasswordAwareTask extends DefaultTask {
private String password;
private boolean strongEncryption;
private TextEncryptor encryptor;
protected TextEncryptor getEncryptor() {
if (encryptor == null) {
if (!strongEncryption) {
BasicTextEncryptor e = new BasicTextEncryptor();
e.setPassword(this.password);
this.encryptor = e;
} else {
StrongTextEncryptor e = new StrongTextEncryptor();
e.setPassword(this.password);
this.encryptor = e;
}
}
return encryptor;
}
@TaskAction
public void action() {
if (this.password == null || this.password.trim().isEmpty()) {
throw new OptionValidationException("--password is required!");
}
validateOptions();
taskAction();
}
public abstract void taskAction();
public abstract void validateOptions();
@Option(option = "strong-encryption", description = "Make sure jce extension is installed")
public void setStrongEncryption(boolean strongEncryption) {
this.strongEncryption = strongEncryption;
}
@Option(option = "password", description = "password [required]")
public void setPassword(String password) {
this.password = password;
}
}
|
package eu.bcvsolutions.idm.connector.kerio.services;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.identityconnectors.framework.common.exceptions.ConnectorException;
import org.identityconnectors.framework.common.objects.Attribute;
import org.identityconnectors.framework.common.objects.AttributeInfo;
import org.identityconnectors.framework.common.objects.AttributeInfoBuilder;
import org.identityconnectors.framework.common.objects.ObjectClass;
import org.identityconnectors.framework.common.objects.OperationOptions;
import org.identityconnectors.framework.common.objects.ResultsHandler;
import org.identityconnectors.framework.common.objects.Schema;
import org.identityconnectors.framework.common.objects.SchemaBuilder;
import org.identityconnectors.framework.common.objects.Uid;
import org.identityconnectors.framework.common.objects.filter.FilterTranslator;
import eu.bcvsolutions.idm.connector.kerio.KCConnector;
import eu.bcvsolutions.idm.connector.kerio.KCConstants;
import eu.bcvsolutions.idm.connector.kerio.SearchAttribute;
import eu.bcvsolutions.idm.connector.kerio.SearchFilterTranslator;
import eu.bcvsolutions.idm.connector.kerio.SearchOperation;
/**
* Service for managing user mailboxes.
*
* @author Filip Měšťánek
*/
public class UsersService extends BaseService {
public static final String DEFAULT_DELETE_METHOD = "UDeleteFolder";
@SuppressWarnings("unchecked")
@Override
public Uid create(ObjectClass oclass, Set<Attribute> attrs, OperationOptions options) {
Map<String, Object> params = new HashMap<String, Object>();
putAttrsIntoMap(attrs, params);
String loginName = (String) params.get(KCConstants.LOGIN_ATTR_NAME);
if (loginName == null || loginName.length() == 0) {
throw new ConnectorException("Create user failed - required attribute " + KCConstants.LOGIN_ATTR_NAME + " is empty.");
}
// Try to find user
SearchOperation op = new SearchOperation(new SearchAttribute(KCConstants.LOGIN_ATTR_NAME, KCConstants.COMPARATOR_EQ, loginName));
Uid userUid = getObjectId(oclass, op, null);
if (userUid != null) {
throw new ConnectorException("Create user failed - user with login " + loginName + " already exists.");
}
if (config.getActivateFromDS()) {
Object id = tryActivateUser(loginName);
if (id != null) {
// Update user from other parameters and return Uid
return updateUser(new Uid(id.toString()), params, false);
}
}
if (!config.getCreateLocalAccount()) {
String message = null;
if (config.getActivateFromDS()) {
message = "Create user failed - user with login " + loginName + " was not found in directory service " +
"and creating local accounts is disabled.";
} else {
message = "Create user failed - creating local accounts is disabled.";
}
throw new ConnectorException(message);
}
params.put("domainId", getDomainId());
List<Map<String, Object>> users = new ArrayList<Map<String,Object>>();
users.add(params);
Map<String, Object> base = new HashMap<String, Object>();
base.put("users", users);
Map<String, Object> response = jsonRPC.sendRequest("Users.create", base);
List<Map<String, Object>> createdList = (List<Map<String, Object>>) response.get("result");
if (createdList.size() != 1) {
throw new ConnectorException("Create user failed - returned " + createdList.size() + " records.");
}
Object id = createdList.get(0).get("id");
return new Uid(id.toString());
}
private Object tryActivateUser(String loginName) {
List<Map<String, Object>> importeeList = getNotActivatedUsers(getDomainId());
String kId = findUserFromImporteeList(loginName, importeeList);
if (kId != null) {
activateUser(kId, getDomainId());
return kId;
}
return null;
}
@SuppressWarnings("unchecked")
public List<Map<String, Object>> getNotActivatedUsers(String domain) {
Map<String, Object> base = new HashMap<String, Object>();
base.put("domainId", domain);
Map<String, Object> response = jsonRPC.sendRequest("Users.getNotActivated", base);
List<Map<String, Object>> newUsers = (List<Map<String, Object>>) response.get("newUsers");
return newUsers;
}
@SuppressWarnings("unchecked")
private String findUserFromImporteeList(String loginName, List<Map<String, Object>> importeeList) {
if (importeeList == null) {
return null;
}
for (Map<String, Object> importee : importeeList) {
Map<String, Object> user = (Map<String, Object>) importee.get("userItem");
String login = (String) user.get(KCConstants.LOGIN_ATTR_NAME);
if (loginName.equals(login)) {
String uid = (String) user.get(KCConstants.UID_ATTR_NAME);
Boolean isImportable = (Boolean) importee.get("isImportable");
if (isImportable != null && isImportable == true) {
return uid;
} else {
String message = (String) importee.get("message");
throw new ConnectorException("Create user failed - user " + loginName + " is not importable from directory service: " + message);
}
}
}
return null;
}
private void activateUser(String kId, String domain) {
System.out.println("Kerio Connector: User " + kId + " will be imported from directory service");
Map<String, Object> base = new HashMap<String, Object>();
List<String> ids = new ArrayList<String>();
ids.add(kId);
base.put("userIds", ids);
try {
jsonRPC.sendRequest("Users.activate", base);
} catch (ConnectorException ex) {
System.err.println("Kerio Connector: Activating user from directory service failed with error: " + ex.getMessage());
throw ex;
}
}
@Override
public Uid update(ObjectClass objclass, Uid uid, Set<Attribute> attrs, OperationOptions options) {
String uidValue = uid.getUidValue();
// Try to find user and the source of his data
String userSource = findUserSource(uidValue);
if (userSource == null) {
throw new ConnectorException("Update user failed - user with uid " + uidValue + " doesn't exist.");
}
Map<String, Object> params = new HashMap<String, Object>();
putAttrsIntoMap(attrs, params);
return updateUser(uid, params, isLocalSource(userSource));
}
private Uid updateUser(Uid uid, Map<String, Object> params, boolean isLocalSource) {
removeNonUpdatableAttributes(params, isLocalSource);
if (params.isEmpty()) {
return uid;
}
Map<String, Object> base = new HashMap<String, Object>();
base.put("pattern", params);
List<String> ids = new ArrayList<String>();
ids.add(uid.getUidValue());
base.put("userIds", ids);
jsonRPC.sendRequest("Users.set", base);
return uid;
}
private String findUserSource(String uidValue) {
List<String> fields = new ArrayList<>();
fields.add("itemSource");
SearchOperation op = new SearchOperation(new SearchAttribute(KCConstants.UID_ATTR_NAME, KCConstants.COMPARATOR_EQ, uidValue));
List<Map<String, Object>> users = findUsers(op, fields);
if (users == null || users.size() != 1) {
return null;
}
String itemSource = (String) users.get(0).get("itemSource");
return itemSource;
}
private void removeNonUpdatableAttributes(Map<String, Object> params, boolean isLocalSource) {
if (isLocalSource) {
return;
}
for (String attrName : config.getNonUpdatableAttributesInDSCollection()) {
params.remove(attrName);
}
}
@Override
public FilterTranslator<SearchOperation> createFilterTranslator(ObjectClass oclass, OperationOptions options) {
return new SearchFilterTranslator();
}
@Override
public void executeQuery(ObjectClass oclass, SearchOperation query, ResultsHandler handler, OperationOptions options) {
List<String> fields = new ArrayList<>();
fields.add("loginName");
List<Map<String, Object>> foundUsers = findUsers(query, fields);
processFoundObjects(foundUsers, handler);
}
@SuppressWarnings("unchecked")
private List<Map<String, Object>> findUsers(SearchOperation query, List<String> fields) {
Map<String, Object> params = getQueryParams(query, fields);
Map<String, Object> base = new HashMap<>();
base.put("query", params);
base.put("domainId", getDomainId());
Map<String, Object> response = jsonRPC.sendRequest("Users.get", base);
List<Map<String, Object>> foundUsers = (List<Map<String, Object>>) response.get("list");
return foundUsers;
}
@Override
public void delete(ObjectClass objClass, Uid uid, OperationOptions options) {
System.out.println("Delete on " + uid.getUidValue());
Map<String, Object> params = new HashMap<String, Object>();
params.put("userId", uid.getUidValue());
params.put("removeReferences", true);
// Custom remove method to be called
// One of UDeleteUser, UDeleteFolder, UMoveFolder - see api enum UserDeleteFolderMode
String method = (String) options.getOptions().get("deleteMethod");
if (method == null) {
params.put("method", DEFAULT_DELETE_METHOD);
} else if (method.equals("deleteUser")) {
params.put("method", "UDeleteUser");
} else if (method.equals("deleteFolder")) {
params.put("method", "UDeleteFolder");
} else if (method.equals("moveFolder")) {
// Move folder to other user
String userName = (String) options.getOptions().get("userName");
if (userName == null) {
throw new ConnectorException("When method " + method + " selected, userName has to be defined!");
}
System.out.println("Moving folder to " + userName);
// Get the other user id
SearchOperation op = new SearchOperation(new SearchAttribute("loginName", KCConstants.COMPARATOR_EQ, userName));
Uid userUid = getObjectId(objClass, op, options);
if (userUid == null) {
throw new ConnectorException("Unable to find user " + userName + "!");
}
params.put("method", "UMoveFolder");
params.put("targetUserId", userUid.getUidValue());
} else {
throw new ConnectorException("Unknown delete method: " + method);
}
List<Map<String, Object>> list = new ArrayList<>();
list.add(params);
Map<String, Object> base = new HashMap<String, Object>();
base.put("requests", list);
jsonRPC.sendRequest("Users.remove", base);
}
@Override
public Schema schema() {
if (schema != null) return schema;
final SchemaBuilder builder = new SchemaBuilder(KCConnector.class);
Set<AttributeInfo> attributes = new HashSet<AttributeInfo>();
attributes.add(new AttributeInfoBuilder(KCConstants.UID_ATTR_NAME).build());
attributes.add(new AttributeInfoBuilder(KCConstants.LOGIN_ATTR_NAME).build());
attributes.add(new AttributeInfoBuilder(KCConstants.FULL_NAME_ATTR_NAME).build());
attributes.add(new AttributeInfoBuilder(KCConstants.DESCRIPTION_ATTR_NAME).build());
attributes.add(new AttributeInfoBuilder(KCConstants.IS_ENABLED_ATTR_NAME).setType(Boolean.class).build());
attributes.add(new AttributeInfoBuilder(KCConstants.PASSWORD_ATTR_NAME).build());
attributes.add(new AttributeInfoBuilder(KCConstants.EMAIL_ADDRESSES_ATTR_NAME).setMultiValued(true).build());
builder.defineObjectClass(ObjectClass.ACCOUNT_NAME, attributes);
schema = builder.build();
return schema;
}
}
|
/*
* SPDX-License-Identifier: Apache-2.0
*
* Copyright 2020-2022 The JReleaser 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.jreleaser.maven.plugin;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.jreleaser.engine.context.ModelAutoConfigurer;
import org.jreleaser.maven.plugin.internal.JReleaserLoggerAdapter;
import org.jreleaser.model.JReleaserContext;
import org.jreleaser.util.JReleaserLogger;
import org.jreleaser.util.PlatformUtils;
import org.jreleaser.workflow.Workflows;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* Create or update a release with auto-config enabled.
*
* @author Andres Almiray
* @since 0.3.0
*/
@Mojo(name = "auto-config-release")
public class JReleaserAutoConfigReleaseMojo extends AbstractMojo {
/**
* The project whose model will be checked.
*/
@Parameter(defaultValue = "${project}", readonly = true, required = true)
private MavenProject project;
@Parameter(defaultValue = "${session}", required = true)
private MavenSession session;
@Parameter(property = "jreleaser.output.directory", defaultValue = "${project.build.directory}/jreleaser")
private File outputDirectory;
/**
* Skips remote operations.
*/
@Parameter(property = "jreleaser.dryrun")
private boolean dryrun;
/**
* Searches for the Git root.
*/
@Parameter(property = "jreleaser.git.root.search")
private boolean gitRootSearch;
/**
* The project name.
*/
@Parameter(property = "jreleaser.project.name", defaultValue = "${project.artifactId}")
private String projectName;
/**
* The project version.
*/
@Parameter(property = "jreleaser.project.version", defaultValue = "${project.version}")
private String projectVersion;
/**
* The project version pattern.
*/
@Parameter(property = "jreleaser.project.version.pattern")
private String projectVersionPattern;
/**
* The project snapshot pattern.
*/
@Parameter(property = "jreleaser.project.snapshot.pattern")
private String projectSnapshotPattern;
/**
* The project snapshot label.
*/
@Parameter(property = "jreleaser.project.snapshot.label")
private String projectSnapshotLabel;
/**
* Calculate full changelog since last non-snapshot release.
*/
@Parameter(property = "jreleaser.project.snapshot.full.changelog")
boolean projectSnapshotFullChangelog;
/**
* The release tag.
*/
@Parameter(property = "jreleaser.tag.name")
private String tagName;
/**
* The previous release tag.
*/
@Parameter(property = "jreleaser.previous.tag.name")
private String previousTagName;
/**
* The release name.
*/
@Parameter(property = "jreleaser.release.name")
private String releaseName;
/**
* The release branch.
*/
@Parameter(property = "jreleaser.release.branch")
private String branch;
/**
* The milestone name.
*/
@Parameter(property = "jreleaser.milestone.name")
private String milestoneName;
/**
* If the release is a prerelease.
*/
@Parameter(property = "jreleaser.prerelease")
private boolean prerelease;
/**
* The prerelease pattern.
*/
@Parameter(property = "jreleaser.prerelease.pattern")
private String prereleasePattern;
/**
* If the release is a draft.
*/
@Parameter(property = "jreleaser.draft")
private boolean draft;
/**
* Overwrite an existing release.
*/
@Parameter(property = "jreleaser.overwrite")
private boolean overwrite;
/**
* Update an existing release.
*/
@Parameter(property = "jreleaser.update")
private boolean update;
/**
* Release section(s) to be updated.
*/
@Parameter(property = "jreleaser.update.sections")
private UpdateSection[] updateSections;
/**
* Skip tagging the release.
*/
@Parameter(property = "jreleaser.skip.tag")
private boolean skipTag;
/**
* Skip creating a release.
*/
@Parameter(property = "jreleaser.skip.release")
private boolean skipRelease;
/**
* Path to changelog file.
*/
@Parameter(property = "jreleaser.changelog")
private String changelog;
/**
* Format generated changelog.
*/
@Parameter(property = "jreleaser.changelog.formatted")
private boolean changelogFormatted;
/**
* Git username.
*/
@Parameter(property = "jreleaser.username")
private String username;
/**
* Commit author name.
*/
@Parameter(property = "jreleaser.commit.author.name")
private String commitAuthorName;
/**
* Commit author e-mail.
*/
@Parameter(property = "jreleaser.commit.author.email")
private String commitAuthorEmail;
/**
* Sign files.
*/
@Parameter(property = "jreleaser.signing")
private boolean signing;
/**
* Generate ascii armored signatures.
*/
@Parameter(property = "jreleaser.armored")
private boolean armored;
/**
* Input file(s) to be uploaded.
*/
@Parameter(property = "jreleaser.files")
private String[] files;
/**
* Input file(s) to be uploaded (as globs).
*/
@Parameter(property = "jreleaser.globs")
private String[] globs;
/**
* Activates paths matching the current platform.
*/
@Parameter(property = "jreleaser.select.current.platform")
private boolean selectCurrentPlatform;
/**
* Activates paths matching the given platform.
*/
@Parameter(property = "jreleaser.select.platform")
private String[] selectPlatforms;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
Banner.display(project, getLog());
JReleaserContext context = ModelAutoConfigurer.builder()
.logger(getLogger())
.basedir(project.getBasedir().toPath())
.outputDirectory(outputDirectory.toPath())
.dryrun(dryrun)
.gitRootSearch(gitRootSearch)
.projectName(projectName)
.projectVersion(projectVersion)
.projectVersionPattern(projectVersionPattern)
.projectSnapshotPattern(projectSnapshotPattern)
.projectSnapshotLabel(projectSnapshotLabel)
.projectSnapshotFullChangelog(projectSnapshotFullChangelog)
.tagName(tagName)
.previousTagName(previousTagName)
.releaseName(releaseName)
.branch(branch)
.milestoneName(milestoneName)
.prerelease(prerelease)
.prereleasePattern(prereleasePattern)
.draft(draft)
.overwrite(overwrite)
.update(update)
.updateSections(collectUpdateSections())
.skipTag(skipTag)
.skipRelease(skipRelease)
.changelog(changelog)
.changelogFormatted(changelogFormatted)
.username(username)
.commitAuthorName(commitAuthorName)
.commitAuthorEmail(commitAuthorEmail)
.signing(signing)
.armored(armored)
.files(collectFiles())
.globs(collectGlobs())
.selectedPlatforms(collectSelectedPlatforms())
.autoConfigure();
Workflows.release(context).execute();
}
private JReleaserLogger getLogger() throws MojoExecutionException {
return new JReleaserLoggerAdapter(createTracer(), getLog());
}
private PrintWriter createTracer() throws MojoExecutionException {
try {
java.nio.file.Files.createDirectories(outputDirectory.toPath());
return new PrintWriter(new FileOutputStream(
outputDirectory.toPath().resolve("trace.log").toFile()));
} catch (IOException e) {
throw new MojoExecutionException("Could not initialize trace file", e);
}
}
private List<String> collectFiles() {
List<String> list = new ArrayList<>();
if (files != null && files.length > 0) {
Collections.addAll(list, files);
}
return list;
}
private List<String> collectGlobs() {
List<String> list = new ArrayList<>();
if (globs != null && globs.length > 0) {
Collections.addAll(list, globs);
}
return list;
}
private Set<org.jreleaser.model.UpdateSection> collectUpdateSections() {
Set<org.jreleaser.model.UpdateSection> set = new LinkedHashSet<>();
if (updateSections != null && updateSections.length > 0) {
for (UpdateSection updateSection : updateSections) {
set.add(org.jreleaser.model.UpdateSection.of(updateSection.name()));
}
}
return set;
}
protected List<String> collectSelectedPlatforms() {
if (selectCurrentPlatform) return Collections.singletonList(PlatformUtils.getCurrentFull());
List<String> list = new ArrayList<>();
if (selectPlatforms != null && selectPlatforms.length > 0) {
Collections.addAll(list, selectPlatforms);
}
return list;
}
}
|
package org.mockserver.model;
import junit.framework.TestCase;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.mockserver.model.HttpForward.forward;
/**
* @author jamesdbloom
*/
public class HttpForwardTest {
@Test
public void shouldAlwaysCreateNewObject() {
assertEquals(new HttpForward().forward(), forward());
assertNotSame(forward(), forward());
}
@Test
public void returnsPort() {
assertEquals(new Integer(9090), new HttpForward().withPort(9090).getPort());
}
@Test
public void returnsHost() {
assertEquals("some_host", new HttpForward().withHost("some_host").getHost());
}
@Test
public void returnsScheme() {
assertEquals(HttpForward.Scheme.HTTPS, new HttpForward().withScheme(HttpForward.Scheme.HTTPS).getScheme());
}
@Test
public void shouldReturnFormattedRequestInToString() {
TestCase.assertEquals("{" + System.getProperty("line.separator") +
" \"host\" : \"some_host\"," + System.getProperty("line.separator") +
" \"port\" : 9090," + System.getProperty("line.separator") +
" \"scheme\" : \"HTTPS\"" + System.getProperty("line.separator") +
"}",
forward()
.withHost("some_host")
.withPort(9090)
.withScheme(HttpForward.Scheme.HTTPS)
.toString()
);
}
}
|
/*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2010 The ZAP Development Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.zaproxy.zap.extension.alert;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.TitledBorder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdesktop.swingx.JXPanel;
import org.jdesktop.swingx.ScrollableSizeHint;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.control.Control;
import org.parosproxy.paros.core.scanner.Alert;
import org.parosproxy.paros.core.scanner.Plugin;
import org.parosproxy.paros.core.scanner.PluginFactory;
import org.parosproxy.paros.extension.AbstractPanel;
import org.parosproxy.paros.model.HistoryReference;
import org.parosproxy.paros.network.HttpMessage;
import org.zaproxy.zap.extension.pscan.ExtensionPassiveScan;
import org.zaproxy.zap.extension.pscan.PluginPassiveScanner;
import org.zaproxy.zap.model.Vulnerabilities;
import org.zaproxy.zap.model.Vulnerability;
import org.zaproxy.zap.utils.DisplayUtils;
import org.zaproxy.zap.utils.FontUtils;
import org.zaproxy.zap.utils.ZapLabel;
import org.zaproxy.zap.utils.ZapNumberSpinner;
import org.zaproxy.zap.utils.ZapTextArea;
import org.zaproxy.zap.utils.ZapTextField;
import org.zaproxy.zap.view.LayoutHelper;
import org.zaproxy.zap.view.ZapTable;
public class AlertViewPanel extends AbstractPanel {
private static final long serialVersionUID = 1L;
private static final Logger logger = LogManager.getLogger(AlertViewPanel.class);
private static final int UNDEFINED_ID = -1;
private static final Insets DEFAULT_INSETS = new Insets(1, 1, 1, 1);
private JScrollPane defaultPane = null;
private JScrollPane alertPane = null;
private ZapTextArea defaultOutput = null;
private JXPanel alertDisplay = null;
private CardLayout cardLayout = null;
private ZapLabel alertUrl = null;
private ZapLabel alertName = null;
private JLabel alertRisk = null;
private JLabel alertConfidence = null;
private ZapLabel alertParam = null;
private ZapLabel alertAttack = null;
private ZapLabel alertEvidence = null;
private ZapTextArea alertDescription = null;
private ZapTextArea alertOtherInfo = null;
private ZapTextArea alertSolution = null;
private ZapTextArea alertReference = null;
private ZapTable alertTagsTable = null;
private AlertTagsTableModel alertTagsTableModel = null;
private ZapLabel alertCweId = null;
private ZapLabel alertWascId = null;
private ZapLabel alertSource;
private JComboBox<String> alertEditName = null;
private JComboBox<String> alertEditRisk = null;
private JComboBox<String> alertEditConfidence = null;
private JComboBox<String> alertEditParam = null;
private ZapTextField alertEditAttack = null;
private ZapTextField alertEditEvidence = null;
private DefaultComboBoxModel<String> nameListModel = null;
private DefaultComboBoxModel<String> paramListModel = null;
private ZapNumberSpinner alertEditCweId = null;
private ZapNumberSpinner alertEditWascId = null;
private JLabel attackLabel;
private JLabel cweidLabel;
private JLabel evidenceLabel;
private JLabel otherLabel;
private JLabel confidenceLabel;
private JLabel riskLabel;
private JLabel sourceLabel;
private JLabel urlLabel;
private JLabel wascidLabel;
private DialogAddAlertTag dialogAddAlertTag;
private DialogModifyAlertTag dialogModifyAlertTag;
private boolean editable = false;
private Alert originalAlert = null;
private List<Vulnerability> vulnerabilities = null;
private HistoryReference historyRef = null;
/** Used to set the {@code HttpMessage} to the new alert when there is no {@code historyRef}. */
private HttpMessage httpMessage;
public AlertViewPanel() {
this(false);
}
public AlertViewPanel(boolean editable) {
super();
this.editable = editable;
initialize();
}
/** This method initializes this */
private void initialize() {
cardLayout = new CardLayout();
this.setLayout(cardLayout);
this.setName("AlertView");
if (!editable) {
this.add(getDefaultPane(), getDefaultPane().getName());
}
this.add(getAlertPane(), getAlertPane().getName());
}
private JScrollPane getAlertPane() {
if (alertPane == null) {
alertPane = new JScrollPane();
alertPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
alertPane.setViewportView(getAlertDisplay());
alertPane.setName("alertPane");
}
return alertPane;
}
private ZapTextArea createZapTextArea() {
ZapTextArea ZapTextArea = new ZapTextArea(3, 30);
ZapTextArea.setLineWrap(true);
ZapTextArea.setWrapStyleWord(true);
ZapTextArea.setEditable(editable);
return ZapTextArea;
}
private JScrollPane createJScrollPane(String name) {
JScrollPane jScrollPane = new JScrollPane();
jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
jScrollPane.setBorder(
BorderFactory.createTitledBorder(
null,
name,
TitledBorder.DEFAULT_JUSTIFICATION,
javax.swing.border.TitledBorder.DEFAULT_POSITION,
FontUtils.getFont(FontUtils.Size.standard)));
return jScrollPane;
}
private JPanel getAlertDisplay() {
if (alertDisplay == null) {
alertDisplay = new JXPanel();
alertDisplay.setLayout(new GridBagLayout());
alertDisplay.setScrollableHeightHint(ScrollableSizeHint.NONE);
alertDisplay.setName("alertDisplay");
// Create the labels
alertEditName = new JComboBox<>();
alertEditName.setEditable(true);
nameListModel = new DefaultComboBoxModel<>();
List<String> allVulns = getAllVulnerabilityNames();
nameListModel.addElement(""); // Default to blank
for (String vuln : allVulns) {
nameListModel.addElement(vuln);
}
alertEditName.setModel(nameListModel);
alertEditName.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if ("comboBoxChanged".equals(e.getActionCommand())) {
Vulnerability v =
getVulnerability((String) alertEditName.getSelectedItem());
if (v != null) {
if (v.getDescription() != null
&& v.getDescription().length() > 0) {
setAlertDescription(v.getDescription());
}
if (v.getSolution() != null && v.getSolution().length() > 0) {
setAlertSolution(v.getSolution());
}
if (v.getReferences() != null) {
StringBuilder sb = new StringBuilder();
for (String ref : v.getReferences()) {
sb.append(ref);
sb.append('\n');
}
setAlertReference(sb.toString());
}
alertEditWascId.setValue(v.getWascId());
}
}
}
});
alertEditRisk = new JComboBox<>(Alert.MSG_RISK);
alertEditConfidence = new JComboBox<>(Alert.MSG_CONFIDENCE);
alertEditConfidence.setSelectedItem(Alert.MSG_CONFIDENCE[Alert.CONFIDENCE_MEDIUM]);
alertEditAttack = new ZapTextField();
paramListModel = new DefaultComboBoxModel<>();
paramListModel.addElement(""); // Default is empty so user can type anything in
alertEditParam = new JComboBox<>();
alertEditParam.setModel(paramListModel);
alertEditParam.setEditable(true);
alertEditEvidence = new ZapTextField();
alertEditCweId = new ZapNumberSpinner();
if (alertEditCweId.getEditor() instanceof JSpinner.DefaultEditor) {
((JSpinner.DefaultEditor) alertEditCweId.getEditor())
.getTextField()
.setHorizontalAlignment(JTextField.LEFT);
}
alertEditWascId = new ZapNumberSpinner();
if (alertEditWascId.getEditor() instanceof JSpinner.DefaultEditor) {
((JSpinner.DefaultEditor) alertEditWascId.getEditor())
.getTextField()
.setHorizontalAlignment(JTextField.LEFT);
}
// Read only ones
alertName = new ZapLabel();
alertName.setFont(FontUtils.getFont(Font.BOLD));
alertName.setLineWrap(true);
alertRisk = new JLabel();
alertConfidence = new JLabel();
alertParam = new ZapLabel();
alertParam.setLineWrap(true);
alertAttack = new ZapLabel();
alertAttack.setLineWrap(true);
alertEvidence = new ZapLabel();
alertEvidence.setLineWrap(true);
alertCweId = new ZapLabel();
alertWascId = new ZapLabel();
alertSource = new ZapLabel();
alertSource.setLineWrap(true);
alertUrl = new ZapLabel();
alertUrl.setLineWrap(true);
alertDescription = createZapTextArea();
JScrollPane descSp = createJScrollPane(Constant.messages.getString("alert.label.desc"));
descSp.setViewportView(alertDescription);
alertDescription.addKeyListener(
new KeyAdapter() {
// Change tab key to transfer focus to the next element
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_TAB) {
alertDescription.transferFocus();
}
}
});
alertOtherInfo = createZapTextArea();
JScrollPane otherSp =
createJScrollPane(Constant.messages.getString("alert.label.other"));
otherSp.setViewportView(alertOtherInfo);
alertOtherInfo.addKeyListener(
new KeyAdapter() {
// Change tab key to transfer focus to the next element
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_TAB) {
alertOtherInfo.transferFocus();
}
}
});
alertSolution = createZapTextArea();
JScrollPane solutionSp =
createJScrollPane(Constant.messages.getString("alert.label.solution"));
solutionSp.setViewportView(alertSolution);
alertSolution.addKeyListener(
new KeyAdapter() {
// Change tab key to transfer focus to the next element
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_TAB) {
alertSolution.transferFocus();
}
}
});
alertReference = createZapTextArea();
JScrollPane referenceSp =
createJScrollPane(Constant.messages.getString("alert.label.ref"));
referenceSp.setViewportView(alertReference);
alertReference.addKeyListener(
new KeyAdapter() {
// Change tab key to transfer focus to the next element
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_TAB) {
alertReference.transferFocus();
}
}
});
int gbcRow = 0;
alertDisplay.add(
editable ? alertEditName : alertName,
LayoutHelper.getGBC(0, gbcRow, 2, 0, DEFAULT_INSETS));
// Show a blank label instead of the edit button if already editing
gbcRow++;
alertDisplay.add(getUrlLabel(), LayoutHelper.getGBC(0, gbcRow, 1, 0, DEFAULT_INSETS));
alertDisplay.add(alertUrl, LayoutHelper.getGBC(1, gbcRow, 1, 1, DEFAULT_INSETS));
gbcRow++;
alertDisplay.add(getRiskLabel(), LayoutHelper.getGBC(0, gbcRow, 1, 0, DEFAULT_INSETS));
alertDisplay.add(
editable ? alertEditRisk : alertRisk,
LayoutHelper.getGBC(1, gbcRow, 1, 1, DEFAULT_INSETS));
gbcRow++;
alertDisplay.add(
getConfidenceLabel(), LayoutHelper.getGBC(0, gbcRow, 1, 0, DEFAULT_INSETS));
alertDisplay.add(
editable ? alertEditConfidence : alertConfidence,
LayoutHelper.getGBC(1, gbcRow, 1, 1, DEFAULT_INSETS));
gbcRow++;
alertDisplay.add(
getParameterLabel(), LayoutHelper.getGBC(0, gbcRow, 1, 0, DEFAULT_INSETS));
alertDisplay.add(
editable ? alertEditParam : alertParam,
LayoutHelper.getGBC(1, gbcRow, 1, 1, DEFAULT_INSETS));
gbcRow++;
alertDisplay.add(
getAttackLabel(), LayoutHelper.getGBC(0, gbcRow, 1, 0, DEFAULT_INSETS));
alertDisplay.add(
editable ? alertEditAttack : alertAttack,
LayoutHelper.getGBC(1, gbcRow, 1, 1, DEFAULT_INSETS));
gbcRow++;
alertDisplay.add(
getEvidenceLabel(), LayoutHelper.getGBC(0, gbcRow, 1, 0, DEFAULT_INSETS));
alertDisplay.add(
editable ? alertEditEvidence : alertEvidence,
LayoutHelper.getGBC(1, gbcRow, 1, 1, DEFAULT_INSETS));
gbcRow++;
alertDisplay.add(getCweidLabel(), LayoutHelper.getGBC(0, gbcRow, 1, 0, DEFAULT_INSETS));
alertDisplay.add(
editable ? alertEditCweId : alertCweId,
LayoutHelper.getGBC(1, gbcRow, 1, 1, DEFAULT_INSETS));
gbcRow++;
alertDisplay.add(
getWascidLabel(), LayoutHelper.getGBC(0, gbcRow, 1, 0, DEFAULT_INSETS));
alertDisplay.add(
editable ? alertEditWascId : alertWascId,
LayoutHelper.getGBC(1, gbcRow, 1, 1, DEFAULT_INSETS));
gbcRow++;
if (!editable) {
alertDisplay.add(
getSourceLabel(), LayoutHelper.getGBC(0, gbcRow, 1, 0, DEFAULT_INSETS));
alertDisplay.add(alertSource, LayoutHelper.getGBC(1, gbcRow, 1, 1, DEFAULT_INSETS));
gbcRow++;
}
alertDisplay.add(
descSp,
LayoutHelper.getGBC(
0, gbcRow, 2, 1.0D, 1.0D, GridBagConstraints.BOTH, DEFAULT_INSETS));
gbcRow++;
alertDisplay.add(
otherSp,
LayoutHelper.getGBC(
0, gbcRow, 2, 1.0D, 1.0D, GridBagConstraints.BOTH, DEFAULT_INSETS));
gbcRow++;
alertDisplay.add(
solutionSp,
LayoutHelper.getGBC(
0, gbcRow, 2, 1.0D, 1.0D, GridBagConstraints.BOTH, DEFAULT_INSETS));
gbcRow++;
alertDisplay.add(
referenceSp,
LayoutHelper.getGBC(
0, gbcRow, 2, 1.0D, 1.0D, GridBagConstraints.BOTH, DEFAULT_INSETS));
gbcRow++;
alertDisplay.add(
createAlertTagsPanel(),
LayoutHelper.getGBC(
0, gbcRow, 2, 1.0D, 1.0D, GridBagConstraints.BOTH, DEFAULT_INSETS));
}
return alertDisplay;
}
private JPanel createAlertTagsPanel() {
JPanel alertTagsPanel = new JXPanel(new BorderLayout());
alertTagsPanel.setName("Alert Tags Panel");
alertTagsPanel.setBorder(
BorderFactory.createTitledBorder(
null,
Constant.messages.getString("alert.label.tags"),
TitledBorder.DEFAULT_JUSTIFICATION,
javax.swing.border.TitledBorder.DEFAULT_POSITION,
FontUtils.getFont(FontUtils.Size.standard)));
alertTagsTableModel = new AlertTagsTableModel();
alertTagsTable = new ZapTable(alertTagsTableModel);
alertTagsTable.setPreferredScrollableViewportSize(
new Dimension(
alertTagsTable.getPreferredSize().width,
alertTagsTable.getRowHeight() * 5));
if (!editable) {
alertTagsTable.setCellSelectionEnabled(true);
}
JScrollPane alertTagsSp = new JScrollPane();
alertTagsSp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
alertTagsSp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
alertTagsSp.setViewportView(alertTagsTable);
alertTagsSp.addKeyListener(
new KeyAdapter() {
// Change tab key to transfer focus to the next element
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_TAB) {
alertTagsTable.transferFocus();
}
}
});
if (editable) {
JToolBar alertTagsToolBar = new JToolBar();
alertTagsToolBar.setEnabled(true);
alertTagsToolBar.setFloatable(false);
alertTagsToolBar.setRollover(true);
alertTagsToolBar.setName("Alert Tags Editing Toolbar");
JButton addTagButton = new JButton();
addTagButton.setToolTipText(Constant.messages.getString("alert.tags.button.add"));
addTagButton.setIcon(
DisplayUtils.getScaledIcon(
new ImageIcon(
AlertViewPanel.class.getResource(
"/resource/icon/16/103.png"))));
addTagButton.addActionListener(e -> showAddAlertTagDialogue());
alertTagsToolBar.add(addTagButton);
JButton deleteTagButton = new JButton();
deleteTagButton.setToolTipText(Constant.messages.getString("alert.tags.button.delete"));
deleteTagButton.setIcon(
DisplayUtils.getScaledIcon(
new ImageIcon(
AlertViewPanel.class.getResource(
"/resource/icon/16/104.png"))));
deleteTagButton.addActionListener(
e -> alertTagsTableModel.deleteTags(alertTagsTable.getSelectedRows()));
deleteTagButton.setEnabled(false);
alertTagsToolBar.add(deleteTagButton);
JButton editTagButton = new JButton();
editTagButton.setToolTipText(Constant.messages.getString("alert.tags.button.modify"));
editTagButton.setIcon(
DisplayUtils.getScaledIcon(
new ImageIcon(
AlertViewPanel.class.getResource(
"/resource/icon/16/018.png"))));
editTagButton.addActionListener(e -> showModifyAlertTagDialogue());
editTagButton.setEnabled(false);
alertTagsToolBar.add(editTagButton);
alertTagsTable
.getSelectionModel()
.addListSelectionListener(
e -> {
if (alertTagsTable.getSelectedRow() == -1) {
deleteTagButton.setEnabled(false);
editTagButton.setEnabled(false);
return;
}
if (!deleteTagButton.isEnabled()) {
deleteTagButton.setEnabled(true);
}
if (!editTagButton.isEnabled()) {
editTagButton.setEnabled(true);
}
});
alertTagsTable.addMouseListener(
new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
JTable table = (JTable) e.getSource();
if (e.getClickCount() == 2 && table.getSelectedRow() != -1) {
showModifyAlertTagDialogue();
}
}
});
alertTagsPanel.add(alertTagsToolBar, BorderLayout.PAGE_START);
}
alertTagsPanel.add(alertTagsSp, BorderLayout.CENTER);
return alertTagsPanel;
}
public void displayAlert(Alert alert) {
this.originalAlert = alert;
alertUrl.setText(alert.getUri());
if (editable) {
nameListModel.addElement(alert.getName());
alertEditName.setSelectedItem(alert.getName());
alertEditRisk.setSelectedItem(Alert.MSG_RISK[alert.getRisk()]);
alertEditConfidence.setSelectedItem(Alert.MSG_CONFIDENCE[alert.getConfidence()]);
alertEditParam.setSelectedItem(alert.getParam());
alertEditAttack.setText(alert.getAttack());
alertEditAttack.discardAllEdits();
alertEditEvidence.setText(alert.getEvidence());
alertEditEvidence.discardAllEdits();
alertEditCweId.setValue(alert.getCweId());
alertEditWascId.setValue(alert.getWascId());
} else {
alertName.setText(alert.getName());
alertRisk.setText(Alert.MSG_RISK[alert.getRisk()]);
alertRisk.setIcon(alert.getIcon());
alertConfidence.setText(Alert.MSG_CONFIDENCE[alert.getConfidence()]);
alertParam.setText(alert.getParam());
alertAttack.setText(alert.getAttack());
alertEvidence.setText(alert.getEvidence());
alertCweId.setText(normalisedId(alert.getCweId()));
alertWascId.setText(normalisedId(alert.getWascId()));
alertSource.setText(getSourceData(alert));
}
setAlertDescription(alert.getDescription());
setAlertOtherInfo(alert.getOtherInfo());
setAlertSolution(alert.getSolution());
setAlertReference(alert.getReference());
setAlertTags(alert.getTags());
cardLayout.show(this, getAlertPane().getName());
}
private static String normalisedId(int id) {
return id != UNDEFINED_ID ? Integer.toString(id) : "";
}
private String getSourceData(Alert alert) {
String source = Constant.messages.getString(alert.getSource().getI18nKey());
if (alert.getPluginId() == UNDEFINED_ID) {
return source;
}
StringBuilder strBuilder = new StringBuilder(source);
strBuilder.append(" (").append(alert.getPluginId());
if (alert.getSource() == Alert.Source.ACTIVE) {
Plugin plugin = PluginFactory.getLoadedPlugin(alert.getPluginId());
if (plugin != null) {
strBuilder.append(" - ").append(plugin.getName());
}
} else if (alert.getSource() == Alert.Source.PASSIVE) {
ExtensionPassiveScan ext =
Control.getSingleton()
.getExtensionLoader()
.getExtension(ExtensionPassiveScan.class);
if (ext != null) {
PluginPassiveScanner scanner = ext.getPluginPassiveScanner(alert.getPluginId());
if (scanner != null) {
strBuilder.append(" - ").append(scanner.getName());
}
}
}
strBuilder.append(')');
return strBuilder.toString();
}
public void clearAlert() {
cardLayout.show(this, getDefaultPane().getName());
originalAlert = null;
historyRef = null;
httpMessage = null;
alertName.setText("");
alertRisk.setText("");
alertConfidence.setText("");
alertParam.setText("");
alertAttack.setText("");
alertDescription.setText("");
alertOtherInfo.setText("");
alertSolution.setText("");
alertReference.setText("");
alertSource.setText("");
setAlertTags(Collections.emptyMap());
if (editable) {
alertEditAttack.setText("");
alertEditAttack.discardAllEdits();
alertEditEvidence.setText("");
alertEditEvidence.discardAllEdits();
alertDescription.discardAllEdits();
alertOtherInfo.discardAllEdits();
alertSolution.discardAllEdits();
alertReference.discardAllEdits();
}
}
/**
* This method initializes jScrollPane
*
* @return javax.swing.JScrollPane
*/
private JScrollPane getDefaultPane() {
if (defaultPane == null) {
defaultPane = new JScrollPane();
defaultPane.setViewportView(getDefaultOutput());
defaultPane.setName("defaultPane");
defaultPane.setHorizontalScrollBarPolicy(
javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
}
return defaultPane;
}
private ZapTextArea getDefaultOutput() {
if (defaultOutput == null) {
defaultOutput = new ZapTextArea();
defaultOutput.setEditable(false);
defaultOutput.setLineWrap(true);
defaultOutput.setName("");
defaultOutput.append(Constant.messages.getString("alerts.label.defaultMessage"));
}
return defaultOutput;
}
public void append(final String msg) {
if (EventQueue.isDispatchThread()) {
getDefaultOutput().append(msg);
return;
}
try {
EventQueue.invokeAndWait(
new Runnable() {
@Override
public void run() {
getDefaultOutput().append(msg);
}
});
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
public void clear() {
getDefaultOutput().setText("");
}
public void setParamNames(String[] paramNames) {
for (String param : paramNames) {
paramListModel.addElement(param);
}
}
public Alert getAlert() {
if (!editable && originalAlert != null) {
Alert alert = originalAlert.newInstance();
alert.setAlertId(originalAlert.getAlertId());
alert.setName((String) alertEditName.getSelectedItem());
alert.setParam((String) alertEditParam.getSelectedItem());
alert.setRiskConfidence(
alertEditRisk.getSelectedIndex(), alertEditConfidence.getSelectedIndex());
alert.setDescription(alertDescription.getText());
alert.setOtherInfo(alertOtherInfo.getText());
alert.setSolution(alertSolution.getText());
alert.setReference(alertReference.getText());
alert.setEvidence(alertEvidence.getText());
alert.setCweId(alertEditCweId.getValue());
alert.setWascId(alertEditWascId.getValue());
alert.setHistoryRef(historyRef);
alert.setTags(getAlertTags());
return alert;
}
Alert alert =
new Alert(
-1,
alertEditRisk.getSelectedIndex(),
alertEditConfidence.getSelectedIndex(),
(String) alertEditName.getSelectedItem());
alert.setHistoryRef(historyRef);
if (originalAlert != null) {
alert.setAlertId(originalAlert.getAlertId());
alert.setSource(originalAlert.getSource());
}
String uri = null;
HttpMessage msg = null;
if (httpMessage != null) {
uri = httpMessage.getRequestHeader().getURI().toString();
msg = httpMessage;
} else if (historyRef != null) {
try {
uri = historyRef.getURI().toString();
msg = historyRef.getHttpMessage();
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
} else if (originalAlert != null) {
uri = originalAlert.getUri();
msg = originalAlert.getMessage();
}
alert.setDetail(
alertDescription.getText(),
uri,
(String) alertEditParam.getSelectedItem(),
alertEditAttack.getText(),
alertOtherInfo.getText(),
alertSolution.getText(),
alertReference.getText(),
alertEditEvidence.getText(),
alertEditCweId.getValue(),
alertEditWascId.getValue(),
msg);
alert.setTags(getAlertTags());
return alert;
}
public Alert getOriginalAlert() {
return this.originalAlert;
}
public void setHistoryRef(HistoryReference historyRef) {
this.historyRef = historyRef;
this.httpMessage = null;
try {
if (historyRef != null) {
HttpMessage msg = historyRef.getHttpMessage();
setParamNames(msg.getParamNames());
this.alertUrl.setText(msg.getRequestHeader().getURI().toString());
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
/**
* Sets the {@code HttpMessage} that will be set to the new alert.
*
* @param httpMessage the {@code HttpMessage} that will be set to the new alert
*/
public void setHttpMessage(HttpMessage httpMessage) {
this.httpMessage = httpMessage;
setParamNames(httpMessage.getParamNames());
this.alertUrl.setText(httpMessage.getRequestHeader().getURI().toString());
this.historyRef = null;
}
public boolean isEditable() {
return editable;
}
private List<Vulnerability> getAllVulnerabilities() {
if (vulnerabilities == null) {
vulnerabilities = Vulnerabilities.getAllVulnerabilities();
}
return vulnerabilities;
}
private Vulnerability getVulnerability(String alert) {
if (alert == null) {
return null;
}
List<Vulnerability> vulns = this.getAllVulnerabilities();
for (Vulnerability v : vulns) {
if (alert.equals(v.getAlert())) {
return v;
}
}
return null;
}
private List<String> getAllVulnerabilityNames() {
List<Vulnerability> vulns = this.getAllVulnerabilities();
List<String> names = new ArrayList<>(vulns.size());
for (Vulnerability v : vulns) {
names.add(v.getAlert());
}
Collections.sort(names);
return names;
}
private void setAlertDescription(String description) {
setTextDiscardEditsAndInitCaretPosition(alertDescription, description);
}
private void setAlertOtherInfo(String otherInfo) {
setTextDiscardEditsAndInitCaretPosition(alertOtherInfo, otherInfo);
}
private void setAlertSolution(String solution) {
setTextDiscardEditsAndInitCaretPosition(alertSolution, solution);
}
private void setAlertReference(String reference) {
setTextDiscardEditsAndInitCaretPosition(alertReference, reference);
}
private static void setTextDiscardEditsAndInitCaretPosition(ZapTextArea textArea, String text) {
textArea.setText(text);
textArea.discardAllEdits();
textArea.setCaretPosition(0);
}
private void setAlertTags(Map<String, String> tags) {
alertTagsTableModel.setTags(tags);
}
private Map<String, String> getAlertTags() {
return alertTagsTableModel.getTags();
}
private JLabel getAttackLabel() {
if (attackLabel == null) {
attackLabel = new JLabel(Constant.messages.getString("alert.label.attack"));
}
return attackLabel;
}
private JLabel getCweidLabel() {
if (cweidLabel == null) {
cweidLabel = new JLabel(Constant.messages.getString("alert.label.cweid"));
}
return cweidLabel;
}
private JLabel getEvidenceLabel() {
if (evidenceLabel == null) {
evidenceLabel = new JLabel(Constant.messages.getString("alert.label.evidence"));
}
return evidenceLabel;
}
private JLabel getParameterLabel() {
if (otherLabel == null) {
otherLabel = new JLabel(Constant.messages.getString("alert.label.parameter"));
}
return otherLabel;
}
private JLabel getConfidenceLabel() {
if (confidenceLabel == null) {
confidenceLabel = new JLabel(Constant.messages.getString("alert.label.confidence"));
}
return confidenceLabel;
}
private JLabel getRiskLabel() {
if (riskLabel == null) {
riskLabel = new JLabel(Constant.messages.getString("alert.label.risk"));
}
return riskLabel;
}
private JLabel getSourceLabel() {
if (sourceLabel == null) {
sourceLabel = new JLabel(Constant.messages.getString("alert.label.source"));
}
return sourceLabel;
}
private JLabel getUrlLabel() {
if (urlLabel == null) {
urlLabel = new JLabel(Constant.messages.getString("alert.label.url"));
}
return urlLabel;
}
private JLabel getWascidLabel() {
if (wascidLabel == null) {
wascidLabel = new JLabel(Constant.messages.getString("alert.label.wascid"));
}
return wascidLabel;
}
private void showAddAlertTagDialogue() {
if (dialogAddAlertTag == null) {
dialogAddAlertTag =
new DialogAddAlertTag(
Control.getSingleton()
.getExtensionLoader()
.getExtension(ExtensionAlert.class)
.getDialogAlertAdd(),
alertTagsTableModel);
dialogAddAlertTag.pack();
}
dialogAddAlertTag.clearFields();
dialogAddAlertTag.setVisible(true);
}
private void showModifyAlertTagDialogue() {
if (dialogModifyAlertTag == null) {
dialogModifyAlertTag =
new DialogModifyAlertTag(
Control.getSingleton()
.getExtensionLoader()
.getExtension(ExtensionAlert.class)
.getDialogAlertAdd(),
alertTagsTableModel);
dialogModifyAlertTag.pack();
}
int selectedRow = alertTagsTable.getSelectedRow();
if (selectedRow != -1) {
dialogModifyAlertTag.setTagRowInAlertTagsTable(selectedRow);
dialogModifyAlertTag.setVisible(true);
}
}
}
|
package com.defano.jmonet.tools.builder;
import com.defano.jmonet.tools.brushes.ShapeStroke;
import java.awt.*;
/**
* A utility for building strokes, both {@link BasicStroke} and {@link ShapeStroke}.
*/
public class StrokeBuilder {
private StrokeBuilder() {}
/**
* Builds a stroke in which a shape is "stamped" along each point of the stroked path. Note that the stamped shape
* (the pen) is not automatically rotated to match the angular perpendicular to the path (as occurs with a
* {@link #withBasicStroke()}.
*
* @return The builder.
*/
public static ShapeStrokeBuilder withShape() {
return new ShapeStrokeBuilder();
}
/**
* Builds a basic stroke.
*
* @return The builder
*/
public static BasicStrokeBuilder withBasicStroke() {
return new BasicStrokeBuilder();
}
}
|
/**
* Copyright 2010 - 2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 jetbrains.exodus.env;
import jetbrains.exodus.ArrayByteIterable;
import jetbrains.exodus.ByteIterable;
import jetbrains.exodus.core.dataStructures.ConcurrentLongObjectCache;
import jetbrains.exodus.core.dataStructures.SoftConcurrentLongObjectCache;
import jetbrains.exodus.core.execution.SharedTimer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Caches Store.get() results retrieved from immutable trees.
* For each key and tree address (KeyEntry), value is immutable, so lock-free caching is ok.
*/
class StoreGetCache {
private static final int SINGLE_CHUNK_GENERATIONS = 4;
private final SoftConcurrentLongObjectCache<ValueEntry> cache;
private final int minTreeSize;
private final int maxValueSize;
StoreGetCache(final int cacheSize, final int minTreeSize, final int maxValueSize) {
cache = new SoftConcurrentLongObjectCache<ValueEntry>(cacheSize) {
@NotNull
@Override
protected ConcurrentLongObjectCache<ValueEntry> newChunk(int chunkSize) {
return new ConcurrentLongObjectCache<ValueEntry>(chunkSize, SINGLE_CHUNK_GENERATIONS) {
@Nullable
@Override
protected SharedTimer.ExpirablePeriodicTask getCacheAdjuster() {
return null;
}
};
}
};
this.minTreeSize = minTreeSize;
this.maxValueSize = maxValueSize;
}
int getMinTreeSize() {
return minTreeSize;
}
int getMaxValueSize() {
return maxValueSize;
}
void close() {
cache.close();
}
@Nullable
ByteIterable tryKey(final long treeRootAddress, @NotNull final ByteIterable key) {
final int keyHashCode = key.hashCode();
final ValueEntry ve = cache.tryKey(treeRootAddress ^ keyHashCode);
return ve == null || ve.treeRootAddress != treeRootAddress ||
ve.keyHashCode != keyHashCode || !ve.key.equals(key) ? null : ve.value;
}
void cacheObject(final long treeRootAddress, @NotNull final ByteIterable key, @NotNull final ArrayByteIterable value) {
final ArrayByteIterable keyCopy = key instanceof ArrayByteIterable ? (ArrayByteIterable) key : new ArrayByteIterable(key);
final int keyHashCode = keyCopy.hashCode();
cache.cacheObject(treeRootAddress ^ keyHashCode, new ValueEntry(treeRootAddress, keyHashCode, keyCopy, value));
}
float hitRate() {
return cache.hitRate();
}
private static class ValueEntry {
private final long treeRootAddress;
private final int keyHashCode;
@NotNull
private final ArrayByteIterable key;
@NotNull
private final ArrayByteIterable value;
ValueEntry(final long treeRootAddress,
final int keyHashCode,
@NotNull final ArrayByteIterable key,
@NotNull final ArrayByteIterable value) {
this.treeRootAddress = treeRootAddress;
this.keyHashCode = keyHashCode;
this.key = key;
this.value = value;
}
}
}
|
import java.io.*;
import javax.servlet.*;
public class MyServlet implements Servlet
{
ServletConfig config = null;
public void init(ServletConfig config)
{
this.config = config;
System.out.println("servlet is initialized");
}
public void service(ServletRequest req, ServletResponse res)
throws IOException, ServletException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.print("<html><body>");
out.print("<b>hello simple servlet</b>");
out.print("</body></html>");
}
public void destroy()
{
System.out.println("servlet is destroyed");
}
public ServletConfig getServletConfig()
{
return config;
}
public String getServletInfo()
{
return "copyright 2007-1010";
}
}
|
/*
* Copyright 2006-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mybatis.generator.config;
public class JavaTypeResolverConfiguration extends TypedPropertyHolder {
public JavaTypeResolverConfiguration() {
super();
}
}
|
/**
* Copyright (c) 2016 Lemur Consulting Ltd.
* <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 uk.co.flax.biosolr.elasticsearch;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.StreamsUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.Collection;
import java.util.Collections;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures;
import static org.hamcrest.Matchers.equalTo;
/**
* Created by mlp on 12/01/16.
* @author mlp
*/
public class OLSOntologyUpdateIntegrationTests extends ESIntegTestCase {
public static final String TEST_IRI = "http://www.ebi.ac.uk/efo/EFO_0000001";
public static final String TEST_CHILD_IRI = "http://www.ifomis.org/bfo/1.1/snap#MaterialEntity";
private final static String INDEX_NAME = "test";
private final static String DOC_TYPE_NAME = "test";
private static final String ANNOTATION_FIELD = "annotation";
private final static String MAPPING_FILE = "/mapping/ols-ontology-mapping.json";
@Override
protected Collection<Class<? extends Plugin>> nodePlugins() {
return pluginList(OntologyUpdatePlugin.class);
}
@Before
public void createEmptyIndex() throws Exception {
logger.info("creating index [{}]", INDEX_NAME);
createIndex(INDEX_NAME);
ensureGreen();
}
@After
public void disposeHelpers() {
OntologyHelperBuilder.getInstance().close();
}
@Test
public void indexAnnotatedDocuments() throws Exception {
String mapping = StreamsUtils.copyToStringFromClasspath(MAPPING_FILE);
client().admin().indices().putMapping(new PutMappingRequest(INDEX_NAME).type(DOC_TYPE_NAME).source(mapping))
.actionGet();
// Add the root record
XContentBuilder source = XContentFactory.jsonBuilder().startObject().field(ANNOTATION_FIELD, TEST_IRI).field("name", randomRealisticUnicodeOfLength(12)).endObject();
IndexResponse response = index(INDEX_NAME, DOC_TYPE_NAME, source);
String id = response.getId();
flush();
QueryBuilder query = QueryBuilders.idsQuery(DOC_TYPE_NAME).addIds(id);
SearchResponse searchResponse = client().prepareSearch(INDEX_NAME)
.setTypes(DOC_TYPE_NAME)
.setFetchSource(true)
.addFields("annotation.uri", "annotation.label")
.setQuery(query).get();
assertNoFailures(searchResponse);
SearchHits hits = searchResponse.getHits();
assertThat(hits.getTotalHits(), equalTo(1L));
}
}
|
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.security.support;
import org.elasticsearch.cli.Terminal;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermissions;
/**
* A utility for cli tools to capture file attributes
* before writing files, and to warn if the permissions/group/owner changes.
*/
public class FileAttributesChecker {
// the paths to check
private final Path[] paths;
// captured attributes for each path
private final PosixFileAttributes[] attributes;
/** Create a checker for the given paths, which will warn to the given terminal if changes are made. */
public FileAttributesChecker(Path... paths) throws IOException {
this.paths = paths;
this.attributes = new PosixFileAttributes[paths.length];
for (int i = 0; i < paths.length; ++i) {
if (Files.exists(paths[i]) == false) continue; // missing file, so changes later don't matter
PosixFileAttributeView view = Files.getFileAttributeView(paths[i], PosixFileAttributeView.class);
if (view == null) continue; // not posix
this.attributes[i] = view.readAttributes();
}
}
/** Check if attributes of the paths have changed, warning to the given terminal if they have. */
public void check(Terminal terminal) throws IOException {
for (int i = 0; i < paths.length; ++i) {
if (attributes[i] == null) {
// we couldn't get attributes in setup, so we can't check them now
continue;
}
PosixFileAttributeView view = Files.getFileAttributeView(paths[i], PosixFileAttributeView.class);
PosixFileAttributes newAttributes = view.readAttributes();
PosixFileAttributes oldAttributes = attributes[i];
if (oldAttributes.permissions().equals(newAttributes.permissions()) == false) {
terminal.errorPrintln(
Terminal.Verbosity.SILENT,
"WARNING: The file permissions of ["
+ paths[i]
+ "] have changed "
+ "from ["
+ PosixFilePermissions.toString(oldAttributes.permissions())
+ "] "
+ "to ["
+ PosixFilePermissions.toString(newAttributes.permissions())
+ "]"
);
terminal.errorPrintln(
Terminal.Verbosity.SILENT,
"Please ensure that the user account running Elasticsearch has read access to this file!"
);
}
if (oldAttributes.owner().getName().equals(newAttributes.owner().getName()) == false) {
terminal.errorPrintln(
Terminal.Verbosity.SILENT,
"WARNING: Owner of file ["
+ paths[i]
+ "] "
+ "used to be ["
+ oldAttributes.owner().getName()
+ "], "
+ "but now is ["
+ newAttributes.owner().getName()
+ "]"
);
}
if (oldAttributes.group().getName().equals(newAttributes.group().getName()) == false) {
terminal.errorPrintln(
Terminal.Verbosity.SILENT,
"WARNING: Group of file ["
+ paths[i]
+ "] "
+ "used to be ["
+ oldAttributes.group().getName()
+ "], "
+ "but now is ["
+ newAttributes.group().getName()
+ "]"
);
}
}
}
}
|
/**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package fi.weasel.commitment2050.commitmentanalysis.service.base;
import aQute.bnd.annotation.ProviderType;
import com.liferay.portal.kernel.bean.BeanReference;
import com.liferay.portal.kernel.dao.db.DB;
import com.liferay.portal.kernel.dao.db.DBManagerUtil;
import com.liferay.portal.kernel.dao.jdbc.SqlUpdate;
import com.liferay.portal.kernel.dao.jdbc.SqlUpdateFactoryUtil;
import com.liferay.portal.kernel.dao.orm.DynamicQuery;
import com.liferay.portal.kernel.dao.orm.DynamicQueryFactoryUtil;
import com.liferay.portal.kernel.dao.orm.Projection;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.model.PersistedModel;
import com.liferay.portal.kernel.module.framework.service.IdentifiableOSGiService;
import com.liferay.portal.kernel.search.Indexable;
import com.liferay.portal.kernel.search.IndexableType;
import com.liferay.portal.kernel.service.BaseLocalServiceImpl;
import com.liferay.portal.kernel.service.PersistedModelLocalServiceRegistry;
import com.liferay.portal.kernel.service.persistence.ClassNamePersistence;
import com.liferay.portal.kernel.service.persistence.UserPersistence;
import com.liferay.portal.kernel.util.OrderByComparator;
import com.liferay.portal.kernel.util.PortalUtil;
import com.liferay.portal.spring.extender.service.ServiceReference;
import fi.weasel.commitment2050.commitmentanalysis.model.Meter;
import fi.weasel.commitment2050.commitmentanalysis.service.MeterLocalService;
import fi.weasel.commitment2050.commitmentanalysis.service.persistence.CommitmentAnalysisResultFinder;
import fi.weasel.commitment2050.commitmentanalysis.service.persistence.CommitmentAnalysisResultPersistence;
import fi.weasel.commitment2050.commitmentanalysis.service.persistence.CommitmentFinder;
import fi.weasel.commitment2050.commitmentanalysis.service.persistence.CommitmentPersistence;
import fi.weasel.commitment2050.commitmentanalysis.service.persistence.DoneOperationPersistence;
import fi.weasel.commitment2050.commitmentanalysis.service.persistence.MeterPersistence;
import fi.weasel.commitment2050.commitmentanalysis.service.persistence.OperationPersistence;
import fi.weasel.commitment2050.commitmentanalysis.service.persistence.ReportMeterPersistence;
import fi.weasel.commitment2050.commitmentanalysis.service.persistence.ReportPersistence;
import java.io.Serializable;
import java.util.List;
import javax.sql.DataSource;
/**
* Provides the base implementation for the meter local service.
*
* <p>
* This implementation exists only as a container for the default service methods generated by ServiceBuilder. All custom service methods should be put in {@link fi.weasel.commitment2050.commitmentanalysis.service.impl.MeterLocalServiceImpl}.
* </p>
*
* @author Brian Wing Shun Chan
* @see fi.weasel.commitment2050.commitmentanalysis.service.impl.MeterLocalServiceImpl
* @see fi.weasel.commitment2050.commitmentanalysis.service.MeterLocalServiceUtil
* @generated
*/
@ProviderType
public abstract class MeterLocalServiceBaseImpl extends BaseLocalServiceImpl
implements MeterLocalService, IdentifiableOSGiService {
/*
* NOTE FOR DEVELOPERS:
*
* Never modify or reference this class directly. Always use {@link fi.weasel.commitment2050.commitmentanalysis.service.MeterLocalServiceUtil} to access the meter local service.
*/
/**
* Adds the meter to the database. Also notifies the appropriate model listeners.
*
* @param meter the meter
* @return the meter that was added
*/
@Indexable(type = IndexableType.REINDEX)
@Override
public Meter addMeter(Meter meter) {
meter.setNew(true);
return meterPersistence.update(meter);
}
/**
* Creates a new meter with the primary key. Does not add the meter to the database.
*
* @param id the primary key for the new meter
* @return the new meter
*/
@Override
public Meter createMeter(String id) {
return meterPersistence.create(id);
}
/**
* Deletes the meter with the primary key from the database. Also notifies the appropriate model listeners.
*
* @param id the primary key of the meter
* @return the meter that was removed
* @throws PortalException if a meter with the primary key could not be found
*/
@Indexable(type = IndexableType.DELETE)
@Override
public Meter deleteMeter(String id) throws PortalException {
return meterPersistence.remove(id);
}
/**
* Deletes the meter from the database. Also notifies the appropriate model listeners.
*
* @param meter the meter
* @return the meter that was removed
*/
@Indexable(type = IndexableType.DELETE)
@Override
public Meter deleteMeter(Meter meter) {
return meterPersistence.remove(meter);
}
@Override
public DynamicQuery dynamicQuery() {
Class<?> clazz = getClass();
return DynamicQueryFactoryUtil.forClass(Meter.class,
clazz.getClassLoader());
}
/**
* Performs a dynamic query on the database and returns the matching rows.
*
* @param dynamicQuery the dynamic query
* @return the matching rows
*/
@Override
public <T> List<T> dynamicQuery(DynamicQuery dynamicQuery) {
return meterPersistence.findWithDynamicQuery(dynamicQuery);
}
/**
* Performs a dynamic query on the database and returns a range of the matching rows.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link fi.weasel.commitment2050.commitmentanalysis.model.impl.MeterModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param dynamicQuery the dynamic query
* @param start the lower bound of the range of model instances
* @param end the upper bound of the range of model instances (not inclusive)
* @return the range of matching rows
*/
@Override
public <T> List<T> dynamicQuery(DynamicQuery dynamicQuery, int start,
int end) {
return meterPersistence.findWithDynamicQuery(dynamicQuery, start, end);
}
/**
* Performs a dynamic query on the database and returns an ordered range of the matching rows.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link fi.weasel.commitment2050.commitmentanalysis.model.impl.MeterModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param dynamicQuery the dynamic query
* @param start the lower bound of the range of model instances
* @param end the upper bound of the range of model instances (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @return the ordered range of matching rows
*/
@Override
public <T> List<T> dynamicQuery(DynamicQuery dynamicQuery, int start,
int end, OrderByComparator<T> orderByComparator) {
return meterPersistence.findWithDynamicQuery(dynamicQuery, start, end,
orderByComparator);
}
/**
* Returns the number of rows matching the dynamic query.
*
* @param dynamicQuery the dynamic query
* @return the number of rows matching the dynamic query
*/
@Override
public long dynamicQueryCount(DynamicQuery dynamicQuery) {
return meterPersistence.countWithDynamicQuery(dynamicQuery);
}
/**
* Returns the number of rows matching the dynamic query.
*
* @param dynamicQuery the dynamic query
* @param projection the projection to apply to the query
* @return the number of rows matching the dynamic query
*/
@Override
public long dynamicQueryCount(DynamicQuery dynamicQuery,
Projection projection) {
return meterPersistence.countWithDynamicQuery(dynamicQuery, projection);
}
@Override
public Meter fetchMeter(String id) {
return meterPersistence.fetchByPrimaryKey(id);
}
/**
* Returns the meter with the primary key.
*
* @param id the primary key of the meter
* @return the meter
* @throws PortalException if a meter with the primary key could not be found
*/
@Override
public Meter getMeter(String id) throws PortalException {
return meterPersistence.findByPrimaryKey(id);
}
/**
* @throws PortalException
*/
@Override
public PersistedModel deletePersistedModel(PersistedModel persistedModel)
throws PortalException {
return meterLocalService.deleteMeter((Meter)persistedModel);
}
@Override
public PersistedModel getPersistedModel(Serializable primaryKeyObj)
throws PortalException {
return meterPersistence.findByPrimaryKey(primaryKeyObj);
}
/**
* Returns a range of all the meters.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link fi.weasel.commitment2050.commitmentanalysis.model.impl.MeterModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param start the lower bound of the range of meters
* @param end the upper bound of the range of meters (not inclusive)
* @return the range of meters
*/
@Override
public List<Meter> getMeters(int start, int end) {
return meterPersistence.findAll(start, end);
}
/**
* Returns the number of meters.
*
* @return the number of meters
*/
@Override
public int getMetersCount() {
return meterPersistence.countAll();
}
/**
* Updates the meter in the database or adds it if it does not yet exist. Also notifies the appropriate model listeners.
*
* @param meter the meter
* @return the meter that was updated
*/
@Indexable(type = IndexableType.REINDEX)
@Override
public Meter updateMeter(Meter meter) {
return meterPersistence.update(meter);
}
/**
* Returns the commitment local service.
*
* @return the commitment local service
*/
public fi.weasel.commitment2050.commitmentanalysis.service.CommitmentLocalService getCommitmentLocalService() {
return commitmentLocalService;
}
/**
* Sets the commitment local service.
*
* @param commitmentLocalService the commitment local service
*/
public void setCommitmentLocalService(
fi.weasel.commitment2050.commitmentanalysis.service.CommitmentLocalService commitmentLocalService) {
this.commitmentLocalService = commitmentLocalService;
}
/**
* Returns the commitment persistence.
*
* @return the commitment persistence
*/
public CommitmentPersistence getCommitmentPersistence() {
return commitmentPersistence;
}
/**
* Sets the commitment persistence.
*
* @param commitmentPersistence the commitment persistence
*/
public void setCommitmentPersistence(
CommitmentPersistence commitmentPersistence) {
this.commitmentPersistence = commitmentPersistence;
}
/**
* Returns the commitment finder.
*
* @return the commitment finder
*/
public CommitmentFinder getCommitmentFinder() {
return commitmentFinder;
}
/**
* Sets the commitment finder.
*
* @param commitmentFinder the commitment finder
*/
public void setCommitmentFinder(CommitmentFinder commitmentFinder) {
this.commitmentFinder = commitmentFinder;
}
/**
* Returns the commitment analysis result local service.
*
* @return the commitment analysis result local service
*/
public fi.weasel.commitment2050.commitmentanalysis.service.CommitmentAnalysisResultLocalService getCommitmentAnalysisResultLocalService() {
return commitmentAnalysisResultLocalService;
}
/**
* Sets the commitment analysis result local service.
*
* @param commitmentAnalysisResultLocalService the commitment analysis result local service
*/
public void setCommitmentAnalysisResultLocalService(
fi.weasel.commitment2050.commitmentanalysis.service.CommitmentAnalysisResultLocalService commitmentAnalysisResultLocalService) {
this.commitmentAnalysisResultLocalService = commitmentAnalysisResultLocalService;
}
/**
* Returns the commitment analysis result persistence.
*
* @return the commitment analysis result persistence
*/
public CommitmentAnalysisResultPersistence getCommitmentAnalysisResultPersistence() {
return commitmentAnalysisResultPersistence;
}
/**
* Sets the commitment analysis result persistence.
*
* @param commitmentAnalysisResultPersistence the commitment analysis result persistence
*/
public void setCommitmentAnalysisResultPersistence(
CommitmentAnalysisResultPersistence commitmentAnalysisResultPersistence) {
this.commitmentAnalysisResultPersistence = commitmentAnalysisResultPersistence;
}
/**
* Returns the commitment analysis result finder.
*
* @return the commitment analysis result finder
*/
public CommitmentAnalysisResultFinder getCommitmentAnalysisResultFinder() {
return commitmentAnalysisResultFinder;
}
/**
* Sets the commitment analysis result finder.
*
* @param commitmentAnalysisResultFinder the commitment analysis result finder
*/
public void setCommitmentAnalysisResultFinder(
CommitmentAnalysisResultFinder commitmentAnalysisResultFinder) {
this.commitmentAnalysisResultFinder = commitmentAnalysisResultFinder;
}
/**
* Returns the done operation local service.
*
* @return the done operation local service
*/
public fi.weasel.commitment2050.commitmentanalysis.service.DoneOperationLocalService getDoneOperationLocalService() {
return doneOperationLocalService;
}
/**
* Sets the done operation local service.
*
* @param doneOperationLocalService the done operation local service
*/
public void setDoneOperationLocalService(
fi.weasel.commitment2050.commitmentanalysis.service.DoneOperationLocalService doneOperationLocalService) {
this.doneOperationLocalService = doneOperationLocalService;
}
/**
* Returns the done operation persistence.
*
* @return the done operation persistence
*/
public DoneOperationPersistence getDoneOperationPersistence() {
return doneOperationPersistence;
}
/**
* Sets the done operation persistence.
*
* @param doneOperationPersistence the done operation persistence
*/
public void setDoneOperationPersistence(
DoneOperationPersistence doneOperationPersistence) {
this.doneOperationPersistence = doneOperationPersistence;
}
/**
* Returns the meter local service.
*
* @return the meter local service
*/
public MeterLocalService getMeterLocalService() {
return meterLocalService;
}
/**
* Sets the meter local service.
*
* @param meterLocalService the meter local service
*/
public void setMeterLocalService(MeterLocalService meterLocalService) {
this.meterLocalService = meterLocalService;
}
/**
* Returns the meter persistence.
*
* @return the meter persistence
*/
public MeterPersistence getMeterPersistence() {
return meterPersistence;
}
/**
* Sets the meter persistence.
*
* @param meterPersistence the meter persistence
*/
public void setMeterPersistence(MeterPersistence meterPersistence) {
this.meterPersistence = meterPersistence;
}
/**
* Returns the operation local service.
*
* @return the operation local service
*/
public fi.weasel.commitment2050.commitmentanalysis.service.OperationLocalService getOperationLocalService() {
return operationLocalService;
}
/**
* Sets the operation local service.
*
* @param operationLocalService the operation local service
*/
public void setOperationLocalService(
fi.weasel.commitment2050.commitmentanalysis.service.OperationLocalService operationLocalService) {
this.operationLocalService = operationLocalService;
}
/**
* Returns the operation persistence.
*
* @return the operation persistence
*/
public OperationPersistence getOperationPersistence() {
return operationPersistence;
}
/**
* Sets the operation persistence.
*
* @param operationPersistence the operation persistence
*/
public void setOperationPersistence(
OperationPersistence operationPersistence) {
this.operationPersistence = operationPersistence;
}
/**
* Returns the report local service.
*
* @return the report local service
*/
public fi.weasel.commitment2050.commitmentanalysis.service.ReportLocalService getReportLocalService() {
return reportLocalService;
}
/**
* Sets the report local service.
*
* @param reportLocalService the report local service
*/
public void setReportLocalService(
fi.weasel.commitment2050.commitmentanalysis.service.ReportLocalService reportLocalService) {
this.reportLocalService = reportLocalService;
}
/**
* Returns the report persistence.
*
* @return the report persistence
*/
public ReportPersistence getReportPersistence() {
return reportPersistence;
}
/**
* Sets the report persistence.
*
* @param reportPersistence the report persistence
*/
public void setReportPersistence(ReportPersistence reportPersistence) {
this.reportPersistence = reportPersistence;
}
/**
* Returns the report meter local service.
*
* @return the report meter local service
*/
public fi.weasel.commitment2050.commitmentanalysis.service.ReportMeterLocalService getReportMeterLocalService() {
return reportMeterLocalService;
}
/**
* Sets the report meter local service.
*
* @param reportMeterLocalService the report meter local service
*/
public void setReportMeterLocalService(
fi.weasel.commitment2050.commitmentanalysis.service.ReportMeterLocalService reportMeterLocalService) {
this.reportMeterLocalService = reportMeterLocalService;
}
/**
* Returns the report meter persistence.
*
* @return the report meter persistence
*/
public ReportMeterPersistence getReportMeterPersistence() {
return reportMeterPersistence;
}
/**
* Sets the report meter persistence.
*
* @param reportMeterPersistence the report meter persistence
*/
public void setReportMeterPersistence(
ReportMeterPersistence reportMeterPersistence) {
this.reportMeterPersistence = reportMeterPersistence;
}
/**
* Returns the counter local service.
*
* @return the counter local service
*/
public com.liferay.counter.kernel.service.CounterLocalService getCounterLocalService() {
return counterLocalService;
}
/**
* Sets the counter local service.
*
* @param counterLocalService the counter local service
*/
public void setCounterLocalService(
com.liferay.counter.kernel.service.CounterLocalService counterLocalService) {
this.counterLocalService = counterLocalService;
}
/**
* Returns the class name local service.
*
* @return the class name local service
*/
public com.liferay.portal.kernel.service.ClassNameLocalService getClassNameLocalService() {
return classNameLocalService;
}
/**
* Sets the class name local service.
*
* @param classNameLocalService the class name local service
*/
public void setClassNameLocalService(
com.liferay.portal.kernel.service.ClassNameLocalService classNameLocalService) {
this.classNameLocalService = classNameLocalService;
}
/**
* Returns the class name persistence.
*
* @return the class name persistence
*/
public ClassNamePersistence getClassNamePersistence() {
return classNamePersistence;
}
/**
* Sets the class name persistence.
*
* @param classNamePersistence the class name persistence
*/
public void setClassNamePersistence(
ClassNamePersistence classNamePersistence) {
this.classNamePersistence = classNamePersistence;
}
/**
* Returns the resource local service.
*
* @return the resource local service
*/
public com.liferay.portal.kernel.service.ResourceLocalService getResourceLocalService() {
return resourceLocalService;
}
/**
* Sets the resource local service.
*
* @param resourceLocalService the resource local service
*/
public void setResourceLocalService(
com.liferay.portal.kernel.service.ResourceLocalService resourceLocalService) {
this.resourceLocalService = resourceLocalService;
}
/**
* Returns the user local service.
*
* @return the user local service
*/
public com.liferay.portal.kernel.service.UserLocalService getUserLocalService() {
return userLocalService;
}
/**
* Sets the user local service.
*
* @param userLocalService the user local service
*/
public void setUserLocalService(
com.liferay.portal.kernel.service.UserLocalService userLocalService) {
this.userLocalService = userLocalService;
}
/**
* Returns the user persistence.
*
* @return the user persistence
*/
public UserPersistence getUserPersistence() {
return userPersistence;
}
/**
* Sets the user persistence.
*
* @param userPersistence the user persistence
*/
public void setUserPersistence(UserPersistence userPersistence) {
this.userPersistence = userPersistence;
}
public void afterPropertiesSet() {
persistedModelLocalServiceRegistry.register("fi.weasel.commitment2050.commitmentanalysis.model.Meter",
meterLocalService);
}
public void destroy() {
persistedModelLocalServiceRegistry.unregister(
"fi.weasel.commitment2050.commitmentanalysis.model.Meter");
}
/**
* Returns the OSGi service identifier.
*
* @return the OSGi service identifier
*/
@Override
public String getOSGiServiceIdentifier() {
return MeterLocalService.class.getName();
}
protected Class<?> getModelClass() {
return Meter.class;
}
protected String getModelClassName() {
return Meter.class.getName();
}
/**
* Performs a SQL query.
*
* @param sql the sql query
*/
protected void runSQL(String sql) {
try {
DataSource dataSource = meterPersistence.getDataSource();
DB db = DBManagerUtil.getDB();
sql = db.buildSQL(sql);
sql = PortalUtil.transformSQL(sql);
SqlUpdate sqlUpdate = SqlUpdateFactoryUtil.getSqlUpdate(dataSource,
sql);
sqlUpdate.update();
}
catch (Exception e) {
throw new SystemException(e);
}
}
@BeanReference(type = fi.weasel.commitment2050.commitmentanalysis.service.CommitmentLocalService.class)
protected fi.weasel.commitment2050.commitmentanalysis.service.CommitmentLocalService commitmentLocalService;
@BeanReference(type = CommitmentPersistence.class)
protected CommitmentPersistence commitmentPersistence;
@BeanReference(type = CommitmentFinder.class)
protected CommitmentFinder commitmentFinder;
@BeanReference(type = fi.weasel.commitment2050.commitmentanalysis.service.CommitmentAnalysisResultLocalService.class)
protected fi.weasel.commitment2050.commitmentanalysis.service.CommitmentAnalysisResultLocalService commitmentAnalysisResultLocalService;
@BeanReference(type = CommitmentAnalysisResultPersistence.class)
protected CommitmentAnalysisResultPersistence commitmentAnalysisResultPersistence;
@BeanReference(type = CommitmentAnalysisResultFinder.class)
protected CommitmentAnalysisResultFinder commitmentAnalysisResultFinder;
@BeanReference(type = fi.weasel.commitment2050.commitmentanalysis.service.DoneOperationLocalService.class)
protected fi.weasel.commitment2050.commitmentanalysis.service.DoneOperationLocalService doneOperationLocalService;
@BeanReference(type = DoneOperationPersistence.class)
protected DoneOperationPersistence doneOperationPersistence;
@BeanReference(type = MeterLocalService.class)
protected MeterLocalService meterLocalService;
@BeanReference(type = MeterPersistence.class)
protected MeterPersistence meterPersistence;
@BeanReference(type = fi.weasel.commitment2050.commitmentanalysis.service.OperationLocalService.class)
protected fi.weasel.commitment2050.commitmentanalysis.service.OperationLocalService operationLocalService;
@BeanReference(type = OperationPersistence.class)
protected OperationPersistence operationPersistence;
@BeanReference(type = fi.weasel.commitment2050.commitmentanalysis.service.ReportLocalService.class)
protected fi.weasel.commitment2050.commitmentanalysis.service.ReportLocalService reportLocalService;
@BeanReference(type = ReportPersistence.class)
protected ReportPersistence reportPersistence;
@BeanReference(type = fi.weasel.commitment2050.commitmentanalysis.service.ReportMeterLocalService.class)
protected fi.weasel.commitment2050.commitmentanalysis.service.ReportMeterLocalService reportMeterLocalService;
@BeanReference(type = ReportMeterPersistence.class)
protected ReportMeterPersistence reportMeterPersistence;
@ServiceReference(type = com.liferay.counter.kernel.service.CounterLocalService.class)
protected com.liferay.counter.kernel.service.CounterLocalService counterLocalService;
@ServiceReference(type = com.liferay.portal.kernel.service.ClassNameLocalService.class)
protected com.liferay.portal.kernel.service.ClassNameLocalService classNameLocalService;
@ServiceReference(type = ClassNamePersistence.class)
protected ClassNamePersistence classNamePersistence;
@ServiceReference(type = com.liferay.portal.kernel.service.ResourceLocalService.class)
protected com.liferay.portal.kernel.service.ResourceLocalService resourceLocalService;
@ServiceReference(type = com.liferay.portal.kernel.service.UserLocalService.class)
protected com.liferay.portal.kernel.service.UserLocalService userLocalService;
@ServiceReference(type = UserPersistence.class)
protected UserPersistence userPersistence;
@ServiceReference(type = PersistedModelLocalServiceRegistry.class)
protected PersistedModelLocalServiceRegistry persistedModelLocalServiceRegistry;
}
|
/**
* DeleteBaseRates.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.axis.v201502;
/**
* The action used to delete {@link BaseRate} objects.
*/
public class DeleteBaseRates extends com.google.api.ads.dfp.axis.v201502.BaseRateAction implements java.io.Serializable {
public DeleteBaseRates() {
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof DeleteBaseRates)) return false;
DeleteBaseRates other = (DeleteBaseRates) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = super.equals(obj);
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = super.hashCode();
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(DeleteBaseRates.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201502", "DeleteBaseRates"));
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
|
package gui.toolbarButton;
import controller.interfaces.ProductListTabItem;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon;
import gui.components.ToolBarComponent;
import gui.events.ProcessListEvent;
import javafx.application.Platform;
public class ProcessListToolbarButton extends ToolbarButton {
public ProcessListToolbarButton(ToolBarComponent toolBar) {
super(toolBar);
setId("processList");
}
@Override
public void init() {
setOnAction(new ProcessListEvent(toolBar.getMainController()));
setIcon(FontAwesomeIcon.ROCKET,"1.5em");
setTooltip("Process current list");
}
@Override
public void update(Object args) {
Platform.runLater(()-> setDisable(!(args instanceof ProductListTabItem)));
}
}
|
package cn.shopee.beetl.tags.exception;
public class BeetlTagException extends RuntimeException {
public BeetlTagException() {
}
public BeetlTagException(String msg) {
super(msg);
}
public BeetlTagException(String message, Throwable rootCause) {
super(message, rootCause);
}
public BeetlTagException(Throwable rootCause) {
super(rootCause);
}
}
|
// $ANTLR 3.5.2 org/openmodelica/corba/parser/OMCorbaDefinitions.g 2019-09-01 18:17:57
package org.openmodelica.corba.parser;
import org.antlr.runtime.*;
import java.util.Stack;
import java.util.List;
import java.util.ArrayList;
@SuppressWarnings("all")
public class OMCorbaDefinitionsLexer extends Lexer {
public static final int EOF=-1;
public static final int T__8=8;
public static final int T__9=9;
public static final int T__10=10;
public static final int T__11=11;
public static final int T__12=12;
public static final int T__13=13;
public static final int T__14=14;
public static final int T__15=15;
public static final int T__16=16;
public static final int T__17=17;
public static final int T__18=18;
public static final int T__19=19;
public static final int T__20=20;
public static final int T__21=21;
public static final int T__22=22;
public static final int T__23=23;
public static final int T__24=24;
public static final int T__25=25;
public static final int T__26=26;
public static final int T__27=27;
public static final int T__28=28;
public static final int T__29=29;
public static final int T__30=30;
public static final int T__31=31;
public static final int ID=4;
public static final int INT=5;
public static final int QID=6;
public static final int WS=7;
// delegates
// delegators
public Lexer[] getDelegates() {
return new Lexer[] {};
}
public OMCorbaDefinitionsLexer() {}
public OMCorbaDefinitionsLexer(CharStream input) {
this(input, new RecognizerSharedState());
}
public OMCorbaDefinitionsLexer(CharStream input, RecognizerSharedState state) {
super(input,state);
}
@Override public String getGrammarFileName() { return "org/openmodelica/corba/parser/OMCorbaDefinitions.g"; }
// $ANTLR start "T__8"
public final void mT__8() throws RecognitionException {
try {
int _type = T__8;
int _channel = DEFAULT_TOKEN_CHANNEL;
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:9:6: ( '(' )
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:9:8: '('
{
match('(');
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "T__8"
// $ANTLR start "T__9"
public final void mT__9() throws RecognitionException {
try {
int _type = T__9;
int _channel = DEFAULT_TOKEN_CHANNEL;
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:10:6: ( ')' )
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:10:8: ')'
{
match(')');
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "T__9"
// $ANTLR start "T__10"
public final void mT__10() throws RecognitionException {
try {
int _type = T__10;
int _channel = DEFAULT_TOKEN_CHANNEL;
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:11:7: ( ',' )
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:11:9: ','
{
match(',');
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "T__10"
// $ANTLR start "T__11"
public final void mT__11() throws RecognitionException {
try {
int _type = T__11;
int _channel = DEFAULT_TOKEN_CHANNEL;
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:12:7: ( '<' )
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:12:9: '<'
{
match('<');
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "T__11"
// $ANTLR start "T__12"
public final void mT__12() throws RecognitionException {
try {
int _type = T__12;
int _channel = DEFAULT_TOKEN_CHANNEL;
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:13:7: ( '>' )
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:13:9: '>'
{
match('>');
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "T__12"
// $ANTLR start "T__13"
public final void mT__13() throws RecognitionException {
try {
int _type = T__13;
int _channel = DEFAULT_TOKEN_CHANNEL;
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:14:7: ( 'Boolean' )
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:14:9: 'Boolean'
{
match("Boolean");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "T__13"
// $ANTLR start "T__14"
public final void mT__14() throws RecognitionException {
try {
int _type = T__14;
int _channel = DEFAULT_TOKEN_CHANNEL;
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:15:7: ( 'Integer' )
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:15:9: 'Integer'
{
match("Integer");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "T__14"
// $ANTLR start "T__15"
public final void mT__15() throws RecognitionException {
try {
int _type = T__15;
int _channel = DEFAULT_TOKEN_CHANNEL;
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:16:7: ( 'Option' )
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:16:9: 'Option'
{
match("Option");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "T__15"
// $ANTLR start "T__16"
public final void mT__16() throws RecognitionException {
try {
int _type = T__16;
int _channel = DEFAULT_TOKEN_CHANNEL;
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:17:7: ( 'Real' )
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:17:9: 'Real'
{
match("Real");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "T__16"
// $ANTLR start "T__17"
public final void mT__17() throws RecognitionException {
try {
int _type = T__17;
int _channel = DEFAULT_TOKEN_CHANNEL;
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:18:7: ( 'String' )
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:18:9: 'String'
{
match("String");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "T__17"
// $ANTLR start "T__18"
public final void mT__18() throws RecognitionException {
try {
int _type = T__18;
int _channel = DEFAULT_TOKEN_CHANNEL;
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:19:7: ( '[' )
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:19:9: '['
{
match('[');
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "T__18"
// $ANTLR start "T__19"
public final void mT__19() throws RecognitionException {
try {
int _type = T__19;
int _channel = DEFAULT_TOKEN_CHANNEL;
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:20:7: ( 'extends' )
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:20:9: 'extends'
{
match("extends");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "T__19"
// $ANTLR start "T__20"
public final void mT__20() throws RecognitionException {
try {
int _type = T__20;
int _channel = DEFAULT_TOKEN_CHANNEL;
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:21:7: ( 'function' )
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:21:9: 'function'
{
match("function");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "T__20"
// $ANTLR start "T__21"
public final void mT__21() throws RecognitionException {
try {
int _type = T__21;
int _channel = DEFAULT_TOKEN_CHANNEL;
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:22:7: ( 'input' )
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:22:9: 'input'
{
match("input");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "T__21"
// $ANTLR start "T__22"
public final void mT__22() throws RecognitionException {
try {
int _type = T__22;
int _channel = DEFAULT_TOKEN_CHANNEL;
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:23:7: ( 'list' )
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:23:9: 'list'
{
match("list");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "T__22"
// $ANTLR start "T__23"
public final void mT__23() throws RecognitionException {
try {
int _type = T__23;
int _channel = DEFAULT_TOKEN_CHANNEL;
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:24:7: ( 'metarecord' )
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:24:9: 'metarecord'
{
match("metarecord");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "T__23"
// $ANTLR start "T__24"
public final void mT__24() throws RecognitionException {
try {
int _type = T__24;
int _channel = DEFAULT_TOKEN_CHANNEL;
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:25:7: ( 'output' )
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:25:9: 'output'
{
match("output");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "T__24"
// $ANTLR start "T__25"
public final void mT__25() throws RecognitionException {
try {
int _type = T__25;
int _channel = DEFAULT_TOKEN_CHANNEL;
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:26:7: ( 'package' )
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:26:9: 'package'
{
match("package");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "T__25"
// $ANTLR start "T__26"
public final void mT__26() throws RecognitionException {
try {
int _type = T__26;
int _channel = DEFAULT_TOKEN_CHANNEL;
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:27:7: ( 'partial' )
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:27:9: 'partial'
{
match("partial");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "T__26"
// $ANTLR start "T__27"
public final void mT__27() throws RecognitionException {
try {
int _type = T__27;
int _channel = DEFAULT_TOKEN_CHANNEL;
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:28:7: ( 'record' )
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:28:9: 'record'
{
match("record");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "T__27"
// $ANTLR start "T__28"
public final void mT__28() throws RecognitionException {
try {
int _type = T__28;
int _channel = DEFAULT_TOKEN_CHANNEL;
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:29:7: ( 'replaceable' )
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:29:9: 'replaceable'
{
match("replaceable");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "T__28"
// $ANTLR start "T__29"
public final void mT__29() throws RecognitionException {
try {
int _type = T__29;
int _channel = DEFAULT_TOKEN_CHANNEL;
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:30:7: ( 'tuple' )
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:30:9: 'tuple'
{
match("tuple");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "T__29"
// $ANTLR start "T__30"
public final void mT__30() throws RecognitionException {
try {
int _type = T__30;
int _channel = DEFAULT_TOKEN_CHANNEL;
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:31:7: ( 'type' )
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:31:9: 'type'
{
match("type");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "T__30"
// $ANTLR start "T__31"
public final void mT__31() throws RecognitionException {
try {
int _type = T__31;
int _channel = DEFAULT_TOKEN_CHANNEL;
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:32:7: ( 'uniontype' )
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:32:9: 'uniontype'
{
match("uniontype");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "T__31"
// $ANTLR start "QID"
public final void mQID() throws RecognitionException {
try {
int _type = QID;
int _channel = DEFAULT_TOKEN_CHANNEL;
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:75:5: ( ( ID '.' )+ ID )
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:75:7: ( ID '.' )+ ID
{
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:75:7: ( ID '.' )+
int cnt1=0;
loop1:
while (true) {
int alt1=2;
alt1 = dfa1.predict(input);
switch (alt1) {
case 1 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:75:8: ID '.'
{
mID();
match('.');
}
break;
default :
if ( cnt1 >= 1 ) break loop1;
EarlyExitException eee = new EarlyExitException(1, input);
throw eee;
}
cnt1++;
}
mID();
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "QID"
// $ANTLR start "ID"
public final void mID() throws RecognitionException {
try {
int _type = ID;
int _channel = DEFAULT_TOKEN_CHANNEL;
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:76:4: ( ( '_' | 'a' .. 'z' | 'A' .. 'Z' ) ( '_' | 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' )* | '\\'' (~ ( '\\\\' | '\\'' ) | '\\\\\\'' | '\\\\\"' | '\\\\?' | '\\\\\\\\' | '\\\\a' | '\\\\b' | '\\\\f' | '\\\\n' | '\\\\r' | '\\\\t' | '\\\\v' )* '\\'' )
int alt4=2;
int LA4_0 = input.LA(1);
if ( ((LA4_0 >= 'A' && LA4_0 <= 'Z')||LA4_0=='_'||(LA4_0 >= 'a' && LA4_0 <= 'z')) ) {
alt4=1;
}
else if ( (LA4_0=='\'') ) {
alt4=2;
}
else {
NoViableAltException nvae =
new NoViableAltException("", 4, 0, input);
throw nvae;
}
switch (alt4) {
case 1 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:76:6: ( '_' | 'a' .. 'z' | 'A' .. 'Z' ) ( '_' | 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' )*
{
if ( (input.LA(1) >= 'A' && input.LA(1) <= 'Z')||input.LA(1)=='_'||(input.LA(1) >= 'a' && input.LA(1) <= 'z') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:76:29: ( '_' | 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' )*
loop2:
while (true) {
int alt2=2;
int LA2_0 = input.LA(1);
if ( ((LA2_0 >= '0' && LA2_0 <= '9')||(LA2_0 >= 'A' && LA2_0 <= 'Z')||LA2_0=='_'||(LA2_0 >= 'a' && LA2_0 <= 'z')) ) {
alt2=1;
}
switch (alt2) {
case 1 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:
{
if ( (input.LA(1) >= '0' && input.LA(1) <= '9')||(input.LA(1) >= 'A' && input.LA(1) <= 'Z')||input.LA(1)=='_'||(input.LA(1) >= 'a' && input.LA(1) <= 'z') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
}
break;
default :
break loop2;
}
}
}
break;
case 2 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:77:6: '\\'' (~ ( '\\\\' | '\\'' ) | '\\\\\\'' | '\\\\\"' | '\\\\?' | '\\\\\\\\' | '\\\\a' | '\\\\b' | '\\\\f' | '\\\\n' | '\\\\r' | '\\\\t' | '\\\\v' )* '\\''
{
match('\'');
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:77:10: (~ ( '\\\\' | '\\'' ) | '\\\\\\'' | '\\\\\"' | '\\\\?' | '\\\\\\\\' | '\\\\a' | '\\\\b' | '\\\\f' | '\\\\n' | '\\\\r' | '\\\\t' | '\\\\v' )*
loop3:
while (true) {
int alt3=13;
int LA3_0 = input.LA(1);
if ( ((LA3_0 >= '\u0000' && LA3_0 <= '&')||(LA3_0 >= '(' && LA3_0 <= '[')||(LA3_0 >= ']' && LA3_0 <= '\uFFFF')) ) {
alt3=1;
}
else if ( (LA3_0=='\\') ) {
switch ( input.LA(2) ) {
case '\'':
{
alt3=2;
}
break;
case '\"':
{
alt3=3;
}
break;
case '?':
{
alt3=4;
}
break;
case '\\':
{
alt3=5;
}
break;
case 'a':
{
alt3=6;
}
break;
case 'b':
{
alt3=7;
}
break;
case 'f':
{
alt3=8;
}
break;
case 'n':
{
alt3=9;
}
break;
case 'r':
{
alt3=10;
}
break;
case 't':
{
alt3=11;
}
break;
case 'v':
{
alt3=12;
}
break;
}
}
switch (alt3) {
case 1 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:77:11: ~ ( '\\\\' | '\\'' )
{
if ( (input.LA(1) >= '\u0000' && input.LA(1) <= '&')||(input.LA(1) >= '(' && input.LA(1) <= '[')||(input.LA(1) >= ']' && input.LA(1) <= '\uFFFF') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
}
break;
case 2 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:77:24: '\\\\\\''
{
match("\\'");
}
break;
case 3 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:77:34: '\\\\\"'
{
match("\\\"");
}
break;
case 4 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:77:41: '\\\\?'
{
match("\\?");
}
break;
case 5 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:77:49: '\\\\\\\\'
{
match("\\\\");
}
break;
case 6 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:77:58: '\\\\a'
{
match("\\a");
}
break;
case 7 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:77:66: '\\\\b'
{
match("\\b");
}
break;
case 8 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:77:74: '\\\\f'
{
match("\\f");
}
break;
case 9 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:77:82: '\\\\n'
{
match("\\n");
}
break;
case 10 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:77:90: '\\\\r'
{
match("\\r");
}
break;
case 11 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:77:98: '\\\\t'
{
match("\\t");
}
break;
case 12 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:77:106: '\\\\v'
{
match("\\v");
}
break;
default :
break loop3;
}
}
match('\'');
}
break;
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "ID"
// $ANTLR start "INT"
public final void mINT() throws RecognitionException {
try {
int _type = INT;
int _channel = DEFAULT_TOKEN_CHANNEL;
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:78:5: ( ( '-' )? ( '0' .. '9' )+ )
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:78:8: ( '-' )? ( '0' .. '9' )+
{
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:78:8: ( '-' )?
int alt5=2;
int LA5_0 = input.LA(1);
if ( (LA5_0=='-') ) {
alt5=1;
}
switch (alt5) {
case 1 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:78:8: '-'
{
match('-');
}
break;
}
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:78:12: ( '0' .. '9' )+
int cnt6=0;
loop6:
while (true) {
int alt6=2;
int LA6_0 = input.LA(1);
if ( ((LA6_0 >= '0' && LA6_0 <= '9')) ) {
alt6=1;
}
switch (alt6) {
case 1 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:
{
if ( (input.LA(1) >= '0' && input.LA(1) <= '9') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
}
break;
default :
if ( cnt6 >= 1 ) break loop6;
EarlyExitException eee = new EarlyExitException(6, input);
throw eee;
}
cnt6++;
}
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "INT"
// $ANTLR start "WS"
public final void mWS() throws RecognitionException {
try {
int _type = WS;
int _channel = DEFAULT_TOKEN_CHANNEL;
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:79:5: ( ( '\\r' | '\\n' | ' ' | '\\t' )+ )
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:79:9: ( '\\r' | '\\n' | ' ' | '\\t' )+
{
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:79:9: ( '\\r' | '\\n' | ' ' | '\\t' )+
int cnt7=0;
loop7:
while (true) {
int alt7=2;
int LA7_0 = input.LA(1);
if ( ((LA7_0 >= '\t' && LA7_0 <= '\n')||LA7_0=='\r'||LA7_0==' ') ) {
alt7=1;
}
switch (alt7) {
case 1 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:
{
if ( (input.LA(1) >= '\t' && input.LA(1) <= '\n')||input.LA(1)=='\r'||input.LA(1)==' ' ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
}
break;
default :
if ( cnt7 >= 1 ) break loop7;
EarlyExitException eee = new EarlyExitException(7, input);
throw eee;
}
cnt7++;
}
skip();
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "WS"
@Override
public void mTokens() throws RecognitionException {
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:1:8: ( T__8 | T__9 | T__10 | T__11 | T__12 | T__13 | T__14 | T__15 | T__16 | T__17 | T__18 | T__19 | T__20 | T__21 | T__22 | T__23 | T__24 | T__25 | T__26 | T__27 | T__28 | T__29 | T__30 | T__31 | QID | ID | INT | WS )
int alt8=28;
alt8 = dfa8.predict(input);
switch (alt8) {
case 1 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:1:10: T__8
{
mT__8();
}
break;
case 2 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:1:15: T__9
{
mT__9();
}
break;
case 3 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:1:20: T__10
{
mT__10();
}
break;
case 4 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:1:26: T__11
{
mT__11();
}
break;
case 5 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:1:32: T__12
{
mT__12();
}
break;
case 6 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:1:38: T__13
{
mT__13();
}
break;
case 7 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:1:44: T__14
{
mT__14();
}
break;
case 8 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:1:50: T__15
{
mT__15();
}
break;
case 9 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:1:56: T__16
{
mT__16();
}
break;
case 10 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:1:62: T__17
{
mT__17();
}
break;
case 11 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:1:68: T__18
{
mT__18();
}
break;
case 12 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:1:74: T__19
{
mT__19();
}
break;
case 13 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:1:80: T__20
{
mT__20();
}
break;
case 14 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:1:86: T__21
{
mT__21();
}
break;
case 15 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:1:92: T__22
{
mT__22();
}
break;
case 16 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:1:98: T__23
{
mT__23();
}
break;
case 17 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:1:104: T__24
{
mT__24();
}
break;
case 18 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:1:110: T__25
{
mT__25();
}
break;
case 19 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:1:116: T__26
{
mT__26();
}
break;
case 20 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:1:122: T__27
{
mT__27();
}
break;
case 21 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:1:128: T__28
{
mT__28();
}
break;
case 22 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:1:134: T__29
{
mT__29();
}
break;
case 23 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:1:140: T__30
{
mT__30();
}
break;
case 24 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:1:146: T__31
{
mT__31();
}
break;
case 25 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:1:152: QID
{
mQID();
}
break;
case 26 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:1:156: ID
{
mID();
}
break;
case 27 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:1:159: INT
{
mINT();
}
break;
case 28 :
// org/openmodelica/corba/parser/OMCorbaDefinitions.g:1:163: WS
{
mWS();
}
break;
}
}
protected DFA1 dfa1 = new DFA1(this);
protected DFA8 dfa8 = new DFA8(this);
static final String DFA1_eotS =
"\1\uffff\1\4\1\uffff\1\4\4\uffff\1\4\13\uffff";
static final String DFA1_eofS =
"\24\uffff";
static final String DFA1_minS =
"\1\47\1\56\1\0\1\56\2\uffff\1\0\1\42\1\56\13\0";
static final String DFA1_maxS =
"\2\172\1\uffff\1\172\2\uffff\1\uffff\1\166\1\56\13\uffff";
static final String DFA1_acceptS =
"\4\uffff\1\2\1\1\16\uffff";
static final String DFA1_specialS =
"\2\uffff\1\2\3\uffff\1\10\2\uffff\1\13\1\0\1\3\1\5\1\7\1\12\1\14\1\1\1"+
"\4\1\6\1\11}>";
static final String[] DFA1_transitionS = {
"\1\2\31\uffff\32\1\4\uffff\1\1\1\uffff\32\1",
"\1\5\1\uffff\12\3\7\uffff\32\3\4\uffff\1\3\1\uffff\32\3",
"\47\6\1\10\64\6\1\7\uffa3\6",
"\1\5\1\uffff\12\3\7\uffff\32\3\4\uffff\1\3\1\uffff\32\3",
"",
"",
"\47\6\1\10\64\6\1\7\uffa3\6",
"\1\12\4\uffff\1\11\27\uffff\1\13\34\uffff\1\14\4\uffff\1\15\1\16\3\uffff"+
"\1\17\7\uffff\1\20\3\uffff\1\21\1\uffff\1\22\1\uffff\1\23",
"\1\5",
"\47\6\1\10\64\6\1\7\uffa3\6",
"\47\6\1\10\64\6\1\7\uffa3\6",
"\47\6\1\10\64\6\1\7\uffa3\6",
"\47\6\1\10\64\6\1\7\uffa3\6",
"\47\6\1\10\64\6\1\7\uffa3\6",
"\47\6\1\10\64\6\1\7\uffa3\6",
"\47\6\1\10\64\6\1\7\uffa3\6",
"\47\6\1\10\64\6\1\7\uffa3\6",
"\47\6\1\10\64\6\1\7\uffa3\6",
"\47\6\1\10\64\6\1\7\uffa3\6",
"\47\6\1\10\64\6\1\7\uffa3\6"
};
static final short[] DFA1_eot = DFA.unpackEncodedString(DFA1_eotS);
static final short[] DFA1_eof = DFA.unpackEncodedString(DFA1_eofS);
static final char[] DFA1_min = DFA.unpackEncodedStringToUnsignedChars(DFA1_minS);
static final char[] DFA1_max = DFA.unpackEncodedStringToUnsignedChars(DFA1_maxS);
static final short[] DFA1_accept = DFA.unpackEncodedString(DFA1_acceptS);
static final short[] DFA1_special = DFA.unpackEncodedString(DFA1_specialS);
static final short[][] DFA1_transition;
static {
int numStates = DFA1_transitionS.length;
DFA1_transition = new short[numStates][];
for (int i=0; i<numStates; i++) {
DFA1_transition[i] = DFA.unpackEncodedString(DFA1_transitionS[i]);
}
}
protected class DFA1 extends DFA {
public DFA1(BaseRecognizer recognizer) {
this.recognizer = recognizer;
this.decisionNumber = 1;
this.eot = DFA1_eot;
this.eof = DFA1_eof;
this.min = DFA1_min;
this.max = DFA1_max;
this.accept = DFA1_accept;
this.special = DFA1_special;
this.transition = DFA1_transition;
}
@Override
public String getDescription() {
return "()+ loopback of 75:7: ( ID '.' )+";
}
@Override
public int specialStateTransition(int s, IntStream _input) throws NoViableAltException {
IntStream input = _input;
int _s = s;
switch ( s ) {
case 0 :
int LA1_10 = input.LA(1);
s = -1;
if ( (LA1_10=='\'') ) {s = 8;}
else if ( ((LA1_10 >= '\u0000' && LA1_10 <= '&')||(LA1_10 >= '(' && LA1_10 <= '[')||(LA1_10 >= ']' && LA1_10 <= '\uFFFF')) ) {s = 6;}
else if ( (LA1_10=='\\') ) {s = 7;}
if ( s>=0 ) return s;
break;
case 1 :
int LA1_16 = input.LA(1);
s = -1;
if ( (LA1_16=='\'') ) {s = 8;}
else if ( ((LA1_16 >= '\u0000' && LA1_16 <= '&')||(LA1_16 >= '(' && LA1_16 <= '[')||(LA1_16 >= ']' && LA1_16 <= '\uFFFF')) ) {s = 6;}
else if ( (LA1_16=='\\') ) {s = 7;}
if ( s>=0 ) return s;
break;
case 2 :
int LA1_2 = input.LA(1);
s = -1;
if ( ((LA1_2 >= '\u0000' && LA1_2 <= '&')||(LA1_2 >= '(' && LA1_2 <= '[')||(LA1_2 >= ']' && LA1_2 <= '\uFFFF')) ) {s = 6;}
else if ( (LA1_2=='\\') ) {s = 7;}
else if ( (LA1_2=='\'') ) {s = 8;}
if ( s>=0 ) return s;
break;
case 3 :
int LA1_11 = input.LA(1);
s = -1;
if ( (LA1_11=='\'') ) {s = 8;}
else if ( ((LA1_11 >= '\u0000' && LA1_11 <= '&')||(LA1_11 >= '(' && LA1_11 <= '[')||(LA1_11 >= ']' && LA1_11 <= '\uFFFF')) ) {s = 6;}
else if ( (LA1_11=='\\') ) {s = 7;}
if ( s>=0 ) return s;
break;
case 4 :
int LA1_17 = input.LA(1);
s = -1;
if ( (LA1_17=='\'') ) {s = 8;}
else if ( ((LA1_17 >= '\u0000' && LA1_17 <= '&')||(LA1_17 >= '(' && LA1_17 <= '[')||(LA1_17 >= ']' && LA1_17 <= '\uFFFF')) ) {s = 6;}
else if ( (LA1_17=='\\') ) {s = 7;}
if ( s>=0 ) return s;
break;
case 5 :
int LA1_12 = input.LA(1);
s = -1;
if ( (LA1_12=='\'') ) {s = 8;}
else if ( ((LA1_12 >= '\u0000' && LA1_12 <= '&')||(LA1_12 >= '(' && LA1_12 <= '[')||(LA1_12 >= ']' && LA1_12 <= '\uFFFF')) ) {s = 6;}
else if ( (LA1_12=='\\') ) {s = 7;}
if ( s>=0 ) return s;
break;
case 6 :
int LA1_18 = input.LA(1);
s = -1;
if ( (LA1_18=='\'') ) {s = 8;}
else if ( ((LA1_18 >= '\u0000' && LA1_18 <= '&')||(LA1_18 >= '(' && LA1_18 <= '[')||(LA1_18 >= ']' && LA1_18 <= '\uFFFF')) ) {s = 6;}
else if ( (LA1_18=='\\') ) {s = 7;}
if ( s>=0 ) return s;
break;
case 7 :
int LA1_13 = input.LA(1);
s = -1;
if ( (LA1_13=='\'') ) {s = 8;}
else if ( ((LA1_13 >= '\u0000' && LA1_13 <= '&')||(LA1_13 >= '(' && LA1_13 <= '[')||(LA1_13 >= ']' && LA1_13 <= '\uFFFF')) ) {s = 6;}
else if ( (LA1_13=='\\') ) {s = 7;}
if ( s>=0 ) return s;
break;
case 8 :
int LA1_6 = input.LA(1);
s = -1;
if ( (LA1_6=='\'') ) {s = 8;}
else if ( ((LA1_6 >= '\u0000' && LA1_6 <= '&')||(LA1_6 >= '(' && LA1_6 <= '[')||(LA1_6 >= ']' && LA1_6 <= '\uFFFF')) ) {s = 6;}
else if ( (LA1_6=='\\') ) {s = 7;}
if ( s>=0 ) return s;
break;
case 9 :
int LA1_19 = input.LA(1);
s = -1;
if ( (LA1_19=='\'') ) {s = 8;}
else if ( ((LA1_19 >= '\u0000' && LA1_19 <= '&')||(LA1_19 >= '(' && LA1_19 <= '[')||(LA1_19 >= ']' && LA1_19 <= '\uFFFF')) ) {s = 6;}
else if ( (LA1_19=='\\') ) {s = 7;}
if ( s>=0 ) return s;
break;
case 10 :
int LA1_14 = input.LA(1);
s = -1;
if ( (LA1_14=='\'') ) {s = 8;}
else if ( ((LA1_14 >= '\u0000' && LA1_14 <= '&')||(LA1_14 >= '(' && LA1_14 <= '[')||(LA1_14 >= ']' && LA1_14 <= '\uFFFF')) ) {s = 6;}
else if ( (LA1_14=='\\') ) {s = 7;}
if ( s>=0 ) return s;
break;
case 11 :
int LA1_9 = input.LA(1);
s = -1;
if ( (LA1_9=='\'') ) {s = 8;}
else if ( ((LA1_9 >= '\u0000' && LA1_9 <= '&')||(LA1_9 >= '(' && LA1_9 <= '[')||(LA1_9 >= ']' && LA1_9 <= '\uFFFF')) ) {s = 6;}
else if ( (LA1_9=='\\') ) {s = 7;}
if ( s>=0 ) return s;
break;
case 12 :
int LA1_15 = input.LA(1);
s = -1;
if ( (LA1_15=='\'') ) {s = 8;}
else if ( ((LA1_15 >= '\u0000' && LA1_15 <= '&')||(LA1_15 >= '(' && LA1_15 <= '[')||(LA1_15 >= ']' && LA1_15 <= '\uFFFF')) ) {s = 6;}
else if ( (LA1_15=='\\') ) {s = 7;}
if ( s>=0 ) return s;
break;
}
NoViableAltException nvae =
new NoViableAltException(getDescription(), 1, _s, input);
error(nvae);
throw nvae;
}
}
static final String DFA8_eotS =
"\6\uffff\5\34\1\uffff\13\34\3\uffff\2\34\2\uffff\17\34\2\uffff\23\34\13"+
"\uffff\3\34\1\142\4\34\1\147\7\34\1\157\4\34\1\uffff\3\34\1\167\1\uffff"+
"\6\34\1\176\1\uffff\3\34\1\u0082\1\u0083\2\34\1\uffff\1\34\1\u0087\2\34"+
"\1\u008a\1\34\1\uffff\1\34\1\u008d\1\u008e\2\uffff\1\u008f\2\34\1\uffff"+
"\1\u0092\1\u0093\1\uffff\2\34\3\uffff\1\u0096\1\34\2\uffff\2\34\1\uffff"+
"\2\34\1\u009c\1\u009d\1\34\2\uffff\1\u009f\1\uffff";
static final String DFA8_eofS =
"\u00a0\uffff";
static final String DFA8_minS =
"\1\11\5\uffff\5\56\1\uffff\13\56\1\0\2\uffff\2\56\2\uffff\17\56\1\0\1"+
"\42\23\56\13\0\25\56\1\uffff\4\56\1\uffff\7\56\1\uffff\7\56\1\uffff\6"+
"\56\1\uffff\3\56\2\uffff\3\56\1\uffff\2\56\1\uffff\2\56\3\uffff\2\56\2"+
"\uffff\2\56\1\uffff\5\56\2\uffff\1\56\1\uffff";
static final String DFA8_maxS =
"\1\172\5\uffff\5\172\1\uffff\13\172\1\uffff\2\uffff\2\172\2\uffff\17\172"+
"\1\uffff\1\166\1\56\22\172\13\uffff\25\172\1\uffff\4\172\1\uffff\7\172"+
"\1\uffff\7\172\1\uffff\6\172\1\uffff\3\172\2\uffff\3\172\1\uffff\2\172"+
"\1\uffff\2\172\3\uffff\2\172\2\uffff\2\172\1\uffff\5\172\2\uffff\1\172"+
"\1\uffff";
static final String DFA8_acceptS =
"\1\uffff\1\1\1\2\1\3\1\4\1\5\5\uffff\1\13\14\uffff\1\33\1\34\2\uffff\1"+
"\32\1\31\104\uffff\1\11\4\uffff\1\17\7\uffff\1\27\7\uffff\1\16\6\uffff"+
"\1\26\3\uffff\1\10\1\12\3\uffff\1\21\2\uffff\1\24\2\uffff\1\6\1\7\1\14"+
"\2\uffff\1\22\1\23\2\uffff\1\15\5\uffff\1\30\1\20\1\uffff\1\25";
static final String DFA8_specialS =
"\27\uffff\1\2\25\uffff\1\3\24\uffff\1\4\1\5\1\6\1\7\1\10\1\11\1\12\1\13"+
"\1\14\1\0\1\1\123\uffff}>";
static final String[] DFA8_transitionS = {
"\2\31\2\uffff\1\31\22\uffff\1\31\6\uffff\1\27\1\1\1\2\2\uffff\1\3\1\30"+
"\2\uffff\12\30\2\uffff\1\4\1\uffff\1\5\2\uffff\1\26\1\6\6\26\1\7\5\26"+
"\1\10\2\26\1\11\1\12\7\26\1\13\3\uffff\1\26\1\uffff\4\26\1\14\1\15\2"+
"\26\1\16\2\26\1\17\1\20\1\26\1\21\1\22\1\26\1\23\1\26\1\24\1\25\5\26",
"",
"",
"",
"",
"",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\16\33\1\32\13"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\15\33\1\36\14"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\17\33\1\37\12"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\4\33\1\40\25"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\23\33\1\41\6"+
"\33",
"",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\27\33\1\42\2"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\24\33\1\43\5"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\15\33\1\44\14"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\10\33\1\45\21"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\4\33\1\46\25"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\24\33\1\47\5"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\1\50\31\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\4\33\1\51\25"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\24\33\1\52\3"+
"\33\1\53\1\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\15\33\1\54\14"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33",
"\47\55\1\57\64\55\1\56\uffa3\55",
"",
"",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\16\33\1\60\13"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33",
"",
"",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\23\33\1\61\6"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\23\33\1\62\6"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\1\63\31\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\21\33\1\64\10"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\23\33\1\65\6"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\15\33\1\66\14"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\17\33\1\67\12"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\22\33\1\70\7"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\23\33\1\71\6"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\23\33\1\72\6"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\2\33\1\73\16"+
"\33\1\74\10\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\2\33\1\75\14"+
"\33\1\76\12\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\17\33\1\77\12"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\17\33\1\100\12"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\10\33\1\101\21"+
"\33",
"\47\55\1\57\64\55\1\56\uffa3\55",
"\1\103\4\uffff\1\102\27\uffff\1\104\34\uffff\1\105\4\uffff\1\106\1\107"+
"\3\uffff\1\110\7\uffff\1\111\3\uffff\1\112\1\uffff\1\113\1\uffff\1\114",
"\1\35",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\13\33\1\115\16"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\4\33\1\116\25"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\10\33\1\117\21"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\13\33\1\120\16"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\10\33\1\121\21"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\4\33\1\122\25"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\2\33\1\123\27"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\24\33\1\124\5"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\23\33\1\125\6"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\1\126\31\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\17\33\1\127\12"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\12\33\1\130\17"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\23\33\1\131\6"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\16\33\1\132\13"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\13\33\1\133\16"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\13\33\1\134\16"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\4\33\1\135\25"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\16\33\1\136\13"+
"\33",
"\47\55\1\57\64\55\1\56\uffa3\55",
"\47\55\1\57\64\55\1\56\uffa3\55",
"\47\55\1\57\64\55\1\56\uffa3\55",
"\47\55\1\57\64\55\1\56\uffa3\55",
"\47\55\1\57\64\55\1\56\uffa3\55",
"\47\55\1\57\64\55\1\56\uffa3\55",
"\47\55\1\57\64\55\1\56\uffa3\55",
"\47\55\1\57\64\55\1\56\uffa3\55",
"\47\55\1\57\64\55\1\56\uffa3\55",
"\47\55\1\57\64\55\1\56\uffa3\55",
"\47\55\1\57\64\55\1\56\uffa3\55",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\4\33\1\137\25"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\6\33\1\140\23"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\16\33\1\141\13"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\15\33\1\143\14"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\15\33\1\144\14"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\23\33\1\145\6"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\23\33\1\146\6"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\21\33\1\150\10"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\24\33\1\151\5"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\1\152\31\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\10\33\1\153\21"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\21\33\1\154\10"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\1\155\31\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\4\33\1\156\25"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\15\33\1\160\14"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\1\161\31\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\4\33\1\162\25"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\15\33\1\163\14"+
"\33",
"",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\6\33\1\164\23"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\3\33\1\165\26"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\10\33\1\166\21"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33",
"",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\4\33\1\170\25"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\23\33\1\171\6"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\6\33\1\172\23"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\1\173\31\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\3\33\1\174\26"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\2\33\1\175\27"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33",
"",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\23\33\1\177\6"+
"\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\15\33\1\u0080"+
"\14\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\21\33\1\u0081"+
"\10\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\22\33\1\u0084"+
"\7\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\16\33\1\u0085"+
"\13\33",
"",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\2\33\1\u0086"+
"\27\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\4\33\1\u0088"+
"\25\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\13\33\1\u0089"+
"\16\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\4\33\1\u008b"+
"\25\33",
"",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\30\33\1\u008c"+
"\1\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33",
"",
"",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\15\33\1\u0090"+
"\14\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\16\33\1\u0091"+
"\13\33",
"",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33",
"",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\1\u0094\31\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\17\33\1\u0095"+
"\12\33",
"",
"",
"",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\21\33\1\u0097"+
"\10\33",
"",
"",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\1\33\1\u0098"+
"\30\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\4\33\1\u0099"+
"\25\33",
"",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\3\33\1\u009a"+
"\26\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\13\33\1\u009b"+
"\16\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\4\33\1\u009e"+
"\25\33",
"",
"",
"\1\35\1\uffff\12\33\7\uffff\32\33\4\uffff\1\33\1\uffff\32\33",
""
};
static final short[] DFA8_eot = DFA.unpackEncodedString(DFA8_eotS);
static final short[] DFA8_eof = DFA.unpackEncodedString(DFA8_eofS);
static final char[] DFA8_min = DFA.unpackEncodedStringToUnsignedChars(DFA8_minS);
static final char[] DFA8_max = DFA.unpackEncodedStringToUnsignedChars(DFA8_maxS);
static final short[] DFA8_accept = DFA.unpackEncodedString(DFA8_acceptS);
static final short[] DFA8_special = DFA.unpackEncodedString(DFA8_specialS);
static final short[][] DFA8_transition;
static {
int numStates = DFA8_transitionS.length;
DFA8_transition = new short[numStates][];
for (int i=0; i<numStates; i++) {
DFA8_transition[i] = DFA.unpackEncodedString(DFA8_transitionS[i]);
}
}
protected class DFA8 extends DFA {
public DFA8(BaseRecognizer recognizer) {
this.recognizer = recognizer;
this.decisionNumber = 8;
this.eot = DFA8_eot;
this.eof = DFA8_eof;
this.min = DFA8_min;
this.max = DFA8_max;
this.accept = DFA8_accept;
this.special = DFA8_special;
this.transition = DFA8_transition;
}
@Override
public String getDescription() {
return "1:1: Tokens : ( T__8 | T__9 | T__10 | T__11 | T__12 | T__13 | T__14 | T__15 | T__16 | T__17 | T__18 | T__19 | T__20 | T__21 | T__22 | T__23 | T__24 | T__25 | T__26 | T__27 | T__28 | T__29 | T__30 | T__31 | QID | ID | INT | WS );";
}
@Override
public int specialStateTransition(int s, IntStream _input) throws NoViableAltException {
IntStream input = _input;
int _s = s;
switch ( s ) {
case 0 :
int LA8_75 = input.LA(1);
s = -1;
if ( (LA8_75=='\'') ) {s = 47;}
else if ( ((LA8_75 >= '\u0000' && LA8_75 <= '&')||(LA8_75 >= '(' && LA8_75 <= '[')||(LA8_75 >= ']' && LA8_75 <= '\uFFFF')) ) {s = 45;}
else if ( (LA8_75=='\\') ) {s = 46;}
if ( s>=0 ) return s;
break;
case 1 :
int LA8_76 = input.LA(1);
s = -1;
if ( (LA8_76=='\'') ) {s = 47;}
else if ( ((LA8_76 >= '\u0000' && LA8_76 <= '&')||(LA8_76 >= '(' && LA8_76 <= '[')||(LA8_76 >= ']' && LA8_76 <= '\uFFFF')) ) {s = 45;}
else if ( (LA8_76=='\\') ) {s = 46;}
if ( s>=0 ) return s;
break;
case 2 :
int LA8_23 = input.LA(1);
s = -1;
if ( ((LA8_23 >= '\u0000' && LA8_23 <= '&')||(LA8_23 >= '(' && LA8_23 <= '[')||(LA8_23 >= ']' && LA8_23 <= '\uFFFF')) ) {s = 45;}
else if ( (LA8_23=='\\') ) {s = 46;}
else if ( (LA8_23=='\'') ) {s = 47;}
if ( s>=0 ) return s;
break;
case 3 :
int LA8_45 = input.LA(1);
s = -1;
if ( (LA8_45=='\'') ) {s = 47;}
else if ( ((LA8_45 >= '\u0000' && LA8_45 <= '&')||(LA8_45 >= '(' && LA8_45 <= '[')||(LA8_45 >= ']' && LA8_45 <= '\uFFFF')) ) {s = 45;}
else if ( (LA8_45=='\\') ) {s = 46;}
if ( s>=0 ) return s;
break;
case 4 :
int LA8_66 = input.LA(1);
s = -1;
if ( (LA8_66=='\'') ) {s = 47;}
else if ( ((LA8_66 >= '\u0000' && LA8_66 <= '&')||(LA8_66 >= '(' && LA8_66 <= '[')||(LA8_66 >= ']' && LA8_66 <= '\uFFFF')) ) {s = 45;}
else if ( (LA8_66=='\\') ) {s = 46;}
if ( s>=0 ) return s;
break;
case 5 :
int LA8_67 = input.LA(1);
s = -1;
if ( (LA8_67=='\'') ) {s = 47;}
else if ( ((LA8_67 >= '\u0000' && LA8_67 <= '&')||(LA8_67 >= '(' && LA8_67 <= '[')||(LA8_67 >= ']' && LA8_67 <= '\uFFFF')) ) {s = 45;}
else if ( (LA8_67=='\\') ) {s = 46;}
if ( s>=0 ) return s;
break;
case 6 :
int LA8_68 = input.LA(1);
s = -1;
if ( (LA8_68=='\'') ) {s = 47;}
else if ( ((LA8_68 >= '\u0000' && LA8_68 <= '&')||(LA8_68 >= '(' && LA8_68 <= '[')||(LA8_68 >= ']' && LA8_68 <= '\uFFFF')) ) {s = 45;}
else if ( (LA8_68=='\\') ) {s = 46;}
if ( s>=0 ) return s;
break;
case 7 :
int LA8_69 = input.LA(1);
s = -1;
if ( (LA8_69=='\'') ) {s = 47;}
else if ( ((LA8_69 >= '\u0000' && LA8_69 <= '&')||(LA8_69 >= '(' && LA8_69 <= '[')||(LA8_69 >= ']' && LA8_69 <= '\uFFFF')) ) {s = 45;}
else if ( (LA8_69=='\\') ) {s = 46;}
if ( s>=0 ) return s;
break;
case 8 :
int LA8_70 = input.LA(1);
s = -1;
if ( (LA8_70=='\'') ) {s = 47;}
else if ( ((LA8_70 >= '\u0000' && LA8_70 <= '&')||(LA8_70 >= '(' && LA8_70 <= '[')||(LA8_70 >= ']' && LA8_70 <= '\uFFFF')) ) {s = 45;}
else if ( (LA8_70=='\\') ) {s = 46;}
if ( s>=0 ) return s;
break;
case 9 :
int LA8_71 = input.LA(1);
s = -1;
if ( (LA8_71=='\'') ) {s = 47;}
else if ( ((LA8_71 >= '\u0000' && LA8_71 <= '&')||(LA8_71 >= '(' && LA8_71 <= '[')||(LA8_71 >= ']' && LA8_71 <= '\uFFFF')) ) {s = 45;}
else if ( (LA8_71=='\\') ) {s = 46;}
if ( s>=0 ) return s;
break;
case 10 :
int LA8_72 = input.LA(1);
s = -1;
if ( (LA8_72=='\'') ) {s = 47;}
else if ( ((LA8_72 >= '\u0000' && LA8_72 <= '&')||(LA8_72 >= '(' && LA8_72 <= '[')||(LA8_72 >= ']' && LA8_72 <= '\uFFFF')) ) {s = 45;}
else if ( (LA8_72=='\\') ) {s = 46;}
if ( s>=0 ) return s;
break;
case 11 :
int LA8_73 = input.LA(1);
s = -1;
if ( (LA8_73=='\'') ) {s = 47;}
else if ( ((LA8_73 >= '\u0000' && LA8_73 <= '&')||(LA8_73 >= '(' && LA8_73 <= '[')||(LA8_73 >= ']' && LA8_73 <= '\uFFFF')) ) {s = 45;}
else if ( (LA8_73=='\\') ) {s = 46;}
if ( s>=0 ) return s;
break;
case 12 :
int LA8_74 = input.LA(1);
s = -1;
if ( (LA8_74=='\'') ) {s = 47;}
else if ( ((LA8_74 >= '\u0000' && LA8_74 <= '&')||(LA8_74 >= '(' && LA8_74 <= '[')||(LA8_74 >= ']' && LA8_74 <= '\uFFFF')) ) {s = 45;}
else if ( (LA8_74=='\\') ) {s = 46;}
if ( s>=0 ) return s;
break;
}
NoViableAltException nvae =
new NoViableAltException(getDescription(), 8, _s, input);
error(nvae);
throw nvae;
}
}
}
|
package pl.alburnus.multitenancy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MultiTenancyTutorialApplication {
public static void main(String[] args) {
SpringApplication.run(MultiTenancyTutorialApplication.class, args);
}
}
|
package com.tui.proof.order.service;
import com.tui.proof.notification.NotificationService;
import com.tui.proof.order.Order;
import com.tui.proof.order.mapping.OrderMapper;
import com.tui.proof.order.repository.OrderRepository;
import com.tui.proof.order.request.OrderCreateRequest;
import com.tui.proof.order.request.OrderUpdateRequest;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import javax.persistence.EntityNotFoundException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class OrderService {
private final OrderMapper orderMapper;
private final OrderRepository orderRepository;
private final NotificationService notificationService;
public List<Order> getAll(Optional<String> searchTerm) {
if (searchTerm.isEmpty()) {
return orderRepository.findAll();
} else {
return orderRepository.searchAll(searchTerm.get());
}
}
public Order create(OrderCreateRequest createRequest) {
Order order = orderMapper.toOrderModel(createRequest);
Order savedOrder = orderRepository.save(order);
notificationService.notifyOfNewOrder(savedOrder);
return savedOrder;
}
public Order update(OrderUpdateRequest orderUpdateRequest) throws OrderNotUpdatableException {
Optional<Order> optionalOrder =
orderRepository.findById(UUID.fromString(orderUpdateRequest.getUuid()));
if (optionalOrder.isPresent()) {
if (isUpdatable(optionalOrder.get())) {
Order updatedOrder =
orderRepository.save(orderMapper.toOrderModel(orderUpdateRequest, optionalOrder.get()));
notificationService.notifyOfUpdatedOrder(updatedOrder);
return updatedOrder;
} else {
throw new OrderNotUpdatableException();
}
} else {
throw new EntityNotFoundException();
}
}
private boolean isUpdatable(Order order) {
return ChronoUnit.MINUTES.between(order.getCreatedDate(), LocalDateTime.now()) < 5;
}
}
|
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package android.support.v14.preference;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.v4.content.res.TypedArrayUtils;
import android.support.v7.preference.PreferenceViewHolder;
import android.support.v7.preference.TwoStatePreference;
import android.util.AttributeSet;
import android.view.View;
import android.view.accessibility.AccessibilityManager;
import android.widget.*;
public class SwitchPreference extends TwoStatePreference
{
private class Listener
implements android.widget.CompoundButton.OnCheckedChangeListener
{
public void onCheckedChanged(CompoundButton compoundbutton, boolean flag)
{
if(!callChangeListener(((Object) (Boolean.valueOf(flag)))))
//* 0 0:aload_0
//* 1 1:getfield #15 <Field SwitchPreference this$0>
//* 2 4:iload_2
//* 3 5:invokestatic #30 <Method Boolean Boolean.valueOf(boolean)>
//* 4 8:invokevirtual #34 <Method boolean SwitchPreference.callChangeListener(Object)>
//* 5 11:ifne 31
{
if(!flag)
//* 6 14:iload_2
//* 7 15:ifne 26
flag = true;
// 8 18:iconst_1
// 9 19:istore_2
else
//* 10 20:aload_1
//* 11 21:iload_2
//* 12 22:invokevirtual #40 <Method void CompoundButton.setChecked(boolean)>
//* 13 25:return
flag = false;
// 14 26:iconst_0
// 15 27:istore_2
compoundbutton.setChecked(flag);
return;
} else
//* 16 28:goto 20
{
setChecked(flag);
// 17 31:aload_0
// 18 32:getfield #15 <Field SwitchPreference this$0>
// 19 35:iload_2
// 20 36:invokevirtual #41 <Method void SwitchPreference.setChecked(boolean)>
return;
// 21 39:return
}
}
final SwitchPreference this$0;
private Listener()
{
this$0 = SwitchPreference.this;
// 0 0:aload_0
// 1 1:aload_1
// 2 2:putfield #15 <Field SwitchPreference this$0>
super();
// 3 5:aload_0
// 4 6:invokespecial #18 <Method void Object()>
// 5 9:return
}
}
public SwitchPreference(Context context)
{
this(context, ((AttributeSet) (null)));
// 0 0:aload_0
// 1 1:aload_1
// 2 2:aconst_null
// 3 3:invokespecial #19 <Method void SwitchPreference(Context, AttributeSet)>
// 4 6:return
}
public SwitchPreference(Context context, AttributeSet attributeset)
{
this(context, attributeset, TypedArrayUtils.getAttr(context, android.support.v7.preference.R.attr.switchPreferenceStyle, 0x101036d));
// 0 0:aload_0
// 1 1:aload_1
// 2 2:aload_2
// 3 3:aload_1
// 4 4:getstatic #26 <Field int android.support.v7.preference.R$attr.switchPreferenceStyle>
// 5 7:ldc1 #27 <Int 0x101036d>
// 6 9:invokestatic #33 <Method int TypedArrayUtils.getAttr(Context, int, int)>
// 7 12:invokespecial #36 <Method void SwitchPreference(Context, AttributeSet, int)>
// 8 15:return
}
public SwitchPreference(Context context, AttributeSet attributeset, int i)
{
this(context, attributeset, i, 0);
// 0 0:aload_0
// 1 1:aload_1
// 2 2:aload_2
// 3 3:iload_3
// 4 4:iconst_0
// 5 5:invokespecial #39 <Method void SwitchPreference(Context, AttributeSet, int, int)>
// 6 8:return
}
public SwitchPreference(Context context, AttributeSet attributeset, int i, int j)
{
super(context, attributeset, i, j);
// 0 0:aload_0
// 1 1:aload_1
// 2 2:aload_2
// 3 3:iload_3
// 4 4:iload 4
// 5 6:invokespecial #40 <Method void TwoStatePreference(Context, AttributeSet, int, int)>
mListener = new Listener();
// 6 9:aload_0
// 7 10:new #8 <Class SwitchPreference$Listener>
// 8 13:dup
// 9 14:aload_0
// 10 15:aconst_null
// 11 16:invokespecial #43 <Method void SwitchPreference$Listener(SwitchPreference, SwitchPreference$1)>
// 12 19:putfield #45 <Field SwitchPreference$Listener mListener>
context = ((Context) (context.obtainStyledAttributes(attributeset, R.styleable.SwitchPreference, i, j)));
// 13 22:aload_1
// 14 23:aload_2
// 15 24:getstatic #51 <Field int[] R$styleable.SwitchPreference>
// 16 27:iload_3
// 17 28:iload 4
// 18 30:invokevirtual #57 <Method TypedArray Context.obtainStyledAttributes(AttributeSet, int[], int, int)>
// 19 33:astore_1
setSummaryOn(((CharSequence) (TypedArrayUtils.getString(((TypedArray) (context)), R.styleable.SwitchPreference_summaryOn, R.styleable.SwitchPreference_android_summaryOn))));
// 20 34:aload_0
// 21 35:aload_1
// 22 36:getstatic #60 <Field int R$styleable.SwitchPreference_summaryOn>
// 23 39:getstatic #63 <Field int R$styleable.SwitchPreference_android_summaryOn>
// 24 42:invokestatic #67 <Method String TypedArrayUtils.getString(TypedArray, int, int)>
// 25 45:invokevirtual #71 <Method void setSummaryOn(CharSequence)>
setSummaryOff(((CharSequence) (TypedArrayUtils.getString(((TypedArray) (context)), R.styleable.SwitchPreference_summaryOff, R.styleable.SwitchPreference_android_summaryOff))));
// 26 48:aload_0
// 27 49:aload_1
// 28 50:getstatic #74 <Field int R$styleable.SwitchPreference_summaryOff>
// 29 53:getstatic #77 <Field int R$styleable.SwitchPreference_android_summaryOff>
// 30 56:invokestatic #67 <Method String TypedArrayUtils.getString(TypedArray, int, int)>
// 31 59:invokevirtual #80 <Method void setSummaryOff(CharSequence)>
setSwitchTextOn(((CharSequence) (TypedArrayUtils.getString(((TypedArray) (context)), R.styleable.SwitchPreference_switchTextOn, R.styleable.SwitchPreference_android_switchTextOn))));
// 32 62:aload_0
// 33 63:aload_1
// 34 64:getstatic #83 <Field int R$styleable.SwitchPreference_switchTextOn>
// 35 67:getstatic #86 <Field int R$styleable.SwitchPreference_android_switchTextOn>
// 36 70:invokestatic #67 <Method String TypedArrayUtils.getString(TypedArray, int, int)>
// 37 73:invokevirtual #89 <Method void setSwitchTextOn(CharSequence)>
setSwitchTextOff(((CharSequence) (TypedArrayUtils.getString(((TypedArray) (context)), R.styleable.SwitchPreference_switchTextOff, R.styleable.SwitchPreference_android_switchTextOff))));
// 38 76:aload_0
// 39 77:aload_1
// 40 78:getstatic #92 <Field int R$styleable.SwitchPreference_switchTextOff>
// 41 81:getstatic #95 <Field int R$styleable.SwitchPreference_android_switchTextOff>
// 42 84:invokestatic #67 <Method String TypedArrayUtils.getString(TypedArray, int, int)>
// 43 87:invokevirtual #98 <Method void setSwitchTextOff(CharSequence)>
setDisableDependentsState(TypedArrayUtils.getBoolean(((TypedArray) (context)), R.styleable.SwitchPreference_disableDependentsState, R.styleable.SwitchPreference_android_disableDependentsState, false));
// 44 90:aload_0
// 45 91:aload_1
// 46 92:getstatic #101 <Field int R$styleable.SwitchPreference_disableDependentsState>
// 47 95:getstatic #104 <Field int R$styleable.SwitchPreference_android_disableDependentsState>
// 48 98:iconst_0
// 49 99:invokestatic #108 <Method boolean TypedArrayUtils.getBoolean(TypedArray, int, int, boolean)>
// 50 102:invokevirtual #112 <Method void setDisableDependentsState(boolean)>
((TypedArray) (context)).recycle();
// 51 105:aload_1
// 52 106:invokevirtual #118 <Method void TypedArray.recycle()>
// 53 109:return
}
private void syncSwitchView(View view)
{
if(view instanceof Switch)
//* 0 0:aload_1
//* 1 1:instanceof #122 <Class Switch>
//* 2 4:ifeq 15
((Switch)view).setOnCheckedChangeListener(((android.widget.CompoundButton.OnCheckedChangeListener) (null)));
// 3 7:aload_1
// 4 8:checkcast #122 <Class Switch>
// 5 11:aconst_null
// 6 12:invokevirtual #126 <Method void Switch.setOnCheckedChangeListener(android.widget.CompoundButton$OnCheckedChangeListener)>
if(view instanceof Checkable)
//* 7 15:aload_1
//* 8 16:instanceof #128 <Class Checkable>
//* 9 19:ifeq 35
((Checkable)view).setChecked(mChecked);
// 10 22:aload_1
// 11 23:checkcast #128 <Class Checkable>
// 12 26:aload_0
// 13 27:getfield #132 <Field boolean mChecked>
// 14 30:invokeinterface #135 <Method void Checkable.setChecked(boolean)>
if(view instanceof Switch)
//* 15 35:aload_1
//* 16 36:instanceof #122 <Class Switch>
//* 17 39:ifeq 71
{
view = ((View) ((Switch)view));
// 18 42:aload_1
// 19 43:checkcast #122 <Class Switch>
// 20 46:astore_1
((Switch) (view)).setTextOn(mSwitchOn);
// 21 47:aload_1
// 22 48:aload_0
// 23 49:getfield #137 <Field CharSequence mSwitchOn>
// 24 52:invokevirtual #140 <Method void Switch.setTextOn(CharSequence)>
((Switch) (view)).setTextOff(mSwitchOff);
// 25 55:aload_1
// 26 56:aload_0
// 27 57:getfield #142 <Field CharSequence mSwitchOff>
// 28 60:invokevirtual #145 <Method void Switch.setTextOff(CharSequence)>
((Switch) (view)).setOnCheckedChangeListener(((android.widget.CompoundButton.OnCheckedChangeListener) (mListener)));
// 29 63:aload_1
// 30 64:aload_0
// 31 65:getfield #45 <Field SwitchPreference$Listener mListener>
// 32 68:invokevirtual #126 <Method void Switch.setOnCheckedChangeListener(android.widget.CompoundButton$OnCheckedChangeListener)>
}
// 33 71:return
}
private void syncViewIfAccessibilityEnabled(View view)
{
if(!((AccessibilityManager)getContext().getSystemService("accessibility")).isEnabled())
//* 0 0:aload_0
//* 1 1:invokevirtual #150 <Method Context getContext()>
//* 2 4:ldc1 #152 <String "accessibility">
//* 3 6:invokevirtual #156 <Method Object Context.getSystemService(String)>
//* 4 9:checkcast #158 <Class AccessibilityManager>
//* 5 12:invokevirtual #162 <Method boolean AccessibilityManager.isEnabled()>
//* 6 15:ifne 19
{
return;
// 7 18:return
} else
{
syncSwitchView(view.findViewById(0x1020040));
// 8 19:aload_0
// 9 20:aload_1
// 10 21:ldc1 #163 <Int 0x1020040>
// 11 23:invokevirtual #169 <Method View View.findViewById(int)>
// 12 26:invokespecial #171 <Method void syncSwitchView(View)>
syncSummaryView(view.findViewById(0x1020010));
// 13 29:aload_0
// 14 30:aload_1
// 15 31:ldc1 #172 <Int 0x1020010>
// 16 33:invokevirtual #169 <Method View View.findViewById(int)>
// 17 36:invokevirtual #175 <Method void syncSummaryView(View)>
return;
// 18 39:return
}
}
public CharSequence getSwitchTextOff()
{
return mSwitchOff;
// 0 0:aload_0
// 1 1:getfield #142 <Field CharSequence mSwitchOff>
// 2 4:areturn
}
public CharSequence getSwitchTextOn()
{
return mSwitchOn;
// 0 0:aload_0
// 1 1:getfield #137 <Field CharSequence mSwitchOn>
// 2 4:areturn
}
public void onBindViewHolder(PreferenceViewHolder preferenceviewholder)
{
super.onBindViewHolder(preferenceviewholder);
// 0 0:aload_0
// 1 1:aload_1
// 2 2:invokespecial #182 <Method void TwoStatePreference.onBindViewHolder(PreferenceViewHolder)>
syncSwitchView(preferenceviewholder.findViewById(0x1020040));
// 3 5:aload_0
// 4 6:aload_1
// 5 7:ldc1 #163 <Int 0x1020040>
// 6 9:invokevirtual #185 <Method View PreferenceViewHolder.findViewById(int)>
// 7 12:invokespecial #171 <Method void syncSwitchView(View)>
syncSummaryView(preferenceviewholder);
// 8 15:aload_0
// 9 16:aload_1
// 10 17:invokevirtual #187 <Method void syncSummaryView(PreferenceViewHolder)>
// 11 20:return
}
protected void performClick(View view)
{
super.performClick(view);
// 0 0:aload_0
// 1 1:aload_1
// 2 2:invokespecial #194 <Method void TwoStatePreference.performClick(View)>
syncViewIfAccessibilityEnabled(view);
// 3 5:aload_0
// 4 6:aload_1
// 5 7:invokespecial #196 <Method void syncViewIfAccessibilityEnabled(View)>
// 6 10:return
}
public void setSwitchTextOff(int i)
{
setSwitchTextOff(((CharSequence) (getContext().getString(i))));
// 0 0:aload_0
// 1 1:aload_0
// 2 2:invokevirtual #150 <Method Context getContext()>
// 3 5:iload_1
// 4 6:invokevirtual #201 <Method String Context.getString(int)>
// 5 9:invokevirtual #98 <Method void setSwitchTextOff(CharSequence)>
// 6 12:return
}
public void setSwitchTextOff(CharSequence charsequence)
{
mSwitchOff = charsequence;
// 0 0:aload_0
// 1 1:aload_1
// 2 2:putfield #142 <Field CharSequence mSwitchOff>
notifyChanged();
// 3 5:aload_0
// 4 6:invokevirtual #204 <Method void notifyChanged()>
// 5 9:return
}
public void setSwitchTextOn(int i)
{
setSwitchTextOn(((CharSequence) (getContext().getString(i))));
// 0 0:aload_0
// 1 1:aload_0
// 2 2:invokevirtual #150 <Method Context getContext()>
// 3 5:iload_1
// 4 6:invokevirtual #201 <Method String Context.getString(int)>
// 5 9:invokevirtual #89 <Method void setSwitchTextOn(CharSequence)>
// 6 12:return
}
public void setSwitchTextOn(CharSequence charsequence)
{
mSwitchOn = charsequence;
// 0 0:aload_0
// 1 1:aload_1
// 2 2:putfield #137 <Field CharSequence mSwitchOn>
notifyChanged();
// 3 5:aload_0
// 4 6:invokevirtual #204 <Method void notifyChanged()>
// 5 9:return
}
private final Listener mListener;
private CharSequence mSwitchOff;
private CharSequence mSwitchOn;
}
|
package me.sonam.jwt;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.reactive.server.FluxExchangeResult;
import org.springframework.test.web.reactive.server.WebTestClient;
import reactor.test.StepVerifier;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
/**
* this is not meant to be run during testing.
* It is just for verifying a provider service to be running for verification
* against pact consumers.
*/
@EnableAutoConfiguration
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class JwtRestServiceRun {
private static final Logger LOG = LoggerFactory.getLogger(JwtRestServiceRun.class);
@Test
public void getJwt() throws InterruptedException {
LOG.info("running sleep");
Thread.sleep(10000L);
LOG.info("done sleeping");
}
}
|
package com.leonelacs.tenki;
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.leonelacs.tenki", appContext.getPackageName());
}
}
|
/*
* Copyright 2016-2017 National Library of Australia
*
* 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 bamboo.trove.services;
import bamboo.task.Document;
import bamboo.trove.common.ContentThreshold;
import bamboo.trove.common.IndexerDocument;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@Service
public class QualityControlService {
public static final List<String> HTML_CONTENT_TYPES = Collections.singletonList("text/html");
public static final List<String> PDF_CONTENT_TYPES = Collections.singletonList("application/pdf");
public static final List<String> DOCUMENT_CONTENT_TYPES = Arrays.asList("application/rtf", "application/msword",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/vnd.oasis.opendocument.text");
public static final List<String> PRESENTATION_CONTENT_TYPES = Arrays.asList("application/vnd.ms-powerpoint",
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
"application/vnd.oasis.opendocument.presentation");
public static final List<String> SPREADSHEET_CONTENT_TYPES = Arrays.asList("application/vnd.ms-excel",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "text/csv", "application/csv",
"application/vnd.oasis.opendocument.spreadsheet");
ContentThreshold filterDocument(IndexerDocument indexerDocument) {
Document document = indexerDocument.getBambooDocument();
// Status code - Unless we actually harvested the content, don't index it
if (document.getStatusCode() != 200) {
return ContentThreshold.METADATA_ONLY;
}
// Content Type
if (isSearchableContentType(document)) {
if(!isFullTextSite(indexerDocument)){
return ContentThreshold.DOCUMENT_START_ONLY;
}
return ContentThreshold.FULL_TEXT;
}
// More rules will likely be added here
return ContentThreshold.METADATA_ONLY;
}
private boolean isSearchableContentType(Document document) {
return HTML_CONTENT_TYPES.contains(document.getContentType())
|| PDF_CONTENT_TYPES.contains(document.getContentType())
|| PRESENTATION_CONTENT_TYPES.contains(document.getContentType())
|| SPREADSHEET_CONTENT_TYPES.contains(document.getContentType())
|| DOCUMENT_CONTENT_TYPES.contains(document.getContentType());
}
/**
* We need to reduce the size of the index so we don't store all the full text for some sites.
* @param document
* @return
*/
private boolean isFullTextSite(IndexerDocument document){
return (document.getBambooDocument().getSite().endsWith(".gov.au") || document.isPandora());
}
}
|
package com.optimuscode.ranking.api;
/**
* Created with IntelliJ IDEA.
* User: sujay
* Date: 11/5/13
* Time: 11:24 AM
* To change this template use File | Settings | File Templates.
*/
public class Person {
private String id;
private Ability ability;
private double score;
public Person(final String id, final Ability ability){
this.id = id;
this.ability = ability;
}
public Ability getAbility(){
return this.ability;
}
public double getScore(){
return this.score;
}
public String getId(){
return this.id;
}
@Override
public String toString() {
return getId();
}
}
|
package com.ewolff.microservice.catalog.cdc;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.hateoas.MediaTypes;
import org.springframework.hateoas.PagedResources;
import org.springframework.hateoas.hal.Jackson2HalModule;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
@Component
public class CatalogClient {
public static class ItemPagedResources extends PagedResources<Item> {
}
private final RestTemplate restTemplate;
private final String catalogServiceHost;
private final long catalogServicePort;
private final boolean useRibbon;
private LoadBalancerClient loadBalancer;
@Autowired
public CatalogClient(
@Value("${catalog.service.host:catalog}") String catalogServiceHost,
@Value("${catalog.service.port:8080}") long catalogServicePort,
@Value("${ribbon.eureka.enabled:false}") boolean useRibbon) {
super();
this.restTemplate = getRestTemplate();
this.catalogServiceHost = catalogServiceHost;
this.catalogServicePort = catalogServicePort;
this.useRibbon = useRibbon;
}
@Autowired(required = false)
public void setLoadBalancer(LoadBalancerClient loadBalancer) {
this.loadBalancer = loadBalancer;
}
protected RestTemplate getRestTemplate() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
false);
mapper.registerModule(new Jackson2HalModule());
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(Arrays.asList(MediaTypes.HAL_JSON));
converter.setObjectMapper(mapper);
return new RestTemplate(
Collections.<HttpMessageConverter<?>> singletonList(converter));
}
public double price(long itemId) {
return getOne(itemId).getPrice();
}
public Collection<Item> findAll() {
PagedResources<Item> pagedResources = restTemplate.getForObject(
catalogURL(), ItemPagedResources.class);
return pagedResources.getContent();
}
private String catalogURL() {
if (useRibbon) {
ServiceInstance instance = loadBalancer.choose("CATALOG");
return "http://" + instance.getHost() + ":" + instance.getPort()
+ "/catalog/";
} else {
return "http://" + catalogServiceHost + ":" + catalogServicePort
+ "/catalog/";
}
}
public Item getOne(long itemId) {
return restTemplate.getForObject(catalogURL() + itemId, Item.class);
}
}
|
/*******************************************************************************
* 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.ofbiz.minilang.method.conditional;
import org.apache.ofbiz.base.util.Debug;
import org.apache.ofbiz.base.util.UtilGenerics;
import org.apache.ofbiz.minilang.MiniLangException;
import org.apache.ofbiz.minilang.SimpleMethod;
import org.w3c.dom.Element;
import java.util.*;
/**
* An abstract factory class for creating <if> element sub-element implementations.
* <p>Mini-language can be extended to support additional condition elements
* by extending this class to provide custom conditional element implementations.
* </p>
*/
public abstract class ConditionalFactory<C extends Conditional> {
public static final String module = ConditionalFactory.class.getName();
private static final Map<String, ConditionalFactory<?>> conditionalFactories;
static {
Map<String, ConditionalFactory<?>> factories = new HashMap<String, ConditionalFactory<?>>();
Iterator<ConditionalFactory<?>> it = UtilGenerics.cast(ServiceLoader.load(ConditionalFactory.class, ConditionalFactory.class.getClassLoader()).iterator());
while (it.hasNext()) {
ConditionalFactory<?> factory = it.next();
factories.put(factory.getName(), factory);
}
conditionalFactories = Collections.unmodifiableMap(factories);
}
public static Conditional makeConditional(Element element, SimpleMethod simpleMethod) throws MiniLangException {
String tagName = element.getTagName();
ConditionalFactory<?> factory = conditionalFactories.get(tagName);
if (factory != null) {
return factory.createCondition(element, simpleMethod);
} else {
Debug.logWarning("Found an unknown if condition: " + tagName, module);
return null;
}
}
public abstract C createCondition(Element element, SimpleMethod simpleMethod) throws MiniLangException;
public abstract String getName();
}
|
package com.mmnaseri.utils.tuples.impl;
import com.mmnaseri.utils.tuples.LabeledTuple;
import com.mmnaseri.utils.tuples.Tuple;
import org.testng.annotations.Test;
import java.util.List;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.arrayWithSize;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
/**
* Tests for {@link TwelveTuple}.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
*/
public class TwelveTupleTest {
@Test
public void creatingTuple() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
assertThat(tuple, is(notNullValue()));
assertThat(tuple.size(), is(12));
}
@Test
public void testToArray() {
Tuple<Object> tuple = Tuple.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
Object[] first = tuple.asArray();
Object[] second = tuple.asArray(Object[]::new);
assertThat(first, is(notNullValue()));
assertThat(second, is(notNullValue()));
assertThat(first, is(arrayWithSize(tuple.size())));
assertThat(second, is(arrayWithSize(tuple.size())));
for (int i = 0; i < tuple.size(); i++) {
assertThat(first[i], is(tuple.get(i)));
assertThat(second[i], is(tuple.get(i)));
}
}
@Test
public void testResizeAsEmpty() {
Tuple<Object> tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
EmptyTuple<Object> other = tuple.asEmpty();
assertThat(other.size(), is(0));
}
@Test
public void testResizeAsOne() {
Tuple<Object> tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
OneTuple<Object, Object> other = tuple.asOne();
assertThat(other.size(), is(1));
assertThat(other.first(), is(tuple.get(0)));
}
@Test
public void testResizeAsTwo() {
Tuple<Object> tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
TwoTuple<Object, Object, Object> other = tuple.asTwo();
assertThat(other.size(), is(2));
assertThat(other.first(), is(tuple.get(0)));
assertThat(other.second(), is(tuple.get(1)));
}
@Test
public void testResizeAsThree() {
Tuple<Object> tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
ThreeTuple<Object, Object, Object, Object> other = tuple.asThree();
assertThat(other.size(), is(3));
assertThat(other.first(), is(tuple.get(0)));
assertThat(other.second(), is(tuple.get(1)));
assertThat(other.third(), is(tuple.get(2)));
}
@Test
public void testResizeAsFour() {
Tuple<Object> tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
FourTuple<Object, Object, Object, Object, Object> other = tuple.asFour();
assertThat(other.size(), is(4));
assertThat(other.first(), is(tuple.get(0)));
assertThat(other.second(), is(tuple.get(1)));
assertThat(other.third(), is(tuple.get(2)));
assertThat(other.fourth(), is(tuple.get(3)));
}
@Test
public void testResizeAsFive() {
Tuple<Object> tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
FiveTuple<Object, Object, Object, Object, Object, Object> other = tuple.asFive();
assertThat(other.size(), is(5));
assertThat(other.first(), is(tuple.get(0)));
assertThat(other.second(), is(tuple.get(1)));
assertThat(other.third(), is(tuple.get(2)));
assertThat(other.fourth(), is(tuple.get(3)));
assertThat(other.fifth(), is(tuple.get(4)));
}
@Test
public void testResizeAsSix() {
Tuple<Object> tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
SixTuple<Object, Object, Object, Object, Object, Object, Object> other = tuple.asSix();
assertThat(other.size(), is(6));
assertThat(other.first(), is(tuple.get(0)));
assertThat(other.second(), is(tuple.get(1)));
assertThat(other.third(), is(tuple.get(2)));
assertThat(other.fourth(), is(tuple.get(3)));
assertThat(other.fifth(), is(tuple.get(4)));
assertThat(other.sixth(), is(tuple.get(5)));
}
@Test
public void testResizeAsSeven() {
Tuple<Object> tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
SevenTuple<Object, Object, Object, Object, Object, Object, Object, Object> other =
tuple.asSeven();
assertThat(other.size(), is(7));
assertThat(other.first(), is(tuple.get(0)));
assertThat(other.second(), is(tuple.get(1)));
assertThat(other.third(), is(tuple.get(2)));
assertThat(other.fourth(), is(tuple.get(3)));
assertThat(other.fifth(), is(tuple.get(4)));
assertThat(other.sixth(), is(tuple.get(5)));
assertThat(other.seventh(), is(tuple.get(6)));
}
@Test
public void testResizeAsEight() {
Tuple<Object> tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
EightTuple<Object, Object, Object, Object, Object, Object, Object, Object, Object> other =
tuple.asEight();
assertThat(other.size(), is(8));
assertThat(other.first(), is(tuple.get(0)));
assertThat(other.second(), is(tuple.get(1)));
assertThat(other.third(), is(tuple.get(2)));
assertThat(other.fourth(), is(tuple.get(3)));
assertThat(other.fifth(), is(tuple.get(4)));
assertThat(other.sixth(), is(tuple.get(5)));
assertThat(other.seventh(), is(tuple.get(6)));
assertThat(other.eighth(), is(tuple.get(7)));
}
@Test
public void testResizeAsNine() {
Tuple<Object> tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
NineTuple<Object, Object, Object, Object, Object, Object, Object, Object, Object, Object>
other = tuple.asNine();
assertThat(other.size(), is(9));
assertThat(other.first(), is(tuple.get(0)));
assertThat(other.second(), is(tuple.get(1)));
assertThat(other.third(), is(tuple.get(2)));
assertThat(other.fourth(), is(tuple.get(3)));
assertThat(other.fifth(), is(tuple.get(4)));
assertThat(other.sixth(), is(tuple.get(5)));
assertThat(other.seventh(), is(tuple.get(6)));
assertThat(other.eighth(), is(tuple.get(7)));
assertThat(other.ninth(), is(tuple.get(8)));
}
@Test
public void testResizeAsTen() {
Tuple<Object> tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
TenTuple<Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object>
other = tuple.asTen();
assertThat(other.size(), is(10));
assertThat(other.first(), is(tuple.get(0)));
assertThat(other.second(), is(tuple.get(1)));
assertThat(other.third(), is(tuple.get(2)));
assertThat(other.fourth(), is(tuple.get(3)));
assertThat(other.fifth(), is(tuple.get(4)));
assertThat(other.sixth(), is(tuple.get(5)));
assertThat(other.seventh(), is(tuple.get(6)));
assertThat(other.eighth(), is(tuple.get(7)));
assertThat(other.ninth(), is(tuple.get(8)));
assertThat(other.tenth(), is(tuple.get(9)));
}
@Test
public void testResizeAsEleven() {
Tuple<Object> tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
ElevenTuple<
Object,
Object,
Object,
Object,
Object,
Object,
Object,
Object,
Object,
Object,
Object,
Object>
other = tuple.asEleven();
assertThat(other.size(), is(11));
assertThat(other.first(), is(tuple.get(0)));
assertThat(other.second(), is(tuple.get(1)));
assertThat(other.third(), is(tuple.get(2)));
assertThat(other.fourth(), is(tuple.get(3)));
assertThat(other.fifth(), is(tuple.get(4)));
assertThat(other.sixth(), is(tuple.get(5)));
assertThat(other.seventh(), is(tuple.get(6)));
assertThat(other.eighth(), is(tuple.get(7)));
assertThat(other.ninth(), is(tuple.get(8)));
assertThat(other.tenth(), is(tuple.get(9)));
assertThat(other.eleventh(), is(tuple.get(10)));
}
@Test
public void testResizeAsTwelve() {
Tuple<Object> tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
TwelveTuple<
Object,
Object,
Object,
Object,
Object,
Object,
Object,
Object,
Object,
Object,
Object,
Object,
Object>
other = tuple.asTwelve();
assertThat(other.size(), is(12));
assertThat(other.first(), is(tuple.get(0)));
assertThat(other.second(), is(tuple.get(1)));
assertThat(other.third(), is(tuple.get(2)));
assertThat(other.fourth(), is(tuple.get(3)));
assertThat(other.fifth(), is(tuple.get(4)));
assertThat(other.sixth(), is(tuple.get(5)));
assertThat(other.seventh(), is(tuple.get(6)));
assertThat(other.eighth(), is(tuple.get(7)));
assertThat(other.ninth(), is(tuple.get(8)));
assertThat(other.tenth(), is(tuple.get(9)));
assertThat(other.eleventh(), is(tuple.get(10)));
assertThat(other.twelfth(), is(tuple.get(11)));
}
@Test
public void accessingMembers() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
assertThat(tuple.get(0), is(0));
assertThat(tuple.get(1), is(1));
assertThat(tuple.get(2), is(2));
assertThat(tuple.get(3), is(3));
assertThat(tuple.get(4), is(4));
assertThat(tuple.get(5), is(5));
assertThat(tuple.get(6), is(6));
assertThat(tuple.get(7), is(7));
assertThat(tuple.get(8), is(8));
assertThat(tuple.get(9), is(9));
assertThat(tuple.get(10), is(10));
assertThat(tuple.get(11), is(11));
}
@Test
public void changingElementByIndex() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
for (int i = 0; i < 12; i++) {
Tuple<?> other = tuple.change(i, -1);
assertThat(other, is(notNullValue()));
assertThat(other.size(), is(12));
assertThat(other.get(i), is(-1));
}
}
@Test
public void changingElementByIndexThroughFunction() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
for (int i = 0; i < 12; i++) {
Tuple<?> other = tuple.change(i, t -> -1);
assertThat(other, is(notNullValue()));
assertThat(other.size(), is(12));
assertThat(other.get(i), is(-1));
}
}
@Test
public void changingFirstElementByAccessor() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
// Changing by value.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
secondTuple = tuple.first(-1);
assertThat(secondTuple, is(notNullValue()));
assertThat(secondTuple.size(), is(tuple.size()));
assertThat(secondTuple.first(), is(-1));
assertThat(secondTuple.second(), is(1));
assertThat(secondTuple.third(), is(2));
assertThat(secondTuple.fourth(), is(3));
assertThat(secondTuple.fifth(), is(4));
assertThat(secondTuple.sixth(), is(5));
assertThat(secondTuple.seventh(), is(6));
assertThat(secondTuple.eighth(), is(7));
assertThat(secondTuple.ninth(), is(8));
assertThat(secondTuple.tenth(), is(9));
assertThat(secondTuple.eleventh(), is(10));
assertThat(secondTuple.twelfth(), is(11));
// Changing by supplier.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
thirdTuple = tuple.first(() -> -1);
assertThat(thirdTuple, is(notNullValue()));
assertThat(thirdTuple.size(), is(tuple.size()));
assertThat(thirdTuple.first(), is(-1));
assertThat(thirdTuple.second(), is(1));
assertThat(thirdTuple.third(), is(2));
assertThat(thirdTuple.fourth(), is(3));
assertThat(thirdTuple.fifth(), is(4));
assertThat(thirdTuple.sixth(), is(5));
assertThat(thirdTuple.seventh(), is(6));
assertThat(thirdTuple.eighth(), is(7));
assertThat(thirdTuple.ninth(), is(8));
assertThat(thirdTuple.tenth(), is(9));
assertThat(thirdTuple.eleventh(), is(10));
assertThat(thirdTuple.twelfth(), is(11));
// Changing by function.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
fourthTuple = tuple.first(previous -> -1);
assertThat(fourthTuple, is(notNullValue()));
assertThat(fourthTuple.size(), is(tuple.size()));
assertThat(fourthTuple.first(), is(-1));
assertThat(fourthTuple.second(), is(1));
assertThat(fourthTuple.third(), is(2));
assertThat(fourthTuple.fourth(), is(3));
assertThat(fourthTuple.fifth(), is(4));
assertThat(fourthTuple.sixth(), is(5));
assertThat(fourthTuple.seventh(), is(6));
assertThat(fourthTuple.eighth(), is(7));
assertThat(fourthTuple.ninth(), is(8));
assertThat(fourthTuple.tenth(), is(9));
assertThat(fourthTuple.eleventh(), is(10));
assertThat(fourthTuple.twelfth(), is(11));
}
@Test
public void changingSecondElementByAccessor() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
// Changing by value.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
secondTuple = tuple.second(-1);
assertThat(secondTuple, is(notNullValue()));
assertThat(secondTuple.size(), is(tuple.size()));
assertThat(secondTuple.first(), is(0));
assertThat(secondTuple.second(), is(-1));
assertThat(secondTuple.third(), is(2));
assertThat(secondTuple.fourth(), is(3));
assertThat(secondTuple.fifth(), is(4));
assertThat(secondTuple.sixth(), is(5));
assertThat(secondTuple.seventh(), is(6));
assertThat(secondTuple.eighth(), is(7));
assertThat(secondTuple.ninth(), is(8));
assertThat(secondTuple.tenth(), is(9));
assertThat(secondTuple.eleventh(), is(10));
assertThat(secondTuple.twelfth(), is(11));
// Changing by supplier.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
thirdTuple = tuple.second(() -> -1);
assertThat(thirdTuple, is(notNullValue()));
assertThat(thirdTuple.size(), is(tuple.size()));
assertThat(thirdTuple.first(), is(0));
assertThat(thirdTuple.second(), is(-1));
assertThat(thirdTuple.third(), is(2));
assertThat(thirdTuple.fourth(), is(3));
assertThat(thirdTuple.fifth(), is(4));
assertThat(thirdTuple.sixth(), is(5));
assertThat(thirdTuple.seventh(), is(6));
assertThat(thirdTuple.eighth(), is(7));
assertThat(thirdTuple.ninth(), is(8));
assertThat(thirdTuple.tenth(), is(9));
assertThat(thirdTuple.eleventh(), is(10));
assertThat(thirdTuple.twelfth(), is(11));
// Changing by function.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
fourthTuple = tuple.second(previous -> -1);
assertThat(fourthTuple, is(notNullValue()));
assertThat(fourthTuple.size(), is(tuple.size()));
assertThat(fourthTuple.first(), is(0));
assertThat(fourthTuple.second(), is(-1));
assertThat(fourthTuple.third(), is(2));
assertThat(fourthTuple.fourth(), is(3));
assertThat(fourthTuple.fifth(), is(4));
assertThat(fourthTuple.sixth(), is(5));
assertThat(fourthTuple.seventh(), is(6));
assertThat(fourthTuple.eighth(), is(7));
assertThat(fourthTuple.ninth(), is(8));
assertThat(fourthTuple.tenth(), is(9));
assertThat(fourthTuple.eleventh(), is(10));
assertThat(fourthTuple.twelfth(), is(11));
}
@Test
public void changingThirdElementByAccessor() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
// Changing by value.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
secondTuple = tuple.third(-1);
assertThat(secondTuple, is(notNullValue()));
assertThat(secondTuple.size(), is(tuple.size()));
assertThat(secondTuple.first(), is(0));
assertThat(secondTuple.second(), is(1));
assertThat(secondTuple.third(), is(-1));
assertThat(secondTuple.fourth(), is(3));
assertThat(secondTuple.fifth(), is(4));
assertThat(secondTuple.sixth(), is(5));
assertThat(secondTuple.seventh(), is(6));
assertThat(secondTuple.eighth(), is(7));
assertThat(secondTuple.ninth(), is(8));
assertThat(secondTuple.tenth(), is(9));
assertThat(secondTuple.eleventh(), is(10));
assertThat(secondTuple.twelfth(), is(11));
// Changing by supplier.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
thirdTuple = tuple.third(() -> -1);
assertThat(thirdTuple, is(notNullValue()));
assertThat(thirdTuple.size(), is(tuple.size()));
assertThat(thirdTuple.first(), is(0));
assertThat(thirdTuple.second(), is(1));
assertThat(thirdTuple.third(), is(-1));
assertThat(thirdTuple.fourth(), is(3));
assertThat(thirdTuple.fifth(), is(4));
assertThat(thirdTuple.sixth(), is(5));
assertThat(thirdTuple.seventh(), is(6));
assertThat(thirdTuple.eighth(), is(7));
assertThat(thirdTuple.ninth(), is(8));
assertThat(thirdTuple.tenth(), is(9));
assertThat(thirdTuple.eleventh(), is(10));
assertThat(thirdTuple.twelfth(), is(11));
// Changing by function.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
fourthTuple = tuple.third(previous -> -1);
assertThat(fourthTuple, is(notNullValue()));
assertThat(fourthTuple.size(), is(tuple.size()));
assertThat(fourthTuple.first(), is(0));
assertThat(fourthTuple.second(), is(1));
assertThat(fourthTuple.third(), is(-1));
assertThat(fourthTuple.fourth(), is(3));
assertThat(fourthTuple.fifth(), is(4));
assertThat(fourthTuple.sixth(), is(5));
assertThat(fourthTuple.seventh(), is(6));
assertThat(fourthTuple.eighth(), is(7));
assertThat(fourthTuple.ninth(), is(8));
assertThat(fourthTuple.tenth(), is(9));
assertThat(fourthTuple.eleventh(), is(10));
assertThat(fourthTuple.twelfth(), is(11));
}
@Test
public void changingFourthElementByAccessor() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
// Changing by value.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
secondTuple = tuple.fourth(-1);
assertThat(secondTuple, is(notNullValue()));
assertThat(secondTuple.size(), is(tuple.size()));
assertThat(secondTuple.first(), is(0));
assertThat(secondTuple.second(), is(1));
assertThat(secondTuple.third(), is(2));
assertThat(secondTuple.fourth(), is(-1));
assertThat(secondTuple.fifth(), is(4));
assertThat(secondTuple.sixth(), is(5));
assertThat(secondTuple.seventh(), is(6));
assertThat(secondTuple.eighth(), is(7));
assertThat(secondTuple.ninth(), is(8));
assertThat(secondTuple.tenth(), is(9));
assertThat(secondTuple.eleventh(), is(10));
assertThat(secondTuple.twelfth(), is(11));
// Changing by supplier.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
thirdTuple = tuple.fourth(() -> -1);
assertThat(thirdTuple, is(notNullValue()));
assertThat(thirdTuple.size(), is(tuple.size()));
assertThat(thirdTuple.first(), is(0));
assertThat(thirdTuple.second(), is(1));
assertThat(thirdTuple.third(), is(2));
assertThat(thirdTuple.fourth(), is(-1));
assertThat(thirdTuple.fifth(), is(4));
assertThat(thirdTuple.sixth(), is(5));
assertThat(thirdTuple.seventh(), is(6));
assertThat(thirdTuple.eighth(), is(7));
assertThat(thirdTuple.ninth(), is(8));
assertThat(thirdTuple.tenth(), is(9));
assertThat(thirdTuple.eleventh(), is(10));
assertThat(thirdTuple.twelfth(), is(11));
// Changing by function.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
fourthTuple = tuple.fourth(previous -> -1);
assertThat(fourthTuple, is(notNullValue()));
assertThat(fourthTuple.size(), is(tuple.size()));
assertThat(fourthTuple.first(), is(0));
assertThat(fourthTuple.second(), is(1));
assertThat(fourthTuple.third(), is(2));
assertThat(fourthTuple.fourth(), is(-1));
assertThat(fourthTuple.fifth(), is(4));
assertThat(fourthTuple.sixth(), is(5));
assertThat(fourthTuple.seventh(), is(6));
assertThat(fourthTuple.eighth(), is(7));
assertThat(fourthTuple.ninth(), is(8));
assertThat(fourthTuple.tenth(), is(9));
assertThat(fourthTuple.eleventh(), is(10));
assertThat(fourthTuple.twelfth(), is(11));
}
@Test
public void changingFifthElementByAccessor() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
// Changing by value.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
secondTuple = tuple.fifth(-1);
assertThat(secondTuple, is(notNullValue()));
assertThat(secondTuple.size(), is(tuple.size()));
assertThat(secondTuple.first(), is(0));
assertThat(secondTuple.second(), is(1));
assertThat(secondTuple.third(), is(2));
assertThat(secondTuple.fourth(), is(3));
assertThat(secondTuple.fifth(), is(-1));
assertThat(secondTuple.sixth(), is(5));
assertThat(secondTuple.seventh(), is(6));
assertThat(secondTuple.eighth(), is(7));
assertThat(secondTuple.ninth(), is(8));
assertThat(secondTuple.tenth(), is(9));
assertThat(secondTuple.eleventh(), is(10));
assertThat(secondTuple.twelfth(), is(11));
// Changing by supplier.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
thirdTuple = tuple.fifth(() -> -1);
assertThat(thirdTuple, is(notNullValue()));
assertThat(thirdTuple.size(), is(tuple.size()));
assertThat(thirdTuple.first(), is(0));
assertThat(thirdTuple.second(), is(1));
assertThat(thirdTuple.third(), is(2));
assertThat(thirdTuple.fourth(), is(3));
assertThat(thirdTuple.fifth(), is(-1));
assertThat(thirdTuple.sixth(), is(5));
assertThat(thirdTuple.seventh(), is(6));
assertThat(thirdTuple.eighth(), is(7));
assertThat(thirdTuple.ninth(), is(8));
assertThat(thirdTuple.tenth(), is(9));
assertThat(thirdTuple.eleventh(), is(10));
assertThat(thirdTuple.twelfth(), is(11));
// Changing by function.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
fourthTuple = tuple.fifth(previous -> -1);
assertThat(fourthTuple, is(notNullValue()));
assertThat(fourthTuple.size(), is(tuple.size()));
assertThat(fourthTuple.first(), is(0));
assertThat(fourthTuple.second(), is(1));
assertThat(fourthTuple.third(), is(2));
assertThat(fourthTuple.fourth(), is(3));
assertThat(fourthTuple.fifth(), is(-1));
assertThat(fourthTuple.sixth(), is(5));
assertThat(fourthTuple.seventh(), is(6));
assertThat(fourthTuple.eighth(), is(7));
assertThat(fourthTuple.ninth(), is(8));
assertThat(fourthTuple.tenth(), is(9));
assertThat(fourthTuple.eleventh(), is(10));
assertThat(fourthTuple.twelfth(), is(11));
}
@Test
public void changingSixthElementByAccessor() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
// Changing by value.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
secondTuple = tuple.sixth(-1);
assertThat(secondTuple, is(notNullValue()));
assertThat(secondTuple.size(), is(tuple.size()));
assertThat(secondTuple.first(), is(0));
assertThat(secondTuple.second(), is(1));
assertThat(secondTuple.third(), is(2));
assertThat(secondTuple.fourth(), is(3));
assertThat(secondTuple.fifth(), is(4));
assertThat(secondTuple.sixth(), is(-1));
assertThat(secondTuple.seventh(), is(6));
assertThat(secondTuple.eighth(), is(7));
assertThat(secondTuple.ninth(), is(8));
assertThat(secondTuple.tenth(), is(9));
assertThat(secondTuple.eleventh(), is(10));
assertThat(secondTuple.twelfth(), is(11));
// Changing by supplier.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
thirdTuple = tuple.sixth(() -> -1);
assertThat(thirdTuple, is(notNullValue()));
assertThat(thirdTuple.size(), is(tuple.size()));
assertThat(thirdTuple.first(), is(0));
assertThat(thirdTuple.second(), is(1));
assertThat(thirdTuple.third(), is(2));
assertThat(thirdTuple.fourth(), is(3));
assertThat(thirdTuple.fifth(), is(4));
assertThat(thirdTuple.sixth(), is(-1));
assertThat(thirdTuple.seventh(), is(6));
assertThat(thirdTuple.eighth(), is(7));
assertThat(thirdTuple.ninth(), is(8));
assertThat(thirdTuple.tenth(), is(9));
assertThat(thirdTuple.eleventh(), is(10));
assertThat(thirdTuple.twelfth(), is(11));
// Changing by function.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
fourthTuple = tuple.sixth(previous -> -1);
assertThat(fourthTuple, is(notNullValue()));
assertThat(fourthTuple.size(), is(tuple.size()));
assertThat(fourthTuple.first(), is(0));
assertThat(fourthTuple.second(), is(1));
assertThat(fourthTuple.third(), is(2));
assertThat(fourthTuple.fourth(), is(3));
assertThat(fourthTuple.fifth(), is(4));
assertThat(fourthTuple.sixth(), is(-1));
assertThat(fourthTuple.seventh(), is(6));
assertThat(fourthTuple.eighth(), is(7));
assertThat(fourthTuple.ninth(), is(8));
assertThat(fourthTuple.tenth(), is(9));
assertThat(fourthTuple.eleventh(), is(10));
assertThat(fourthTuple.twelfth(), is(11));
}
@Test
public void changingSeventhElementByAccessor() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
// Changing by value.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
secondTuple = tuple.seventh(-1);
assertThat(secondTuple, is(notNullValue()));
assertThat(secondTuple.size(), is(tuple.size()));
assertThat(secondTuple.first(), is(0));
assertThat(secondTuple.second(), is(1));
assertThat(secondTuple.third(), is(2));
assertThat(secondTuple.fourth(), is(3));
assertThat(secondTuple.fifth(), is(4));
assertThat(secondTuple.sixth(), is(5));
assertThat(secondTuple.seventh(), is(-1));
assertThat(secondTuple.eighth(), is(7));
assertThat(secondTuple.ninth(), is(8));
assertThat(secondTuple.tenth(), is(9));
assertThat(secondTuple.eleventh(), is(10));
assertThat(secondTuple.twelfth(), is(11));
// Changing by supplier.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
thirdTuple = tuple.seventh(() -> -1);
assertThat(thirdTuple, is(notNullValue()));
assertThat(thirdTuple.size(), is(tuple.size()));
assertThat(thirdTuple.first(), is(0));
assertThat(thirdTuple.second(), is(1));
assertThat(thirdTuple.third(), is(2));
assertThat(thirdTuple.fourth(), is(3));
assertThat(thirdTuple.fifth(), is(4));
assertThat(thirdTuple.sixth(), is(5));
assertThat(thirdTuple.seventh(), is(-1));
assertThat(thirdTuple.eighth(), is(7));
assertThat(thirdTuple.ninth(), is(8));
assertThat(thirdTuple.tenth(), is(9));
assertThat(thirdTuple.eleventh(), is(10));
assertThat(thirdTuple.twelfth(), is(11));
// Changing by function.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
fourthTuple = tuple.seventh(previous -> -1);
assertThat(fourthTuple, is(notNullValue()));
assertThat(fourthTuple.size(), is(tuple.size()));
assertThat(fourthTuple.first(), is(0));
assertThat(fourthTuple.second(), is(1));
assertThat(fourthTuple.third(), is(2));
assertThat(fourthTuple.fourth(), is(3));
assertThat(fourthTuple.fifth(), is(4));
assertThat(fourthTuple.sixth(), is(5));
assertThat(fourthTuple.seventh(), is(-1));
assertThat(fourthTuple.eighth(), is(7));
assertThat(fourthTuple.ninth(), is(8));
assertThat(fourthTuple.tenth(), is(9));
assertThat(fourthTuple.eleventh(), is(10));
assertThat(fourthTuple.twelfth(), is(11));
}
@Test
public void changingEighthElementByAccessor() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
// Changing by value.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
secondTuple = tuple.eighth(-1);
assertThat(secondTuple, is(notNullValue()));
assertThat(secondTuple.size(), is(tuple.size()));
assertThat(secondTuple.first(), is(0));
assertThat(secondTuple.second(), is(1));
assertThat(secondTuple.third(), is(2));
assertThat(secondTuple.fourth(), is(3));
assertThat(secondTuple.fifth(), is(4));
assertThat(secondTuple.sixth(), is(5));
assertThat(secondTuple.seventh(), is(6));
assertThat(secondTuple.eighth(), is(-1));
assertThat(secondTuple.ninth(), is(8));
assertThat(secondTuple.tenth(), is(9));
assertThat(secondTuple.eleventh(), is(10));
assertThat(secondTuple.twelfth(), is(11));
// Changing by supplier.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
thirdTuple = tuple.eighth(() -> -1);
assertThat(thirdTuple, is(notNullValue()));
assertThat(thirdTuple.size(), is(tuple.size()));
assertThat(thirdTuple.first(), is(0));
assertThat(thirdTuple.second(), is(1));
assertThat(thirdTuple.third(), is(2));
assertThat(thirdTuple.fourth(), is(3));
assertThat(thirdTuple.fifth(), is(4));
assertThat(thirdTuple.sixth(), is(5));
assertThat(thirdTuple.seventh(), is(6));
assertThat(thirdTuple.eighth(), is(-1));
assertThat(thirdTuple.ninth(), is(8));
assertThat(thirdTuple.tenth(), is(9));
assertThat(thirdTuple.eleventh(), is(10));
assertThat(thirdTuple.twelfth(), is(11));
// Changing by function.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
fourthTuple = tuple.eighth(previous -> -1);
assertThat(fourthTuple, is(notNullValue()));
assertThat(fourthTuple.size(), is(tuple.size()));
assertThat(fourthTuple.first(), is(0));
assertThat(fourthTuple.second(), is(1));
assertThat(fourthTuple.third(), is(2));
assertThat(fourthTuple.fourth(), is(3));
assertThat(fourthTuple.fifth(), is(4));
assertThat(fourthTuple.sixth(), is(5));
assertThat(fourthTuple.seventh(), is(6));
assertThat(fourthTuple.eighth(), is(-1));
assertThat(fourthTuple.ninth(), is(8));
assertThat(fourthTuple.tenth(), is(9));
assertThat(fourthTuple.eleventh(), is(10));
assertThat(fourthTuple.twelfth(), is(11));
}
@Test
public void changingNinthElementByAccessor() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
// Changing by value.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
secondTuple = tuple.ninth(-1);
assertThat(secondTuple, is(notNullValue()));
assertThat(secondTuple.size(), is(tuple.size()));
assertThat(secondTuple.first(), is(0));
assertThat(secondTuple.second(), is(1));
assertThat(secondTuple.third(), is(2));
assertThat(secondTuple.fourth(), is(3));
assertThat(secondTuple.fifth(), is(4));
assertThat(secondTuple.sixth(), is(5));
assertThat(secondTuple.seventh(), is(6));
assertThat(secondTuple.eighth(), is(7));
assertThat(secondTuple.ninth(), is(-1));
assertThat(secondTuple.tenth(), is(9));
assertThat(secondTuple.eleventh(), is(10));
assertThat(secondTuple.twelfth(), is(11));
// Changing by supplier.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
thirdTuple = tuple.ninth(() -> -1);
assertThat(thirdTuple, is(notNullValue()));
assertThat(thirdTuple.size(), is(tuple.size()));
assertThat(thirdTuple.first(), is(0));
assertThat(thirdTuple.second(), is(1));
assertThat(thirdTuple.third(), is(2));
assertThat(thirdTuple.fourth(), is(3));
assertThat(thirdTuple.fifth(), is(4));
assertThat(thirdTuple.sixth(), is(5));
assertThat(thirdTuple.seventh(), is(6));
assertThat(thirdTuple.eighth(), is(7));
assertThat(thirdTuple.ninth(), is(-1));
assertThat(thirdTuple.tenth(), is(9));
assertThat(thirdTuple.eleventh(), is(10));
assertThat(thirdTuple.twelfth(), is(11));
// Changing by function.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
fourthTuple = tuple.ninth(previous -> -1);
assertThat(fourthTuple, is(notNullValue()));
assertThat(fourthTuple.size(), is(tuple.size()));
assertThat(fourthTuple.first(), is(0));
assertThat(fourthTuple.second(), is(1));
assertThat(fourthTuple.third(), is(2));
assertThat(fourthTuple.fourth(), is(3));
assertThat(fourthTuple.fifth(), is(4));
assertThat(fourthTuple.sixth(), is(5));
assertThat(fourthTuple.seventh(), is(6));
assertThat(fourthTuple.eighth(), is(7));
assertThat(fourthTuple.ninth(), is(-1));
assertThat(fourthTuple.tenth(), is(9));
assertThat(fourthTuple.eleventh(), is(10));
assertThat(fourthTuple.twelfth(), is(11));
}
@Test
public void changingTenthElementByAccessor() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
// Changing by value.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
secondTuple = tuple.tenth(-1);
assertThat(secondTuple, is(notNullValue()));
assertThat(secondTuple.size(), is(tuple.size()));
assertThat(secondTuple.first(), is(0));
assertThat(secondTuple.second(), is(1));
assertThat(secondTuple.third(), is(2));
assertThat(secondTuple.fourth(), is(3));
assertThat(secondTuple.fifth(), is(4));
assertThat(secondTuple.sixth(), is(5));
assertThat(secondTuple.seventh(), is(6));
assertThat(secondTuple.eighth(), is(7));
assertThat(secondTuple.ninth(), is(8));
assertThat(secondTuple.tenth(), is(-1));
assertThat(secondTuple.eleventh(), is(10));
assertThat(secondTuple.twelfth(), is(11));
// Changing by supplier.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
thirdTuple = tuple.tenth(() -> -1);
assertThat(thirdTuple, is(notNullValue()));
assertThat(thirdTuple.size(), is(tuple.size()));
assertThat(thirdTuple.first(), is(0));
assertThat(thirdTuple.second(), is(1));
assertThat(thirdTuple.third(), is(2));
assertThat(thirdTuple.fourth(), is(3));
assertThat(thirdTuple.fifth(), is(4));
assertThat(thirdTuple.sixth(), is(5));
assertThat(thirdTuple.seventh(), is(6));
assertThat(thirdTuple.eighth(), is(7));
assertThat(thirdTuple.ninth(), is(8));
assertThat(thirdTuple.tenth(), is(-1));
assertThat(thirdTuple.eleventh(), is(10));
assertThat(thirdTuple.twelfth(), is(11));
// Changing by function.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
fourthTuple = tuple.tenth(previous -> -1);
assertThat(fourthTuple, is(notNullValue()));
assertThat(fourthTuple.size(), is(tuple.size()));
assertThat(fourthTuple.first(), is(0));
assertThat(fourthTuple.second(), is(1));
assertThat(fourthTuple.third(), is(2));
assertThat(fourthTuple.fourth(), is(3));
assertThat(fourthTuple.fifth(), is(4));
assertThat(fourthTuple.sixth(), is(5));
assertThat(fourthTuple.seventh(), is(6));
assertThat(fourthTuple.eighth(), is(7));
assertThat(fourthTuple.ninth(), is(8));
assertThat(fourthTuple.tenth(), is(-1));
assertThat(fourthTuple.eleventh(), is(10));
assertThat(fourthTuple.twelfth(), is(11));
}
@Test
public void changingEleventhElementByAccessor() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
// Changing by value.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
secondTuple = tuple.eleventh(-1);
assertThat(secondTuple, is(notNullValue()));
assertThat(secondTuple.size(), is(tuple.size()));
assertThat(secondTuple.first(), is(0));
assertThat(secondTuple.second(), is(1));
assertThat(secondTuple.third(), is(2));
assertThat(secondTuple.fourth(), is(3));
assertThat(secondTuple.fifth(), is(4));
assertThat(secondTuple.sixth(), is(5));
assertThat(secondTuple.seventh(), is(6));
assertThat(secondTuple.eighth(), is(7));
assertThat(secondTuple.ninth(), is(8));
assertThat(secondTuple.tenth(), is(9));
assertThat(secondTuple.eleventh(), is(-1));
assertThat(secondTuple.twelfth(), is(11));
// Changing by supplier.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
thirdTuple = tuple.eleventh(() -> -1);
assertThat(thirdTuple, is(notNullValue()));
assertThat(thirdTuple.size(), is(tuple.size()));
assertThat(thirdTuple.first(), is(0));
assertThat(thirdTuple.second(), is(1));
assertThat(thirdTuple.third(), is(2));
assertThat(thirdTuple.fourth(), is(3));
assertThat(thirdTuple.fifth(), is(4));
assertThat(thirdTuple.sixth(), is(5));
assertThat(thirdTuple.seventh(), is(6));
assertThat(thirdTuple.eighth(), is(7));
assertThat(thirdTuple.ninth(), is(8));
assertThat(thirdTuple.tenth(), is(9));
assertThat(thirdTuple.eleventh(), is(-1));
assertThat(thirdTuple.twelfth(), is(11));
// Changing by function.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
fourthTuple = tuple.eleventh(previous -> -1);
assertThat(fourthTuple, is(notNullValue()));
assertThat(fourthTuple.size(), is(tuple.size()));
assertThat(fourthTuple.first(), is(0));
assertThat(fourthTuple.second(), is(1));
assertThat(fourthTuple.third(), is(2));
assertThat(fourthTuple.fourth(), is(3));
assertThat(fourthTuple.fifth(), is(4));
assertThat(fourthTuple.sixth(), is(5));
assertThat(fourthTuple.seventh(), is(6));
assertThat(fourthTuple.eighth(), is(7));
assertThat(fourthTuple.ninth(), is(8));
assertThat(fourthTuple.tenth(), is(9));
assertThat(fourthTuple.eleventh(), is(-1));
assertThat(fourthTuple.twelfth(), is(11));
}
@Test
public void changingTwelfthElementByAccessor() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
// Changing by value.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
secondTuple = tuple.twelfth(-1);
assertThat(secondTuple, is(notNullValue()));
assertThat(secondTuple.size(), is(tuple.size()));
assertThat(secondTuple.first(), is(0));
assertThat(secondTuple.second(), is(1));
assertThat(secondTuple.third(), is(2));
assertThat(secondTuple.fourth(), is(3));
assertThat(secondTuple.fifth(), is(4));
assertThat(secondTuple.sixth(), is(5));
assertThat(secondTuple.seventh(), is(6));
assertThat(secondTuple.eighth(), is(7));
assertThat(secondTuple.ninth(), is(8));
assertThat(secondTuple.tenth(), is(9));
assertThat(secondTuple.eleventh(), is(10));
assertThat(secondTuple.twelfth(), is(-1));
// Changing by supplier.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
thirdTuple = tuple.twelfth(() -> -1);
assertThat(thirdTuple, is(notNullValue()));
assertThat(thirdTuple.size(), is(tuple.size()));
assertThat(thirdTuple.first(), is(0));
assertThat(thirdTuple.second(), is(1));
assertThat(thirdTuple.third(), is(2));
assertThat(thirdTuple.fourth(), is(3));
assertThat(thirdTuple.fifth(), is(4));
assertThat(thirdTuple.sixth(), is(5));
assertThat(thirdTuple.seventh(), is(6));
assertThat(thirdTuple.eighth(), is(7));
assertThat(thirdTuple.ninth(), is(8));
assertThat(thirdTuple.tenth(), is(9));
assertThat(thirdTuple.eleventh(), is(10));
assertThat(thirdTuple.twelfth(), is(-1));
// Changing by function.
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
fourthTuple = tuple.twelfth(previous -> -1);
assertThat(fourthTuple, is(notNullValue()));
assertThat(fourthTuple.size(), is(tuple.size()));
assertThat(fourthTuple.first(), is(0));
assertThat(fourthTuple.second(), is(1));
assertThat(fourthTuple.third(), is(2));
assertThat(fourthTuple.fourth(), is(3));
assertThat(fourthTuple.fifth(), is(4));
assertThat(fourthTuple.sixth(), is(5));
assertThat(fourthTuple.seventh(), is(6));
assertThat(fourthTuple.eighth(), is(7));
assertThat(fourthTuple.ninth(), is(8));
assertThat(fourthTuple.tenth(), is(9));
assertThat(fourthTuple.eleventh(), is(10));
assertThat(fourthTuple.twelfth(), is(-1));
}
@Test
public void droppingByIndex() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
for (int i = 0; i < 12; i++) {
Tuple<?> other = tuple.drop(i);
assertThat(other, is(notNullValue()));
assertThat(other.size(), is(11));
for (int j = 0; j < 12; j++) {
if (j == i) {
continue;
}
assertThat(other.get(j < i ? j : j - 1), is(tuple.get(j)));
}
}
}
@Test
public void droppingFirstElementByAccessor() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
ElevenTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
other = tuple.dropFirst();
assertThat(other, is(notNullValue()));
assertThat(other.size(), is(11));
assertThat(other.first(), is(tuple.second()));
assertThat(other.second(), is(tuple.third()));
assertThat(other.third(), is(tuple.fourth()));
assertThat(other.fourth(), is(tuple.fifth()));
assertThat(other.fifth(), is(tuple.sixth()));
assertThat(other.sixth(), is(tuple.seventh()));
assertThat(other.seventh(), is(tuple.eighth()));
assertThat(other.eighth(), is(tuple.ninth()));
assertThat(other.ninth(), is(tuple.tenth()));
assertThat(other.tenth(), is(tuple.eleventh()));
assertThat(other.eleventh(), is(tuple.twelfth()));
}
@Test
public void droppingSecondElementByAccessor() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
ElevenTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
other = tuple.dropSecond();
assertThat(other, is(notNullValue()));
assertThat(other.size(), is(11));
assertThat(other.first(), is(tuple.first()));
assertThat(other.second(), is(tuple.third()));
assertThat(other.third(), is(tuple.fourth()));
assertThat(other.fourth(), is(tuple.fifth()));
assertThat(other.fifth(), is(tuple.sixth()));
assertThat(other.sixth(), is(tuple.seventh()));
assertThat(other.seventh(), is(tuple.eighth()));
assertThat(other.eighth(), is(tuple.ninth()));
assertThat(other.ninth(), is(tuple.tenth()));
assertThat(other.tenth(), is(tuple.eleventh()));
assertThat(other.eleventh(), is(tuple.twelfth()));
}
@Test
public void droppingThirdElementByAccessor() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
ElevenTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
other = tuple.dropThird();
assertThat(other, is(notNullValue()));
assertThat(other.size(), is(11));
assertThat(other.first(), is(tuple.first()));
assertThat(other.second(), is(tuple.second()));
assertThat(other.third(), is(tuple.fourth()));
assertThat(other.fourth(), is(tuple.fifth()));
assertThat(other.fifth(), is(tuple.sixth()));
assertThat(other.sixth(), is(tuple.seventh()));
assertThat(other.seventh(), is(tuple.eighth()));
assertThat(other.eighth(), is(tuple.ninth()));
assertThat(other.ninth(), is(tuple.tenth()));
assertThat(other.tenth(), is(tuple.eleventh()));
assertThat(other.eleventh(), is(tuple.twelfth()));
}
@Test
public void droppingFourthElementByAccessor() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
ElevenTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
other = tuple.dropFourth();
assertThat(other, is(notNullValue()));
assertThat(other.size(), is(11));
assertThat(other.first(), is(tuple.first()));
assertThat(other.second(), is(tuple.second()));
assertThat(other.third(), is(tuple.third()));
assertThat(other.fourth(), is(tuple.fifth()));
assertThat(other.fifth(), is(tuple.sixth()));
assertThat(other.sixth(), is(tuple.seventh()));
assertThat(other.seventh(), is(tuple.eighth()));
assertThat(other.eighth(), is(tuple.ninth()));
assertThat(other.ninth(), is(tuple.tenth()));
assertThat(other.tenth(), is(tuple.eleventh()));
assertThat(other.eleventh(), is(tuple.twelfth()));
}
@Test
public void droppingFifthElementByAccessor() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
ElevenTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
other = tuple.dropFifth();
assertThat(other, is(notNullValue()));
assertThat(other.size(), is(11));
assertThat(other.first(), is(tuple.first()));
assertThat(other.second(), is(tuple.second()));
assertThat(other.third(), is(tuple.third()));
assertThat(other.fourth(), is(tuple.fourth()));
assertThat(other.fifth(), is(tuple.sixth()));
assertThat(other.sixth(), is(tuple.seventh()));
assertThat(other.seventh(), is(tuple.eighth()));
assertThat(other.eighth(), is(tuple.ninth()));
assertThat(other.ninth(), is(tuple.tenth()));
assertThat(other.tenth(), is(tuple.eleventh()));
assertThat(other.eleventh(), is(tuple.twelfth()));
}
@Test
public void droppingSixthElementByAccessor() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
ElevenTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
other = tuple.dropSixth();
assertThat(other, is(notNullValue()));
assertThat(other.size(), is(11));
assertThat(other.first(), is(tuple.first()));
assertThat(other.second(), is(tuple.second()));
assertThat(other.third(), is(tuple.third()));
assertThat(other.fourth(), is(tuple.fourth()));
assertThat(other.fifth(), is(tuple.fifth()));
assertThat(other.sixth(), is(tuple.seventh()));
assertThat(other.seventh(), is(tuple.eighth()));
assertThat(other.eighth(), is(tuple.ninth()));
assertThat(other.ninth(), is(tuple.tenth()));
assertThat(other.tenth(), is(tuple.eleventh()));
assertThat(other.eleventh(), is(tuple.twelfth()));
}
@Test
public void droppingSeventhElementByAccessor() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
ElevenTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
other = tuple.dropSeventh();
assertThat(other, is(notNullValue()));
assertThat(other.size(), is(11));
assertThat(other.first(), is(tuple.first()));
assertThat(other.second(), is(tuple.second()));
assertThat(other.third(), is(tuple.third()));
assertThat(other.fourth(), is(tuple.fourth()));
assertThat(other.fifth(), is(tuple.fifth()));
assertThat(other.sixth(), is(tuple.sixth()));
assertThat(other.seventh(), is(tuple.eighth()));
assertThat(other.eighth(), is(tuple.ninth()));
assertThat(other.ninth(), is(tuple.tenth()));
assertThat(other.tenth(), is(tuple.eleventh()));
assertThat(other.eleventh(), is(tuple.twelfth()));
}
@Test
public void droppingEighthElementByAccessor() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
ElevenTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
other = tuple.dropEighth();
assertThat(other, is(notNullValue()));
assertThat(other.size(), is(11));
assertThat(other.first(), is(tuple.first()));
assertThat(other.second(), is(tuple.second()));
assertThat(other.third(), is(tuple.third()));
assertThat(other.fourth(), is(tuple.fourth()));
assertThat(other.fifth(), is(tuple.fifth()));
assertThat(other.sixth(), is(tuple.sixth()));
assertThat(other.seventh(), is(tuple.seventh()));
assertThat(other.eighth(), is(tuple.ninth()));
assertThat(other.ninth(), is(tuple.tenth()));
assertThat(other.tenth(), is(tuple.eleventh()));
assertThat(other.eleventh(), is(tuple.twelfth()));
}
@Test
public void droppingNinthElementByAccessor() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
ElevenTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
other = tuple.dropNinth();
assertThat(other, is(notNullValue()));
assertThat(other.size(), is(11));
assertThat(other.first(), is(tuple.first()));
assertThat(other.second(), is(tuple.second()));
assertThat(other.third(), is(tuple.third()));
assertThat(other.fourth(), is(tuple.fourth()));
assertThat(other.fifth(), is(tuple.fifth()));
assertThat(other.sixth(), is(tuple.sixth()));
assertThat(other.seventh(), is(tuple.seventh()));
assertThat(other.eighth(), is(tuple.eighth()));
assertThat(other.ninth(), is(tuple.tenth()));
assertThat(other.tenth(), is(tuple.eleventh()));
assertThat(other.eleventh(), is(tuple.twelfth()));
}
@Test
public void droppingTenthElementByAccessor() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
ElevenTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
other = tuple.dropTenth();
assertThat(other, is(notNullValue()));
assertThat(other.size(), is(11));
assertThat(other.first(), is(tuple.first()));
assertThat(other.second(), is(tuple.second()));
assertThat(other.third(), is(tuple.third()));
assertThat(other.fourth(), is(tuple.fourth()));
assertThat(other.fifth(), is(tuple.fifth()));
assertThat(other.sixth(), is(tuple.sixth()));
assertThat(other.seventh(), is(tuple.seventh()));
assertThat(other.eighth(), is(tuple.eighth()));
assertThat(other.ninth(), is(tuple.ninth()));
assertThat(other.tenth(), is(tuple.eleventh()));
assertThat(other.eleventh(), is(tuple.twelfth()));
}
@Test
public void droppingEleventhElementByAccessor() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
ElevenTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
other = tuple.dropEleventh();
assertThat(other, is(notNullValue()));
assertThat(other.size(), is(11));
assertThat(other.first(), is(tuple.first()));
assertThat(other.second(), is(tuple.second()));
assertThat(other.third(), is(tuple.third()));
assertThat(other.fourth(), is(tuple.fourth()));
assertThat(other.fifth(), is(tuple.fifth()));
assertThat(other.sixth(), is(tuple.sixth()));
assertThat(other.seventh(), is(tuple.seventh()));
assertThat(other.eighth(), is(tuple.eighth()));
assertThat(other.ninth(), is(tuple.ninth()));
assertThat(other.tenth(), is(tuple.tenth()));
assertThat(other.eleventh(), is(tuple.twelfth()));
}
@Test
public void droppingTwelfthElementByAccessor() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
ElevenTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
other = tuple.dropTwelfth();
assertThat(other, is(notNullValue()));
assertThat(other.size(), is(11));
assertThat(other.first(), is(tuple.first()));
assertThat(other.second(), is(tuple.second()));
assertThat(other.third(), is(tuple.third()));
assertThat(other.fourth(), is(tuple.fourth()));
assertThat(other.fifth(), is(tuple.fifth()));
assertThat(other.sixth(), is(tuple.sixth()));
assertThat(other.seventh(), is(tuple.seventh()));
assertThat(other.eighth(), is(tuple.eighth()));
assertThat(other.ninth(), is(tuple.ninth()));
assertThat(other.tenth(), is(tuple.tenth()));
assertThat(other.eleventh(), is(tuple.eleventh()));
}
@Test
public void clearingTuple() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
Tuple<?> other = tuple.clear();
assertThat(other, is(notNullValue()));
assertThat(other.size(), is(0));
}
@Test
public void streamingTuple() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
List<Object> items = tuple.stream().collect(toList());
assertThat(items, is(hasSize(12)));
assertThat(items, is(contains(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)));
}
@Test
public void gettingTupleAsList() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
List<Object> items = tuple.asList();
assertThat(items, is(hasSize(12)));
assertThat(items, is(contains(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)));
}
@Test
public void checkingPredicateByIndex() {
TwelveTuple<
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = TwelveTuple.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
for (int i = 0; i < 12; i++) {
assertThat(tuple.check(i, x -> x % 2 == 0), is(i % 2 == 0));
}
}
@Test
public void checkingPredicateByAccessor() {
TwelveTuple<
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = TwelveTuple.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
assertThat(tuple.checkFirst(x -> x % 2 == 0), is(true));
assertThat(tuple.checkSecond(x -> x % 2 == 0), is(false));
assertThat(tuple.checkThird(x -> x % 2 == 0), is(true));
assertThat(tuple.checkFourth(x -> x % 2 == 0), is(false));
assertThat(tuple.checkFifth(x -> x % 2 == 0), is(true));
assertThat(tuple.checkSixth(x -> x % 2 == 0), is(false));
assertThat(tuple.checkSeventh(x -> x % 2 == 0), is(true));
assertThat(tuple.checkEighth(x -> x % 2 == 0), is(false));
assertThat(tuple.checkNinth(x -> x % 2 == 0), is(true));
assertThat(tuple.checkTenth(x -> x % 2 == 0), is(false));
assertThat(tuple.checkEleventh(x -> x % 2 == 0), is(true));
assertThat(tuple.checkTwelfth(x -> x % 2 == 0), is(false));
}
@Test
public void extendingByValue() {
TwelveTuple<
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = TwelveTuple.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
ThirteenOrMoreTuple<
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
secondTuple = TwelveTuple.extendWith(-1).apply(tuple);
assertThat(secondTuple, is(notNullValue()));
assertThat(secondTuple.size(), is(13));
assertThat(secondTuple.first(), is(tuple.first()));
assertThat(secondTuple.second(), is(tuple.second()));
assertThat(secondTuple.third(), is(tuple.third()));
assertThat(secondTuple.fourth(), is(tuple.fourth()));
assertThat(secondTuple.fifth(), is(tuple.fifth()));
assertThat(secondTuple.sixth(), is(tuple.sixth()));
assertThat(secondTuple.seventh(), is(tuple.seventh()));
assertThat(secondTuple.eighth(), is(tuple.eighth()));
assertThat(secondTuple.ninth(), is(tuple.ninth()));
assertThat(secondTuple.tenth(), is(tuple.tenth()));
assertThat(secondTuple.eleventh(), is(tuple.eleventh()));
assertThat(secondTuple.twelfth(), is(tuple.twelfth()));
assertThat(secondTuple.get(12), is(-1));
assertThat(secondTuple.drop(12), is(tuple));
}
@Test
public void extendingBySupplier() {
TwelveTuple<
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = TwelveTuple.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
ThirteenOrMoreTuple<
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
secondTuple = TwelveTuple.extendWith(() -> -1).apply(tuple);
assertThat(secondTuple, is(notNullValue()));
assertThat(secondTuple.size(), is(13));
assertThat(secondTuple.first(), is(tuple.first()));
assertThat(secondTuple.second(), is(tuple.second()));
assertThat(secondTuple.third(), is(tuple.third()));
assertThat(secondTuple.fourth(), is(tuple.fourth()));
assertThat(secondTuple.fifth(), is(tuple.fifth()));
assertThat(secondTuple.sixth(), is(tuple.sixth()));
assertThat(secondTuple.seventh(), is(tuple.seventh()));
assertThat(secondTuple.eighth(), is(tuple.eighth()));
assertThat(secondTuple.ninth(), is(tuple.ninth()));
assertThat(secondTuple.tenth(), is(tuple.tenth()));
assertThat(secondTuple.eleventh(), is(tuple.eleventh()));
assertThat(secondTuple.twelfth(), is(tuple.twelfth()));
assertThat(secondTuple.get(12), is(-1));
assertThat(secondTuple.drop(12), is(tuple));
}
@Test
public void extendingByFunction() {
TwelveTuple<
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = TwelveTuple.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
ThirteenOrMoreTuple<
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
secondTuple =
TwelveTuple.extendWith(
(TwelveTuple<
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
t) -> -1)
.apply(tuple);
assertThat(secondTuple, is(notNullValue()));
assertThat(secondTuple.size(), is(13));
assertThat(secondTuple.first(), is(tuple.first()));
assertThat(secondTuple.second(), is(tuple.second()));
assertThat(secondTuple.third(), is(tuple.third()));
assertThat(secondTuple.fourth(), is(tuple.fourth()));
assertThat(secondTuple.fifth(), is(tuple.fifth()));
assertThat(secondTuple.sixth(), is(tuple.sixth()));
assertThat(secondTuple.seventh(), is(tuple.seventh()));
assertThat(secondTuple.eighth(), is(tuple.eighth()));
assertThat(secondTuple.ninth(), is(tuple.ninth()));
assertThat(secondTuple.tenth(), is(tuple.tenth()));
assertThat(secondTuple.eleventh(), is(tuple.eleventh()));
assertThat(secondTuple.twelfth(), is(tuple.twelfth()));
assertThat(secondTuple.get(12), is(-1));
assertThat(secondTuple.drop(12), is(tuple));
}
@Test
public void labelingTuple() {
TwelveTuple<
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = TwelveTuple.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
LabeledTuple<Integer> other =
tuple.withLabels("e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "e10", "e11");
assertThat(other, is(notNullValue()));
assertThat(other.size(), is(12));
assertThat(
other.labels(),
is(contains("e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "e10", "e11")));
assertThat(other.get("e0"), is(tuple.get(0)));
assertThat(other.get("e1"), is(tuple.get(1)));
assertThat(other.get("e2"), is(tuple.get(2)));
assertThat(other.get("e3"), is(tuple.get(3)));
assertThat(other.get("e4"), is(tuple.get(4)));
assertThat(other.get("e5"), is(tuple.get(5)));
assertThat(other.get("e6"), is(tuple.get(6)));
assertThat(other.get("e7"), is(tuple.get(7)));
assertThat(other.get("e8"), is(tuple.get(8)));
assertThat(other.get("e9"), is(tuple.get(9)));
assertThat(other.get("e10"), is(tuple.get(10)));
assertThat(other.get("e11"), is(tuple.get(11)));
LabeledTuple<Integer> extended = other.extend(-1, "last");
assertThat(extended, is(notNullValue()));
assertThat(extended.size(), is(13));
assertThat(extended.get("last"), is(-1));
}
@Test
public void equality() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
secondTuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
assertThat(tuple, is(secondTuple));
}
@Test
public void hashCodeCalculation() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
secondTuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
assertThat(tuple.hashCode(), is(secondTuple.hashCode()));
}
@Test
public void toStringCalculation() {
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
tuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
TwelveTuple<
Object,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer,
Integer>
secondTuple = Tuple.twelve(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
assertThat(tuple.toString(), is(secondTuple.toString()));
}
}
|
package cn.com.warlock.emitter.zk;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.com.warlock.emitter.BaseUniqueIDGenerator;
import cn.com.warlock.emitter.IDGenerator;
import cn.com.warlock.emitter.zk.connection.ZooKeeperConnection;
public class SynchronizedUniqueIDGeneratorFactory {
final static Logger logger = LoggerFactory
.getLogger(SynchronizedUniqueIDGeneratorFactory.class);
final static Map<String, IDGenerator> instances = new HashMap<>();
public static synchronized IDGenerator generatorFor(ZooKeeperConnection zooKeeperConnection,
String znode) throws IOException {
if (!instances.containsKey(znode)) {
final int clusterId = ClusterID.get(zooKeeperConnection.get(), znode);
SynchronizedGeneratorIdentity generatorIdentityHolder = new SynchronizedGeneratorIdentity(
zooKeeperConnection, znode, clusterId, null);
return generatorFor(generatorIdentityHolder);
}
return instances.get(znode);
}
public static synchronized IDGenerator generatorFor(SynchronizedGeneratorIdentity synchronizedGeneratorIdentity) throws IOException {
String instanceKey = synchronizedGeneratorIdentity.getZNode();
if (!instances.containsKey(instanceKey)) {
logger.debug("Creating new instance.");
instances.putIfAbsent(instanceKey,
new BaseUniqueIDGenerator(synchronizedGeneratorIdentity));
}
return instances.get(instanceKey);
}
}
|
package seedu.address.model.pet;
import static java.util.Objects.requireNonNull;
import static seedu.address.commons.util.AppUtil.checkArgument;
import java.util.Objects;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import seedu.address.ui.DisplaySystemType;
import seedu.address.ui.list.DisplayItem;
/**
* Represents a Food Collection object in Pet Store Helper. It is used to model a collection of the same type
* of food that could exist in a pet list. (If there are 3 pets in a list, each requiring 10 units of cat food,
* a food collection of the cat food in the list will have name as catfood and amount as 30.)
* Guarantees: immutable; name is valid as declared in {@link #isValidFoodCollectionName(String)}
*/
public class FoodCollection implements DisplayItem {
public static final String MESSAGE_CONSTRAINTS = "Name and amount of food collection should both exist "
+ "and separated by a colon ':'.";
public static final String MESSAGE_NAME_CONSTRAINTS = "Food collection names should only contain alphanumeric "
+ "characters and spaces only, and it should not be blank";
public static final String MESSAGE_AMOUNT_CONSTRAINTS = "Food collection amount must be a positive integer number.";
public static final String VALIDATION_REGEX = "[^\\s].*";
private final String name;
private int amount;
private ObservableList<FoodAmountAndPet> foodAmountAndPets = FXCollections.observableArrayList();
private final ObservableList<FoodAmountAndPet> unmodifiablePets =
FXCollections.unmodifiableObservableList(foodAmountAndPets);
/**
* Constructs a {@code Food}.
*
* @param food A valid food to generate Food Collection from.
* @param pet The owner of the food being added.
*/
private FoodCollection(Food food, Pet pet) {
requireNonNull(food);
requireNonNull(pet);
checkArgument(isValidFoodCollectionName(food.foodName), MESSAGE_NAME_CONSTRAINTS);
this.name = food.foodName;
checkArgument(isValidFoodCollectionAmount(food.foodAmount), MESSAGE_AMOUNT_CONSTRAINTS);
this.amount = food.foodAmount;
this.foodAmountAndPets.add(new FoodAmountAndPet(food.foodAmount, pet));
}
/**
* Adds food into the food collection.
* @param pet The owner of the food being added
* @param other The food to be added.
* @return true if it is successfully added, which means
* the type of food has the same name as that of the food collection.
*/
public boolean addFoodToCollection(Food other, Pet pet) {
if (isSameType(other)) {
amount += other.foodAmount;
this.foodAmountAndPets.add(new FoodAmountAndPet(other.foodAmount, pet));
return true;
} else {
return false;
}
}
/**
* Generates a food collection from a given food object.
*/
public static FoodCollection generateFoodCollection(Food food, Pet pet) {
return new FoodCollection(food, pet);
}
/**
* Returns true if a given string is a valid food collection name.
*/
public static boolean isValidFoodCollectionName(String test) {
return test.matches(VALIDATION_REGEX);
}
/**
* Returns true if a given food collection amount is positive.
*/
public static boolean isValidFoodCollectionAmount(Integer test) {
return test > 0;
}
/**
* Returns true if the input food collection object is of same type as this food collection.
*/
public boolean isSameType(FoodCollection other) {
if (other == null) {
return false;
} else {
return name.equals(other.name);
}
}
/**
* Returns true if the input food object is of same type as this food collection.
*/
public boolean isSameType(Food other) {
if (other == null) {
return false;
} else {
return name.equals(other.foodName);
}
}
/**
* Returns true if the input food collection object is of same amount as this food collection.
*/
public boolean isSameAmount(FoodCollection other) {
if (other == null) {
return false;
} else {
return amount == other.amount;
}
}
/**
* Returns the name of this food collection.
*/
public String getName() {
return name;
}
/**
* Returns the amount of food in this collection.
*/
public Integer getAmount() {
return amount;
}
/**
* Returns a list of FoodAmountAndPet as an ObservableList so that it can be displayed in Ui when the user
* requires to view a breakdown of the composition of the amount of this food collection by the owners of food.
*/
public ObservableList<FoodAmountAndPet> getUnmodifiablePets() {
return unmodifiablePets;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| ((other instanceof FoodCollection) // instanceof handles nulls
&& isSameType((FoodCollection) other)
&& isSameAmount((FoodCollection) other)); // state checks
}
@Override
public int hashCode() {
return Objects.hash(amount, name);
}
/**
* Format state as text for viewing.
*/
public String toString() {
return "[" + name + "]: " + amount;
}
@Override
public DisplaySystemType getDisplaySystemType() {
return DisplaySystemType.INVENTORY;
}
}
|
/*
* Copyright 2014-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.android;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.jvm.core.HasJavaAbi;
import com.facebook.buck.jvm.core.JavaLibrary;
import com.facebook.buck.jvm.java.JavaBuckConfig;
import com.facebook.buck.jvm.java.JavaLibraryDescription;
import com.facebook.buck.jvm.java.JavaSourceJar;
import com.facebook.buck.jvm.java.JavacOptions;
import com.facebook.buck.jvm.java.JavacOptionsFactory;
import com.facebook.buck.jvm.java.toolchain.JavacOptionsProvider;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.Flavor;
import com.facebook.buck.model.Flavored;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleCreationContext;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRuleType;
import com.facebook.buck.rules.CellPathResolver;
import com.facebook.buck.rules.Description;
import com.facebook.buck.rules.HasDepsQuery;
import com.facebook.buck.rules.HasProvidedDepsQuery;
import com.facebook.buck.rules.ImplicitDepsInferringDescription;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.toolchain.ToolchainProvider;
import com.facebook.buck.util.immutables.BuckStyleImmutable;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableSet;
import java.util.Optional;
import org.immutables.value.Value;
public class AndroidLibraryDescription
implements Description<AndroidLibraryDescriptionArg>,
Flavored,
ImplicitDepsInferringDescription<
AndroidLibraryDescription.AbstractAndroidLibraryDescriptionArg> {
public static final BuildRuleType TYPE = BuildRuleType.of("android_library");
private static final Flavor DUMMY_R_DOT_JAVA_FLAVOR =
AndroidLibraryGraphEnhancer.DUMMY_R_DOT_JAVA_FLAVOR;
public enum JvmLanguage {
JAVA,
KOTLIN,
SCALA,
}
private final ToolchainProvider toolchainProvider;
private final JavaBuckConfig javaBuckConfig;
private final AndroidLibraryCompilerFactory compilerFactory;
public AndroidLibraryDescription(
ToolchainProvider toolchainProvider,
JavaBuckConfig javaBuckConfig,
AndroidLibraryCompilerFactory compilerFactory) {
this.toolchainProvider = toolchainProvider;
this.javaBuckConfig = javaBuckConfig;
this.compilerFactory = compilerFactory;
}
@Override
public Class<AndroidLibraryDescriptionArg> getConstructorArgType() {
return AndroidLibraryDescriptionArg.class;
}
@Override
public BuildRule createBuildRule(
BuildRuleCreationContext context,
BuildTarget buildTarget,
BuildRuleParams params,
AndroidLibraryDescriptionArg args) {
ProjectFilesystem projectFilesystem = context.getProjectFilesystem();
if (buildTarget.getFlavors().contains(JavaLibrary.SRC_JAR)) {
return new JavaSourceJar(
buildTarget, projectFilesystem, params, args.getSrcs(), args.getMavenCoords());
}
if (args.isSkipNonUnionRDotJava()) {
Preconditions.checkArgument(
args.getResourceUnionPackage().isPresent(),
"union_package should be specified if skip_non_union_r_dot_java is set");
}
boolean hasDummyRDotJavaFlavor = buildTarget.getFlavors().contains(DUMMY_R_DOT_JAVA_FLAVOR);
JavacOptions javacOptions =
JavacOptionsFactory.create(
toolchainProvider
.getByName(JavacOptionsProvider.DEFAULT_NAME, JavacOptionsProvider.class)
.getJavacOptions(),
buildTarget,
projectFilesystem,
context.getBuildRuleResolver(),
args);
AndroidLibrary.Builder androidLibraryBuilder =
AndroidLibrary.builder(
buildTarget,
projectFilesystem,
params,
context.getBuildRuleResolver(),
context.getCellPathResolver(),
javaBuckConfig,
javacOptions,
args,
compilerFactory.getCompiler(args.getLanguage().orElse(JvmLanguage.JAVA)));
if (hasDummyRDotJavaFlavor) {
return androidLibraryBuilder.buildDummyRDotJava();
} else if (HasJavaAbi.isAbiTarget(buildTarget)) {
return androidLibraryBuilder.buildAbi();
}
return androidLibraryBuilder.build();
}
@Override
public boolean hasFlavors(ImmutableSet<Flavor> flavors) {
return flavors.isEmpty()
|| flavors.equals(ImmutableSet.of(JavaLibrary.SRC_JAR))
|| flavors.equals(ImmutableSet.of(DUMMY_R_DOT_JAVA_FLAVOR))
|| flavors.equals(ImmutableSet.of(HasJavaAbi.CLASS_ABI_FLAVOR))
|| flavors.equals(ImmutableSet.of(HasJavaAbi.SOURCE_ABI_FLAVOR))
|| flavors.equals(ImmutableSet.of(HasJavaAbi.SOURCE_ONLY_ABI_FLAVOR))
|| flavors.equals(ImmutableSet.of(HasJavaAbi.VERIFIED_SOURCE_ABI_FLAVOR));
}
@Override
public void findDepsForTargetFromConstructorArgs(
BuildTarget buildTarget,
CellPathResolver cellRoots,
AbstractAndroidLibraryDescriptionArg constructorArg,
ImmutableCollection.Builder<BuildTarget> extraDepsBuilder,
ImmutableCollection.Builder<BuildTarget> targetGraphOnlyDepsBuilder) {
compilerFactory
.getCompiler(constructorArg.getLanguage().orElse(JvmLanguage.JAVA))
.addTargetDeps(extraDepsBuilder, targetGraphOnlyDepsBuilder);
}
public interface CoreArg
extends JavaLibraryDescription.CoreArg,
AndroidKotlinCoreArg,
HasDepsQuery,
HasProvidedDepsQuery {
Optional<SourcePath> getManifest();
Optional<String> getResourceUnionPackage();
@Value.Default
default boolean isSkipNonUnionRDotJava() {
return false;
}
Optional<String> getFinalRName();
}
@BuckStyleImmutable
@Value.Immutable(copy = true)
interface AbstractAndroidLibraryDescriptionArg extends CoreArg {}
}
|
package com.example.alain.lbstest;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
public LocationClient mLocationClient;
private TextView positionText;
private MapView mapView;
private BaiduMap baiduMap;
private boolean isFirstLocate = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLocationClient = new LocationClient(getApplicationContext());
mLocationClient.registerLocationListener(new MyLocationListener());
SDKInitializer.initialize(getApplicationContext());
setContentView(R.layout.activity_main);
mapView = (MapView) findViewById(R.id.bmapView);
baiduMap = mapView.getMap();
baiduMap.setMyLocationEnabled(true);
positionText = (TextView) findViewById(R.id.position_text_view);
List<String> permissionList = new ArrayList<>();
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
permissionList.add(Manifest.permission.READ_PHONE_STATE);
}
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (!permissionList.isEmpty()) {
String [] permissions = permissionList.toArray(new String[permissionList.size()]);
ActivityCompat.requestPermissions(MainActivity.this, permissions, 1);
} else {
requestLocation();
}
}
private void navigateTo(BDLocation location) {
if (isFirstLocate) {
Toast.makeText(this, "nav to " + location.getAddrStr(), Toast.LENGTH_SHORT).show();
LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(ll);
baiduMap.animateMapStatus(update);
update = MapStatusUpdateFactory.zoomTo(16f);
baiduMap.animateMapStatus(update);
isFirstLocate = false;
}
MyLocationData.Builder locationBuilder = new MyLocationData.
Builder();
locationBuilder.latitude(location.getLatitude());
locationBuilder.longitude(location.getLongitude());
MyLocationData locationData = locationBuilder.build();
baiduMap.setMyLocationData(locationData);
}
private void requestLocation() {
initLocation();
mLocationClient.start();
}
private void initLocation(){
LocationClientOption option = new LocationClientOption();
option.setScanSpan(5000);
option.setIsNeedAddress(true);
// option.setLocationMode(LocationClientOption.LocationMode.Device_Sensors);
mLocationClient.setLocOption(option);
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
mLocationClient.stop();
mapView.onDestroy();
baiduMap.setMyLocationEnabled(false);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults.length > 0) {
for (int result : grantResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "必须同意所有权限才能使用本程序", Toast.LENGTH_SHORT).show();
finish();
return;
}
}
requestLocation();
} else {
Toast.makeText(this, "发生未知错误", Toast.LENGTH_SHORT).show();
finish();
}
break;
default:
}
}
public class MyLocationListener implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
StringBuilder currentPosition = new StringBuilder();
currentPosition.append("纬度:").append(location.getLatitude()).append("\n");
currentPosition.append("经线:").append(location.getLongitude()).append("\n");
currentPosition.append("国家:").append(location.getCountry()).append("\n");
currentPosition.append("省:").append(location.getProvince()).append("\n");
currentPosition.append("市:").append(location.getCity()).append("\n");
currentPosition.append("区:").append(location.getDistrict()).append("\n");
currentPosition.append("街道:").append(location.getStreet()).append("\n");
currentPosition.append("定位方式:");
if (location.getLocType() == BDLocation.TypeGpsLocation) {
currentPosition.append("GPS");
} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
currentPosition.append("网络");
}
positionText.setText(currentPosition);
if (location.getLocType() == BDLocation.TypeGpsLocation
|| location.getLocType() == BDLocation.TypeNetWorkLocation) {
navigateTo(location);
}
}
}
}
|
/*
* Copyright 2020 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.optaplanner.core.impl.score.stream.drools.tri;
import static java.util.Objects.requireNonNull;
import java.util.function.Function;
import org.drools.model.Variable;
import org.optaplanner.core.api.function.TriFunction;
import org.optaplanner.core.api.score.stream.tri.TriConstraintCollector;
import org.optaplanner.core.impl.score.stream.drools.common.DroolsAbstractGroupBy;
import org.optaplanner.core.impl.score.stream.drools.common.DroolsAbstractGroupByAccumulator;
import org.optaplanner.core.impl.score.stream.drools.common.TriTuple;
import org.optaplanner.core.impl.score.stream.tri.DefaultTriConstraintCollector;
public class DroolsTriToBiGroupByAccumulator<A, B, C, NewA, NewB>
extends DroolsAbstractGroupByAccumulator<TriTuple<A, B, C>> {
private final TriFunction<A, B, C, NewA> groupKeyMapping;
private final TriConstraintCollector<A, B, C, ?, NewB> collector;
private final Variable<A> aVariable;
private final Variable<B> bVariable;
private final Variable<C> cVariable;
public DroolsTriToBiGroupByAccumulator(TriFunction<A, B, C, NewA> groupKeyMapping,
TriConstraintCollector<A, B, C, ?, NewB> collector, Variable<A> aVariable, Variable<B> bVariable,
Variable<C> cVariable) {
this.groupKeyMapping = requireNonNull(groupKeyMapping);
// Null collector means we're only re-grouping without using a collector.
this.collector = collector != null ? collector : DefaultTriConstraintCollector.noop();
this.aVariable = requireNonNull(aVariable);
this.bVariable = requireNonNull(bVariable);
this.cVariable = requireNonNull(cVariable);
}
@Override
protected DroolsAbstractGroupBy<TriTuple<A, B, C>, ?> newContext() {
return new DroolsTriToBiGroupBy<>(groupKeyMapping, collector);
}
@Override
protected <X> TriTuple<A, B, C> createInput(Function<Variable<X>, X> valueFinder) {
final A a = materialize(aVariable, valueFinder);
final B b = materialize(bVariable, valueFinder);
final C c = materialize(cVariable, valueFinder);
return new TriTuple<>(a, b, c);
}
}
|
/*
* Copyright Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags and
* the COPYRIGHT.txt file distributed with this work.
*
* 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.teiid.core.types;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.sql.Blob;
/**
* Base type for geography and geometry.
*
* Simply a blob reference with an srid.
*/
public abstract class AbstractGeospatialType extends BlobType {
private int srid;
private Reference<?> geoCache;
public AbstractGeospatialType() {
}
public AbstractGeospatialType(Blob blob) {
super(blob);
}
public AbstractGeospatialType(byte[] bytes) {
super(bytes);
}
public int getSrid() {
return srid;
}
public void setSrid(int srid) {
this.srid = srid;
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
super.writeExternal(out);
out.writeInt(srid);
}
@Override
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
super.readExternal(in);
srid = in.readInt();
}
/**
* Get the Object model representation of the geospatial value
* @return
*/
public synchronized Object getGeoCache() {
if (geoCache == null) {
return null;
}
Object result = geoCache.get();
if (result != null && geoCache instanceof WeakReference) {
geoCache = new SoftReference(result);
}
return result;
}
/**
* Set the Object model representation of the geospatial value
* @return
*/
public synchronized void setGeoCache(Object objectReference) {
if (objectReference == null) {
this.geoCache = null;
} else {
this.geoCache = new WeakReference(objectReference);
}
}
public synchronized void copyTo(AbstractGeospatialType geo) {
geo.setGeoCache(geoCache==null?null:geoCache.get());
geo.setSrid(srid);
geo.setReference(this.reference);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.