hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
a8658cbda8e3f478aba5daaa48a14babd535dd4e
8,099
/** * Copyright (C) 2014 OpenTravel Alliance (info@opentravel.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opentravel.schemacompiler.codegen.swagger.model; import org.opentravel.schemacompiler.codegen.json.model.JsonModelObject; import org.opentravel.schemacompiler.codegen.json.model.JsonSchemaNamedReference; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import java.util.ArrayList; import java.util.List; /** * Class that defines the meta-model for a Swagger document. */ public class SwaggerDocument implements JsonModelObject { public static final String SWAGGER_SPEC_V2 = "2.0"; private String specVersion = SWAGGER_SPEC_V2; private SwaggerOtmResource otmResource; private SwaggerInfo info; private String host; private String basePath; private List<SwaggerScheme> schemes = new ArrayList<>(); private List<String> consumes = new ArrayList<>(); private List<String> produces = new ArrayList<>(); private List<SwaggerPathItem> pathItems = new ArrayList<>(); private List<JsonSchemaNamedReference> definitions = new ArrayList<>(); private List<SwaggerParameter> globalParameters = new ArrayList<>(); private List<SwaggerSecurityScheme> securitySchemes = new ArrayList<>(); /** * Returns the value of the 'specVersion' field. * * @return String */ public String getSpecVersion() { return specVersion; } /** * Assigns the value of the 'specVersion' field. * * @param specVersion the field value to assign */ public void setSpecVersion(String specVersion) { this.specVersion = specVersion; } /** * Returns the value of the 'otmResource' field. * * @return SwaggerOtmResource */ public SwaggerOtmResource getOtmResource() { return otmResource; } /** * Assigns the value of the 'otmResource' field. * * @param otmResource the field value to assign */ public void setOtmResource(SwaggerOtmResource otmResource) { this.otmResource = otmResource; } /** * Returns the value of the 'info' field. * * @return SwaggerInfo */ public SwaggerInfo getInfo() { return info; } /** * Assigns the value of the 'info' field. * * @param info the field value to assign */ public void setInfo(SwaggerInfo info) { this.info = info; } /** * Returns the value of the 'host' field. * * @return String */ public String getHost() { return host; } /** * Assigns the value of the 'host' field. * * @param host the field value to assign */ public void setHost(String host) { this.host = host; } /** * Returns the value of the 'basePath' field. * * @return String */ public String getBasePath() { return basePath; } /** * Assigns the value of the 'basePath' field. * * @param basePath the field value to assign */ public void setBasePath(String basePath) { this.basePath = basePath; } /** * Returns the value of the 'schemes' field. * * @return List&lt;SwaggerScheme&gt; */ public List<SwaggerScheme> getSchemes() { return schemes; } /** * Returns the value of the 'consumes' field. * * @return List&lt;String&gt; */ public List<String> getConsumes() { return consumes; } /** * Returns the value of the 'produces' field. * * @return List&lt;String&gt; */ public List<String> getProduces() { return produces; } /** * Returns the value of the 'pathItems' field. * * @return List&lt;SwaggerPathItem&gt; */ public List<SwaggerPathItem> getPathItems() { return pathItems; } /** * Returns the value of the 'definitions' field. * * @return List&lt;JsonSchemaNamedReference&gt; */ public List<JsonSchemaNamedReference> getDefinitions() { return definitions; } /** * Returns the value of the 'globalParameters' field. * * @return List&lt;SwaggerParameter&gt; */ public List<SwaggerParameter> getGlobalParameters() { return globalParameters; } /** * Returns the value of the 'securitySchemes' field. * * @return List&lt;SwaggerSecurityScheme&gt; */ public List<SwaggerSecurityScheme> getSecuritySchemes() { return securitySchemes; } /** * Returns the value of the 'swaggerSpecV2' field. * * @return String */ public static String getSwaggerSpecV2() { return SWAGGER_SPEC_V2; } /** * @see org.opentravel.schemacompiler.codegen.json.model.JsonModelObject#toJson() */ public JsonObject toJson() { JsonObject pathsJson = new JsonObject(); JsonObject json = new JsonObject(); addProperty( json, "swagger", specVersion ); addJsonProperty( json, "x-otm-resource", otmResource ); addJsonProperty( json, "info", (info != null) ? info : new SwaggerInfo() ); addProperty( json, "host", host ); addProperty( json, "basePath", basePath ); if (!schemes.isEmpty()) { JsonArray jsonArray = new JsonArray(); for (SwaggerScheme value : schemes) { if (value != null) { jsonArray.add( value.getDisplayValue() ); } } json.add( "schemes", jsonArray ); } addProperty( json, "consumes", consumes ); addProperty( json, "produces", produces ); for (SwaggerPathItem pathItem : pathItems) { pathsJson.add( pathItem.getPathTemplate(), pathItem.toJson() ); } json.add( "paths", pathsJson ); if (!definitions.isEmpty()) { JsonObject defsJson = new JsonObject(); addJsonProperties( defsJson, definitions ); json.add( "definitions", defsJson ); } if (!globalParameters.isEmpty()) { JsonObject paramsJson = new JsonObject(); addJsonProperties( paramsJson, globalParameters ); json.add( "parameters", paramsJson ); } securitySchemesToJson( json ); return json; } /** * Adds information for each known security schema as properties of the given <code>JsonObject</code>. * * @param json the JSON object being populated */ private void securitySchemesToJson(JsonObject json) { if (!securitySchemes.isEmpty()) { JsonObject securityDefsJson = new JsonObject(); JsonArray securityReqsJson = new JsonArray(); for (SwaggerSecurityScheme securityScheme : securitySchemes) { JsonObject securityReqirement = new JsonObject(); JsonArray scopeNames = new JsonArray(); if (securityScheme.getType() == SwaggerSecurityType.OAUTH2) { securityScheme.getScopes().forEach( s -> scopeNames.add( s.getName() ) ); } securityReqirement.add( securityScheme.getName(), scopeNames ); securityReqsJson.add( securityReqirement ); securityDefsJson.add( securityScheme.getName(), securityScheme.toJson() ); } json.add( "securityDefinitions", securityDefsJson ); json.add( "security", securityReqsJson ); } } }
28.219512
106
0.613533
3c1131341fd71a640d78b031597a9df354d6686e
972
package testsupport.traits; import com.jnape.palatable.lambda.functions.Fn1; import com.jnape.palatable.traitor.traits.Trait; import java.util.concurrent.CountDownLatch; import static com.jnape.palatable.lambda.functions.builtin.fn1.Repeat.repeat; import static java.util.concurrent.TimeUnit.SECONDS; import static org.junit.Assert.fail; public class InfiniteIterableSupport implements Trait<Fn1<Iterable<?>, Iterable<?>>> { @Override public void test(Fn1<Iterable<?>, Iterable<?>> testSubject) { CountDownLatch latch = new CountDownLatch(1); new Thread(() -> { testSubject.apply(repeat(0)).iterator().next(); latch.countDown(); }).start(); try { if (!latch.await(1, SECONDS)) fail("Termination when given an infinite iterable could not be proven in time"); } catch (InterruptedException e) { throw new AssertionError("interrupted", e); } } }
33.517241
96
0.670782
77183306d45ac3c0496eb2b1afcc9f50ca2f511d
455
package de.plushnikov.intellij.plugin.action.delombok; import com.intellij.openapi.application.ApplicationManager; import de.plushnikov.intellij.plugin.processor.clazz.EqualsAndHashCodeProcessor; public class DelombokEqualsAndHashCodeAction extends AbstractDelombokAction { @Override protected DelombokHandler createHandler() { return new DelombokHandler(ApplicationManager.getApplication().getService(EqualsAndHashCodeProcessor.class)); } }
35
113
0.846154
c69bbaff6e9e46b7670be2e169d9d1e9332376ca
296
package br.com.ufc.quixada.dspersist.schoolmanagement.dto.student.searchOptions; import java.util.List; import br.com.ufc.quixada.dspersist.schoolmanagement.models.StudentCourse; public interface IFindNameOfStudentWithCourses { String getName(); List<StudentCourse> getStudentCourses(); }
26.909091
80
0.824324
c8c36c8216b031f6fd69ace80800073a763d6ad6
146
package com.donne.designPattern.abstractFactory; public interface HumanFactory { Human createYellowHuman(); Human createBlackHuman(); }
18.25
48
0.773973
5513f822ea253e6d3060a87f450b44486cc578ae
749
package com.freshchat.flutter_freshchat_example; import android.os.Bundle; import io.flutter.app.FlutterActivity; import io.flutter.plugins.GeneratedPluginRegistrant; public class MainActivity extends FlutterActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); GeneratedPluginRegistrant.registerWith(this); // registering for receiving new chat messages NewMessagesBCReceiver messagesBCReceiver = new NewMessagesBCReceiver(); IntentFilter intentFilter = new IntentFilter(Freshchat.FRESHCHAT_UNREAD_MESSAGE_COUNT_CHANGED); getLocalBroadcastManager(getApplicationContext()).registerReceiver(messagesBCReceiver, intentFilter); } }
37.45
109
0.791722
20ea4a99456e871dbe761937bd9907da287868ab
2,611
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Copyright @ 2015 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.java.sip.communicator.impl.protocol.sip.xcap.model.presrules; /** * The Presence Rules sub-handling element. Specifies the subscription * authorization decision that the server should make. * <p/> * Compliant with rfc5025. * * @author Grigorii Balutsel */ public enum SubHandlingType { /** * This action tells the server to reject the subscription, placing it in * the "terminated" state. */ Block("block"), /** * This action tells the server to place the subscription in the "pending" * state, and await input from the presentity to determine how to proceed. */ Confirm("confirm"), /** * This action tells the server to place the subscription into the "active" * state, and to produce a presence document that indicates that the * presentity is unavailable. */ PoliteBlock("polite-block"), /** * This action tells the server to place the subscription into the "active" * state. */ Allow("allow"); /** * Current enum value. */ private final String value; /** * Creates enum with the specified value. * * @param value the value to set. */ SubHandlingType(String value) { this.value = value; } /** * Gets the value. * * @return the value */ public String value() { return value; } /** * Creates enum from its value. * * @param value the enum's value. * @return created enum. */ public static SubHandlingType fromString(String value) { if (value != null) { for (SubHandlingType subHandling : SubHandlingType.values()) { if (value.equalsIgnoreCase(subHandling.value())) { return subHandling; } } return null; } return null; } }
26.373737
79
0.617005
72a2ea0bfae1c4f06aa8eac89392f7645c883eec
1,024
package com.epicpay.epic_gateway_sdk.models; import com.google.gson.annotations.SerializedName; /** * BankAccount */ public class BankAccount { @SerializedName("account_type") public String accountType; @SerializedName("routing_number") public String routingNumber; @SerializedName("account_number") public String accountNumber; @SerializedName("account_holder_name") public String accountHolderName; public BankAccount accountType(String account_type) { this.accountType = account_type; return this; } public BankAccount routingNumber(String routingNumber) { this.routingNumber = routingNumber; return this; } public BankAccount accountNumber(String accountNumber) { this.accountNumber = accountNumber; return this; } public BankAccount accountHolderName(String accountHolderName) { this.accountHolderName = accountHolderName; return this; } }
26.25641
69
0.682617
6503b0260e847ddd0de702d4cc0e5f57e5375e21
13,948
package com.udacity.demur.popularmovies; import android.annotation.SuppressLint; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; import android.os.Parcelable; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityOptionsCompat; import androidx.core.util.Pair; import androidx.databinding.DataBindingUtil; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProviders; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.google.gson.Gson; import com.udacity.demur.popularmovies.adapter.MoviesAdapter; import com.udacity.demur.popularmovies.database.LikedEntryJsonAndPoster; import com.udacity.demur.popularmovies.databinding.ActivityMainBinding; import com.udacity.demur.popularmovies.model.Movie; import com.udacity.demur.popularmovies.model.MovieSet; import com.udacity.demur.popularmovies.service.RecyclerViewStateHelper; import com.udacity.demur.popularmovies.service.RetrofitClient; import com.udacity.demur.popularmovies.service.TMDbClient; import com.udacity.demur.popularmovies.viewmodel.LikedViewModel; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import retrofit2.Call; import retrofit2.Callback; public class MainActivity extends AppCompatActivity implements MoviesAdapter.MoviesAdapterOnClickHandler { private static final String TAG = MainActivity.class.getSimpleName(); ActivityMainBinding mBinding; private final String LAYOUT_MANAGER_STATE_KEY = "layout_manager_state"; private final String MOVIE_SET_KEY = "movie_set"; public static final String SHARED_PREFS_NAME = "Settings"; public static final String SHARED_PREFS_SORT_MODE_KEY = "sort_mode"; public static final String EXTRA_MOVIE_KEY = "movie"; private Parcelable mLayoutManagerState; private MovieSet mMovieSet; private RecyclerView.LayoutManager mLayoutManager; private MoviesAdapter mMovieAdapter; private SharedPreferences mSharedPrefs; private TMDbClient mClient; private static int mGridSpanCount = 3; private LikedViewModel mLikedViewModel; private RecyclerViewStateHelper rvHelper = new RecyclerViewStateHelper(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main); mBinding.setRvHelper(rvHelper); mSharedPrefs = getApplicationContext().getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE); mLikedViewModel = ViewModelProviders.of(this).get(LikedViewModel.class); mLayoutManager = new GridLayoutManager(this, mGridSpanCount); mBinding.recyclerView.setHasFixedSize(true); mBinding.recyclerView.setLayoutManager(mLayoutManager); mBinding.recyclerView.addOnScrollListener(new InfiniteScrollListener((GridLayoutManager) mLayoutManager, this) { @Override public void loadNextPage(final int currentPage) { // options for retrofit client Map<String, String> options = new HashMap<String, String>() {{ put("page", String.valueOf(currentPage)); }}; switch (mSharedPrefs.getInt(SHARED_PREFS_SORT_MODE_KEY, R.id.action_sort_popular)) { case R.id.action_sort_top_rated: requestTMDB(mClient.listTopRatedMovies(options), currentPage); break; case R.id.action_sort_popular: default: requestTMDB(mClient.listPopularMovies(options), currentPage); } } }); mMovieAdapter = new MoviesAdapter(this, this); mBinding.recyclerView.setAdapter(mMovieAdapter); mClient = RetrofitClient.getInstance(getApplicationContext()); if (null != mMovieSet || (null != savedInstanceState && savedInstanceState.containsKey(MOVIE_SET_KEY) && null != savedInstanceState.getSerializable(MOVIE_SET_KEY))) { if (null == mMovieSet) { mMovieSet = (MovieSet) savedInstanceState.getSerializable(MOVIE_SET_KEY); } if (null != mMovieSet && null != mMovieSet.getMovies()) { mMovieAdapter.swapMovieList(mMovieSet.getMovies()); } else { mMovieAdapter.swapMovieList(null); } } else { populateRecycleView(); } mBinding.swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { mBinding.swipeRefresh.setRefreshing(false); populateRecycleView(); } }); mBinding.swipeRefresh.setColorSchemeResources(R.color.colorAccent); } public void populateRecycleView() { detachLikedViewModelObserver(); switch (mSharedPrefs.getInt(SHARED_PREFS_SORT_MODE_KEY, R.id.action_sort_popular)) { case R.id.action_sort_top_rated: requestTMDB(mClient.listTopRatedMovies()); break; case R.id.action_sort_liked: attachLikedViewModelObserver(); break; case R.id.action_sort_popular: default: requestTMDB(mClient.listPopularMovies()); } } // Default TMDB call public void requestTMDB(Call<MovieSet> call) { requestTMDB(call, -1); } // TMDB call with defined page number public void requestTMDB(Call<MovieSet> call, final int page) { if (page <= 0) { rvHelper.setLoadingState(true); rvHelper.setErrorState(false); } call.enqueue(new Callback<MovieSet>() { @Override public void onResponse(@NonNull Call<MovieSet> call, @NonNull retrofit2.Response<MovieSet> response) { if (page <= 0) { rvHelper.setLoadingState(false); } if (response.code() == 200) { if (page <= 0) { mMovieSet = response.body(); } else { mMovieSet.addMovies(response.body()); } mMovieAdapter.swapMovieList( null != mMovieSet && null != mMovieSet.getMovies() ? mMovieSet.getMovies() : null); if (page <= 0) { mBinding.recyclerView.scrollToPosition(0); } } else { if (page <= 0) { mBinding.ivMessageIcon.setImageResource(R.drawable.ic_error_outline); mBinding.tvMessage.setText(R.string.error_unexpected_response); rvHelper.setErrorState(true); } else { Toast.makeText(MainActivity.this, R.string.error_unexpected_response, Toast.LENGTH_LONG).show(); } } } @Override public void onFailure(@NonNull Call<MovieSet> call, @NonNull Throwable t) { if (Utilities.isOnline()) { mBinding.ivMessageIcon.setImageResource(R.drawable.ic_error); mBinding.tvMessage.setText(R.string.error_problem_connecting); if (page > 0) { Toast.makeText(MainActivity.this, R.string.error_problem_connecting, Toast.LENGTH_LONG).show(); } } else { mBinding.ivMessageIcon.setImageResource(R.drawable.ic_warning); mBinding.tvMessage.setText(R.string.error_no_connection); if (page > 0) { Toast.makeText(MainActivity.this, R.string.error_no_connection, Toast.LENGTH_LONG).show(); } } if (page <= 0) { rvHelper.setLoadingState(false); rvHelper.setErrorState(true); } } }); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putParcelable(LAYOUT_MANAGER_STATE_KEY, mLayoutManager.onSaveInstanceState()); // No need to preserve recycler view movie list for the liked set this way, cause that is managed by ViewModel as LiveData if (mSharedPrefs.getInt(SHARED_PREFS_SORT_MODE_KEY, R.id.action_sort_popular) != R.id.action_sort_liked) { outState.putSerializable(MOVIE_SET_KEY, mMovieSet); } super.onSaveInstanceState(outState); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); if (null != savedInstanceState) { if (savedInstanceState.containsKey(LAYOUT_MANAGER_STATE_KEY) && null != savedInstanceState.getParcelable(LAYOUT_MANAGER_STATE_KEY)) { mLayoutManagerState = savedInstanceState.getParcelable(LAYOUT_MANAGER_STATE_KEY); } if (savedInstanceState.containsKey(MOVIE_SET_KEY) && null != savedInstanceState.getSerializable(MOVIE_SET_KEY)) { mMovieSet = (MovieSet) savedInstanceState.getSerializable(MOVIE_SET_KEY); } } } @Override protected void onResume() { super.onResume(); if (null != mLayoutManagerState) { mLayoutManager.onRestoreInstanceState(mLayoutManagerState); // Preventing recurring use of this state on the rest of onResume single calls (without onRestoreInstanceState) mLayoutManagerState = null; } } @SuppressLint("ApplySharedPref") @Override public boolean onOptionsItemSelected(MenuItem item) { if (R.id.menu_sort_group == item.getGroupId() && item.getItemId() != mSharedPrefs.getInt(SHARED_PREFS_SORT_MODE_KEY, R.id.action_sort_popular)) { item.setChecked(true); mSharedPrefs .edit() .putInt(SHARED_PREFS_SORT_MODE_KEY, item.getItemId()) .commit(); populateRecycleView(); } else if (item.getItemId() == android.R.id.home) { supportFinishAfterTransition(); return true; } return super.onOptionsItemSelected(item); } @Override public void onClick(Movie movie, View title, View poster) { Intent detailIntent = new Intent(this, DetailActivity.class); detailIntent.putExtra(EXTRA_MOVIE_KEY, movie); ActivityOptionsCompat options = ActivityOptionsCompat.makeBasic(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { title.setVisibility(View.VISIBLE); Pair<View, String> p1 = Pair.create(title, "movie_title"); Pair<View, String> p2 = Pair.create(poster, "movie_poster"); options = ActivityOptionsCompat.makeSceneTransitionAnimation(MainActivity.this, p1, p2); } startActivity(detailIntent, options.toBundle()); } @SuppressLint("ApplySharedPref") @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.sort, menu); int prevSortMode = mSharedPrefs.getInt(SHARED_PREFS_SORT_MODE_KEY, R.id.action_sort_popular); // Fix saved preference in case it's corrupted if (null == menu.findItem(prevSortMode)) { mSharedPrefs .edit() .putInt(SHARED_PREFS_SORT_MODE_KEY, R.id.action_sort_popular) .commit(); prevSortMode = R.id.action_sort_popular; } menu.findItem(prevSortMode).setChecked(true); return true; } final Observer<List<LikedEntryJsonAndPoster>> likedObserver = new Observer<List<LikedEntryJsonAndPoster>>() { @Override public void onChanged(@Nullable final List<LikedEntryJsonAndPoster> likedJsonAndPosterEntries) { Log.d(TAG, "Updating list of Liked entries from LiveData in the ViewModel"); if (likedJsonAndPosterEntries != null) { ArrayList<Movie> movies = new ArrayList<>(); Map<Integer, byte[]> posterMap = new HashMap<>(); for (LikedEntryJsonAndPoster likedEntry : likedJsonAndPosterEntries) { Movie movie = new Gson().fromJson(likedEntry.getMovieJson(), Movie.class); //movie.setBytePoster(likedEntry.getPoster()); movie.setLiked(true); movies.add(movie); posterMap.put(movie.getId(), likedEntry.getPoster()); } mMovieSet = new MovieSet(); mMovieSet.setMovies(movies); mMovieAdapter.swapMovieList(movies); mLikedViewModel.setPosterMap(posterMap); } } }; private void attachLikedViewModelObserver() { mLikedViewModel.getLiked().observe(this, likedObserver); Log.d(TAG, "LikedViewModel observer attached"); } private void detachLikedViewModelObserver() { mLikedViewModel.getLiked().removeObserver(likedObserver); Log.d(TAG, "LikedViewModel observer detached"); } }
43.182663
130
0.635145
76824e44acf195560fddd53e3ca1c464d62f91fb
117,375
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // API class package org.mozilla.javascript; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import org.mozilla.javascript.debug.DebuggableObject; import org.mozilla.javascript.annotations.JSConstructor; import org.mozilla.javascript.annotations.JSFunction; import org.mozilla.javascript.annotations.JSGetter; import org.mozilla.javascript.annotations.JSSetter; import org.mozilla.javascript.annotations.JSStaticFunction; /** * This is the default implementation of the Scriptable interface. This * class provides convenient default behavior that makes it easier to * define host objects. * <p> * Various properties and methods of JavaScript objects can be conveniently * defined using methods of ScriptableObject. * <p> * Classes extending ScriptableObject must define the getClassName method. * * @see org.mozilla.javascript.Scriptable */ public abstract class ScriptableObject implements Scriptable, Serializable, DebuggableObject, ConstProperties { static final long serialVersionUID = 2829861078851942586L; /** * The empty property attribute. * * Used by getAttributes() and setAttributes(). * * @see org.mozilla.javascript.ScriptableObject#getAttributes(String) * @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int) */ public static final int EMPTY = 0x00; /** * Property attribute indicating assignment to this property is ignored. * * @see org.mozilla.javascript.ScriptableObject * #put(String, Scriptable, Object) * @see org.mozilla.javascript.ScriptableObject#getAttributes(String) * @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int) */ public static final int READONLY = 0x01; /** * Property attribute indicating property is not enumerated. * * Only enumerated properties will be returned by getIds(). * * @see org.mozilla.javascript.ScriptableObject#getIds() * @see org.mozilla.javascript.ScriptableObject#getAttributes(String) * @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int) */ public static final int DONTENUM = 0x02; /** * Property attribute indicating property cannot be deleted. * * @see org.mozilla.javascript.ScriptableObject#delete(String) * @see org.mozilla.javascript.ScriptableObject#getAttributes(String) * @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int) */ public static final int PERMANENT = 0x04; /** * Property attribute indicating that this is a const property that has not * been assigned yet. The first 'const' assignment to the property will * clear this bit. */ public static final int UNINITIALIZED_CONST = 0x08; public static final int CONST = PERMANENT|READONLY|UNINITIALIZED_CONST; /** * The prototype of this object. */ private Scriptable prototypeObject; /** * The parent scope of this object. */ private Scriptable parentScopeObject; private transient Slot[] slots; // If count >= 0, it gives number of keys or if count < 0, // it indicates sealed object where ~count gives number of keys private int count; // gateways into the definition-order linked list of slots private transient Slot firstAdded; private transient Slot lastAdded; private volatile Map<Object,Object> associatedValues; private static final int SLOT_QUERY = 1; private static final int SLOT_MODIFY = 2; private static final int SLOT_MODIFY_CONST = 3; private static final int SLOT_MODIFY_GETTER_SETTER = 4; private static final int SLOT_CONVERT_ACCESSOR_TO_DATA = 5; // initial slot array size, must be a power of 2 private static final int INITIAL_SLOT_SIZE = 4; private boolean isExtensible = true; private static class Slot implements Serializable { private static final long serialVersionUID = -6090581677123995491L; String name; // This can change due to caching int indexOrHash; private volatile short attributes; transient volatile boolean wasDeleted; volatile Object value; transient Slot next; // next in hash table bucket transient volatile Slot orderedNext; // next in linked list Slot(String name, int indexOrHash, int attributes) { this.name = name; this.indexOrHash = indexOrHash; this.attributes = (short)attributes; } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); if (name != null) { indexOrHash = name.hashCode(); } } boolean setValue(Object value, Scriptable owner, Scriptable start) { if ((attributes & READONLY) != 0) { return true; } if (owner == start) { this.value = value; return true; } else { return false; } } Object getValue(Scriptable start) { return value; } int getAttributes() { return attributes; } synchronized void setAttributes(int value) { checkValidAttributes(value); attributes = (short)value; } void markDeleted() { wasDeleted = true; value = null; name = null; } ScriptableObject getPropertyDescriptor(Context cx, Scriptable scope) { return buildDataDescriptor(scope, value, attributes); } } protected static ScriptableObject buildDataDescriptor(Scriptable scope, Object value, int attributes) { ScriptableObject desc = new NativeObject(); ScriptRuntime.setBuiltinProtoAndParent(desc, scope, TopLevel.Builtins.Object); desc.defineProperty("value", value, EMPTY); desc.defineProperty("writable", (attributes & READONLY) == 0, EMPTY); desc.defineProperty("enumerable", (attributes & DONTENUM) == 0, EMPTY); desc.defineProperty("configurable", (attributes & PERMANENT) == 0, EMPTY); return desc; } private static final class GetterSlot extends Slot { static final long serialVersionUID = -4900574849788797588L; Object getter; Object setter; GetterSlot(String name, int indexOrHash, int attributes) { super(name, indexOrHash, attributes); } @Override ScriptableObject getPropertyDescriptor(Context cx, Scriptable scope) { int attr = getAttributes(); ScriptableObject desc = new NativeObject(); ScriptRuntime.setBuiltinProtoAndParent(desc, scope, TopLevel.Builtins.Object); desc.defineProperty("enumerable", (attr & DONTENUM) == 0, EMPTY); desc.defineProperty("configurable", (attr & PERMANENT) == 0, EMPTY); if (getter != null) desc.defineProperty("get", getter, EMPTY); if (setter != null) desc.defineProperty("set", setter, EMPTY); return desc; } @Override boolean setValue(Object value, Scriptable owner, Scriptable start) { if (setter == null) { if (getter != null) { if (Context.getContext().hasFeature(Context.FEATURE_STRICT_MODE)) { // Based on TC39 ES3.1 Draft of 9-Feb-2009, 8.12.4, step 2, // we should throw a TypeError in this case. throw ScriptRuntime.typeError1("msg.set.prop.no.setter", name); } // Assignment to a property with only a getter defined. The // assignment is ignored. See bug 478047. return true; } } else { Context cx = Context.getContext(); if (setter instanceof MemberBox) { MemberBox nativeSetter = (MemberBox)setter; Class<?> pTypes[] = nativeSetter.argTypes; // XXX: cache tag since it is already calculated in // defineProperty ? Class<?> valueType = pTypes[pTypes.length - 1]; int tag = FunctionObject.getTypeTag(valueType); Object actualArg = FunctionObject.convertArg(cx, start, value, tag); Object setterThis; Object[] args; if (nativeSetter.delegateTo == null) { setterThis = start; args = new Object[] { actualArg }; } else { setterThis = nativeSetter.delegateTo; args = new Object[] { start, actualArg }; } nativeSetter.invoke(setterThis, args); } else if (setter instanceof Function) { Function f = (Function)setter; f.call(cx, f.getParentScope(), start, new Object[] { value }); } return true; } return super.setValue(value, owner, start); } @Override Object getValue(Scriptable start) { if (getter != null) { if (getter instanceof MemberBox) { MemberBox nativeGetter = (MemberBox)getter; Object getterThis; Object[] args; if (nativeGetter.delegateTo == null) { getterThis = start; args = ScriptRuntime.emptyArgs; } else { getterThis = nativeGetter.delegateTo; args = new Object[] { start }; } return nativeGetter.invoke(getterThis, args); } else if (getter instanceof Function) { Function f = (Function)getter; Context cx = Context.getContext(); return f.call(cx, f.getParentScope(), start, ScriptRuntime.emptyArgs); } } Object val = this.value; if (val instanceof LazilyLoadedCtor) { LazilyLoadedCtor initializer = (LazilyLoadedCtor)val; try { initializer.init(); } finally { this.value = val = initializer.getValue(); } } return val; } @Override void markDeleted() { super.markDeleted(); getter = null; setter = null; } } /** * A wrapper around a slot that allows the slot to be used in a new slot * table while keeping it functioning in its old slot table/linked list * context. This is used when linked slots are copied to a new slot table. * In a multi-threaded environment, these slots may still be accessed * through their old slot table. See bug 688458. */ private static class RelinkedSlot extends Slot { final Slot slot; RelinkedSlot(Slot slot) { super(slot.name, slot.indexOrHash, slot.attributes); // Make sure we always wrap the actual slot, not another relinked one this.slot = unwrapSlot(slot); } @Override boolean setValue(Object value, Scriptable owner, Scriptable start) { return slot.setValue(value, owner, start); } @Override Object getValue(Scriptable start) { return slot.getValue(start); } @Override ScriptableObject getPropertyDescriptor(Context cx, Scriptable scope) { return slot.getPropertyDescriptor(cx, scope); } @Override int getAttributes() { return slot.getAttributes(); } @Override void setAttributes(int value) { slot.setAttributes(value); } @Override void markDeleted() { super.markDeleted(); slot.markDeleted(); } private void writeObject(ObjectOutputStream out) throws IOException { out.writeObject(slot); // just serialize the wrapped slot } } static void checkValidAttributes(int attributes) { final int mask = READONLY | DONTENUM | PERMANENT | UNINITIALIZED_CONST; if ((attributes & ~mask) != 0) { throw new IllegalArgumentException(String.valueOf(attributes)); } } public ScriptableObject() { } public ScriptableObject(Scriptable scope, Scriptable prototype) { if (scope == null) throw new IllegalArgumentException(); parentScopeObject = scope; prototypeObject = prototype; } /** * Gets the value that will be returned by calling the typeof operator on this object. * @return default is "object" unless {@link #avoidObjectDetection()} is <code>true</code> in which * case it returns "undefined" */ public String getTypeOf() { return avoidObjectDetection() ? "undefined" : "object"; } /** * Return the name of the class. * * This is typically the same name as the constructor. * Classes extending ScriptableObject must implement this abstract * method. */ public abstract String getClassName(); /** * Returns true if the named property is defined. * * @param name the name of the property * @param start the object in which the lookup began * @return true if and only if the property was found in the object */ public boolean has(String name, Scriptable start) { return null != getSlot(name, 0, SLOT_QUERY); } /** * Returns true if the property index is defined. * * @param index the numeric index for the property * @param start the object in which the lookup began * @return true if and only if the property was found in the object */ public boolean has(int index, Scriptable start) { return null != getSlot(null, index, SLOT_QUERY); } /** * Returns the value of the named property or NOT_FOUND. * * If the property was created using defineProperty, the * appropriate getter method is called. * * @param name the name of the property * @param start the object in which the lookup began * @return the value of the property (may be null), or NOT_FOUND */ public Object get(String name, Scriptable start) { Slot slot = getSlot(name, 0, SLOT_QUERY); if (slot == null) { return Scriptable.NOT_FOUND; } return slot.getValue(start); } /** * Returns the value of the indexed property or NOT_FOUND. * * @param index the numeric index for the property * @param start the object in which the lookup began * @return the value of the property (may be null), or NOT_FOUND */ public Object get(int index, Scriptable start) { Slot slot = getSlot(null, index, SLOT_QUERY); if (slot == null) { return Scriptable.NOT_FOUND; } return slot.getValue(start); } /** * Sets the value of the named property, creating it if need be. * * If the property was created using defineProperty, the * appropriate setter method is called. <p> * * If the property's attributes include READONLY, no action is * taken. * This method will actually set the property in the start * object. * * @param name the name of the property * @param start the object whose property is being set * @param value value to set the property to */ public void put(String name, Scriptable start, Object value) { if (putImpl(name, 0, start, value)) return; if (start == this) throw Kit.codeBug(); start.put(name, start, value); } /** * Sets the value of the indexed property, creating it if need be. * * @param index the numeric index for the property * @param start the object whose property is being set * @param value value to set the property to */ public void put(int index, Scriptable start, Object value) { if (putImpl(null, index, start, value)) return; if (start == this) throw Kit.codeBug(); start.put(index, start, value); } /** * Removes a named property from the object. * * If the property is not found, or it has the PERMANENT attribute, * no action is taken. * * @param name the name of the property */ public void delete(String name) { checkNotSealed(name, 0); removeSlot(name, 0); } /** * Removes the indexed property from the object. * * If the property is not found, or it has the PERMANENT attribute, * no action is taken. * * @param index the numeric index for the property */ public void delete(int index) { checkNotSealed(null, index); removeSlot(null, index); } /** * Sets the value of the named const property, creating it if need be. * * If the property was created using defineProperty, the * appropriate setter method is called. <p> * * If the property's attributes include READONLY, no action is * taken. * This method will actually set the property in the start * object. * * @param name the name of the property * @param start the object whose property is being set * @param value value to set the property to */ public void putConst(String name, Scriptable start, Object value) { if (putConstImpl(name, 0, start, value, READONLY)) return; if (start == this) throw Kit.codeBug(); if (start instanceof ConstProperties) ((ConstProperties)start).putConst(name, start, value); else start.put(name, start, value); } public void defineConst(String name, Scriptable start) { if (putConstImpl(name, 0, start, Undefined.instance, UNINITIALIZED_CONST)) return; if (start == this) throw Kit.codeBug(); if (start instanceof ConstProperties) ((ConstProperties)start).defineConst(name, start); } /** * Returns true if the named property is defined as a const on this object. * @param name * @return true if the named property is defined as a const, false * otherwise. */ public boolean isConst(String name) { Slot slot = getSlot(name, 0, SLOT_QUERY); if (slot == null) { return false; } return (slot.getAttributes() & (PERMANENT|READONLY)) == (PERMANENT|READONLY); } /** * @deprecated Use {@link #getAttributes(String name)}. The engine always * ignored the start argument. */ public final int getAttributes(String name, Scriptable start) { return getAttributes(name); } /** * @deprecated Use {@link #getAttributes(int index)}. The engine always * ignored the start argument. */ public final int getAttributes(int index, Scriptable start) { return getAttributes(index); } /** * @deprecated Use {@link #setAttributes(String name, int attributes)}. * The engine always ignored the start argument. */ public final void setAttributes(String name, Scriptable start, int attributes) { setAttributes(name, attributes); } /** * @deprecated Use {@link #setAttributes(int index, int attributes)}. * The engine always ignored the start argument. */ public void setAttributes(int index, Scriptable start, int attributes) { setAttributes(index, attributes); } /** * Get the attributes of a named property. * * The property is specified by <code>name</code> * as defined for <code>has</code>.<p> * * @param name the identifier for the property * @return the bitset of attributes * @exception EvaluatorException if the named property is not found * @see org.mozilla.javascript.ScriptableObject#has(String, Scriptable) * @see org.mozilla.javascript.ScriptableObject#READONLY * @see org.mozilla.javascript.ScriptableObject#DONTENUM * @see org.mozilla.javascript.ScriptableObject#PERMANENT * @see org.mozilla.javascript.ScriptableObject#EMPTY */ public int getAttributes(String name) { return findAttributeSlot(name, 0, SLOT_QUERY).getAttributes(); } /** * Get the attributes of an indexed property. * * @param index the numeric index for the property * @exception EvaluatorException if the named property is not found * is not found * @return the bitset of attributes * @see org.mozilla.javascript.ScriptableObject#has(String, Scriptable) * @see org.mozilla.javascript.ScriptableObject#READONLY * @see org.mozilla.javascript.ScriptableObject#DONTENUM * @see org.mozilla.javascript.ScriptableObject#PERMANENT * @see org.mozilla.javascript.ScriptableObject#EMPTY */ public int getAttributes(int index) { return findAttributeSlot(null, index, SLOT_QUERY).getAttributes(); } /** * Set the attributes of a named property. * * The property is specified by <code>name</code> * as defined for <code>has</code>.<p> * * The possible attributes are READONLY, DONTENUM, * and PERMANENT. Combinations of attributes * are expressed by the bitwise OR of attributes. * EMPTY is the state of no attributes set. Any unused * bits are reserved for future use. * * @param name the name of the property * @param attributes the bitset of attributes * @exception EvaluatorException if the named property is not found * @see org.mozilla.javascript.Scriptable#has(String, Scriptable) * @see org.mozilla.javascript.ScriptableObject#READONLY * @see org.mozilla.javascript.ScriptableObject#DONTENUM * @see org.mozilla.javascript.ScriptableObject#PERMANENT * @see org.mozilla.javascript.ScriptableObject#EMPTY */ public void setAttributes(String name, int attributes) { checkNotSealed(name, 0); findAttributeSlot(name, 0, SLOT_MODIFY).setAttributes(attributes); } /** * Set the attributes of an indexed property. * * @param index the numeric index for the property * @param attributes the bitset of attributes * @exception EvaluatorException if the named property is not found * @see org.mozilla.javascript.Scriptable#has(String, Scriptable) * @see org.mozilla.javascript.ScriptableObject#READONLY * @see org.mozilla.javascript.ScriptableObject#DONTENUM * @see org.mozilla.javascript.ScriptableObject#PERMANENT * @see org.mozilla.javascript.ScriptableObject#EMPTY */ public void setAttributes(int index, int attributes) { checkNotSealed(null, index); findAttributeSlot(null, index, SLOT_MODIFY).setAttributes(attributes); } /** * XXX: write docs. */ public void setGetterOrSetter(String name, int index, Callable getterOrSetter, boolean isSetter) { setGetterOrSetter(name, index, getterOrSetter, isSetter, false); } private void setGetterOrSetter(String name, int index, Callable getterOrSetter, boolean isSetter, boolean force) { if (name != null && index != 0) throw new IllegalArgumentException(name); if (!force) { checkNotSealed(name, index); } final GetterSlot gslot; if (isExtensible()) { gslot = (GetterSlot)getSlot(name, index, SLOT_MODIFY_GETTER_SETTER); } else { Slot slot = unwrapSlot(getSlot(name, index, SLOT_QUERY)); if (!(slot instanceof GetterSlot)) return; gslot = (GetterSlot) slot; } if (!force) { int attributes = gslot.getAttributes(); if ((attributes & READONLY) != 0) { throw Context.reportRuntimeError1("msg.modify.readonly", name); } } if (isSetter) { gslot.setter = getterOrSetter; } else { gslot.getter = getterOrSetter; } gslot.value = Undefined.instance; } /** * Get the getter or setter for a given property. Used by __lookupGetter__ * and __lookupSetter__. * * @param name Name of the object. If nonnull, index must be 0. * @param index Index of the object. If nonzero, name must be null. * @param isSetter If true, return the setter, otherwise return the getter. * @exception IllegalArgumentException if both name and index are nonnull * and nonzero respectively. * @return Null if the property does not exist. Otherwise returns either * the getter or the setter for the property, depending on * the value of isSetter (may be undefined if unset). */ public Object getGetterOrSetter(String name, int index, boolean isSetter) { if (name != null && index != 0) throw new IllegalArgumentException(name); Slot slot = unwrapSlot(getSlot(name, index, SLOT_QUERY)); if (slot == null) return null; if (slot instanceof GetterSlot) { GetterSlot gslot = (GetterSlot)slot; Object result = isSetter ? gslot.setter : gslot.getter; return result != null ? result : Undefined.instance; } else return Undefined.instance; } /** * Returns whether a property is a getter or a setter * @param name property name * @param index property index * @param setter true to check for a setter, false for a getter * @return whether the property is a getter or a setter */ protected boolean isGetterOrSetter(String name, int index, boolean setter) { Slot slot = unwrapSlot(getSlot(name, index, SLOT_QUERY)); if (slot instanceof GetterSlot) { if (setter && ((GetterSlot)slot).setter != null) return true; if (!setter && ((GetterSlot)slot).getter != null) return true; } return false; } void addLazilyInitializedValue(String name, int index, LazilyLoadedCtor init, int attributes) { if (name != null && index != 0) throw new IllegalArgumentException(name); checkNotSealed(name, index); GetterSlot gslot = (GetterSlot)getSlot(name, index, SLOT_MODIFY_GETTER_SETTER); gslot.setAttributes(attributes); gslot.getter = null; gslot.setter = null; gslot.value = init; } /** * Returns the prototype of the object. */ public Scriptable getPrototype() { return prototypeObject; } /** * Sets the prototype of the object. */ public void setPrototype(Scriptable m) { prototypeObject = m; } /** * Returns the parent (enclosing) scope of the object. */ public Scriptable getParentScope() { return parentScopeObject; } /** * Sets the parent (enclosing) scope of the object. */ public void setParentScope(Scriptable m) { parentScopeObject = m; } /** * Returns an array of ids for the properties of the object. * * <p>Any properties with the attribute DONTENUM are not listed. <p> * * @return an array of java.lang.Objects with an entry for every * listed property. Properties accessed via an integer index will * have a corresponding * Integer entry in the returned array. Properties accessed by * a String will have a String entry in the returned array. */ public Object[] getIds() { return getIds(false); } /** * Returns an array of ids for the properties of the object. * * <p>All properties, even those with attribute DONTENUM, are listed. <p> * * @return an array of java.lang.Objects with an entry for every * listed property. Properties accessed via an integer index will * have a corresponding * Integer entry in the returned array. Properties accessed by * a String will have a String entry in the returned array. */ public Object[] getAllIds() { return getIds(true); } /** * Implements the [[DefaultValue]] internal method. * * <p>Note that the toPrimitive conversion is a no-op for * every type other than Object, for which [[DefaultValue]] * is called. See ECMA 9.1.<p> * * A <code>hint</code> of null means "no hint". * * @param typeHint the type hint * @return the default value for the object * * See ECMA 8.6.2.6. */ public Object getDefaultValue(Class<?> typeHint) { return getDefaultValue(this, typeHint); } public static Object getDefaultValue(Scriptable object, Class<?> typeHint) { Context cx = null; for (int i=0; i < 2; i++) { boolean tryToString; if (typeHint == ScriptRuntime.StringClass) { tryToString = (i == 0); } else { tryToString = (i == 1); } String methodName; Object[] args; if (tryToString) { methodName = "toString"; args = ScriptRuntime.emptyArgs; } else { methodName = "valueOf"; args = new Object[1]; String hint; if (typeHint == null) { hint = "undefined"; } else if (typeHint == ScriptRuntime.StringClass) { hint = "string"; } else if (typeHint == ScriptRuntime.ScriptableClass) { hint = "object"; } else if (typeHint == ScriptRuntime.FunctionClass) { hint = "function"; } else if (typeHint == ScriptRuntime.BooleanClass || typeHint == Boolean.TYPE) { hint = "boolean"; } else if (typeHint == ScriptRuntime.NumberClass || typeHint == ScriptRuntime.ByteClass || typeHint == Byte.TYPE || typeHint == ScriptRuntime.ShortClass || typeHint == Short.TYPE || typeHint == ScriptRuntime.IntegerClass || typeHint == Integer.TYPE || typeHint == ScriptRuntime.FloatClass || typeHint == Float.TYPE || typeHint == ScriptRuntime.DoubleClass || typeHint == Double.TYPE) { hint = "number"; } else { throw Context.reportRuntimeError1( "msg.invalid.type", typeHint.toString()); } args[0] = hint; } Object v = getProperty(object, methodName); if (!(v instanceof Function)) continue; Function fun = (Function) v; if (cx == null) cx = Context.getContext(); v = fun.call(cx, fun.getParentScope(), object, args); if (v != null) { if (!(v instanceof Scriptable)) { return v; } if (typeHint == ScriptRuntime.ScriptableClass || typeHint == ScriptRuntime.FunctionClass) { return v; } if (tryToString && v instanceof Wrapper) { // Let a wrapped java.lang.String pass for a primitive // string. Object u = ((Wrapper)v).unwrap(); if (u instanceof String) return u; } } } // fall through to error String arg = (typeHint == null) ? "undefined" : typeHint.getName(); throw ScriptRuntime.typeError1("msg.default.value", arg); } /** * Implements the instanceof operator. * * <p>This operator has been proposed to ECMA. * * @param instance The value that appeared on the LHS of the instanceof * operator * @return true if "this" appears in value's prototype chain * */ public boolean hasInstance(Scriptable instance) { // Default for JS objects (other than Function) is to do prototype // chasing. This will be overridden in NativeFunction and non-JS // objects. return ScriptRuntime.jsDelegatesTo(instance, this); } /** * Emulate the SpiderMonkey (and Firefox) feature of allowing * custom objects to avoid detection by normal "object detection" * code patterns. This is used to implement document.all. * See https://bugzilla.mozilla.org/show_bug.cgi?id=412247. * This is an analog to JOF_DETECTING from SpiderMonkey; see * https://bugzilla.mozilla.org/show_bug.cgi?id=248549. * Other than this special case, embeddings should return false. * @return true if this object should avoid object detection * @since 1.7R1 */ public boolean avoidObjectDetection() { return false; } /** * Custom <tt>==</tt> operator. * Must return {@link Scriptable#NOT_FOUND} if this object does not * have custom equality operator for the given value, * <tt>Boolean.TRUE</tt> if this object is equivalent to <tt>value</tt>, * <tt>Boolean.FALSE</tt> if this object is not equivalent to * <tt>value</tt>. * <p> * The default implementation returns Boolean.TRUE * if <tt>this == value</tt> or {@link Scriptable#NOT_FOUND} otherwise. * It indicates that by default custom equality is available only if * <tt>value</tt> is <tt>this</tt> in which case true is returned. */ protected Object equivalentValues(Object value) { return (this == value) ? Boolean.TRUE : Scriptable.NOT_FOUND; } /** * Defines JavaScript objects from a Java class that implements Scriptable. * * If the given class has a method * <pre> * static void init(Context cx, Scriptable scope, boolean sealed);</pre> * * or its compatibility form * <pre> * static void init(Scriptable scope);</pre> * * then it is invoked and no further initialization is done.<p> * * However, if no such a method is found, then the class's constructors and * methods are used to initialize a class in the following manner.<p> * * First, the zero-parameter constructor of the class is called to * create the prototype. If no such constructor exists, * a {@link EvaluatorException} is thrown. <p> * * Next, all methods are scanned for special prefixes that indicate that they * have special meaning for defining JavaScript objects. * These special prefixes are * <ul> * <li><code>jsFunction_</code> for a JavaScript function * <li><code>jsStaticFunction_</code> for a JavaScript function that * is a property of the constructor * <li><code>jsGet_</code> for a getter of a JavaScript property * <li><code>jsSet_</code> for a setter of a JavaScript property * <li><code>jsConstructor</code> for a JavaScript function that * is the constructor * </ul><p> * * If the method's name begins with "jsFunction_", a JavaScript function * is created with a name formed from the rest of the Java method name * following "jsFunction_". So a Java method named "jsFunction_foo" will * define a JavaScript method "foo". Calling this JavaScript function * will cause the Java method to be called. The parameters of the method * must be of number and types as defined by the FunctionObject class. * The JavaScript function is then added as a property * of the prototype. <p> * * If the method's name begins with "jsStaticFunction_", it is handled * similarly except that the resulting JavaScript function is added as a * property of the constructor object. The Java method must be static. * * If the method's name begins with "jsGet_" or "jsSet_", the method is * considered to define a property. Accesses to the defined property * will result in calls to these getter and setter methods. If no * setter is defined, the property is defined as READONLY.<p> * * If the method's name is "jsConstructor", the method is * considered to define the body of the constructor. Only one * method of this name may be defined. You may use the varargs forms * for constructors documented in {@link FunctionObject#FunctionObject(String, Member, Scriptable)} * * If no method is found that can serve as constructor, a Java * constructor will be selected to serve as the JavaScript * constructor in the following manner. If the class has only one * Java constructor, that constructor is used to define * the JavaScript constructor. If the the class has two constructors, * one must be the zero-argument constructor (otherwise an * {@link EvaluatorException} would have already been thrown * when the prototype was to be created). In this case * the Java constructor with one or more parameters will be used * to define the JavaScript constructor. If the class has three * or more constructors, an {@link EvaluatorException} * will be thrown.<p> * * Finally, if there is a method * <pre> * static void finishInit(Scriptable scope, FunctionObject constructor, * Scriptable prototype)</pre> * * it will be called to finish any initialization. The <code>scope</code> * argument will be passed, along with the newly created constructor and * the newly created prototype.<p> * * @param scope The scope in which to define the constructor. * @param clazz The Java class to use to define the JavaScript objects * and properties. * @exception IllegalAccessException if access is not available * to a reflected class member * @exception InstantiationException if unable to instantiate * the named class * @exception InvocationTargetException if an exception is thrown * during execution of methods of the named class * @see org.mozilla.javascript.Function * @see org.mozilla.javascript.FunctionObject * @see org.mozilla.javascript.ScriptableObject#READONLY * @see org.mozilla.javascript.ScriptableObject * #defineProperty(String, Class, int) */ public static <T extends Scriptable> void defineClass( Scriptable scope, Class<T> clazz) throws IllegalAccessException, InstantiationException, InvocationTargetException { defineClass(scope, clazz, false, false); } /** * Defines JavaScript objects from a Java class, optionally * allowing sealing. * * Similar to <code>defineClass(Scriptable scope, Class clazz)</code> * except that sealing is allowed. An object that is sealed cannot have * properties added or removed. Note that sealing is not allowed in * the current ECMA/ISO language specification, but is likely for * the next version. * * @param scope The scope in which to define the constructor. * @param clazz The Java class to use to define the JavaScript objects * and properties. The class must implement Scriptable. * @param sealed Whether or not to create sealed standard objects that * cannot be modified. * @exception IllegalAccessException if access is not available * to a reflected class member * @exception InstantiationException if unable to instantiate * the named class * @exception InvocationTargetException if an exception is thrown * during execution of methods of the named class * @since 1.4R3 */ public static <T extends Scriptable> void defineClass( Scriptable scope, Class<T> clazz, boolean sealed) throws IllegalAccessException, InstantiationException, InvocationTargetException { defineClass(scope, clazz, sealed, false); } /** * Defines JavaScript objects from a Java class, optionally * allowing sealing and mapping of Java inheritance to JavaScript * prototype-based inheritance. * * Similar to <code>defineClass(Scriptable scope, Class clazz)</code> * except that sealing and inheritance mapping are allowed. An object * that is sealed cannot have properties added or removed. Note that * sealing is not allowed in the current ECMA/ISO language specification, * but is likely for the next version. * * @param scope The scope in which to define the constructor. * @param clazz The Java class to use to define the JavaScript objects * and properties. The class must implement Scriptable. * @param sealed Whether or not to create sealed standard objects that * cannot be modified. * @param mapInheritance Whether or not to map Java inheritance to * JavaScript prototype-based inheritance. * @return the class name for the prototype of the specified class * @exception IllegalAccessException if access is not available * to a reflected class member * @exception InstantiationException if unable to instantiate * the named class * @exception InvocationTargetException if an exception is thrown * during execution of methods of the named class * @since 1.6R2 */ public static <T extends Scriptable> String defineClass( Scriptable scope, Class<T> clazz, boolean sealed, boolean mapInheritance) throws IllegalAccessException, InstantiationException, InvocationTargetException { BaseFunction ctor = buildClassCtor(scope, clazz, sealed, mapInheritance); if (ctor == null) return null; String name = ctor.getClassPrototype().getClassName(); defineProperty(scope, name, ctor, ScriptableObject.DONTENUM); return name; } static <T extends Scriptable> BaseFunction buildClassCtor( Scriptable scope, Class<T> clazz, boolean sealed, boolean mapInheritance) throws IllegalAccessException, InstantiationException, InvocationTargetException { Method[] methods = FunctionObject.getMethodList(clazz); for (int i=0; i < methods.length; i++) { Method method = methods[i]; if (!method.getName().equals("init")) continue; Class<?>[] parmTypes = method.getParameterTypes(); if (parmTypes.length == 3 && parmTypes[0] == ScriptRuntime.ContextClass && parmTypes[1] == ScriptRuntime.ScriptableClass && parmTypes[2] == Boolean.TYPE && Modifier.isStatic(method.getModifiers())) { Object args[] = { Context.getContext(), scope, sealed ? Boolean.TRUE : Boolean.FALSE }; method.invoke(null, args); return null; } if (parmTypes.length == 1 && parmTypes[0] == ScriptRuntime.ScriptableClass && Modifier.isStatic(method.getModifiers())) { Object args[] = { scope }; method.invoke(null, args); return null; } } // If we got here, there isn't an "init" method with the right // parameter types. Constructor<?>[] ctors = clazz.getConstructors(); Constructor<?> protoCtor = null; for (int i=0; i < ctors.length; i++) { if (ctors[i].getParameterTypes().length == 0) { protoCtor = ctors[i]; break; } } if (protoCtor == null) { throw Context.reportRuntimeError1( "msg.zero.arg.ctor", clazz.getName()); } Scriptable proto = (Scriptable) protoCtor.newInstance(ScriptRuntime.emptyArgs); String className = proto.getClassName(); // check for possible redefinition Object existing = getProperty(getTopLevelScope(scope), className); if (existing instanceof BaseFunction) { Object existingProto = ((BaseFunction)existing).getPrototypeProperty(); if (existingProto != null && clazz.equals(existingProto.getClass())) { return (BaseFunction)existing; } } // Set the prototype's prototype, trying to map Java inheritance to JS // prototype-based inheritance if requested to do so. Scriptable superProto = null; if (mapInheritance) { Class<? super T> superClass = clazz.getSuperclass(); if (ScriptRuntime.ScriptableClass.isAssignableFrom(superClass) && !Modifier.isAbstract(superClass.getModifiers())) { Class<? extends Scriptable> superScriptable = extendsScriptable(superClass); String name = ScriptableObject.defineClass(scope, superScriptable, sealed, mapInheritance); if (name != null) { superProto = ScriptableObject.getClassPrototype(scope, name); } } } if (superProto == null) { superProto = ScriptableObject.getObjectPrototype(scope); } proto.setPrototype(superProto); // Find out whether there are any methods that begin with // "js". If so, then only methods that begin with special // prefixes will be defined as JavaScript entities. final String functionPrefix = "jsFunction_"; final String staticFunctionPrefix = "jsStaticFunction_"; final String getterPrefix = "jsGet_"; final String setterPrefix = "jsSet_"; final String ctorName = "jsConstructor"; Member ctorMember = findAnnotatedMember(methods, JSConstructor.class); if (ctorMember == null) { ctorMember = findAnnotatedMember(ctors, JSConstructor.class); } if (ctorMember == null) { ctorMember = FunctionObject.findSingleMethod(methods, ctorName); } if (ctorMember == null) { if (ctors.length == 1) { ctorMember = ctors[0]; } else if (ctors.length == 2) { if (ctors[0].getParameterTypes().length == 0) ctorMember = ctors[1]; else if (ctors[1].getParameterTypes().length == 0) ctorMember = ctors[0]; } if (ctorMember == null) { throw Context.reportRuntimeError1( "msg.ctor.multiple.parms", clazz.getName()); } } FunctionObject ctor = new FunctionObject(className, ctorMember, scope); if (ctor.isVarArgsMethod()) { throw Context.reportRuntimeError1 ("msg.varargs.ctor", ctorMember.getName()); } ctor.initAsConstructor(scope, proto); Method finishInit = null; HashSet<String> staticNames = new HashSet<String>(), instanceNames = new HashSet<String>(); for (Method method : methods) { if (method == ctorMember) { continue; } String name = method.getName(); if (name.equals("finishInit")) { Class<?>[] parmTypes = method.getParameterTypes(); if (parmTypes.length == 3 && parmTypes[0] == ScriptRuntime.ScriptableClass && parmTypes[1] == FunctionObject.class && parmTypes[2] == ScriptRuntime.ScriptableClass && Modifier.isStatic(method.getModifiers())) { finishInit = method; continue; } } // ignore any compiler generated methods. if (name.indexOf('$') != -1) continue; if (name.equals(ctorName)) continue; Annotation annotation = null; String prefix = null; if (method.isAnnotationPresent(JSFunction.class)) { annotation = method.getAnnotation(JSFunction.class); } else if (method.isAnnotationPresent(JSStaticFunction.class)) { annotation = method.getAnnotation(JSStaticFunction.class); } else if (method.isAnnotationPresent(JSGetter.class)) { annotation = method.getAnnotation(JSGetter.class); } else if (method.isAnnotationPresent(JSSetter.class)) { continue; } if (annotation == null) { if (name.startsWith(functionPrefix)) { prefix = functionPrefix; } else if (name.startsWith(staticFunctionPrefix)) { prefix = staticFunctionPrefix; } else if (name.startsWith(getterPrefix)) { prefix = getterPrefix; } else if (annotation == null) { // note that setterPrefix is among the unhandled names here - // we deal with that when we see the getter continue; } } boolean isStatic = annotation instanceof JSStaticFunction || prefix == staticFunctionPrefix; HashSet<String> names = isStatic ? staticNames : instanceNames; String propName = getPropertyName(name, prefix, annotation); if (names.contains(propName)) { throw Context.reportRuntimeError2("duplicate.defineClass.name", name, propName); } names.add(propName); name = propName; if (annotation instanceof JSGetter || prefix == getterPrefix) { if (!(proto instanceof ScriptableObject)) { throw Context.reportRuntimeError2( "msg.extend.scriptable", proto.getClass().toString(), name); } Method setter = findSetterMethod(methods, name, setterPrefix); int attr = ScriptableObject.PERMANENT | ScriptableObject.DONTENUM | (setter != null ? 0 : ScriptableObject.READONLY); ((ScriptableObject) proto).defineProperty(name, null, method, setter, attr); continue; } if (isStatic && !Modifier.isStatic(method.getModifiers())) { throw Context.reportRuntimeError( "jsStaticFunction must be used with static method."); } FunctionObject f = new FunctionObject(name, method, proto); if (f.isVarArgsConstructor()) { throw Context.reportRuntimeError1 ("msg.varargs.fun", ctorMember.getName()); } defineProperty(isStatic ? ctor : proto, name, f, DONTENUM); if (sealed) { f.sealObject(); } } // Call user code to complete initialization if necessary. if (finishInit != null) { Object[] finishArgs = { scope, ctor, proto }; finishInit.invoke(null, finishArgs); } // Seal the object if necessary. if (sealed) { ctor.sealObject(); if (proto instanceof ScriptableObject) { ((ScriptableObject) proto).sealObject(); } } return ctor; } private static Member findAnnotatedMember(AccessibleObject[] members, Class<? extends Annotation> annotation) { for (AccessibleObject member : members) { if (member.isAnnotationPresent(annotation)) { return (Member) member; } } return null; } private static Method findSetterMethod(Method[] methods, String name, String prefix) { String newStyleName = "set" + Character.toUpperCase(name.charAt(0)) + name.substring(1); for (Method method : methods) { JSSetter annotation = method.getAnnotation(JSSetter.class); if (annotation != null) { if (name.equals(annotation.value()) || ("".equals(annotation.value()) && newStyleName.equals(method.getName()))) { return method; } } } String oldStyleName = prefix + name; for (Method method : methods) { if (oldStyleName.equals(method.getName())) { return method; } } return null; } private static String getPropertyName(String methodName, String prefix, Annotation annotation) { if (prefix != null) { return methodName.substring(prefix.length()); } String propName = null; if (annotation instanceof JSGetter) { propName = ((JSGetter) annotation).value(); if (propName == null || propName.length() == 0) { if (methodName.length() > 3 && methodName.startsWith("get")) { propName = methodName.substring(3); if (Character.isUpperCase(propName.charAt(0))) { if (propName.length() == 1) { propName = propName.toLowerCase(); } else if (!Character.isUpperCase(propName.charAt(1))){ propName = Character.toLowerCase(propName.charAt(0)) + propName.substring(1); } } } } } else if (annotation instanceof JSFunction) { propName = ((JSFunction) annotation).value(); } else if (annotation instanceof JSStaticFunction) { propName = ((JSStaticFunction) annotation).value(); } if (propName == null || propName.length() == 0) { propName = methodName; } return propName; } @SuppressWarnings({"unchecked"}) private static <T extends Scriptable> Class<T> extendsScriptable(Class<?> c) { if (ScriptRuntime.ScriptableClass.isAssignableFrom(c)) return (Class<T>) c; return null; } /** * Define a JavaScript property. * * Creates the property with an initial value and sets its attributes. * * @param propertyName the name of the property to define. * @param value the initial value of the property * @param attributes the attributes of the JavaScript property * @see org.mozilla.javascript.Scriptable#put(String, Scriptable, Object) */ public void defineProperty(String propertyName, Object value, int attributes) { checkNotSealed(propertyName, 0); put(propertyName, this, value); setAttributes(propertyName, attributes); } /** * Utility method to add properties to arbitrary Scriptable object. * If destination is instance of ScriptableObject, calls * defineProperty there, otherwise calls put in destination * ignoring attributes */ public static void defineProperty(Scriptable destination, String propertyName, Object value, int attributes) { if (!(destination instanceof ScriptableObject)) { destination.put(propertyName, destination, value); return; } ScriptableObject so = (ScriptableObject)destination; so.defineProperty(propertyName, value, attributes); } /** * Utility method to add properties to arbitrary Scriptable object. * If destination is instance of ScriptableObject, calls * defineProperty there, otherwise calls put in destination * ignoring attributes */ public static void defineConstProperty(Scriptable destination, String propertyName) { if (destination instanceof ConstProperties) { ConstProperties cp = (ConstProperties)destination; cp.defineConst(propertyName, destination); } else defineProperty(destination, propertyName, Undefined.instance, CONST); } /** * Define a JavaScript property with getter and setter side effects. * * If the setter is not found, the attribute READONLY is added to * the given attributes. <p> * * The getter must be a method with zero parameters, and the setter, if * found, must be a method with one parameter.<p> * * @param propertyName the name of the property to define. This name * also affects the name of the setter and getter * to search for. If the propertyId is "foo", then * <code>clazz</code> will be searched for "getFoo" * and "setFoo" methods. * @param clazz the Java class to search for the getter and setter * @param attributes the attributes of the JavaScript property * @see org.mozilla.javascript.Scriptable#put(String, Scriptable, Object) */ public void defineProperty(String propertyName, Class<?> clazz, int attributes) { int length = propertyName.length(); if (length == 0) throw new IllegalArgumentException(); char[] buf = new char[3 + length]; propertyName.getChars(0, length, buf, 3); buf[3] = Character.toUpperCase(buf[3]); buf[0] = 'g'; buf[1] = 'e'; buf[2] = 't'; String getterName = new String(buf); buf[0] = 's'; String setterName = new String(buf); Method[] methods = FunctionObject.getMethodList(clazz); Method getter = FunctionObject.findSingleMethod(methods, getterName); Method setter = FunctionObject.findSingleMethod(methods, setterName); if (setter == null) attributes |= ScriptableObject.READONLY; defineProperty(propertyName, null, getter, setter == null ? null : setter, attributes); } /** * Define a JavaScript property. * * Use this method only if you wish to define getters and setters for * a given property in a ScriptableObject. To create a property without * special getter or setter side effects, use * <code>defineProperty(String,int)</code>. * * If <code>setter</code> is null, the attribute READONLY is added to * the given attributes.<p> * * Several forms of getters or setters are allowed. In all cases the * type of the value parameter can be any one of the following types: * Object, String, boolean, Scriptable, byte, short, int, long, float, * or double. The runtime will perform appropriate conversions based * upon the type of the parameter (see description in FunctionObject). * The first forms are nonstatic methods of the class referred to * by 'this': * <pre> * Object getFoo(); * void setFoo(SomeType value);</pre> * Next are static methods that may be of any class; the object whose * property is being accessed is passed in as an extra argument: * <pre> * static Object getFoo(Scriptable obj); * static void setFoo(Scriptable obj, SomeType value);</pre> * Finally, it is possible to delegate to another object entirely using * the <code>delegateTo</code> parameter. In this case the methods are * nonstatic methods of the class delegated to, and the object whose * property is being accessed is passed in as an extra argument: * <pre> * Object getFoo(Scriptable obj); * void setFoo(Scriptable obj, SomeType value);</pre> * * @param propertyName the name of the property to define. * @param delegateTo an object to call the getter and setter methods on, * or null, depending on the form used above. * @param getter the method to invoke to get the value of the property * @param setter the method to invoke to set the value of the property * @param attributes the attributes of the JavaScript property */ public void defineProperty(String propertyName, Object delegateTo, Method getter, Method setter, int attributes) { MemberBox getterBox = null; if (getter != null) { getterBox = new MemberBox(getter); boolean delegatedForm; if (!Modifier.isStatic(getter.getModifiers())) { delegatedForm = (delegateTo != null); getterBox.delegateTo = delegateTo; } else { delegatedForm = true; // Ignore delegateTo for static getter but store // non-null delegateTo indicator. getterBox.delegateTo = Void.TYPE; } String errorId = null; Class<?>[] parmTypes = getter.getParameterTypes(); if (parmTypes.length == 0) { if (delegatedForm) { errorId = "msg.obj.getter.parms"; } } else if (parmTypes.length == 1) { Object argType = parmTypes[0]; // Allow ScriptableObject for compatibility if (!(argType == ScriptRuntime.ScriptableClass || argType == ScriptRuntime.ScriptableObjectClass)) { errorId = "msg.bad.getter.parms"; } else if (!delegatedForm) { errorId = "msg.bad.getter.parms"; } } else { errorId = "msg.bad.getter.parms"; } if (errorId != null) { throw Context.reportRuntimeError1(errorId, getter.toString()); } } MemberBox setterBox = null; if (setter != null) { if (setter.getReturnType() != Void.TYPE) throw Context.reportRuntimeError1("msg.setter.return", setter.toString()); setterBox = new MemberBox(setter); boolean delegatedForm; if (!Modifier.isStatic(setter.getModifiers())) { delegatedForm = (delegateTo != null); setterBox.delegateTo = delegateTo; } else { delegatedForm = true; // Ignore delegateTo for static setter but store // non-null delegateTo indicator. setterBox.delegateTo = Void.TYPE; } String errorId = null; Class<?>[] parmTypes = setter.getParameterTypes(); if (parmTypes.length == 1) { if (delegatedForm) { errorId = "msg.setter2.expected"; } } else if (parmTypes.length == 2) { Object argType = parmTypes[0]; // Allow ScriptableObject for compatibility if (!(argType == ScriptRuntime.ScriptableClass || argType == ScriptRuntime.ScriptableObjectClass)) { errorId = "msg.setter2.parms"; } else if (!delegatedForm) { errorId = "msg.setter1.parms"; } } else { errorId = "msg.setter.parms"; } if (errorId != null) { throw Context.reportRuntimeError1(errorId, setter.toString()); } } GetterSlot gslot = (GetterSlot)getSlot(propertyName, 0, SLOT_MODIFY_GETTER_SETTER); gslot.setAttributes(attributes); gslot.getter = getterBox; gslot.setter = setterBox; } /** * Defines one or more properties on this object. * * @param cx the current Context * @param props a map of property ids to property descriptors */ public void defineOwnProperties(Context cx, ScriptableObject props) { Object[] ids = props.getIds(); for (Object id : ids) { Object descObj = props.get(id); ScriptableObject desc = ensureScriptableObject(descObj); checkPropertyDefinition(desc); } for (Object id : ids) { ScriptableObject desc = (ScriptableObject)props.get(id); defineOwnProperty(cx, id, desc); } } /** * Defines a property on an object. * * @param cx the current Context * @param id the name/index of the property * @param desc the new property descriptor, as described in 8.6.1 */ public void defineOwnProperty(Context cx, Object id, ScriptableObject desc) { checkPropertyDefinition(desc); defineOwnProperty(cx, id, desc, true); } /** * Defines a property on an object. * * Based on [[DefineOwnProperty]] from 8.12.10 of the spec. * * @param cx the current Context * @param id the name/index of the property * @param desc the new property descriptor, as described in 8.6.1 * @param checkValid whether to perform validity checks */ protected void defineOwnProperty(Context cx, Object id, ScriptableObject desc, boolean checkValid) { Slot slot = getSlot(cx, id, SLOT_QUERY); boolean isNew = slot == null; if (checkValid) { ScriptableObject current = slot == null ? null : slot.getPropertyDescriptor(cx, this); String name = ScriptRuntime.toString(id); checkPropertyChange(name, current, desc); } boolean isAccessor = isAccessorDescriptor(desc); final int attributes; if (slot == null) { // new slot slot = getSlot(cx, id, isAccessor ? SLOT_MODIFY_GETTER_SETTER : SLOT_MODIFY); attributes = applyDescriptorToAttributeBitset(DONTENUM|READONLY|PERMANENT, desc); } else { attributes = applyDescriptorToAttributeBitset(slot.getAttributes(), desc); } slot = unwrapSlot(slot); if (isAccessor) { if ( !(slot instanceof GetterSlot) ) { slot = getSlot(cx, id, SLOT_MODIFY_GETTER_SETTER); } GetterSlot gslot = (GetterSlot) slot; Object getter = getProperty(desc, "get"); if (getter != NOT_FOUND) { gslot.getter = getter; } Object setter = getProperty(desc, "set"); if (setter != NOT_FOUND) { gslot.setter = setter; } gslot.value = Undefined.instance; gslot.setAttributes(attributes); } else { if (slot instanceof GetterSlot && isDataDescriptor(desc)) { slot = getSlot(cx, id, SLOT_CONVERT_ACCESSOR_TO_DATA); } Object value = getProperty(desc, "value"); if (value != NOT_FOUND) { slot.value = value; } else if (isNew) { slot.value = Undefined.instance; } slot.setAttributes(attributes); } } protected void checkPropertyDefinition(ScriptableObject desc) { Object getter = getProperty(desc, "get"); if (getter != NOT_FOUND && getter != Undefined.instance && !(getter instanceof Callable)) { throw ScriptRuntime.notFunctionError(getter); } Object setter = getProperty(desc, "set"); if (setter != NOT_FOUND && setter != Undefined.instance && !(setter instanceof Callable)) { throw ScriptRuntime.notFunctionError(setter); } if (isDataDescriptor(desc) && isAccessorDescriptor(desc)) { throw ScriptRuntime.typeError0("msg.both.data.and.accessor.desc"); } } protected void checkPropertyChange(String id, ScriptableObject current, ScriptableObject desc) { if (current == null) { // new property if (!isExtensible()) throw ScriptRuntime.typeError0("msg.not.extensible"); } else { if (isFalse(current.get("configurable", current))) { if (isTrue(getProperty(desc, "configurable"))) throw ScriptRuntime.typeError1( "msg.change.configurable.false.to.true", id); if (isTrue(current.get("enumerable", current)) != isTrue(getProperty(desc, "enumerable"))) throw ScriptRuntime.typeError1( "msg.change.enumerable.with.configurable.false", id); boolean isData = isDataDescriptor(desc); boolean isAccessor = isAccessorDescriptor(desc); if (!isData && !isAccessor) { // no further validation required for generic descriptor } else if (isData && isDataDescriptor(current)) { if (isFalse(current.get("writable", current))) { if (isTrue(getProperty(desc, "writable"))) throw ScriptRuntime.typeError1( "msg.change.writable.false.to.true.with.configurable.false", id); if (!sameValue(getProperty(desc, "value"), current.get("value", current))) throw ScriptRuntime.typeError1( "msg.change.value.with.writable.false", id); } } else if (isAccessor && isAccessorDescriptor(current)) { if (!sameValue(getProperty(desc, "set"), current.get("set", current))) throw ScriptRuntime.typeError1( "msg.change.setter.with.configurable.false", id); if (!sameValue(getProperty(desc, "get"), current.get("get", current))) throw ScriptRuntime.typeError1( "msg.change.getter.with.configurable.false", id); } else { if (isDataDescriptor(current)) throw ScriptRuntime.typeError1( "msg.change.property.data.to.accessor.with.configurable.false", id); else throw ScriptRuntime.typeError1( "msg.change.property.accessor.to.data.with.configurable.false", id); } } } } protected static boolean isTrue(Object value) { return (value != NOT_FOUND) && ScriptRuntime.toBoolean(value); } protected static boolean isFalse(Object value) { return !isTrue(value); } /** * Implements SameValue as described in ES5 9.12, additionally checking * if new value is defined. * @param newValue the new value * @param currentValue the current value * @return true if values are the same as defined by ES5 9.12 */ protected boolean sameValue(Object newValue, Object currentValue) { if (newValue == NOT_FOUND) { return true; } if (currentValue == NOT_FOUND) { currentValue = Undefined.instance; } // Special rules for numbers: NaN is considered the same value, // while zeroes with different signs are considered different. if (currentValue instanceof Number && newValue instanceof Number) { double d1 = ((Number)currentValue).doubleValue(); double d2 = ((Number)newValue).doubleValue(); if (Double.isNaN(d1) && Double.isNaN(d2)) { return true; } if (d1 == 0.0 && Double.doubleToLongBits(d1) != Double.doubleToLongBits(d2)) { return false; } } return ScriptRuntime.shallowEq(currentValue, newValue); } protected int applyDescriptorToAttributeBitset(int attributes, ScriptableObject desc) { Object enumerable = getProperty(desc, "enumerable"); if (enumerable != NOT_FOUND) { attributes = ScriptRuntime.toBoolean(enumerable) ? attributes & ~DONTENUM : attributes | DONTENUM; } Object writable = getProperty(desc, "writable"); if (writable != NOT_FOUND) { attributes = ScriptRuntime.toBoolean(writable) ? attributes & ~READONLY : attributes | READONLY; } Object configurable = getProperty(desc, "configurable"); if (configurable != NOT_FOUND) { attributes = ScriptRuntime.toBoolean(configurable) ? attributes & ~PERMANENT : attributes | PERMANENT; } return attributes; } /** * Implements IsDataDescriptor as described in ES5 8.10.2 * @param desc a property descriptor * @return true if this is a data descriptor. */ protected boolean isDataDescriptor(ScriptableObject desc) { return hasProperty(desc, "value") || hasProperty(desc, "writable"); } /** * Implements IsAccessorDescriptor as described in ES5 8.10.1 * @param desc a property descriptor * @return true if this is an accessor descriptor. */ protected boolean isAccessorDescriptor(ScriptableObject desc) { return hasProperty(desc, "get") || hasProperty(desc, "set"); } /** * Implements IsGenericDescriptor as described in ES5 8.10.3 * @param desc a property descriptor * @return true if this is a generic descriptor. */ protected boolean isGenericDescriptor(ScriptableObject desc) { return !isDataDescriptor(desc) && !isAccessorDescriptor(desc); } protected static Scriptable ensureScriptable(Object arg) { if ( !(arg instanceof Scriptable) ) throw ScriptRuntime.typeError1("msg.arg.not.object", ScriptRuntime.typeof(arg)); return (Scriptable) arg; } protected static ScriptableObject ensureScriptableObject(Object arg) { if ( !(arg instanceof ScriptableObject) ) throw ScriptRuntime.typeError1("msg.arg.not.object", ScriptRuntime.typeof(arg)); return (ScriptableObject) arg; } /** * Search for names in a class, adding the resulting methods * as properties. * * <p> Uses reflection to find the methods of the given names. Then * FunctionObjects are constructed from the methods found, and * are added to this object as properties with the given names. * * @param names the names of the Methods to add as function properties * @param clazz the class to search for the Methods * @param attributes the attributes of the new properties * @see org.mozilla.javascript.FunctionObject */ public void defineFunctionProperties(String[] names, Class<?> clazz, int attributes) { Method[] methods = FunctionObject.getMethodList(clazz); for (int i=0; i < names.length; i++) { String name = names[i]; Method m = FunctionObject.findSingleMethod(methods, name); if (m == null) { throw Context.reportRuntimeError2( "msg.method.not.found", name, clazz.getName()); } FunctionObject f = new FunctionObject(name, m, this); defineProperty(name, f, attributes); } } /** * Get the Object.prototype property. * See ECMA 15.2.4. */ public static Scriptable getObjectPrototype(Scriptable scope) { return TopLevel.getBuiltinPrototype(getTopLevelScope(scope), TopLevel.Builtins.Object); } /** * Get the Function.prototype property. * See ECMA 15.3.4. */ public static Scriptable getFunctionPrototype(Scriptable scope) { return TopLevel.getBuiltinPrototype(getTopLevelScope(scope), TopLevel.Builtins.Function); } public static Scriptable getArrayPrototype(Scriptable scope) { return TopLevel.getBuiltinPrototype(getTopLevelScope(scope), TopLevel.Builtins.Array); } /** * Get the prototype for the named class. * * For example, <code>getClassPrototype(s, "Date")</code> will first * walk up the parent chain to find the outermost scope, then will * search that scope for the Date constructor, and then will * return Date.prototype. If any of the lookups fail, or * the prototype is not a JavaScript object, then null will * be returned. * * @param scope an object in the scope chain * @param className the name of the constructor * @return the prototype for the named class, or null if it * cannot be found. */ public static Scriptable getClassPrototype(Scriptable scope, String className) { scope = getTopLevelScope(scope); Object ctor = getProperty(scope, className); Object proto; if (ctor instanceof BaseFunction) { proto = ((BaseFunction)ctor).getPrototypeProperty(); } else if (ctor instanceof Scriptable) { Scriptable ctorObj = (Scriptable)ctor; proto = ctorObj.get("prototype", ctorObj); } else { return null; } if (proto instanceof Scriptable) { return (Scriptable)proto; } return null; } /** * Get the global scope. * * <p>Walks the parent scope chain to find an object with a null * parent scope (the global object). * * @param obj a JavaScript object * @return the corresponding global scope */ public static Scriptable getTopLevelScope(Scriptable obj) { for (;;) { Scriptable parent = obj.getParentScope(); if (parent == null) { return obj; } obj = parent; } } public boolean isExtensible() { return isExtensible; } public void preventExtensions() { isExtensible = false; } /** * Seal this object. * * It is an error to add properties to or delete properties from * a sealed object. It is possible to change the value of an * existing property. Once an object is sealed it may not be unsealed. * * @since 1.4R3 */ public synchronized void sealObject() { if (count >= 0) { // Make sure all LazilyLoadedCtors are initialized before sealing. Slot slot = firstAdded; while (slot != null) { Object value = slot.value; if (value instanceof LazilyLoadedCtor) { LazilyLoadedCtor initializer = (LazilyLoadedCtor) value; try { initializer.init(); } finally { slot.value = initializer.getValue(); } } slot = slot.orderedNext; } count = ~count; } } /** * Return true if this object is sealed. * * @return true if sealed, false otherwise. * @since 1.4R3 * @see #sealObject() */ public final boolean isSealed() { return count < 0; } private void checkNotSealed(String name, int index) { if (!isSealed()) return; String str = (name != null) ? name : Integer.toString(index); throw Context.reportRuntimeError1("msg.modify.sealed", str); } /** * Gets a named property from an object or any object in its prototype chain. * <p> * Searches the prototype chain for a property named <code>name</code>. * <p> * @param obj a JavaScript object * @param name a property name * @return the value of a property with name <code>name</code> found in * <code>obj</code> or any object in its prototype chain, or * <code>Scriptable.NOT_FOUND</code> if not found * @since 1.5R2 */ public static Object getProperty(Scriptable obj, String name) { Scriptable start = obj; Object result; do { result = obj.get(name, start); if (result != Scriptable.NOT_FOUND) break; obj = obj.getPrototype(); } while (obj != null); return result; } /** * Gets an indexed property from an object or any object in its prototype * chain and coerces it to the requested Java type. * <p> * Searches the prototype chain for a property with integral index * <code>index</code>. Note that if you wish to look for properties with numerical * but non-integral indicies, you should use getProperty(Scriptable,String) with * the string value of the index. * <p> * @param s a JavaScript object * @param index an integral index * @param type the required Java type of the result * @return the value of a property with name <code>name</code> found in * <code>obj</code> or any object in its prototype chain, or * null if not found. Note that it does not return * {@link Scriptable#NOT_FOUND} as it can ordinarily not be * converted to most of the types. * @since 1.7R3 */ public static <T> T getTypedProperty(Scriptable s, int index, Class<T> type) { Object val = getProperty(s, index); if(val == Scriptable.NOT_FOUND) { val = null; } return type.cast(Context.jsToJava(val, type)); } /** * Gets an indexed property from an object or any object in its prototype chain. * <p> * Searches the prototype chain for a property with integral index * <code>index</code>. Note that if you wish to look for properties with numerical * but non-integral indicies, you should use getProperty(Scriptable,String) with * the string value of the index. * <p> * @param obj a JavaScript object * @param index an integral index * @return the value of a property with index <code>index</code> found in * <code>obj</code> or any object in its prototype chain, or * <code>Scriptable.NOT_FOUND</code> if not found * @since 1.5R2 */ public static Object getProperty(Scriptable obj, int index) { Scriptable start = obj; Object result; do { result = obj.get(index, start); if (result != Scriptable.NOT_FOUND) break; obj = obj.getPrototype(); } while (obj != null); return result; } /** * Gets a named property from an object or any object in its prototype chain * and coerces it to the requested Java type. * <p> * Searches the prototype chain for a property named <code>name</code>. * <p> * @param s a JavaScript object * @param name a property name * @param type the required Java type of the result * @return the value of a property with name <code>name</code> found in * <code>obj</code> or any object in its prototype chain, or * null if not found. Note that it does not return * {@link Scriptable#NOT_FOUND} as it can ordinarily not be * converted to most of the types. * @since 1.7R3 */ public static <T> T getTypedProperty(Scriptable s, String name, Class<T> type) { Object val = getProperty(s, name); if(val == Scriptable.NOT_FOUND) { val = null; } return type.cast(Context.jsToJava(val, type)); } /** * Returns whether a named property is defined in an object or any object * in its prototype chain. * <p> * Searches the prototype chain for a property named <code>name</code>. * <p> * @param obj a JavaScript object * @param name a property name * @return the true if property was found * @since 1.5R2 */ public static boolean hasProperty(Scriptable obj, String name) { return null != getBase(obj, name); } /** * If hasProperty(obj, name) would return true, then if the property that * was found is compatible with the new property, this method just returns. * If the property is not compatible, then an exception is thrown. * * A property redefinition is incompatible if the first definition was a * const declaration or if this one is. They are compatible only if neither * was const. */ public static void redefineProperty(Scriptable obj, String name, boolean isConst) { Scriptable base = getBase(obj, name); if (base == null) return; if (base instanceof ConstProperties) { ConstProperties cp = (ConstProperties)base; if (cp.isConst(name)) throw ScriptRuntime.typeError1("msg.const.redecl", name); } if (isConst) throw ScriptRuntime.typeError1("msg.var.redecl", name); } /** * Returns whether an indexed property is defined in an object or any object * in its prototype chain. * <p> * Searches the prototype chain for a property with index <code>index</code>. * <p> * @param obj a JavaScript object * @param index a property index * @return the true if property was found * @since 1.5R2 */ public static boolean hasProperty(Scriptable obj, int index) { return null != getBase(obj, index); } /** * Puts a named property in an object or in an object in its prototype chain. * <p> * Searches for the named property in the prototype chain. If it is found, * the value of the property in <code>obj</code> is changed through a call * to {@link Scriptable#put(String, Scriptable, Object)} on the * prototype passing <code>obj</code> as the <code>start</code> argument. * This allows the prototype to veto the property setting in case the * prototype defines the property with [[ReadOnly]] attribute. If the * property is not found, it is added in <code>obj</code>. * @param obj a JavaScript object * @param name a property name * @param value any JavaScript value accepted by Scriptable.put * @since 1.5R2 */ public static void putProperty(Scriptable obj, String name, Object value) { Scriptable base = getBase(obj, name); if (base == null) base = obj; base.put(name, obj, value); } /** * Puts a named property in an object or in an object in its prototype chain. * <p> * Searches for the named property in the prototype chain. If it is found, * the value of the property in <code>obj</code> is changed through a call * to {@link Scriptable#put(String, Scriptable, Object)} on the * prototype passing <code>obj</code> as the <code>start</code> argument. * This allows the prototype to veto the property setting in case the * prototype defines the property with [[ReadOnly]] attribute. If the * property is not found, it is added in <code>obj</code>. * @param obj a JavaScript object * @param name a property name * @param value any JavaScript value accepted by Scriptable.put * @since 1.5R2 */ public static void putConstProperty(Scriptable obj, String name, Object value) { Scriptable base = getBase(obj, name); if (base == null) base = obj; if (base instanceof ConstProperties) ((ConstProperties)base).putConst(name, obj, value); } /** * Puts an indexed property in an object or in an object in its prototype chain. * <p> * Searches for the indexed property in the prototype chain. If it is found, * the value of the property in <code>obj</code> is changed through a call * to {@link Scriptable#put(int, Scriptable, Object)} on the prototype * passing <code>obj</code> as the <code>start</code> argument. This allows * the prototype to veto the property setting in case the prototype defines * the property with [[ReadOnly]] attribute. If the property is not found, * it is added in <code>obj</code>. * @param obj a JavaScript object * @param index a property index * @param value any JavaScript value accepted by Scriptable.put * @since 1.5R2 */ public static void putProperty(Scriptable obj, int index, Object value) { Scriptable base = getBase(obj, index); if (base == null) base = obj; base.put(index, obj, value); } /** * Removes the property from an object or its prototype chain. * <p> * Searches for a property with <code>name</code> in obj or * its prototype chain. If it is found, the object's delete * method is called. * @param obj a JavaScript object * @param name a property name * @return true if the property doesn't exist or was successfully removed * @since 1.5R2 */ public static boolean deleteProperty(Scriptable obj, String name) { Scriptable base = getBase(obj, name); if (base == null) return true; base.delete(name); return !base.has(name, obj); } /** * Removes the property from an object or its prototype chain. * <p> * Searches for a property with <code>index</code> in obj or * its prototype chain. If it is found, the object's delete * method is called. * @param obj a JavaScript object * @param index a property index * @return true if the property doesn't exist or was successfully removed * @since 1.5R2 */ public static boolean deleteProperty(Scriptable obj, int index) { Scriptable base = getBase(obj, index); if (base == null) return true; base.delete(index); return !base.has(index, obj); } /** * Returns an array of all ids from an object and its prototypes. * <p> * @param obj a JavaScript object * @return an array of all ids from all object in the prototype chain. * If a given id occurs multiple times in the prototype chain, * it will occur only once in this list. * @since 1.5R2 */ public static Object[] getPropertyIds(Scriptable obj) { if (obj == null) { return ScriptRuntime.emptyArgs; } Object[] result = obj.getIds(); ObjToIntMap map = null; for (;;) { obj = obj.getPrototype(); if (obj == null) { break; } Object[] ids = obj.getIds(); if (ids.length == 0) { continue; } if (map == null) { if (result.length == 0) { result = ids; continue; } map = new ObjToIntMap(result.length + ids.length); for (int i = 0; i != result.length; ++i) { map.intern(result[i]); } result = null; // Allow to GC the result } for (int i = 0; i != ids.length; ++i) { map.intern(ids[i]); } } if (map != null) { result = map.getKeys(); } return result; } /** * Call a method of an object. * @param obj the JavaScript object * @param methodName the name of the function property * @param args the arguments for the call * * @see Context#getCurrentContext() */ public static Object callMethod(Scriptable obj, String methodName, Object[] args) { return callMethod(null, obj, methodName, args); } /** * Call a method of an object. * @param cx the Context object associated with the current thread. * @param obj the JavaScript object * @param methodName the name of the function property * @param args the arguments for the call */ public static Object callMethod(Context cx, Scriptable obj, String methodName, Object[] args) { Object funObj = getProperty(obj, methodName); if (!(funObj instanceof Function)) { throw ScriptRuntime.notFunctionError(obj, methodName); } Function fun = (Function)funObj; // XXX: What should be the scope when calling funObj? // The following favor scope stored in the object on the assumption // that is more useful especially under dynamic scope setup. // An alternative is to check for dynamic scope flag // and use ScriptableObject.getTopLevelScope(fun) if the flag is not // set. But that require access to Context and messy code // so for now it is not checked. Scriptable scope = ScriptableObject.getTopLevelScope(obj); if (cx != null) { return fun.call(cx, scope, obj, args); } else { return Context.call(null, fun, scope, obj, args); } } private static Scriptable getBase(Scriptable obj, String name) { do { if (obj.has(name, obj)) break; obj = obj.getPrototype(); } while(obj != null); return obj; } private static Scriptable getBase(Scriptable obj, int index) { do { if (obj.has(index, obj)) break; obj = obj.getPrototype(); } while(obj != null); return obj; } /** * Get arbitrary application-specific value associated with this object. * @param key key object to select particular value. * @see #associateValue(Object key, Object value) */ public final Object getAssociatedValue(Object key) { Map<Object,Object> h = associatedValues; if (h == null) return null; return h.get(key); } /** * Get arbitrary application-specific value associated with the top scope * of the given scope. * The method first calls {@link #getTopLevelScope(Scriptable scope)} * and then searches the prototype chain of the top scope for the first * object containing the associated value with the given key. * * @param scope the starting scope. * @param key key object to select particular value. * @see #getAssociatedValue(Object key) */ public static Object getTopScopeValue(Scriptable scope, Object key) { scope = ScriptableObject.getTopLevelScope(scope); for (;;) { if (scope instanceof ScriptableObject) { ScriptableObject so = (ScriptableObject)scope; Object value = so.getAssociatedValue(key); if (value != null) { return value; } } scope = scope.getPrototype(); if (scope == null) { return null; } } } /** * Associate arbitrary application-specific value with this object. * Value can only be associated with the given object and key only once. * The method ignores any subsequent attempts to change the already * associated value. * <p> The associated values are not serialized. * @param key key object to select particular value. * @param value the value to associate * @return the passed value if the method is called first time for the * given key or old value for any subsequent calls. * @see #getAssociatedValue(Object key) */ public synchronized final Object associateValue(Object key, Object value) { if (value == null) throw new IllegalArgumentException(); Map<Object,Object> h = associatedValues; if (h == null) { h = new HashMap<Object,Object>(); associatedValues = h; } return Kit.initHash(h, key, value); } /** * * @param name * @param index * @param start * @param value * @return false if this != start and no slot was found. true if this == start * or this != start and a READONLY slot was found. */ private boolean putImpl(String name, int index, Scriptable start, Object value) { // This method is very hot (basically called on each assignment) // so we inline the extensible/sealed checks below. Slot slot; if (this != start) { slot = getSlot(name, index, SLOT_QUERY); if (slot == null) { return false; } } else if (!isExtensible) { slot = getSlot(name, index, SLOT_QUERY); if (slot == null) { return true; } } else { if (count < 0) checkNotSealed(name, index); slot = getSlot(name, index, SLOT_MODIFY); } return slot.setValue(value, this, start); } /** * * @param name * @param index * @param start * @param value * @param constFlag EMPTY means normal put. UNINITIALIZED_CONST means * defineConstProperty. READONLY means const initialization expression. * @return false if this != start and no slot was found. true if this == start * or this != start and a READONLY slot was found. */ private boolean putConstImpl(String name, int index, Scriptable start, Object value, int constFlag) { assert (constFlag != EMPTY); Slot slot; if (this != start) { slot = getSlot(name, index, SLOT_QUERY); if (slot == null) { return false; } } else if (!isExtensible()) { slot = getSlot(name, index, SLOT_QUERY); if (slot == null) { return true; } } else { checkNotSealed(name, index); // either const hoisted declaration or initialization slot = unwrapSlot(getSlot(name, index, SLOT_MODIFY_CONST)); int attr = slot.getAttributes(); if ((attr & READONLY) == 0) throw Context.reportRuntimeError1("msg.var.redecl", name); if ((attr & UNINITIALIZED_CONST) != 0) { slot.value = value; // clear the bit on const initialization if (constFlag != UNINITIALIZED_CONST) slot.setAttributes(attr & ~UNINITIALIZED_CONST); } return true; } return slot.setValue(value, this, start); } private Slot findAttributeSlot(String name, int index, int accessType) { Slot slot = getSlot(name, index, accessType); if (slot == null) { String str = (name != null ? name : Integer.toString(index)); throw Context.reportRuntimeError1("msg.prop.not.found", str); } return slot; } private static Slot unwrapSlot(Slot slot) { return (slot instanceof RelinkedSlot) ? ((RelinkedSlot)slot).slot : slot; } /** * Locate the slot with given name or index. Depending on the accessType * parameter and the current slot status, a new slot may be allocated. * * @param name property name or null if slot holds spare array index. * @param index index or 0 if slot holds property name. */ private Slot getSlot(String name, int index, int accessType) { // Check the hashtable without using synchronization Slot[] slotsLocalRef = slots; // Get stable local reference if (slotsLocalRef == null && accessType == SLOT_QUERY) { return null; } int indexOrHash = (name != null ? name.hashCode() : index); if (slotsLocalRef != null) { Slot slot; int slotIndex = getSlotIndex(slotsLocalRef.length, indexOrHash); for (slot = slotsLocalRef[slotIndex]; slot != null; slot = slot.next) { Object sname = slot.name; if (indexOrHash == slot.indexOrHash && (sname == name || (name != null && name.equals(sname)))) { break; } } switch (accessType) { case SLOT_QUERY: return slot; case SLOT_MODIFY: case SLOT_MODIFY_CONST: if (slot != null) return slot; break; case SLOT_MODIFY_GETTER_SETTER: slot = unwrapSlot(slot); if (slot instanceof GetterSlot) return slot; break; case SLOT_CONVERT_ACCESSOR_TO_DATA: slot = unwrapSlot(slot); if ( !(slot instanceof GetterSlot) ) return slot; break; } } // A new slot has to be inserted or the old has to be replaced // by GetterSlot. Time to synchronize. return createSlot(name, indexOrHash, accessType); } private synchronized Slot createSlot(String name, int indexOrHash, int accessType) { Slot[] slotsLocalRef = slots; int insertPos; if (count == 0) { // Always throw away old slots if any on empty insert. slotsLocalRef = new Slot[INITIAL_SLOT_SIZE]; slots = slotsLocalRef; insertPos = getSlotIndex(slotsLocalRef.length, indexOrHash); } else { int tableSize = slotsLocalRef.length; insertPos = getSlotIndex(tableSize, indexOrHash); Slot prev = slotsLocalRef[insertPos]; Slot slot = prev; while (slot != null) { if (slot.indexOrHash == indexOrHash && (slot.name == name || (name != null && name.equals(slot.name)))) { break; } prev = slot; slot = slot.next; } if (slot != null) { // A slot with same name/index already exists. This means that // a slot is being redefined from a value to a getter slot or // vice versa, or it could be a race in application code. // Check if we need to replace the slot depending on the // accessType flag and return the appropriate slot instance. Slot inner = unwrapSlot(slot); Slot newSlot; if (accessType == SLOT_MODIFY_GETTER_SETTER && !(inner instanceof GetterSlot)) { newSlot = new GetterSlot(name, indexOrHash, inner.getAttributes()); } else if (accessType == SLOT_CONVERT_ACCESSOR_TO_DATA && (inner instanceof GetterSlot)) { newSlot = new Slot(name, indexOrHash, inner.getAttributes()); } else if (accessType == SLOT_MODIFY_CONST) { return null; } else { return inner; } newSlot.value = inner.value; newSlot.next = slot.next; // add new slot to linked list if (lastAdded != null) { lastAdded.orderedNext = newSlot; } if (firstAdded == null) { firstAdded = newSlot; } lastAdded = newSlot; // add new slot to hash table if (prev == slot) { slotsLocalRef[insertPos] = newSlot; } else { prev.next = newSlot; } // other housekeeping slot.markDeleted(); return newSlot; } else { // Check if the table is not too full before inserting. if (4 * (count + 1) > 3 * slotsLocalRef.length) { // table size must be a power of 2, always grow by x2 slotsLocalRef = new Slot[slotsLocalRef.length * 2]; copyTable(slots, slotsLocalRef, count); slots = slotsLocalRef; insertPos = getSlotIndex(slotsLocalRef.length, indexOrHash); } } } Slot newSlot = (accessType == SLOT_MODIFY_GETTER_SETTER ? new GetterSlot(name, indexOrHash, 0) : new Slot(name, indexOrHash, 0)); if (accessType == SLOT_MODIFY_CONST) newSlot.setAttributes(CONST); ++count; // add new slot to linked list if (lastAdded != null) lastAdded.orderedNext = newSlot; if (firstAdded == null) firstAdded = newSlot; lastAdded = newSlot; // add new slot to hash table, return it addKnownAbsentSlot(slotsLocalRef, newSlot, insertPos); return newSlot; } private synchronized void removeSlot(String name, int index) { int indexOrHash = (name != null ? name.hashCode() : index); Slot[] slotsLocalRef = slots; if (count != 0) { int tableSize = slotsLocalRef.length; int slotIndex = getSlotIndex(tableSize, indexOrHash); Slot prev = slotsLocalRef[slotIndex]; Slot slot = prev; while (slot != null) { if (slot.indexOrHash == indexOrHash && (slot.name == name || (name != null && name.equals(slot.name)))) { break; } prev = slot; slot = slot.next; } if (slot != null && (slot.getAttributes() & PERMANENT) == 0) { count--; // remove slot from hash table if (prev == slot) { slotsLocalRef[slotIndex] = slot.next; } else { prev.next = slot.next; } // remove from ordered list. Previously this was done lazily in // getIds() but delete is an infrequent operation so O(n) // should be ok // ordered list always uses the actual slot Slot deleted = unwrapSlot(slot); if (deleted == firstAdded) { prev = null; firstAdded = deleted.orderedNext; } else { prev = firstAdded; while (prev.orderedNext != deleted) { prev = prev.orderedNext; } prev.orderedNext = deleted.orderedNext; } if (deleted == lastAdded) { lastAdded = prev; } // Mark the slot as removed. slot.markDeleted(); } } } private static int getSlotIndex(int tableSize, int indexOrHash) { // tableSize is a power of 2 return indexOrHash & (tableSize - 1); } // Must be inside synchronized (this) private static void copyTable(Slot[] oldSlots, Slot[] newSlots, int count) { if (count == 0) throw Kit.codeBug(); int tableSize = newSlots.length; int i = oldSlots.length; for (;;) { --i; Slot slot = oldSlots[i]; while (slot != null) { int insertPos = getSlotIndex(tableSize, slot.indexOrHash); // If slot has next chain in old table use a new // RelinkedSlot wrapper to keep old table valid Slot insSlot = slot.next == null ? slot : new RelinkedSlot(slot); addKnownAbsentSlot(newSlots, insSlot, insertPos); slot = slot.next; if (--count == 0) return; } } } /** * Add slot with keys that are known to absent from the table. * This is an optimization to use when inserting into empty table, * after table growth or during deserialization. */ private static void addKnownAbsentSlot(Slot[] slots, Slot slot, int insertPos) { if (slots[insertPos] == null) { slots[insertPos] = slot; } else { Slot prev = slots[insertPos]; Slot next = prev.next; while (next != null) { prev = next; next = prev.next; } prev.next = slot; } } Object[] getIds(boolean getAll) { Slot[] s = slots; Object[] a = ScriptRuntime.emptyArgs; if (s == null) return a; int c = 0; Slot slot = firstAdded; while (slot != null && slot.wasDeleted) { // we used to removed deleted slots from the linked list here // but this is now done in removeSlot(). There may still be deleted // slots (e.g. from slot conversion) but we don't want to mess // with the list in unsynchronized code. slot = slot.orderedNext; } while (slot != null) { if (getAll || (slot.getAttributes() & DONTENUM) == 0) { if (c == 0) a = new Object[s.length]; a[c++] = slot.name != null ? slot.name : Integer.valueOf(slot.indexOrHash); } slot = slot.orderedNext; while (slot != null && slot.wasDeleted) { // skip deleted slots, see comment above slot = slot.orderedNext; } } if (c == a.length) return a; Object[] result = new Object[c]; System.arraycopy(a, 0, result, 0, c); return result; } private synchronized void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); int objectsCount = count; if (objectsCount < 0) { // "this" was sealed objectsCount = ~objectsCount; } if (objectsCount == 0) { out.writeInt(0); } else { out.writeInt(slots.length); Slot slot = firstAdded; while (slot != null && slot.wasDeleted) { // as long as we're traversing the order-added linked list, // remove deleted slots slot = slot.orderedNext; } firstAdded = slot; while (slot != null) { out.writeObject(slot); Slot next = slot.orderedNext; while (next != null && next.wasDeleted) { // remove deleted slots next = next.orderedNext; } slot.orderedNext = next; slot = next; } } } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); int tableSize = in.readInt(); if (tableSize != 0) { // If tableSize is not a power of 2 find the closest // power of 2 >= the original size. if ((tableSize & (tableSize - 1)) != 0) { if (tableSize > 1 << 30) throw new RuntimeException("Property table overflow"); int newSize = INITIAL_SLOT_SIZE; while (newSize < tableSize) newSize <<= 1; tableSize = newSize; } slots = new Slot[tableSize]; int objectsCount = count; if (objectsCount < 0) { // "this" was sealed objectsCount = ~objectsCount; } Slot prev = null; for (int i=0; i != objectsCount; ++i) { lastAdded = (Slot)in.readObject(); if (i==0) { firstAdded = lastAdded; } else { prev.orderedNext = lastAdded; } int slotIndex = getSlotIndex(tableSize, lastAdded.indexOrHash); addKnownAbsentSlot(slots, lastAdded, slotIndex); prev = lastAdded; } } } protected ScriptableObject getOwnPropertyDescriptor(Context cx, Object id) { Slot slot = getSlot(cx, id, SLOT_QUERY); if (slot == null) return null; Scriptable scope = getParentScope(); return slot.getPropertyDescriptor(cx, (scope == null ? this : scope)); } protected Slot getSlot(Context cx, Object id, int accessType) { String name = ScriptRuntime.toStringIdOrIndex(cx, id); if (name == null) { return getSlot(null, ScriptRuntime.lastIndexResult(cx), accessType); } else { return getSlot(name, 0, accessType); } } // Partial implementation of java.util.Map. See NativeObject for // a subclass that implements java.util.Map. public int size() { return count < 0 ? ~count : count; } public boolean isEmpty() { return count == 0 || count == -1; } public Object get(Object key) { Object value = null; if (key instanceof String) { value = get((String) key, this); } else if (key instanceof Number) { value = get(((Number) key).intValue(), this); } if (value == Scriptable.NOT_FOUND || value == Undefined.instance) { return null; } else if (value instanceof Wrapper) { return ((Wrapper) value).unwrap(); } else { return value; } } }
37.777599
106
0.570743
dd5587e113162333419b236d3f9ae3519c3f41a5
12,544
package br.edu.uniacademia.ativcompl; import java.text.SimpleDateFormat; import java.util.Arrays; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import br.edu.uniacademia.ativcompl.domain.Activity; import br.edu.uniacademia.ativcompl.domain.Address; import br.edu.uniacademia.ativcompl.domain.Campus; import br.edu.uniacademia.ativcompl.domain.Category; import br.edu.uniacademia.ativcompl.domain.Course; import br.edu.uniacademia.ativcompl.domain.Student; import br.edu.uniacademia.ativcompl.domain.User; import br.edu.uniacademia.ativcompl.domain.UserType; import br.edu.uniacademia.ativcompl.domain.enums.Valuation; import br.edu.uniacademia.ativcompl.repositories.ActivityRepository; import br.edu.uniacademia.ativcompl.repositories.AddressRepository; import br.edu.uniacademia.ativcompl.repositories.CampusRepository; import br.edu.uniacademia.ativcompl.repositories.CategoryRepository; import br.edu.uniacademia.ativcompl.repositories.CourseRepository; import br.edu.uniacademia.ativcompl.repositories.StudentRepository; import br.edu.uniacademia.ativcompl.repositories.UserRepository; import br.edu.uniacademia.ativcompl.repositories.UserTypeRepository; @SpringBootApplication public class AtivcomplApplication implements CommandLineRunner{ @Autowired private AddressRepository addressRepository; @Autowired private UserRepository userRepository; @Autowired private UserTypeRepository userTypeRepository; @Autowired private CampusRepository campusRepository; @Autowired private CourseRepository courseRepository; @Autowired private CategoryRepository categoryRepository; @Autowired private StudentRepository studentRepository; @Autowired private ActivityRepository activityRepository; public static void main(String[] args) { SpringApplication.run(AtivcomplApplication.class, args); } @Override public void run(String... args) throws Exception { // Address addr1 = new Address(null, "Rua I", "621", "Jardim Itália II", "Uberaba"); // Address addr2 = new Address(null, "Rua Primavera", "560", "Baixa da Colina", "Rio Branco"); // Address addr3 = new Address(null, "Rua Major Izidoro Jerônimo da Rocha", "450","Jacarecica", "Maceió"); // Address addr4 = new Address(null, "Quadra SHIN QI 2", "581", "Setor de Habitações Individuais Norte", "Brasília"); // Address addr5 = new Address(null, "Rua Monte Sião", "967", "Tarumã", "Manaus"); // Address addr6 = new Address(null, "Quadra QRSW 5 Bloco A-3", "604", "Setor Sudoeste", "Brasília"); // Address addr7 = new Address(null, "Rua Noé Fortes", "519", "Uruguai", "Teresina"); Address addr8 = new Address(null, "Rua Dom Luiz", "970", "Centro", "Belo Jardim"); Address addr9 = new Address(null, "Alameda do Lago", "608", "Posse", "Teresópolis"); Address addr10 = new Address(null, "Rua J", "914", "Nova Cidade", "Manaus"); Address addr11 = new Address(null, "Rua H", "854", "Alto Maron", "Vitória da Conquista"); Address addr12 = new Address(null, "Vila Militar", "817", "Tambauzinho", "João Pessoa"); Address addr13 = new Address(null, "Rua Alemanha", "546", "Loteamento Menino Jesus I", "Sinop"); Address addr14 = new Address(null, "Rua Pinheiro Machado", "650", "Cidade Alta", "Alegrete"); Address addr15 = new Address(null, "Rua Juvêncio Hilário de Santana", "767", "Bugio", "Aracaju"); Address addr16 = new Address(null, "Rua Zabaram", "647", "Jorge Teixeira", "Manaus"); Address addr17 = new Address(null, "Rodovia BR-364", "672", "Eletronorte", "Porto Velho"); Address addr18 = new Address(null, "Quadra CLS 110 Bloco B", "986", "Asa Sul", "Brasília"); Address addr19 = new Address(null, "Rua Severina Batista Andrade Goulart", "657", "Novo Horizonte", "Crato"); Address addr20 = new Address(null, "Rua Gravataí", "864", "Potengi", "Natal"); // Coordenador: "Sistemas de Informação" e "Engenharia de Software" User user1 = new User(null, "375.577.622-74", "Vitória Carolina Barbosa", "vitoriacarolinabarbosa-96@lphbrasil.com.br", "UQk4wSoai7"); // Supervisor: "Sistemas de Informação" e "Engenharia de Software" User user2 = new User(null, "124.906.495-31", "Guilherme Samuel Pires", "guilhermesamuelpires@cedda.com.br", "1XbTTe9udg"); // Coordenador: "Administração" User user3 = new User(null, "441.377.809-00", "Agatha Brenda Moreira", "agathabrendamoreira@pubdesign.com.br", "p4x2RimGji"); // Supervisor: "Administração" User user4 = new User(null, "420.790.053-59", "Joana Carolina Souza", "joanacarolinasouza@jbtc.com", "4ld5o8RYYb"); // Coordenador: "NuserTiporição" e "Fisioterapia" User user5 = new User(null, "169.588.437-03", "Bernardo Anthony Davi Drumond", "bernardoanthonydavidrumond-77@raya3.com.br", "W2BRb4G4Qz"); // Supervisor: "NuserTiporição" e "Fisioterapia" User user6 = new User(null, "272.659.622-30", "Isabel Renata Agatha Pinto", "isabelrenataagathapinto@charquesorocaba.com.br", "ILyZyTXflo"); // Coordenador: "Teologia" e "Filosofia" // Supervisor: "Teologia" e "Filosofia" User user7 = new User(null, "267.364.255-22", "Luiz Kaique Isaac Jesus", "luizkaiqueisaacjesus@budsoncorporation.com", "owX8j6ltA0"); // Administador e Aluno "Sistemas de Informação" User user8 = new User(null, "017.728.964-38", "Nathan Noah Thiago da Costa", "nathannoahthiagodacosta@esplanadaviagens.com.br", "MN98AOw70K"); // Alunos: // "Sistemas de Informação" User user9 = new User(null, "824.973.055-01", "Diogo Raul Silva", "diogoraulsilva-78@digen.com.br", "D7Zi2H17rW"); // "Engenharia de Software" User user10 = new User(null, "770.164.986-70", "Rafaela Clara Bárbara da Rocha", "rrafaelaclarabarbaradarocha@candello.abv.br", "O4bOFIrC6U"); User user11 = new User(null, "634.546.494-55", "Bernardo Anderson Lima", "bernardoandersonlima-77@inductothermgroup.com.br", "4RuW0MAPLb"); // "Administração" User user12 = new User(null, "193.628.382-49", "Antonella Heloise Aragão", "antonellaheloisearagao_@grupoitamaraty.com.br", "SDAmsNgDEy"); User user13 = new User(null, "759.012.025-11", "Milena Nicole Ester Melo", "milenanicoleestermelo-70@ouserTipolock.com", "KiDJmNXmd4"); User user14 = new User(null, "558.108.283-96", "Ruan Pedro Viana", "ruanpedroviana..ruanpedroviana@anbima.com.br", "QP8Eg0Y7Pw"); // "NuserTiporição" User user15 = new User(null, "020.984.203-23", "Lucas Oliver das Neves", "lucasoliverdasneves__lucasoliverdasneves@zoomfoccus.com.br", "FoeKiXm0ZB"); User user16 = new User(null, "955.586.448-93", "Tomás Paulo Jesus", "ttomaspaulojesus@nelsoncosta.com.br", "N05yZtdyMU"); // "Fisioterapia" User user17 = new User(null, "348.646.029-30", "Pedro Henrique Diego Roberto Martins", "pedrohenriquediegorobertomartins..pedrohenriquediegorobertomartins@tec3.com.br", "LzmEdCpfRp"); User user18 = new User(null, "845.932.684-51", "Osvaldo Edson Vieira", "osvaldoedsonvieira__osvaldoedsonvieira@focustg.com.br", "eqNBljRNau"); // "Teologia" User user19 = new User(null, "459.518.706-82", "Joaquim Lucca da Cruz", "joaquimluccadacruz__joaquimluccadacruz@callan.com.br", "r9EngPfORH"); // "Filosofia" User user20 = new User(null, "685.776.221-00", "João Miguel da Conceição", "joaomigueldaconceicao__joaomigueldaconceicao@carlosalbertoleite.com.br", "qMEWbTgXku"); UserType userTipo1 = new UserType(null, "Coordenador"); UserType userTipo2 = new UserType(null, "Supervisor"); UserType userTipo3 = new UserType(null, "Administrador"); UserType userTipo4 = new UserType(null, "Aluno"); Campus cmp1 = new Campus(null, "Academia"); Campus cmp2 = new Campus(null, "Arnaldo Janssen"); Campus cmp3 = new Campus(null, "Seminário Santo Antônio"); Course crs1 = new Course(null, "Sistemas de Informação", 216.0, cmp1); Course crs2 = new Course(null, "Engenharia de Software", 144.0, cmp1); Course crs3 = new Course(null, "Administração", 216.0, cmp1); Course crs4 = new Course(null, "NuserTiporição", 320.0, cmp2); Course crs5 = new Course(null, "Fisioterapia", 180.0, cmp2); Course crs6 = new Course(null, "Teologia", 320.0, cmp3); Course crs7 = new Course(null, "Filosofia", 180.0, cmp3); Category cat1 = new Category(null, "Exercício de Monitoria"); Category cat2 = new Category(null, "Iniciação Científica"); Category cat3 = new Category(null, "Curso de Extensão"); Category cat4 = new Category(null, "Palestra"); Category cat5 = new Category(null, "Curso de Línguas"); Category cat6 = new Category(null, "Curso de Programação"); Student stu1 = new Student(null, user8, addr8); Student stu2 = new Student(null, user9, addr9); Student stu3 = new Student(null, user10, addr10); Student stu4 = new Student(null, user11, addr11); Student stu5 = new Student(null, user12, addr12); Student stu6 = new Student(null, user13, addr13); Student stu7 = new Student(null, user14, addr14); Student stu8 = new Student(null, user15, addr15); Student stu9 = new Student(null, user16, addr16); Student stu10 = new Student(null, user17, addr17); Student stu11 = new Student(null, user18, addr18); Student stu12 = new Student(null, user19, addr19); Student stu13 = new Student(null, user20, addr20); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Activity at1 = new Activity(null, "Curso de Phyton", sdf.parse("15/05/2021"), 12.0, 5.0, false, "", null, "", stu1, cat6); Activity at2 = new Activity(null, "Curso de Inglês", sdf.parse("20/02/2020"), 1200.0, 640.0, false, "", null, "", stu2, cat5); Activity at3 = new Activity(null, "Curso de PHP", sdf.parse("20/04/2021"), 6.0, 6.0, true, "abc12es381a", Valuation.ACEITAR, "", stu3, cat6); Activity at4 = new Activity(null, "Palestra Senhor dos Aneis", sdf.parse("28/08/2021"), 3.0, 3.0, true, "25e23rty31hj", Valuation.NEGAR_TOTAL, "Essa palestra não condiz com o curso", stu4, cat4); user1.getUsersTypes().addAll(Arrays.asList(userTipo1)); user2.getUsersTypes().addAll(Arrays.asList(userTipo2)); user3.getUsersTypes().addAll(Arrays.asList(userTipo1)); user4.getUsersTypes().addAll(Arrays.asList(userTipo2)); user5.getUsersTypes().addAll(Arrays.asList(userTipo1)); user6.getUsersTypes().addAll(Arrays.asList(userTipo2)); user7.getUsersTypes().addAll(Arrays.asList(userTipo1, userTipo2)); user8.getUsersTypes().addAll(Arrays.asList(userTipo3, userTipo4)); user9.getUsersTypes().addAll(Arrays.asList(userTipo4)); user10.getUsersTypes().addAll(Arrays.asList(userTipo4)); user11.getUsersTypes().addAll(Arrays.asList(userTipo4)); user12.getUsersTypes().addAll(Arrays.asList(userTipo4)); user13.getUsersTypes().addAll(Arrays.asList(userTipo4)); user14.getUsersTypes().addAll(Arrays.asList(userTipo4)); user15.getUsersTypes().addAll(Arrays.asList(userTipo4)); user16.getUsersTypes().addAll(Arrays.asList(userTipo4)); user17.getUsersTypes().addAll(Arrays.asList(userTipo4)); user18.getUsersTypes().addAll(Arrays.asList(userTipo4)); user19.getUsersTypes().addAll(Arrays.asList(userTipo4)); user20.getUsersTypes().addAll(Arrays.asList(userTipo4)); userTipo1.getUsers().addAll(Arrays.asList(user1, user3, user5, user7)); userTipo2.getUsers().addAll(Arrays.asList(user2, user4, user6, user7)); userTipo3.getUsers().addAll(Arrays.asList(user8)); userTipo4.getUsers().addAll(Arrays.asList(user8, user9, user10, user11, user12, user13, user14, user15, user16, user17, user18, user19, user20)); cmp1.getCourses().addAll(Arrays.asList(crs1, crs2, crs3)); cmp2.getCourses().addAll(Arrays.asList(crs4, crs5)); cmp3.getCourses().addAll(Arrays.asList(crs6, crs7)); addressRepository.saveAll(Arrays.asList(addr8, addr9, addr10, addr11, addr12, addr13, addr14, addr15, addr16, addr17, addr18, addr19, addr20)); userRepository.saveAll(Arrays.asList(user1, user2, user3, user4, user5, user6, user7, user8, user9, user10, user11, user12, user13, user14, user15, user16, user17, user18, user19, user20)); userTypeRepository.saveAll(Arrays.asList(userTipo1, userTipo2, userTipo3, userTipo4)); campusRepository.saveAll(Arrays.asList(cmp1, cmp2, cmp3)); courseRepository.saveAll(Arrays.asList(crs1, crs2, crs3, crs4, crs5, crs6, crs7)); categoryRepository.saveAll(Arrays.asList(cat1, cat2, cat3, cat4, cat5, cat6)); studentRepository.saveAll(Arrays.asList(stu1, stu2, stu3, stu4, stu5, stu6, stu7, stu8, stu9, stu10, stu11, stu12, stu13)); activityRepository.saveAll(Arrays.asList(at1, at2, at3, at4)); } }
60.019139
197
0.738361
e13fb167b8c790e918a4eb96137bbd350d8f7a30
316
package io.keyko.monitoring.agent.core.utils; import java.math.BigInteger; import java.time.Instant; public abstract class AvroUtils { public static long toLogicalTypeTimestamp(BigInteger input) { Instant millis = Instant.ofEpochMilli(input.longValue()); return millis.toEpochMilli(); } }
24.307692
65
0.740506
f805b3dfc37526a7d81ff495b0bfbd00b128cfc2
28,499
/* * 03/07/2004 * * WindowsBatchTokenMaker.java - Scanner for Windows batch files. * * This library is distributed under a modified BSD license. See the included RSyntaxTextArea.License.txt file for * details. */ package org.cajunc2.dev80.ui.syntax; import javax.swing.text.Segment; import org.fife.ui.rsyntaxtextarea.AbstractTokenMaker; import org.fife.ui.rsyntaxtextarea.RSyntaxUtilities; import org.fife.ui.rsyntaxtextarea.Token; import org.fife.ui.rsyntaxtextarea.TokenMap; import org.fife.ui.rsyntaxtextarea.TokenTypes; /** * A token maker that turns text into a linked list of <code>Token</code>s for * syntax highlighting Microsoft Windows batch files. * * @author Robert Futrell * @version 0.1 */ public class Z80TokenMaker extends AbstractTokenMaker { protected final String operators = "+-"; private int currentTokenStart; private int currentTokenType; private VariableType varType; /** * Constructor. */ public Z80TokenMaker() { super(); // Initializes tokensToHighlight. } /** * Checks the token to give it the exact ID it deserves before being passed * up to the super method. * * @param segment * <code>Segment</code> to get text from. * @param start * Start offset in <code>segment</code> of token. * @param end * End offset in <code>segment</code> of token. * @param tokenType * The token's type. * @param startOffset * The offset in the document at which the token occurs. */ @Override public void addToken(Segment segment, int start, int end, int tokenType, int startOffset) { switch (tokenType) { // Since reserved words, functions, and data types are all passed // into here as "identifiers," we have to see what the token // really is... case TokenTypes.IDENTIFIER: int value = wordsToHighlight.get(segment, start, end); if (value != -1) tokenType = value; break; default: break; } super.addToken(segment, start, end, tokenType, startOffset); } /** * {@inheritDoc} */ @Override public String[] getLineCommentStartAndEnd(int languageIndex) { return new String[] { ";", null }; } /** * Returns whether tokens of the specified type should have "mark * occurrences" enabled for the current programming language. * * @param type * The token type. * @return Whether tokens of this type should have "mark occurrences" * enabled. */ @Override public boolean getMarkOccurrencesOfTokenType(int type) { return type == TokenTypes.ANNOTATION || type == TokenTypes.VARIABLE; } /** * Returns the words to highlight * * @return A <code>TokenMap</code> containing the words to highlight * @see org.fife.ui.rsyntaxtextarea.AbstractTokenMaker#getWordsToHighlight */ @Override public TokenMap getWordsToHighlight() { TokenMap tokenMap = new TokenMap(true); // Ignore case. int register = TokenTypes.VARIABLE; int instruction = TokenTypes.FUNCTION; int directive = TokenTypes.PREPROCESSOR; int condition = TokenTypes.RESERVED_WORD; int operator = TokenTypes.OPERATOR; /* Registers */ tokenMap.put("A", register); tokenMap.put("F", register); tokenMap.put("B", register); tokenMap.put("C", register); tokenMap.put("D", register); tokenMap.put("E", register); tokenMap.put("H", register); tokenMap.put("L", register); tokenMap.put("AF'", register); tokenMap.put("IXH", register); tokenMap.put("IXL", register); tokenMap.put("IYH", register); tokenMap.put("IYL", register); tokenMap.put("AF", register); tokenMap.put("BC", register); tokenMap.put("DE", register); tokenMap.put("HL", register); tokenMap.put("IX", register); tokenMap.put("IY", register); tokenMap.put("I", register); tokenMap.put("R", register); tokenMap.put("SP", register); tokenMap.put("PC", register); /* CPU Instructions */ tokenMap.put("ADC", instruction); tokenMap.put("ADD", instruction); tokenMap.put("AND", instruction); tokenMap.put("BIT", instruction); tokenMap.put("CALL", instruction); tokenMap.put("CCF", instruction); tokenMap.put("CP", instruction); tokenMap.put("CPD", instruction); tokenMap.put("CPDR", instruction); tokenMap.put("CPI", instruction); tokenMap.put("CPIR", instruction); tokenMap.put("CPL", instruction); tokenMap.put("DAA", instruction); tokenMap.put("DEC", instruction); tokenMap.put("DI", instruction); tokenMap.put("DJNZ", instruction); tokenMap.put("EI", instruction); tokenMap.put("EX", instruction); tokenMap.put("EXX", instruction); tokenMap.put("HALT", instruction); tokenMap.put("IM", instruction); tokenMap.put("IN", instruction); tokenMap.put("INC", instruction); tokenMap.put("IND", instruction); tokenMap.put("INDR", instruction); tokenMap.put("INI", instruction); tokenMap.put("INIR", instruction); tokenMap.put("JP", instruction); tokenMap.put("JR", instruction); tokenMap.put("LD", instruction); tokenMap.put("LDD", instruction); tokenMap.put("LDDR", instruction); tokenMap.put("LDI", instruction); tokenMap.put("LDIR", instruction); tokenMap.put("NEG", instruction); tokenMap.put("NOP", instruction); tokenMap.put("OR", instruction); tokenMap.put("OTDR", instruction); tokenMap.put("OTIR", instruction); tokenMap.put("OUT", instruction); tokenMap.put("OUTD", instruction); tokenMap.put("OUTI", instruction); tokenMap.put("POP", instruction); tokenMap.put("PUSH", instruction); tokenMap.put("RES", instruction); tokenMap.put("RET", instruction); tokenMap.put("RETI", instruction); tokenMap.put("RETN", instruction); tokenMap.put("RL", instruction); tokenMap.put("RLA", instruction); tokenMap.put("RLC", instruction); tokenMap.put("RLCA", instruction); tokenMap.put("RLD", instruction); tokenMap.put("RR", instruction); tokenMap.put("RRA", instruction); tokenMap.put("RRC", instruction); tokenMap.put("RRCA", instruction); tokenMap.put("RRD", instruction); tokenMap.put("RST", instruction); tokenMap.put("SBC", instruction); tokenMap.put("SCF", instruction); tokenMap.put("SET", instruction); tokenMap.put("SLA", instruction); tokenMap.put("SLL", instruction); tokenMap.put("SL1", instruction); tokenMap.put("SRA", instruction); tokenMap.put("SRL", instruction); tokenMap.put("SUB", instruction); tokenMap.put("XOR", instruction); /* Assembler Directives */ tokenMap.put("macro", directive); tokenMap.put("endm", directive); tokenMap.put("if", directive); tokenMap.put("else", directive); tokenMap.put("endif", directive); tokenMap.put("incbin", directive); tokenMap.put("include", directive); tokenMap.put("seek", directive); tokenMap.put("org", directive); tokenMap.put("end", directive); tokenMap.put("ds", directive); tokenMap.put("dw", directive); tokenMap.put("db", directive); tokenMap.put("dm", directive); tokenMap.put("section", directive); tokenMap.put("ends", directive); tokenMap.put("virtual", directive); tokenMap.put("equ", directive); /* Conditions */ // tokenMap.put("c", condition); tokenMap.put("nc", condition); tokenMap.put("z", condition); tokenMap.put("nz", condition); tokenMap.put("m", condition); tokenMap.put("p", condition); tokenMap.put("pe", condition); tokenMap.put("po", condition); tokenMap.put(",", operator); tokenMap.put("+", operator); tokenMap.put("-", operator); return tokenMap; } /** * Returns a list of tokens representing the given text. * * @param text * The text to break into tokens. * @param startTokenType * The token with which to start tokenizing. * @param startOffset * The offset at which the line of tokens begins. * @return A linked list of tokens representing <code>text</code>. */ @Override public Token getTokenList(Segment text, int startTokenType, final int startOffset) { resetTokenList(); char[] array = text.array; int offset = text.offset; int count = text.count; int end = offset + count; // See, when we find a token, its starting position is always of the // form: // 'startOffset + (currentTokenStart-offset)'; but since startOffset and // offset are constant, tokens' starting positions become: // 'newStartOffset+currentTokenStart' for one less subtraction // operation. int newStartOffset = startOffset - offset; currentTokenStart = offset; currentTokenType = startTokenType; // beginning: for (int i = offset; i < end; i++) { char c = array[i]; switch (currentTokenType) { case TokenTypes.NULL: currentTokenStart = i; // Starting a new token here. switch (c) { case ' ': case '\t': currentTokenType = TokenTypes.WHITESPACE; continue; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': currentTokenType = TokenTypes.LITERAL_NUMBER_DECIMAL_INT; continue; case ';': currentTokenType = TokenTypes.COMMENT_EOL; continue; case '#': currentTokenType = TokenTypes.LITERAL_NUMBER_HEXADECIMAL; continue; default: currentTokenType = TokenTypes.ANNOTATION; continue; } case TokenTypes.LITERAL_NUMBER_HEXADECIMAL: switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'a': case 'A': case 'b': case 'B': case 'c': case 'C': case 'd': case 'D': case 'e': case 'E': case 'f': case 'F': case 'h': case 'H': continue; case ' ': case '\t': addToken(text, currentTokenStart, i - 1, TokenTypes.LITERAL_NUMBER_HEXADECIMAL, newStartOffset + currentTokenStart); currentTokenStart = i; currentTokenType = TokenTypes.WHITESPACE; continue; default: addToken(text, currentTokenStart, i - 1, TokenTypes.LITERAL_NUMBER_HEXADECIMAL, newStartOffset + currentTokenStart); currentTokenStart = i; currentTokenType = TokenTypes.IDENTIFIER; continue; } case TokenTypes.LITERAL_NUMBER_DECIMAL_INT: switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': continue; case ' ': case '\t': addToken(text, currentTokenStart, i - 1, TokenTypes.LITERAL_NUMBER_DECIMAL_INT, newStartOffset + currentTokenStart); currentTokenStart = i; currentTokenType = TokenTypes.WHITESPACE; continue; default: addToken(text, currentTokenStart, i - 1, TokenTypes.LITERAL_NUMBER_DECIMAL_INT, newStartOffset + currentTokenStart); currentTokenStart = i; currentTokenType = TokenTypes.IDENTIFIER; continue; } case TokenTypes.WHITESPACE: switch (c) { case ' ': case '\t': currentTokenType = TokenTypes.WHITESPACE; continue; case ';': addToken(text, currentTokenStart, i - 1, TokenTypes.WHITESPACE, newStartOffset + currentTokenStart); currentTokenStart = i; currentTokenType = TokenTypes.COMMENT_EOL; continue; case '"': addToken(text, currentTokenStart, i - 1, TokenTypes.WHITESPACE, newStartOffset + currentTokenStart); currentTokenStart = i; currentTokenType = TokenTypes.LITERAL_STRING_DOUBLE_QUOTE; continue; case '(': addToken(text, currentTokenStart, i - 1, TokenTypes.WHITESPACE, newStartOffset + currentTokenStart); currentTokenStart = i; currentTokenType = TokenTypes.DATA_TYPE; continue; case '#': addToken(text, currentTokenStart, i - 1, TokenTypes.WHITESPACE, newStartOffset + currentTokenStart); currentTokenStart = i; currentTokenType = TokenTypes.LITERAL_NUMBER_HEXADECIMAL; continue; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': addToken(text, currentTokenStart, i - 1, TokenTypes.WHITESPACE, newStartOffset + currentTokenStart); currentTokenStart = i; currentTokenType = TokenTypes.LITERAL_NUMBER_DECIMAL_INT; continue; default: addToken(text, currentTokenStart, i - 1, TokenTypes.WHITESPACE, newStartOffset + currentTokenStart); currentTokenStart = i; currentTokenType = TokenTypes.IDENTIFIER; continue; } case TokenTypes.IDENTIFIER: switch (c) { case ' ': case '\t': addToken(text, currentTokenStart, i - 1, TokenTypes.IDENTIFIER, newStartOffset + currentTokenStart); currentTokenStart = i; currentTokenType = TokenTypes.WHITESPACE; continue; case ',': addToken(text, currentTokenStart, i - 1, TokenTypes.IDENTIFIER, newStartOffset + currentTokenStart); currentTokenStart = i; currentTokenType = TokenTypes.IDENTIFIER; continue; default: continue; } case TokenTypes.ANNOTATION: switch (c) { case ' ': case '\t': addToken(text, currentTokenStart, i - 1, TokenTypes.IDENTIFIER, newStartOffset + currentTokenStart); currentTokenStart = i; currentTokenType = TokenTypes.WHITESPACE; continue; case ':': addToken(text, currentTokenStart, i, TokenTypes.ANNOTATION, newStartOffset + currentTokenStart); currentTokenStart = i + 1; currentTokenType = TokenTypes.WHITESPACE; continue; default: currentTokenType = TokenTypes.ANNOTATION; continue; } case TokenTypes.COMMENT_EOL: if (c == '\n') { addToken(text, currentTokenStart, i, TokenTypes.COMMENT_EOL, newStartOffset + currentTokenStart); currentTokenStart = i; currentTokenType = TokenTypes.WHITESPACE; } continue; case TokenTypes.LITERAL_STRING_DOUBLE_QUOTE: if (c == '"') { addToken(text, currentTokenStart, i, TokenTypes.LITERAL_STRING_DOUBLE_QUOTE, newStartOffset + currentTokenStart); currentTokenStart = i + 1; currentTokenType = TokenTypes.WHITESPACE; } continue; case TokenTypes.DATA_TYPE: switch (c) { case ')': addToken(text, currentTokenStart, i, TokenTypes.DATA_TYPE, newStartOffset + currentTokenStart); currentTokenStart = i + 1; currentTokenType = TokenTypes.WHITESPACE; continue; case ' ': case '\t': addToken(text, currentTokenStart, i - 1, TokenTypes.IDENTIFIER, newStartOffset + currentTokenStart); currentTokenStart = i; currentTokenType = TokenTypes.WHITESPACE; continue; default: continue; } } } // Deal with the (possibly there) last token. if (currentTokenType != TokenTypes.NULL) { addToken(text, currentTokenStart, end - 1, currentTokenType, newStartOffset + currentTokenStart); } addNullToken(); // Return the first token in our linked list. return firstToken; } public Token getTokenListOld(Segment text, int startTokenType, final int startOffset) { resetTokenList(); char[] array = text.array; int offset = text.offset; int count = text.count; int end = offset + count; // See, when we find a token, its starting position is always of the // form: // 'startOffset + (currentTokenStart-offset)'; but since startOffset and // offset are constant, tokens' starting positions become: // 'newStartOffset+currentTokenStart' for one less subtraction // operation. int newStartOffset = startOffset - offset; currentTokenStart = offset; currentTokenType = startTokenType; // beginning: for (int i = offset; i < end; i++) { char c = array[i]; switch (currentTokenType) { case TokenTypes.COMMENT_EOL: i = end - 1; addToken(text, currentTokenStart, i, TokenTypes.COMMENT_EOL, newStartOffset + currentTokenStart); // We need to set token type to null so at the bottom we don't // add one more token. currentTokenType = TokenTypes.NULL; break; case TokenTypes.NULL: currentTokenStart = i; // Starting a new token here. switch (c) { case ' ': case '\t': currentTokenType = TokenTypes.WHITESPACE; break; case '"': currentTokenType = TokenTypes.ERROR_STRING_DOUBLE; break; case '%': currentTokenType = TokenTypes.VARIABLE; break; // The "separators". case '(': case ')': addToken(text, currentTokenStart, i, TokenTypes.SEPARATOR, newStartOffset + currentTokenStart); currentTokenType = TokenTypes.NULL; break; // Newer version of EOL comments, or a label case ';': // If this will be the first token added, it is // a new-style comment or a label currentTokenType = TokenTypes.COMMENT_EOL; break; default: // Just to speed things up a tad, as this will usually be // the case (if spaces above failed). if (RSyntaxUtilities.isLetterOrDigit(c) || c == '\\') { currentTokenType = TokenTypes.IDENTIFIER; break; } int indexOf = operators.indexOf(c, 0); if (indexOf > -1) { addToken(text, currentTokenStart, i, TokenTypes.OPERATOR, newStartOffset + currentTokenStart); currentTokenType = TokenTypes.NULL; break; } currentTokenType = TokenTypes.IDENTIFIER; break; } // End of switch (c). break; case TokenTypes.WHITESPACE: switch (c) { case ' ': case '\t': break; // Still whitespace. case '"': addToken(text, currentTokenStart, i - 1, TokenTypes.WHITESPACE, newStartOffset + currentTokenStart); currentTokenStart = i; currentTokenType = TokenTypes.ERROR_STRING_DOUBLE; break; case '%': addToken(text, currentTokenStart, i - 1, TokenTypes.WHITESPACE, newStartOffset + currentTokenStart); currentTokenStart = i; currentTokenType = TokenTypes.VARIABLE; break; // The "separators". case '(': case ')': addToken(text, currentTokenStart, i - 1, TokenTypes.WHITESPACE, newStartOffset + currentTokenStart); addToken(text, i, i, TokenTypes.SEPARATOR, newStartOffset + i); currentTokenType = TokenTypes.NULL; break; // The "separators2". case ',': case ';': addToken(text, currentTokenStart, i - 1, TokenTypes.WHITESPACE, newStartOffset + currentTokenStart); addToken(text, i, i, TokenTypes.IDENTIFIER, newStartOffset + i); currentTokenType = TokenTypes.NULL; break; // Newer version of EOL comments, or a label case ':': addToken(text, currentTokenStart, i - 1, TokenTypes.WHITESPACE, newStartOffset + currentTokenStart); currentTokenStart = i; // If the previous (whitespace) token was the first token // added, this is a new-style comment or a label if (firstToken.getNextToken() == null) { if (i < end - 1 && array[i + 1] == ':') { // new-style // comment currentTokenType = TokenTypes.COMMENT_EOL; } else { // Label currentTokenType = TokenTypes.PREPROCESSOR; } } else { // Just a colon currentTokenType = TokenTypes.IDENTIFIER; } break; default: // Add the whitespace token and start anew. addToken(text, currentTokenStart, i - 1, TokenTypes.WHITESPACE, newStartOffset + currentTokenStart); currentTokenStart = i; // Just to speed things up a tad, as this will usually be // the case (if spaces above failed). if (RSyntaxUtilities.isLetterOrDigit(c) || c == '\\') { currentTokenType = TokenTypes.IDENTIFIER; break; } int indexOf = operators.indexOf(c, 0); if (indexOf > -1) { addToken(text, currentTokenStart, i, TokenTypes.OPERATOR, newStartOffset + currentTokenStart); currentTokenType = TokenTypes.NULL; break; } currentTokenType = TokenTypes.IDENTIFIER; } // End of switch (c). break; default: // Should never happen case TokenTypes.IDENTIFIER: switch (c) { case ' ': case '\t': // Check for REM comments. if (i - currentTokenStart == 3 && (array[i - 3] == 'r' || array[i - 3] == 'R') && (array[i - 2] == 'e' || array[i - 2] == 'E') && (array[i - 1] == 'm' || array[i - 1] == 'M')) { currentTokenType = TokenTypes.COMMENT_EOL; break; } addToken(text, currentTokenStart, i - 1, TokenTypes.IDENTIFIER, newStartOffset + currentTokenStart); currentTokenStart = i; currentTokenType = TokenTypes.WHITESPACE; break; case '"': addToken(text, currentTokenStart, i - 1, TokenTypes.IDENTIFIER, newStartOffset + currentTokenStart); currentTokenStart = i; currentTokenType = TokenTypes.ERROR_STRING_DOUBLE; break; case '%': addToken(text, currentTokenStart, i - 1, TokenTypes.IDENTIFIER, newStartOffset + currentTokenStart); currentTokenStart = i; currentTokenType = TokenTypes.VARIABLE; break; // Should be part of identifiers, but not at end of "REM". case '\\': // Check for REM comments. if (i - currentTokenStart == 3 && (array[i - 3] == 'r' || array[i - 3] == 'R') && (array[i - 2] == 'e' || array[i - 2] == 'E') && (array[i - 1] == 'm' || array[i - 1] == 'M')) { currentTokenType = TokenTypes.COMMENT_EOL; } break; case '.': case '_': break; // Characters good for identifiers. // The "separators". case '(': case ')': addToken(text, currentTokenStart, i - 1, TokenTypes.IDENTIFIER, newStartOffset + currentTokenStart); addToken(text, i, i, TokenTypes.SEPARATOR, newStartOffset + i); currentTokenType = TokenTypes.NULL; break; // The "separators2". case ',': case ';': addToken(text, currentTokenStart, i - 1, TokenTypes.IDENTIFIER, newStartOffset + currentTokenStart); addToken(text, i, i, TokenTypes.IDENTIFIER, newStartOffset + i); currentTokenType = TokenTypes.NULL; break; default: // Just to speed things up a tad, as this will usually be // the case. if (RSyntaxUtilities.isLetterOrDigit(c) || c == '\\') { break; } int indexOf = operators.indexOf(c); if (indexOf > -1) { addToken(text, currentTokenStart, i - 1, TokenTypes.IDENTIFIER, newStartOffset + currentTokenStart); addToken(text, i, i, TokenTypes.OPERATOR, newStartOffset + i); currentTokenType = TokenTypes.NULL; break; } // Otherwise, fall through and assume we're still okay as an // IDENTIFIER... } // End of switch (c). break; case TokenTypes.PREPROCESSOR: // Used for labels i = end - 1; addToken(text, currentTokenStart, i, TokenTypes.PREPROCESSOR, newStartOffset + currentTokenStart); // We need to set token type to null so at the bottom we don't // add one more token. currentTokenType = TokenTypes.NULL; break; case TokenTypes.ERROR_STRING_DOUBLE: if (c == '"') { addToken(text, currentTokenStart, i, TokenTypes.LITERAL_STRING_DOUBLE_QUOTE, newStartOffset + currentTokenStart); currentTokenStart = i + 1; currentTokenType = TokenTypes.NULL; } // Otherwise, we're still an unclosed string... break; case TokenTypes.VARIABLE: if (i == currentTokenStart + 1) { // first character after '%'. varType = VariableType.NORMAL_VAR; switch (c) { case '{': varType = VariableType.BRACKET_VAR; break; case '~': varType = VariableType.TILDE_VAR; break; case '%': varType = VariableType.DOUBLE_PERCENT_VAR; break; default: if (RSyntaxUtilities.isLetter(c) || c == '_' || c == ' ') { // No // tab, // just // space; // spaces // are // okay // in // variable // names. break; } else if (RSyntaxUtilities.isDigit(c)) { // Single-digit // command-line // argument // ("%1"). addToken(text, currentTokenStart, i, TokenTypes.VARIABLE, newStartOffset + currentTokenStart); currentTokenType = TokenTypes.NULL; break; } else { // Anything else, ???. addToken(text, currentTokenStart, i - 1, TokenTypes.VARIABLE, newStartOffset + currentTokenStart); // ??? i--; currentTokenType = TokenTypes.NULL; break; } } // End of switch (c). } else { // Character other than first after the '%'. switch (varType) { case BRACKET_VAR: if (c == '}') { addToken(text, currentTokenStart, i, TokenTypes.VARIABLE, newStartOffset + currentTokenStart); currentTokenType = TokenTypes.NULL; } break; case TILDE_VAR: if (!RSyntaxUtilities.isLetterOrDigit(c)) { addToken(text, currentTokenStart, i - 1, TokenTypes.VARIABLE, newStartOffset + currentTokenStart); i--; currentTokenType = TokenTypes.NULL; } break; case DOUBLE_PERCENT_VAR: // Can be terminated with "%%", or (essentially) a // space. // substring chars are valid if (c == '%') { if (i < end - 1 && array[i + 1] == '%') { i++; addToken(text, currentTokenStart, i, TokenTypes.VARIABLE, newStartOffset + currentTokenStart); currentTokenType = TokenTypes.NULL; } } else if (!RSyntaxUtilities.isLetterOrDigit(c) && c != ':' && c != '~' && c != ',' && c != '-') { addToken(text, currentTokenStart, i - 1, TokenTypes.VARIABLE, newStartOffset + currentTokenStart); currentTokenType = TokenTypes.NULL; i--; } break; default: if (c == '%') { addToken(text, currentTokenStart, i, TokenTypes.VARIABLE, newStartOffset + currentTokenStart); currentTokenType = TokenTypes.NULL; } break; } } break; } // End of switch (currentTokenType). } // End of for (int i=offset; i<end; i++). // Deal with the (possibly there) last token. if (currentTokenType != TokenTypes.NULL) { // Check for REM comments. if (end - currentTokenStart == 3 && (array[end - 3] == 'r' || array[end - 3] == 'R') && (array[end - 2] == 'e' || array[end - 2] == 'E') && (array[end - 1] == 'm' || array[end - 1] == 'M')) { currentTokenType = TokenTypes.COMMENT_EOL; } addToken(text, currentTokenStart, end - 1, currentTokenType, newStartOffset + currentTokenStart); } addNullToken(); // Return the first token in our linked list. return firstToken; } private enum VariableType { BRACKET_VAR, TILDE_VAR, NORMAL_VAR, DOUBLE_PERCENT_VAR; // Escaped '%' // var, special // highlighting // rules? } }
30.977174
115
0.602056
b0b007ca3466d9a2e50308201a784f9fda0e7c8e
1,290
package com.google.android.gms.dynamite; import android.os.IBinder; import android.os.IInterface; import android.os.Parcel; import android.os.RemoteException; import com.google.android.gms.dynamic.IObjectWrapper; import com.google.android.gms.dynamic.IObjectWrapper.zza; import com.google.android.gms.internal.zzed; import com.google.android.gms.internal.zzef; public final class zzl extends zzed implements zzk { zzl(IBinder iBinder) { super(iBinder, "com.google.android.gms.dynamite.IDynamiteLoader"); } public final int zza(IObjectWrapper iObjectWrapper, String str, boolean z) throws RemoteException { Parcel zzaz = zzaz(); zzef.zza(zzaz, (IInterface) iObjectWrapper); zzaz.writeString(str); zzef.zza(zzaz, z); zzaz = zza(3, zzaz); int readInt = zzaz.readInt(); zzaz.recycle(); return readInt; } public final IObjectWrapper zza(IObjectWrapper iObjectWrapper, String str, int i) throws RemoteException { Parcel zzaz = zzaz(); zzef.zza(zzaz, (IInterface) iObjectWrapper); zzaz.writeString(str); zzaz.writeInt(i); zzaz = zza(2, zzaz); IObjectWrapper zzap = zza.zzap(zzaz.readStrongBinder()); zzaz.recycle(); return zzap; } }
33.076923
110
0.683721
375607439a97bdc9850b339464ac2270cad488e8
168
package com.flarebyte.cm.com.core.owls.control; /** * A list of control constructs to be done in order. * * @author olivier * */ public interface Sequence { }
14
52
0.678571
250a37c5056bc4d1575400867c462f11ab96dcc1
351
package com.janus.bookCake.data.exceptions; public class NetworkConnectionException extends Exception { public NetworkConnectionException() { super(); } public NetworkConnectionException(String message) { super(message); } public NetworkConnectionException(final Throwable cause) { super(cause); } }
21.9375
62
0.698006
a15093e5152ea3982fd9bc688111928e02ef0d18
273
package com.iamacitizen.core.exception; /** * Classe que representa uma exceção de banco de dados. * @author felipe */ public class SerigyDatabaseException extends RuntimeException { public SerigyDatabaseException(String message) { super(message); } }
21
63
0.732601
22242d041b7b120187fa128b9a8b1fe4535650bf
2,178
package ua.hillel.java.elementary1.discovery.implementations.kosenkov; import ua.hillel.java.elementary1.discovery.Service; import java.util.Objects; import java.util.concurrent.TimeUnit; // A wrapper class to bundle service with registration time and ttl information // public class Record<T extends Service> { private T service; private double partialWeightSum; private long registrationTimeMillis; private long ttl; private TimeUnit ttlUnit; public Record() {}; public Record(T service, long ttl, TimeUnit ttlUnit) { if (service == null) { throw new IllegalArgumentException("Service to record can not be null"); } this.service = service; this.ttl = ttl; this.ttlUnit = ttlUnit; registrationTimeMillis = System.currentTimeMillis(); } public T getService() { return service; } public double getPartialWeightSum() { return partialWeightSum; } public void setPartialWeightSum(double partialWeightSum) { this.partialWeightSum = partialWeightSum; } // TTL implementation public boolean serviceIsExpired() { long millisPassed = System.currentTimeMillis() - registrationTimeMillis; long ttlMillis = ttlUnit.toMillis(ttl); return millisPassed > ttlMillis; } // LRU (least recently used) implementation; public void updateRegistrationTime() { registrationTimeMillis = System.currentTimeMillis(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record record = (Record) o; return Double.compare(record.partialWeightSum, partialWeightSum) == 0 && registrationTimeMillis == record.registrationTimeMillis && ttl == record.ttl && Objects.equals(service, record.service) && ttlUnit == record.ttlUnit; } @Override public int hashCode() { return Objects.hash(service, registrationTimeMillis, ttl, ttlUnit); } }
31.114286
88
0.639118
f79b2d07192d8158a788eec7fe0daa6070c9a8c7
529
package org.nearbyshops.enduserappnew.DI.DaggerModules; import android.app.Application; import dagger.Module; import dagger.Provides; import org.nearbyshops.enduserappnew.MyApplication; import javax.inject.Singleton; /** * Created by sumeet on 14/5/16. */ @Module public class AppModule { MyApplication mApplication; public AppModule(MyApplication application) { mApplication = application; } @Provides @Singleton Application providesApplication() { return mApplication; } }
17.633333
55
0.729679
807d5baf51737d31d2027bb3f2b0d76256c136d7
1,185
/* * Copyright 2013-2016 consulo.io * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package consulo.fsharp.lang.psi; import com.intellij.extapi.psi.ASTWrapperPsiElement; import com.intellij.psi.tree.IElementType; import consulo.fsharp.FSharpLanguage; import consulo.psi.tree.ElementTypeAsPsiFactory; /** * @author VISTALL * @since 24-Nov-16. */ public interface FSharpElementTypes { IElementType IMPORT_DECLARATION = new ElementTypeAsPsiFactory("IMPORT_DECLARATION", FSharpLanguage.INSTANCE, ASTWrapperPsiElement.class); IElementType REFERENCE_EXPRESSION = new ElementTypeAsPsiFactory("REFERENCE_EXPRESSION", FSharpLanguage.INSTANCE, ASTWrapperPsiElement.class); }
34.852941
142
0.785654
1e2df367bd343a10da0529ed3478619d7e4b94bc
13,975
package org.infinispan.marshall.core; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Set; import org.infinispan.commons.marshall.LambdaExternalizer; import org.infinispan.commons.marshall.ValueMatcherMode; import org.infinispan.commons.util.Util; import org.infinispan.functional.MetaParam; import org.jboss.marshalling.util.IdentityIntMap; public class MarshallableFunctionExternalizers { // TODO: Should really rely on ValuteMatcherMode enumeration ordering private static final short VALUE_MATCH_ALWAYS = 0x1000; private static final short VALUE_MATCH_EXPECTED = 0x2000; private static final short VALUE_MATCH_EXPECTED_OR_NEW = 0x3000; private static final short VALUE_MATCH_NON_NULL = 0x4000; private static final short VALUE_MATCH_NEVER = 0x5000; private static final int VALUE_MATCH_MASK = 0xF000; private static final int SET_VALUE_RETURN_PREV_OR_NULL = 1 | VALUE_MATCH_ALWAYS; private static final int SET_VALUE_RETURN_VIEW = 2 | VALUE_MATCH_ALWAYS; private static final int SET_VALUE_IF_ABSENT_RETURN_PREV_OR_NULL = 3 | VALUE_MATCH_EXPECTED; private static final int SET_VALUE_IF_ABSENT_RETURN_BOOLEAN = 4 | VALUE_MATCH_EXPECTED; private static final int SET_VALUE_IF_PRESENT_RETURN_PREV_OR_NULL = 5 | VALUE_MATCH_NON_NULL; private static final int SET_VALUE_IF_PRESENT_RETURN_BOOLEAN = 6 | VALUE_MATCH_NON_NULL; private static final int REMOVE_RETURN_PREV_OR_NULL = 7 | VALUE_MATCH_ALWAYS; private static final int REMOVE_RETURN_BOOLEAN = 8 | VALUE_MATCH_ALWAYS; private static final int REMOVE_IF_VALUE_EQUALS_RETURN_BOOLEAN = 9 | VALUE_MATCH_EXPECTED; private static final int SET_VALUE_CONSUMER = 10 | VALUE_MATCH_ALWAYS; private static final int REMOVE_CONSUMER = 11 | VALUE_MATCH_ALWAYS; private static final int RETURN_READ_WRITE_FIND = 12 | VALUE_MATCH_ALWAYS; private static final int RETURN_READ_WRITE_GET = 13 | VALUE_MATCH_ALWAYS; private static final int RETURN_READ_WRITE_VIEW = 14 | VALUE_MATCH_ALWAYS; private static final int RETURN_READ_ONLY_FIND_OR_NULL = 15 | VALUE_MATCH_ALWAYS; private static final int RETURN_READ_ONLY_FIND_IS_PRESENT = 16 | VALUE_MATCH_ALWAYS; private static final int IDENTITY = 17 | VALUE_MATCH_ALWAYS; public static final class ConstantLambdaExternalizer implements LambdaExternalizer<Object> { private final IdentityIntMap<Class<?>> numbers = new IdentityIntMap<>(16); public ConstantLambdaExternalizer() { numbers.put(MarshallableFunctions.setValueReturnPrevOrNull().getClass(), SET_VALUE_RETURN_PREV_OR_NULL); numbers.put(MarshallableFunctions.setValueReturnView().getClass(), SET_VALUE_RETURN_VIEW); numbers.put(MarshallableFunctions.setValueIfAbsentReturnPrevOrNull().getClass(), SET_VALUE_IF_ABSENT_RETURN_PREV_OR_NULL); numbers.put(MarshallableFunctions.setValueIfAbsentReturnBoolean().getClass(), SET_VALUE_IF_ABSENT_RETURN_BOOLEAN); numbers.put(MarshallableFunctions.setValueIfPresentReturnPrevOrNull().getClass(), SET_VALUE_IF_PRESENT_RETURN_PREV_OR_NULL); numbers.put(MarshallableFunctions.setValueIfPresentReturnBoolean().getClass(), SET_VALUE_IF_PRESENT_RETURN_BOOLEAN); numbers.put(MarshallableFunctions.removeReturnPrevOrNull().getClass(), REMOVE_RETURN_PREV_OR_NULL); numbers.put(MarshallableFunctions.removeReturnBoolean().getClass(), REMOVE_RETURN_BOOLEAN); numbers.put(MarshallableFunctions.removeIfValueEqualsReturnBoolean().getClass(), REMOVE_IF_VALUE_EQUALS_RETURN_BOOLEAN); numbers.put(MarshallableFunctions.setValueConsumer().getClass(), SET_VALUE_CONSUMER); numbers.put(MarshallableFunctions.removeConsumer().getClass(), REMOVE_CONSUMER); numbers.put(MarshallableFunctions.returnReadWriteFind().getClass(), RETURN_READ_WRITE_FIND); numbers.put(MarshallableFunctions.returnReadWriteGet().getClass(), RETURN_READ_WRITE_GET); numbers.put(MarshallableFunctions.returnReadWriteView().getClass(), RETURN_READ_WRITE_VIEW); numbers.put(MarshallableFunctions.returnReadOnlyFindOrNull().getClass(), RETURN_READ_ONLY_FIND_OR_NULL); numbers.put(MarshallableFunctions.returnReadOnlyFindIsPresent().getClass(), RETURN_READ_ONLY_FIND_IS_PRESENT); numbers.put(MarshallableFunctions.identity().getClass(), IDENTITY); } @Override public ValueMatcherMode valueMatcher(Object o) { int i = numbers.get(o.getClass(), -1); if (i > 0) { int valueMatcherId = ((i & VALUE_MATCH_MASK) >> 12) - 1; return ValueMatcherMode.valueOf(valueMatcherId); } return ValueMatcherMode.MATCH_ALWAYS; } @Override public Set<Class<?>> getTypeClasses() { return Util.<Class<?>>asSet( MarshallableFunctions.setValueReturnPrevOrNull().getClass(), MarshallableFunctions.setValueReturnView().getClass(), MarshallableFunctions.setValueIfAbsentReturnPrevOrNull().getClass(), MarshallableFunctions.setValueIfAbsentReturnBoolean().getClass(), MarshallableFunctions.setValueIfPresentReturnPrevOrNull().getClass(), MarshallableFunctions.setValueIfPresentReturnBoolean().getClass(), MarshallableFunctions.removeReturnPrevOrNull().getClass(), MarshallableFunctions.removeReturnBoolean().getClass(), MarshallableFunctions.removeIfValueEqualsReturnBoolean().getClass(), MarshallableFunctions.setValueConsumer().getClass(), MarshallableFunctions.removeConsumer().getClass(), MarshallableFunctions.returnReadWriteFind().getClass(), MarshallableFunctions.returnReadWriteGet().getClass(), MarshallableFunctions.returnReadWriteView().getClass(), MarshallableFunctions.returnReadOnlyFindOrNull().getClass(), MarshallableFunctions.returnReadOnlyFindIsPresent().getClass(), MarshallableFunctions.identity().getClass() ); } @Override public Integer getId() { return org.infinispan.commons.marshall.Ids.LAMBDA_CONSTANT; } public void writeObject(ObjectOutput oo, Object o) throws IOException { int id = numbers.get(o.getClass(), -1); oo.writeShort(id); } public Object readObject(ObjectInput input) throws IOException { short id = input.readShort(); switch (id) { case SET_VALUE_RETURN_PREV_OR_NULL: return MarshallableFunctions.setValueReturnPrevOrNull(); case SET_VALUE_RETURN_VIEW: return MarshallableFunctions.setValueReturnView(); case SET_VALUE_IF_ABSENT_RETURN_PREV_OR_NULL: return MarshallableFunctions.setValueIfAbsentReturnPrevOrNull(); case SET_VALUE_IF_ABSENT_RETURN_BOOLEAN: return MarshallableFunctions.setValueIfAbsentReturnBoolean(); case SET_VALUE_IF_PRESENT_RETURN_PREV_OR_NULL: return MarshallableFunctions.setValueIfPresentReturnPrevOrNull(); case SET_VALUE_IF_PRESENT_RETURN_BOOLEAN: return MarshallableFunctions.setValueIfPresentReturnBoolean(); case REMOVE_RETURN_PREV_OR_NULL: return MarshallableFunctions.removeReturnPrevOrNull(); case REMOVE_RETURN_BOOLEAN: return MarshallableFunctions.removeReturnBoolean(); case REMOVE_IF_VALUE_EQUALS_RETURN_BOOLEAN: return MarshallableFunctions.removeIfValueEqualsReturnBoolean(); case SET_VALUE_CONSUMER: return MarshallableFunctions.setValueConsumer(); case REMOVE_CONSUMER: return MarshallableFunctions.removeConsumer(); case RETURN_READ_WRITE_FIND: return MarshallableFunctions.returnReadWriteFind(); case RETURN_READ_WRITE_GET: return MarshallableFunctions.returnReadWriteGet(); case RETURN_READ_WRITE_VIEW: return MarshallableFunctions.returnReadWriteView(); case RETURN_READ_ONLY_FIND_OR_NULL: return MarshallableFunctions.returnReadOnlyFindOrNull(); case RETURN_READ_ONLY_FIND_IS_PRESENT: return MarshallableFunctions.returnReadOnlyFindIsPresent(); case IDENTITY: return MarshallableFunctions.identity(); default: throw new IllegalStateException("Unknown lambda ID: " + id); } } } public static final class LambdaWithMetasExternalizer implements LambdaExternalizer<MarshallableFunctions.LambdaWithMetas> { private final IdentityIntMap<Class<?>> numbers = new IdentityIntMap<>(8); public LambdaWithMetasExternalizer() { numbers.put(MarshallableFunctions.SetValueMetasReturnPrevOrNull.class, SET_VALUE_RETURN_PREV_OR_NULL); numbers.put(MarshallableFunctions.SetValueMetasReturnView.class, SET_VALUE_RETURN_VIEW); numbers.put(MarshallableFunctions.SetValueMetasIfAbsentReturnPrevOrNull.class, SET_VALUE_IF_ABSENT_RETURN_PREV_OR_NULL); numbers.put(MarshallableFunctions.SetValueMetasIfAbsentReturnBoolean.class, SET_VALUE_IF_ABSENT_RETURN_BOOLEAN); numbers.put(MarshallableFunctions.SetValueMetasIfPresentReturnPrevOrNull.class, SET_VALUE_IF_PRESENT_RETURN_PREV_OR_NULL); numbers.put(MarshallableFunctions.SetValueMetasIfPresentReturnBoolean.class, SET_VALUE_IF_PRESENT_RETURN_BOOLEAN); numbers.put(MarshallableFunctions.SetValueMetas.class, SET_VALUE_CONSUMER); } @Override public ValueMatcherMode valueMatcher(Object o) { // TODO: Code duplication int i = numbers.get(o.getClass(), -1); if (i > 0) { int valueMatcherId = ((i & VALUE_MATCH_MASK) >> 12) - 1; return ValueMatcherMode.valueOf(valueMatcherId); } return ValueMatcherMode.MATCH_ALWAYS; } @Override public Set<Class<? extends MarshallableFunctions.LambdaWithMetas>> getTypeClasses() { return Util.<Class<? extends MarshallableFunctions.LambdaWithMetas>>asSet( MarshallableFunctions.SetValueMetasReturnPrevOrNull.class, MarshallableFunctions.SetValueMetasReturnView.class, MarshallableFunctions.SetValueMetasIfAbsentReturnPrevOrNull.class, MarshallableFunctions.SetValueMetasIfAbsentReturnBoolean.class, MarshallableFunctions.SetValueMetasIfPresentReturnPrevOrNull.class, MarshallableFunctions.SetValueMetasIfPresentReturnBoolean.class, MarshallableFunctions.SetValueMetas.class ); } @Override public Integer getId() { return org.infinispan.commons.marshall.Ids.LAMBDA_WITH_METAS; } @Override public void writeObject(ObjectOutput oo, MarshallableFunctions.LambdaWithMetas o) throws IOException { int id = numbers.get(o.getClass(), -1); oo.writeShort(id); writeMetas(oo, o); } @Override public MarshallableFunctions.LambdaWithMetas readObject(ObjectInput input) throws IOException, ClassNotFoundException { short id = input.readShort(); MetaParam.Writable[] metas = readMetas(input); switch (id) { case SET_VALUE_RETURN_PREV_OR_NULL: return new MarshallableFunctions.SetValueMetasReturnPrevOrNull<>(metas); case SET_VALUE_IF_ABSENT_RETURN_PREV_OR_NULL: return new MarshallableFunctions.SetValueMetasIfAbsentReturnPrevOrNull<>(metas); case SET_VALUE_IF_ABSENT_RETURN_BOOLEAN: return new MarshallableFunctions.SetValueMetasIfAbsentReturnBoolean<>(metas); case SET_VALUE_RETURN_VIEW: return new MarshallableFunctions.SetValueMetasReturnView<>(metas); case SET_VALUE_IF_PRESENT_RETURN_PREV_OR_NULL: return new MarshallableFunctions.SetValueMetasIfPresentReturnPrevOrNull<>(metas); case SET_VALUE_IF_PRESENT_RETURN_BOOLEAN: return new MarshallableFunctions.SetValueMetasIfPresentReturnBoolean<>(metas); case SET_VALUE_CONSUMER: return new MarshallableFunctions.SetValueMetas<>(metas); default: throw new IllegalStateException("Unknown lambda and meta parameters with ID: " + id); } } } static MetaParam.Writable[] readMetas(ObjectInput input) throws IOException, ClassNotFoundException { int len = input.readInt(); MetaParam.Writable[] metas = new MetaParam.Writable[len]; for(int i = 0; i < len; i++) metas[i] = (MetaParam.Writable) input.readObject(); return metas; } private static void writeMetas(ObjectOutput oo, MarshallableFunctions.LambdaWithMetas o) throws IOException { oo.writeInt(o.metas().length); for (MetaParam.Writable meta : o.metas()) oo.writeObject(meta); } public static final class SetValueIfEqualsReturnBooleanExternalizer implements LambdaExternalizer<MarshallableFunctions.SetValueIfEqualsReturnBoolean> { public void writeObject(ObjectOutput oo, MarshallableFunctions.SetValueIfEqualsReturnBoolean o) throws IOException { oo.writeObject(o.oldValue); writeMetas(oo, o); } public MarshallableFunctions.SetValueIfEqualsReturnBoolean readObject(ObjectInput input) throws IOException, ClassNotFoundException { Object oldValue = input.readObject(); MetaParam.Writable[] metas = readMetas(input); return new MarshallableFunctions.SetValueIfEqualsReturnBoolean<>(oldValue, metas); } @Override public ValueMatcherMode valueMatcher(Object o) { return ValueMatcherMode.MATCH_EXPECTED; } @Override public Set<Class<? extends MarshallableFunctions.SetValueIfEqualsReturnBoolean>> getTypeClasses() { return Util.<Class<? extends MarshallableFunctions.SetValueIfEqualsReturnBoolean>>asSet(MarshallableFunctions.SetValueIfEqualsReturnBoolean.class); } @Override public Integer getId() { return org.infinispan.commons.marshall.Ids.LAMBDA_SET_VALUE_IF_EQUALS_RETURN_BOOLEAN; } } }
56.124498
156
0.749123
65e82ddb6aa4193874d01e5ba74f73ed90baa3db
3,294
/** * Copyright 2005-2015 Red Hat, Inc. * * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package io.fabric8.devops; import io.fabric8.utils.Pair; import org.junit.Test; import java.io.File; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** */ public class YamlTest { @Test public void testGenerateYaml() throws Exception { ProjectConfig config = new ProjectConfig(); config.setPipeline("maven/Deploy.groovy"); config.setChatRoom("myroom"); config.setCodeReview(true); config.setIssueProjectName("THING"); config.addLink("Room", "http://letschat.vagrant.f8/rooms/foo"); config.addLink("Jenkins", "http://jenkins.vagrant.f8/builds/foo"); String yaml = ProjectConfigs.toYaml(config); System.out.println("Config: " + config + " is yaml: " + yaml); } @Test public void testParseYaml() throws Exception { String basedir = System.getProperty("basedir", "."); File file = new File(basedir, "src/test/resources/fabric8.yml"); assertThat(file).exists(); ProjectConfig config = ProjectConfigs.parseProjectConfig(file); System.out.println("Parsed: " + config); assertThat(config.getChatRoom()).isEqualTo("myroom"); assertThat(config.getIssueProjectName()).isEqualTo("foo"); assertThat(config.getPipeline()).isEqualTo("maven/CanaryReleaseThenStage.groovy"); LinkedHashMap<String, String> environments = config.getEnvironments(); // lets assert that things are in the correct order... List<Pair<String,String>> expectedEnvironents = Arrays.asList( new Pair<String,String>("Testing", "gogsadmin-james4-testing"), new Pair<String,String>("Staging", "gogsadmin-james4-staging"), new Pair<String,String>("Production", "gogsadmin-james4-prod") ); int idx = 0; Set<Map.Entry<String, String>> entries = environments.entrySet(); for (Map.Entry<String, String> entry : entries) { String key = entry.getKey(); String value = entry.getValue(); System.out.println("Found environment " + key + " = " + value); Pair<String, String> actual = new Pair<>(key, value); assertTrue("Too many entries - found unexpected value: " + actual, expectedEnvironents.size() > idx); Pair<String, String> expected = expectedEnvironents.get(idx++); assertEquals("environment " + idx, expected, actual); } } }
38.752941
113
0.667881
4bcabffdcb27f21e4a234bd73bc942da05b0ef9c
185
package coffee_and_tea.jdk15.jep360_sealed_classes_preview; public sealed interface AccountDeposit permits DebitAccount, SavingAccount, CreditAccount { void deposit(int amount); }
30.833333
91
0.837838
51c06ae1c57f38a08497dc8d5485f6ce266ad200
2,809
package FrontEnd; import java.awt.BorderLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import BackEnd.Descuento; import BackEnd.Empleado; public class VentanaModificarDescuento extends JPanel { public VentanaModificarDescuento(JFrame marco, Empleado empleado, Descuento aModificar) { setLayout(new BorderLayout(0, 0)); JLabel lblAadirNuevoDescuento = new JLabel("Modificar Descuento existente"); lblAadirNuevoDescuento.setHorizontalAlignment(SwingConstants.CENTER); lblAadirNuevoDescuento.setFont(new Font("Dialog", Font.BOLD, 17)); add(lblAadirNuevoDescuento, BorderLayout.NORTH); JPanel panel = new JPanel(); add(panel, BorderLayout.CENTER); panel.setLayout(null); JButton btnAgregar = new JButton("Continuar"); btnAgregar.setBounds(283, 227, 117, 25); panel.add(btnAgregar); JTextField txtPalabraclave = new JTextField(); txtPalabraclave.setBounds(227, 42, 114, 19); panel.add(txtPalabraclave); txtPalabraclave.setColumns(10); txtPalabraclave.setText(aModificar.getPalabraClave()); JSlider slider = new JSlider(); slider.setValue(1); slider.setBounds(147, 151, 243, 16); panel.add(slider); slider.setValue(aModificar.getPorcentaje()); JLabel lblValor = new JLabel(aModificar.getPorcentaje()+"%"); lblValor.setBounds(59, 152, 70, 15); panel.add(lblValor); JLabel lblNombre = new JLabel("Nombre"); lblNombre.setBounds(164, 44, 70, 15); panel.add(lblNombre); JLabel lblPorcentaje = new JLabel("Porcentaje"); lblPorcentaje.setHorizontalAlignment(SwingConstants.CENTER); lblPorcentaje.setBounds(59, 128, 331, 15); panel.add(lblPorcentaje); JButton btnCancelar = new JButton("Cancelar"); btnCancelar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { marco.setContentPane(new PanelControl(marco, empleado)); marco.validate(); } }); btnCancelar.setBounds(67, 227, 117, 25); panel.add(btnCancelar); slider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { lblValor.setText(slider.getValue()+"%"); } }); btnAgregar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { aModificar.setPalabraClave(txtPalabraclave.getText()); aModificar.setPorcentaje(slider.getValue()); marco.setContentPane(new VentanaModificarDescuentoModificarProductos(marco, empleado,aModificar)); marco.validate(); } }); } }
30.868132
102
0.753649
75a8ded7c4096812a9594f8fd572ef7305d31ff2
1,332
// Copyright 2021 The KeepTry Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package cache; import java.util.LinkedHashMap; import java.util.Map; // Leetcode 146. LRU Cache public class LRU_LinkedHashMap2 { /* get() and put() in O(1) average time */ class LRUCache extends LinkedHashMap { private int cap = 0; public LRUCache(int capacity) { super(capacity, 0.75f, true); this.cap = capacity; } protected boolean removeEldestEntry(Map.Entry e) { return size() > cap; } // int get(int key) Return the value of the key if the key exists, otherwise return -1. public int get(int key) { return (int) super.getOrDefault(key, -1); // } public void put(int key, int value) { super.put(key, value); // } } }
27.75
91
0.677177
0992815b5a03828eac49528e335ce26b22734d2f
5,326
package com.hbm.render.entity; import org.lwjgl.opengl.GL11; import com.hbm.entity.logic.EntityDeathBlast; import com.hbm.lib.RefStrings; import com.hbm.main.ClientProxy; import com.hbm.render.amlfrom1710.AdvancedModelLoader; import com.hbm.render.amlfrom1710.IModelCustom; import com.hbm.render.amlfrom1710.Vec3; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.entity.Render; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.entity.Entity; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.client.registry.IRenderFactory; public class RenderDeathBlast extends Render<EntityDeathBlast> { public static final IRenderFactory<EntityDeathBlast> FACTORY = (RenderManager man) -> {return new RenderDeathBlast(man);}; private static final IModelCustom sphere = AdvancedModelLoader.loadModel(new ResourceLocation(RefStrings.MODID, "models/sphere.obj")); protected RenderDeathBlast(RenderManager renderManager) { super(renderManager); } @Override public void doRender(EntityDeathBlast entity, double x, double y, double z, float entityYaw, float partialTicks) { if(!ClientProxy.renderingConstant) return; GL11.glPushMatrix(); GL11.glTranslatef((float)x, (float)y, (float)z); GlStateManager.disableLighting(); GlStateManager.enableCull(); GlStateManager.disableTexture2D(); GlStateManager.shadeModel(GL11.GL_SMOOTH); GlStateManager.depthMask(false); GL11.glPushMatrix(); //GL11.glRotatef((entity.ticksExisted % 360) * 10, 0, 1, 0); GlStateManager.enableBlend(); GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE); //GL11.glDisable(GL11.GL_ALPHA_TEST); GlStateManager.color(1.0F, 0, 0); Vec3 vector = Vec3.createVectorHelper(0.5D, 0, 0); Tessellator tessellator = Tessellator.getInstance(); BufferBuilder buf = tessellator.getBuffer(); RenderHelper.disableStandardItemLighting(); for(int i = 0; i < 8; i++) { buf.begin(GL11.GL_TRIANGLE_FAN, DefaultVertexFormats.POSITION_COLOR); buf.pos(vector.xCoord, 250.0D, vector.zCoord).color(1.0F, 0, 0, 1.0F).endVertex(); buf.pos(vector.xCoord, 0.0D, vector.zCoord).color(1.0F, 0, 0, 1.0F).endVertex(); vector.rotateAroundY(45); buf.pos(vector.xCoord, 0.0D, vector.zCoord).color(1.0F, 0, 0, 1.0F).endVertex(); buf.pos(vector.xCoord, 250.0D, vector.zCoord).color(1.0F, 0, 0, 1.0F).endVertex(); tessellator.draw(); } GlStateManager.color(1.0F, 0, 1.0F); for(int i = 0; i < 8; i++) { buf.begin(GL11.GL_TRIANGLE_FAN, DefaultVertexFormats.POSITION_COLOR); buf.pos(vector.xCoord / 2, 250.0D, vector.zCoord / 2).color(1.0F, 0, 1.0F, 1.0F).endVertex(); buf.pos(vector.xCoord / 2, 0.0D, vector.zCoord / 2).color(1.0F, 0, 1.0F, 1.0F).endVertex(); vector.rotateAroundY(45); buf.pos(vector.xCoord / 2, 0.0D, vector.zCoord / 2).color(1.0F, 0, 1.0F, 1.0F).endVertex(); buf.pos(vector.xCoord / 2, 250.0D, vector.zCoord / 2).color(1.0F, 0, 1.0F, 1.0F).endVertex(); tessellator.draw(); } GL11.glPopMatrix(); GlStateManager.depthMask(true); GlStateManager.disableCull(); GlStateManager.disableBlend(); GlStateManager.enableTexture2D(); GlStateManager.shadeModel(GL11.GL_FLAT); GL11.glPopMatrix(); renderOrb(entity, x, y, z, entityYaw, partialTicks); } public void renderOrb(Entity entity, double x, double y, double z, float p_76986_8_, float p_76986_9_) { GL11.glPushMatrix(); GL11.glTranslatef((float)x, (float)y, (float)z); GlStateManager.disableLighting(); GlStateManager.enableCull(); GlStateManager.disableTexture2D(); double scale = 15 - 15D * (((double)entity.ticksExisted+p_76986_9_) / ((double)EntityDeathBlast.maxAge)); float alpha = ((float)(entity.ticksExisted+p_76986_9_) / (float)(EntityDeathBlast.maxAge)); if(scale < 0) scale = 0; GL11.glColor4d(1.0, 0, 1.0, alpha); GlStateManager.enableBlend(); GL11.glScaled(scale, scale, scale); //OpenGlHelper.glBlendFunc(770, 771, 1, 0); GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0); sphere.renderAll(); GlStateManager.color(1.0F, 0, 0, alpha); GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE); GL11.glScaled(1.5, 1.5, 1.5); sphere.renderAll(); GlStateManager.disableBlend(); GlStateManager.enableLighting(); GlStateManager.enableTexture2D(); GlStateManager.disableCull(); GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); GL11.glPopMatrix(); } @Override public void doRenderShadowAndFire(Entity entityIn, double x, double y, double z, float yaw, float partialTicks) {} @Override protected ResourceLocation getEntityTexture(EntityDeathBlast entity) { return null; } }
38.594203
135
0.680811
0a48ec37703df5a07b8625f3a309bf28914c320e
4,163
/* * Copyright 2017 DSATool 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 dsatool.credits; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import dsatool.gui.Main; import dsatool.util.ErrorLogger; import dsatool.util.Util; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; import javafx.scene.control.Tooltip; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.Region; public class Credits { public static List<Credits> credits = new ArrayList<>(); static { credits.add(new Credits("DSATool\nCopyright (c) 2017, DSATool Team", "Apache License 2.0", Util.getAppDir() + "/licenses/ALv2.txt", "http://github.com/DSATool/DSATool", null)); credits.add(new Credits("ControlsFX\nCopyright (c) 2013, ControlsFX", "Lizenz", Util.getAppDir() + "/licenses/controlsfx-license.txt", "http://fxexperience.com/controlsfx/", null)); credits.add(new Credits("JavaFX\nCopyright (c) 2008, Oracle", "GPLv2 with Class Path Exception", Util.getAppDir() + "/licenses/GPLv2_CPE.txt", "https://openjfx.io/", null)); credits.add(new Credits("Material Icons", "Apache License Version 2.0", Util.getAppDir() + "/licenses/ALv2.txt", "https://material.io/icons/", null)); credits.add(new Credits("Jsonant", "Apache License Version 2.0", Util.getAppDir() + "/licenses/ALv2.txt", "https://github.com/errt/Jsonant", null)); credits.add(new Credits("BoxTable", "Apache License Version 2.0", Util.getAppDir() + "/licenses/ALv2.txt", "https://github.com/errt/BoxTable", null)); } private final String text; private final String license; private final String licenseUrl; private final String url; private final String imagePath; @FXML private Label textLabel; @FXML private Label licenseLabel; @FXML private Hyperlink licenseLink; @FXML private Hyperlink urlLabel; @FXML private ImageView image; public Credits(final String text, final String license, final String licenseUrl, final String url, final String imagePath) { this.text = text; this.license = license; this.licenseUrl = licenseUrl; this.url = url; this.imagePath = imagePath; } public Region getControl() { final FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setController(this); Region control = null; try { control = fxmlLoader.load(getClass().getResource("Credits.fxml").openStream()); } catch (final Exception e) { ErrorLogger.logError(e); } textLabel.setText(text); if (license != null && licenseUrl != null) { licenseLabel.setVisible(false); licenseLabel.setManaged(false); licenseLink.setText(license); licenseLink.setTooltip(new Tooltip(licenseUrl)); licenseLink.setOnAction(e -> Main.app.getHostServices().showDocument(licenseUrl)); } else { if (license != null) { licenseLabel.setText(license); } else { licenseLabel.setVisible(false); licenseLabel.setManaged(false); } licenseLink.setVisible(false); licenseLink.setManaged(false); } if (url != null) { urlLabel.setText(url); urlLabel.setOnAction(e -> Main.app.getHostServices().showDocument(url)); } else { urlLabel.setVisible(false); urlLabel.setManaged(false); } if (imagePath != null) { try { image.setImage(new Image(new FileInputStream(new File(imagePath)), 150, 75, true, true)); } catch (final FileNotFoundException e) { ErrorLogger.logError(e); } } else { image.setVisible(false); image.setManaged(false); } return control; } }
32.023077
152
0.724958
c2bc26b4c6d1d0045c8bf59b591468810a59c556
10,221
/*- * ============LICENSE_START========================================== * OPENECOMP - DCAE * =================================================================== * Copyright (c) 2017 AT&T Intellectual Property. 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. * ============LICENSE_END============================================ */ /** */ package org.openecomp.dcae.controller.core.manager.impl; import org.openecomp.dcae.controller.core.manager.DcaeManager; import org.openecomp.dcae.controller.core.manager.ManagerFactory; import org.openecomp.dcae.controller.core.manager.ManagerPackage; import org.openecomp.dcae.controller.core.service.ServicePackage; import org.openecomp.dcae.controller.core.stream.StreamPackage; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EOperation; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.EcorePackage; import org.eclipse.emf.ecore.impl.EPackageImpl; /** * <!-- begin-user-doc --> * An implementation of the model <b>Package</b>. * <!-- end-user-doc --> * @generated */ public class ManagerPackageImpl extends EPackageImpl implements ManagerPackage { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass dcaeManagerEClass = null; /** * Creates an instance of the model <b>Package</b>, registered with * {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package * package URI value. * <p>Note: the correct way to create the package is via the static * factory method {@link #init init()}, which also performs * initialization of the package, or returns the registered package, * if one already exists. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.eclipse.emf.ecore.EPackage.Registry * @see org.openecomp.dcae.controller.core.manager.ManagerPackage#eNS_URI * @see #init() * @generated */ private ManagerPackageImpl() { super(eNS_URI, ManagerFactory.eINSTANCE); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static boolean isInited = false; /** * Creates, registers, and initializes the <b>Package</b> for this model, and for any others upon which it depends. * * <p>This method is used to initialize {@link ManagerPackage#eINSTANCE} when that field is accessed. * Clients should not invoke it directly. Instead, they should simply access that field to obtain the package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #eNS_URI * @see #createPackageContents() * @see #initializePackageContents() * @generated */ public static ManagerPackage init() { if (isInited) return (ManagerPackage)EPackage.Registry.INSTANCE.getEPackage(ManagerPackage.eNS_URI); // Obtain or create and register package ManagerPackageImpl theManagerPackage = (ManagerPackageImpl)(EPackage.Registry.INSTANCE.get(eNS_URI) instanceof ManagerPackageImpl ? EPackage.Registry.INSTANCE.get(eNS_URI) : new ManagerPackageImpl()); isInited = true; // Initialize simple dependencies ServicePackage.eINSTANCE.eClass(); // Create package meta-data objects theManagerPackage.createPackageContents(); // Initialize created meta-data theManagerPackage.initializePackageContents(); // Mark meta-data to indicate it can't be changed theManagerPackage.freeze(); // Update the registry and return the package EPackage.Registry.INSTANCE.put(ManagerPackage.eNS_URI, theManagerPackage); return theManagerPackage; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EClass getDcaeManager() { return dcaeManagerEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getDcaeManager_InputStreams() { return (EReference)dcaeManagerEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EReference getDcaeManager_OutputStreams() { return (EReference)dcaeManagerEClass.getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EOperation getDcaeManager__Test() { return dcaeManagerEClass.getEOperations().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EOperation getDcaeManager__Suspend() { return dcaeManagerEClass.getEOperations().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EOperation getDcaeManager__Resume() { return dcaeManagerEClass.getEOperations().get(2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EOperation getDcaeManager__PublicKey() { return dcaeManagerEClass.getEOperations().get(3); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EOperation getDcaeManager__ConfigurationChanged() { return dcaeManagerEClass.getEOperations().get(4); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EOperation getDcaeManager__UpdateStreams__EList_EList() { return dcaeManagerEClass.getEOperations().get(5); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ManagerFactory getManagerFactory() { return (ManagerFactory)getEFactoryInstance(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private boolean isCreated = false; /** * Creates the meta-model objects for the package. This method is * guarded to have no affect on any invocation but its first. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void createPackageContents() { if (isCreated) return; isCreated = true; // Create classes and their features dcaeManagerEClass = createEClass(DCAE_MANAGER); createEReference(dcaeManagerEClass, DCAE_MANAGER__INPUT_STREAMS); createEReference(dcaeManagerEClass, DCAE_MANAGER__OUTPUT_STREAMS); createEOperation(dcaeManagerEClass, DCAE_MANAGER___TEST); createEOperation(dcaeManagerEClass, DCAE_MANAGER___SUSPEND); createEOperation(dcaeManagerEClass, DCAE_MANAGER___RESUME); createEOperation(dcaeManagerEClass, DCAE_MANAGER___PUBLIC_KEY); createEOperation(dcaeManagerEClass, DCAE_MANAGER___CONFIGURATION_CHANGED); createEOperation(dcaeManagerEClass, DCAE_MANAGER___UPDATE_STREAMS__ELIST_ELIST); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private boolean isInitialized = false; /** * Complete the initialization of the package and its meta-model. This * method is guarded to have no affect on any invocation but its first. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void initializePackageContents() { if (isInitialized) return; isInitialized = true; // Initialize package setName(eNAME); setNsPrefix(eNS_PREFIX); setNsURI(eNS_URI); // Obtain other dependent packages StreamPackage theStreamPackage = (StreamPackage)EPackage.Registry.INSTANCE.getEPackage(StreamPackage.eNS_URI); ServicePackage theServicePackage = (ServicePackage)EPackage.Registry.INSTANCE.getEPackage(ServicePackage.eNS_URI); EcorePackage theEcorePackage = (EcorePackage)EPackage.Registry.INSTANCE.getEPackage(EcorePackage.eNS_URI); // Create type parameters // Set bounds for type parameters // Add supertypes to classes // Initialize classes, features, and operations; add parameters initEClass(dcaeManagerEClass, DcaeManager.class, "DcaeManager", IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getDcaeManager_InputStreams(), theStreamPackage.getDcaeStream(), null, "inputStreams", null, 0, -1, DcaeManager.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getDcaeManager_OutputStreams(), theStreamPackage.getDcaeStream(), null, "outputStreams", null, 0, -1, DcaeManager.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEOperation(getDcaeManager__Test(), theServicePackage.getHealthTestResponse(), "test", 0, 1, !IS_UNIQUE, IS_ORDERED); initEOperation(getDcaeManager__Suspend(), null, "suspend", 0, 1, !IS_UNIQUE, IS_ORDERED); initEOperation(getDcaeManager__Resume(), null, "resume", 0, 1, !IS_UNIQUE, IS_ORDERED); initEOperation(getDcaeManager__PublicKey(), theEcorePackage.getEString(), "publicKey", 0, 1, !IS_UNIQUE, IS_ORDERED); initEOperation(getDcaeManager__ConfigurationChanged(), null, "configurationChanged", 0, 1, !IS_UNIQUE, IS_ORDERED); EOperation op = initEOperation(getDcaeManager__UpdateStreams__EList_EList(), null, "updateStreams", 0, 1, !IS_UNIQUE, IS_ORDERED); addEParameter(op, theStreamPackage.getDcaeStream(), "inputStreams", 0, -1, !IS_UNIQUE, IS_ORDERED); addEParameter(op, theStreamPackage.getDcaeStream(), "outputStreams", 0, -1, !IS_UNIQUE, IS_ORDERED); // Create resource createResource(eNS_URI); // Create annotations // http://www.eclipse.org/emf/2011/Xcore createXcoreAnnotations(); } /** * Initializes the annotations for <b>http://www.eclipse.org/emf/2011/Xcore</b>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void createXcoreAnnotations() { String source = "http://www.eclipse.org/emf/2011/Xcore"; addAnnotation (this, source, new String[] { "ecomp", "http://openecomp.org" }); } } //ManagerPackageImpl
32.242902
269
0.699149
c2d972cb7897a5ec353a3323969defb66d4e51bd
4,395
/* * Copyright (c) 2011-2019, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package boofcv.alg.fiducial.qrcode; import boofcv.struct.distort.Point2Transform2_F64; import boofcv.struct.geo.Point2D3D; import boofcv.struct.geo.PointIndex2D_F64; import georegression.struct.point.Point2D_F64; import georegression.struct.point.Point3D_F64; import org.ejml.UtilEjml; import org.junit.jupiter.api.Test; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Peter Abeles */ public class TestQrPose3DUtils { @Test public void getLandmarkByIndex() { QrCode qr = new QrCode(); // this version has a locator pattern, but we don't care about those. sanity check to see // that it's ignored qr.version = 2; for (int i = 0; i < 4; i++) { qr.ppCorner.get(i).set(i,i+1); qr.ppRight.get(i).set(4+i,4+i+1); qr.ppDown.get(i).set(8+i,8+i+1); } QrPose3DUtils alg = new QrPose3DUtils(); List<PointIndex2D_F64> list = alg.getLandmarkByIndex(qr); assertEquals(12,list.size()); for (int i = 0; i < 12; i++) { assertEquals(0,list.get(i).distance(i,i+1), UtilEjml.TEST_F64); } } @Test public void getLandmark2D3D() { QrCode qr = new QrCode(); // try different versions. This will change the coordinate of points in the marker frame for( int v : new int[]{1,2,4,10}) { int N = QrCode.totalModules(v); double w = 2.0*7/(double)N; qr.version = v; for (int i = 0; i < 4; i++) { qr.ppCorner.get(i).set(i, i + 1); qr.ppRight.get(i).set(4 + i, 4 + i + 1); qr.ppDown.get(i).set(8 + i, 8 + i + 1); } QrPose3DUtils alg = createAlg(); List<Point2D3D> list = alg.getLandmark2D3D(qr); assertEquals(12, list.size()); for (int i = 0; i < 12; i++) { // coordinate system is center (0,0) +x right +y up. normalized to have values -1 to 1 Point3D_F64 X = list.get(i).location; assertTrue(X.x >= -1 && X.x <= 1); assertTrue(X.y >= -1 && X.y <= 1); assertEquals(0, X.z); assertEquals(0, list.get(i).observation.distance(0.1 * i, 0.1 * (i + 1)), UtilEjml.TEST_F64); } // check a few hand computed points assertEquals(0, list.get(0).location.distance(-1, 1, 0), UtilEjml.TEST_F64); assertEquals(0, list.get(5).location.distance(1, 1, 0), UtilEjml.TEST_F64); assertEquals(0, list.get(11).location.distance(-1, -1, 0), UtilEjml.TEST_F64); assertEquals(0, list.get(1).location.distance(-1+w, 1, 0), UtilEjml.TEST_F64); } } /** * Compare answer to what getLandmark2D3D() returns since the info is the same */ @Test public void getLandmark3D() { QrCode qr = new QrCode(); // try different versions. This will change the coordinate of points in the marker frame for( int v : new int[]{1,2,4,10}) { qr.version = v; for (int i = 0; i < 4; i++) { qr.ppCorner.get(i).set(i, i + 1); qr.ppRight.get(i).set(4 + i, 4 + i + 1); qr.ppDown.get(i).set(8 + i, 8 + i + 1); } QrPose3DUtils alg = createAlg(); List<Point2D3D> expected = alg.getLandmark2D3D(qr); List<Point3D_F64> found = alg.getLandmark3D(qr.version); assertEquals(expected.size(),found.size()); for (int i = 0; i < expected.size(); i++) { assertEquals(0,expected.get(i).location.distance(found.get(i)), UtilEjml.TEST_F64); } } } private QrPose3DUtils createAlg() { QrPose3DUtils alg = new QrPose3DUtils(); alg.setLensDistortion(new Point2Transform2_F64() { @Override public void compute(double x, double y, Point2D_F64 out) { // just change the point's scale to make it easy to see if it was applied out.x = x*0.1; out.y = y*0.1; } @Override public Point2Transform2_F64 copyConcurrent() { return null; } },null); return alg; } }
29.695946
97
0.664391
520d4d6870a8b7a6637f5136e704f2cfa6387745
1,440
/** * $RCSfile: ,v $ * $Revision: $ * $Date: $ * * Copyright (C) 2004-2011 Jive Software. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jivesoftware.sparkimpl.settings; import org.jivesoftware.resource.Default; public class JiveInfo { private JiveInfo() { } public static String getName() { return Default.getString(Default.APPLICATION_NAME); } public static String getVersion() { return Default.getString(Default.APPLICATION_VERSION); } /* * This should be used for an actual * build number, rather than duplicating * getVersion(); i propose to use the * SVN revision number of the build */ public static String getBuildNumber() { return "12555"; } public static String getOS() { return System.getProperty("os.name"); } }
27.169811
76
0.65625
1be79ce9e5a1ddedcaa731db9c4213df509189c6
820
package net.exploitables.slashlib.commands; import discord4j.core.object.command.ApplicationCommandOption; /** * A Class which represents a sub command, or any top level command that is not top level. */ public abstract class SubCommand extends ChatCommand { protected SubCommand(String name, String description) { super(name, description, ApplicationCommandOption.Type.SUB_COMMAND); } /** * Throw an {@link IllegalStateException} when trying to set the default permission of a SubCommand as it does nothing. * @throws IllegalStateException when called */ @Override protected void setDefaultPermissionFalse() { throw new IllegalStateException("Default Permission only works on TopCommand or TopGroupCommand! Command: " + this.getClass().getSimpleName()); } }
35.652174
151
0.742683
9e6406f7de31914af28e8d8252367361ae7ba486
414
package nl.miwgroningen.se6.heartcoded.CaTo.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; /** * @author Shalena Omapersad <shalenao@hotmail.com> * * Controls the contact page. */ @Controller public class ContactController { @GetMapping("/contact") protected String showContactPage() { return "contactPage"; } }
20.7
58
0.741546
810491d450024bca5fcbe0400bba3371ff826fcd
310
package bg.infosys.crc.entities.web.security; import javax.persistence.Entity; import javax.persistence.Table; import bg.infosys.common.ws.security.db.entities.AbstractRefreshToken; @Entity @Table(name = "refresh_tokens", schema = "web_security") public class RefreshToken extends AbstractRefreshToken { }
23.846154
70
0.809677
c7d05c240235f4ec53dde7df3fbd127017b910f7
1,515
package simulations.sockets_UDP; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; import java.awt.event.ActionEvent; public class StartController extends Application { @Override public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("/simulations/sockets_UDP/start.fxml")); primaryStage.setScene(new Scene(root)); primaryStage.show(); } public static void main(String[] args) { launch(args); } public void socketEventHandler(javafx.event.ActionEvent event) { popup.display("socket", "creates a new communication point for both client and server"); } public void bindEventHandler(javafx.event.ActionEvent event) { popup.display("bind", "attaches a local address to a socket for client"); } public void sendEventHandler(javafx.event.ActionEvent event) { popup.display("send", "can send data from both client and server over this connection established"); } public void closeEventHandler(javafx.event.ActionEvent event) { popup.display("close", "link between client and server over this connection which was established is released"); } public void recieveEventHandler(javafx.event.ActionEvent event) { popup.display("recieve", "can recieve data from both client and server over this connection established"); } }
31.5625
120
0.722772
962a768f1c019d032cb732cad32181df42966363
4,128
/* * * Copyright (c) 2013 - 2020 Lijun Liao * * 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.xipki.scep.client; import org.xipki.security.HashAlgo; import org.xipki.security.X509Cert; import org.xipki.util.Args; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** * CA Certificate validator. * * @author Lijun Liao * */ public interface CaCertValidator { /** * Whether the certificate can be trusted. * @param cert * Target certificate. * @return whether the certificate is trusted. */ boolean isTrusted(X509Cert cert); /** * CA certificate validator with caching certificates. */ final class CachingCertificateValidator implements CaCertValidator { private final ConcurrentHashMap<String, Boolean> cachedAnswers; private final CaCertValidator delegate; public CachingCertificateValidator(CaCertValidator delegate) { this.delegate = Args.notNull(delegate, "delegate"); this.cachedAnswers = new ConcurrentHashMap<>(); } @Override public boolean isTrusted(X509Cert cert) { Args.notNull(cert, "cert"); String hexFp = HashAlgo.SHA256.hexHash(cert.getEncoded()); Boolean bo = cachedAnswers.get(hexFp); if (bo != null) { return bo; } else { boolean answer = delegate.isTrusted(cert); cachedAnswers.put(hexFp, answer); return answer; } } } // class CachingCertificateValidator /** * {@link CaCertValidator} with pre-povisioned CA certificates. * */ final class PreprovisionedCaCertValidator implements CaCertValidator { private final Set<String> fpOfCerts; public PreprovisionedCaCertValidator(X509Cert cert) { Args.notNull(cert, "cert"); fpOfCerts = new HashSet<>(1); String hexFp = HashAlgo.SHA256.hexHash(cert.getEncoded()); fpOfCerts.add(hexFp); } public PreprovisionedCaCertValidator(Set<X509Cert> certs) { Args.notEmpty(certs, "certs"); fpOfCerts = new HashSet<>(certs.size()); for (X509Cert m : certs) { String hexFp = HashAlgo.SHA256.hexHash(m.getEncoded()); fpOfCerts.add(hexFp); } } @Override public boolean isTrusted(X509Cert cert) { Args.notNull(cert, "cert"); String hextFp = HashAlgo.SHA256.hexHash(cert.getEncoded()); return fpOfCerts.contains(hextFp); } } // class PreprovisionedCaCertValidator final class PreprovisionedHashCaCertValidator implements CaCertValidator { private final HashAlgo hashAlgo; private final Set<byte[]> hashValues; public PreprovisionedHashCaCertValidator(HashAlgo hashAlgo, Set<byte[]> hashValues) { this.hashAlgo = Args.notNull(hashAlgo, "hashAlgo"); Args.notEmpty(hashValues, "hashValues"); final int hLen = hashAlgo.getLength(); for (byte[] m : hashValues) { if (m.length != hLen) { throw new IllegalArgumentException("invalid the length of hashValue: " + m.length + " != " + hLen); } } this.hashValues = new HashSet<>(hashValues.size()); for (byte[] m : hashValues) { this.hashValues.add(Arrays.copyOf(m, m.length)); } } @Override public boolean isTrusted(X509Cert cert) { Args.notNull(cert, "cert"); byte[] actual = hashAlgo.hash(cert.getEncoded()); for (byte[] m : hashValues) { if (Arrays.equals(actual, m)) { return true; } } return false; } } // class PreprovisionedHashCaCertValidator }
26.632258
89
0.66812
87dec6e7ce0c650a344bc000cba2f43815c605f6
2,236
/* * Copyright 2016 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.guvnor.ala.build.maven.config.impl; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.guvnor.ala.build.maven.config.MavenBuildConfig; import org.guvnor.ala.config.CloneableConfig; public class MavenBuildConfigImpl implements MavenBuildConfig, CloneableConfig<MavenBuildConfig> { private List<String> goals; private Properties properties; public MavenBuildConfigImpl() { goals = new ArrayList<>( MavenBuildConfig.super.getGoals() ); properties = new Properties( MavenBuildConfig.super.getProperties() ); } public MavenBuildConfigImpl( final List<String> goals, final Properties properties ) { this.goals = new ArrayList<>( goals ); this.properties = new Properties( properties ); } @Override public List<String> getGoals() { return goals; } public void setGoals( List<String> goals ) { this.goals = goals; } @Override public Properties getProperties() { return properties; } public void setProperties( final Properties properties ) { this.properties = properties; } @Override public String toString() { return "MavenBuildConfigImpl{" + "goals=" + goals + ", properties=" + properties + '}'; } @Override public MavenBuildConfig asNewClone( final MavenBuildConfig source ) { return new MavenBuildConfigImpl( source.getGoals(), source.getProperties() ); } }
30.216216
85
0.660555
760c120b696fcf268725640575448d66d21a086d
1,553
package org.hetida.designer.backend.converter; import lombok.extern.log4j.Log4j2; import org.hetida.designer.backend.dto.PointDTO; import org.hetida.designer.backend.model.Point; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @Component @Log4j2 public class PointConverter { public List<PointDTO> convertToPointDtos(final List<Point> entities) { return entities == null ? null : entities.stream() .map(this::convertToPointDto) .collect(Collectors.toList()); } public List<Point> convertToPointEntities(final List<PointDTO> dtos) { List<Point> points = new ArrayList<>(); if (dtos != null) { int currentSequenceNr = 0; for (PointDTO point : dtos) { points.add(this.convertToPointEntity(point, currentSequenceNr)); currentSequenceNr++; } } return points; } private PointDTO convertToPointDto(Point entity) { PointDTO pointDTO = new PointDTO(); pointDTO.setId(entity.getId()); pointDTO.setPosX(entity.getPosX()); pointDTO.setPosY(entity.getPosY()); return pointDTO; } private Point convertToPointEntity(PointDTO dto, int sequenceNr) { Point point = new Point(); point.setId(dto.getId()); point.setPosX(dto.getPosX()); point.setPosY(dto.getPosY()); point.setSequenceNr(sequenceNr); return point; } }
29.865385
80
0.646491
6ab8d8219a83e4afed0915847897b4196ab6177c
1,029
package ca.snappay.openapi.response; import ca.snappay.openapi.constant.Constants; import com.google.gson.annotations.SerializedName; import lombok.Data; import java.util.List; /** * This class is the generic type of OpenAPI response. * * @author shawndu * @version 1.0 */ @Data public abstract class OpenApiResponse<T extends OpenApiResponseData> { private String code; @SerializedName("msg") private String message; private Long total; private List<T> data; private String psn; private String sign; /** * Checks if the request is successful. * * @return true if the request is successful; or false otherwise. */ public boolean isSuccessful() { return Constants.CODE_SUCCESS.equals(code); } /** * Gets the single result. * * @return the result, if any. */ public T getResult() { if (isSuccessful() && total == 1) { return data.get(0); } else { return null; } } }
19.055556
70
0.622935
9ec5ab26c919e8ed56c6491265a92e5b09f599d1
15,780
/** * Copyright 2020 SPeCS. * * 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. under the License. */ package pt.up.fe.specs.clava.utils.foriter; import java.util.Optional; import pt.up.fe.specs.clava.ClavaLog; import pt.up.fe.specs.clava.ClavaNodes; import pt.up.fe.specs.clava.ast.expr.BinaryOperator; import pt.up.fe.specs.clava.ast.expr.DeclRefExpr; import pt.up.fe.specs.clava.ast.expr.Expr; import pt.up.fe.specs.clava.ast.expr.Literal; import pt.up.fe.specs.clava.ast.expr.UnaryOperator; import pt.up.fe.specs.clava.ast.expr.enums.BinaryOperatorKind; import pt.up.fe.specs.clava.ast.expr.enums.UnaryOperatorKind; import pt.up.fe.specs.clava.ast.stmt.ExprStmt; import pt.up.fe.specs.clava.ast.stmt.ForStmt; import pt.up.fe.specs.clava.ast.stmt.Stmt; import pt.up.fe.specs.clava.ast.type.BuiltinType; import pt.up.fe.specs.clava.ast.type.Type; import pt.up.fe.specs.clava.utils.Typable; import pt.up.fe.specs.util.exceptions.NotImplementedException; public class ForIterationsExpression { // private final VarDecl iterVar; private final String iterVarName; private final Type iterVarType; private final Expr initExpr; private final StepData stepData; private final ConditionData conditionData; public ForIterationsExpression(String iterVarName, Type iterVarType, Expr initExpr, StepData stepData, ConditionData conditionData) { // this.iterVar = iterVar; this.iterVarName = iterVarName; this.iterVarType = iterVarType; this.initExpr = initExpr; this.stepData = stepData; this.conditionData = conditionData; } // public VarDecl getIterVar() { // return iterVar; // } public String getIterVarName() { return iterVarName; } public Type getIterVarType() { return iterVarType; } public Expr getInitExpr() { return initExpr; } public StepData getStepData() { return stepData; } public ConditionData getConditionData() { return conditionData; } public Optional<Expr> getIterationsExpr() { var end = getBoundary(false); var start = getBoundary(true); Expr interval = end; // If start is not zero, include subtraction if (!start.getCode().equals("0")) { interval = start.getFactory().binaryOperator(BinaryOperatorKind.Sub, iterVarType, end, start); } // Adjust interval, if needed interval = adjustInterval(interval); // Divide by step, if not literally 1 if (stepData.getStepValue().getCode().equals("1")) { return Optional.of(interval); } // Divide by step value interval = protectTerm(interval); var step = protectTerm(stepData.getStepValue()); interval = step.getFactory().binaryOperator(BinaryOperatorKind.Div, iterVarType, interval, step); return Optional.of(interval); } private Expr adjustInterval(Expr interval) { // No adjustment needed if (conditionData.getRelation() == ForCondRelation.GT || conditionData.getRelation() == ForCondRelation.LT) { return interval; } // Only adjust if GE or LE return interval.getFactory().binaryOperator(BinaryOperatorKind.Add, iterVarType, interval, stepData.getStepValue()); } private Expr getBoundary(boolean isStart) { Expr boundary = null; switch (stepData.getDirection()) { case INC: boundary = isStart ? initExpr : conditionData.getValue(); break; case DEC: boundary = isStart ? conditionData.getValue() : initExpr; break; default: throw new NotImplementedException(stepData.getDirection()); } // Add parenthesis, if necessary boundary = protectTerm(boundary); return boundary; } private Expr protectTerm(Expr expr) { // If literal, just return it if (expr instanceof Literal) { return expr; } return expr.getFactory().parenExpr(expr); } public static Optional<ForIterationsExpression> newInstance(ForStmt forStmt) { // Get init variable // var iterVar = forStmt.getInitVar().orElse(null); // // if (iterVar == null) { // ClavaLog.debug("ForIterationsExpression: could not determine iteration variable of 'for' at " // + forStmt.getLocation()); // return Optional.empty(); // } var iterVarNode = forStmt.getIterationVarNode().orElse(null); if (iterVarNode == null) { ClavaLog.debug("ForIterationsExpression: could not determine iteration variable of 'for' at " + forStmt.getLocation()); return Optional.empty(); } var iterVarName = ClavaNodes.getName(iterVarNode); var iterVarType = ((Typable) iterVarNode).getType(); // Get init value // var initExpr = iterVar.getInit().orElse(null); var initExpr = forStmt.getInitValueExpr().orElse(null); if (initExpr == null) { ClavaLog.debug( "ForIterationsExpression: could not determine initial value of iteration variable " + iterVarName + " at " + forStmt.getLocation()); return Optional.empty(); } // Get step value and step direction var stepData = forStmt.getInc().flatMap(incStmt -> getStepData(incStmt, iterVarName)).orElse(null); if (stepData == null) { ClavaLog.debug( "ForIterationsExpression: could not determine step data of 'for' at " + forStmt.getLocation()); return Optional.empty(); } // Get condition data var conditionData = forStmt.getCond().flatMap(cond -> getConditionData(cond, iterVarName)).orElse(null); if (conditionData == null) { ClavaLog.debug("ForIterationsExpression: could not determine condition data of 'for' at " + forStmt.getLocation()); return Optional.empty(); } // System.out.println("STEP DATA: " + stepData); // System.out.println("COND DATA: " + conditionData); // Verify data var forIterations = new ForIterationsExpression(iterVarName, iterVarType, initExpr, stepData, conditionData); if (!verify(forIterations)) { return Optional.empty(); } return Optional.of(forIterations); } private static boolean verify(ForIterationsExpression forIterations) { var condRelation = forIterations.getConditionData().getRelation(); // LT and LE should only be used with INC, GT and GE should only be used with DEC switch (forIterations.getStepData().getDirection()) { case INC: if (condRelation == ForCondRelation.GE || condRelation == ForCondRelation.GT) { ClavaLog.debug(() -> "ForIterationsExpression: cannot use > or >= in condition when step increases"); return false; } break; case DEC: if (condRelation == ForCondRelation.LE || condRelation == ForCondRelation.LT) { ClavaLog.debug(() -> "ForIterationsExpression: cannot use < or <= in condition when step decreases"); return false; } break; } // LE and GE are only supported when iteration variable in an integer if (condRelation == ForCondRelation.GE || condRelation == ForCondRelation.LE) { var iterVarType = forIterations.getIterVarType().desugarAll(); // Only supports built-in type (after desugaring) if (!(iterVarType instanceof BuiltinType)) { ClavaLog.debug( () -> "ForIterationsExpression: cannot verify <= or >= if iteration variable is not a built-in type, " + iterVarType); return false; } var builtinType = (BuiltinType) iterVarType; var isInteger = builtinType.get(BuiltinType.KIND).isInteger(); if (!isInteger) { ClavaLog.debug( () -> "ForIterationsExpression: operation <= or >= in condition expression only supported if iteration variable is an integer, " + iterVarType); return false; } } return true; } private static Optional<ConditionData> getConditionData(Stmt conditionStmt, String iterVarName) { // Only supports ExprStmt if (!(conditionStmt instanceof ExprStmt)) { ClavaLog.debug(() -> "ForIterationsExpression: cond statement is not an ExprStmt, " + conditionStmt); return Optional.empty(); } var condExpr = ((ExprStmt) conditionStmt).getExpr(); if (!(condExpr instanceof BinaryOperator)) { ClavaLog.debug(() -> "ForIterationsExpression: cond expr is not a binary operator, " + condExpr); return Optional.empty(); } var binaryOp = (BinaryOperator) condExpr; // Find iteration var int iterVarIndex = getVarIndex(iterVarName, binaryOp); if (iterVarIndex == -1) { ClavaLog.debug( () -> "ForIterationsExpression: could not find iteration variable on one of the sides of the condition expression, " + condExpr); return Optional.empty(); } int condValueExprIndex = getCondExprIndex(iterVarIndex); var condValueExpr = binaryOp.getChild(Expr.class, condValueExprIndex); var condRelation = getCondRelation(binaryOp.getOp(), iterVarIndex); return Optional.of(new ConditionData(condValueExpr, condRelation)); } private static ForCondRelation getCondRelation(BinaryOperatorKind op, int iterVarIndex) { switch (op) { case LT: return iterVarIndex == 0 ? ForCondRelation.LT : ForCondRelation.GT; case GT: return iterVarIndex == 0 ? ForCondRelation.GT : ForCondRelation.LT; case LE: return iterVarIndex == 0 ? ForCondRelation.LE : ForCondRelation.GE; case GE: return iterVarIndex == 0 ? ForCondRelation.GE : ForCondRelation.LE; default: ClavaLog.debug( () -> "ForIterationsExpression: unsupported binary operator in condition expression, " + op.getOpString()); return null; } } private static int getCondExprIndex(int iterVarIndex) { if (iterVarIndex == 0) { return 1; } if (iterVarIndex == 1) { return 0; } throw new RuntimeException("Invalid iteration variable index: " + iterVarIndex); } private static int getVarIndex(String varName, BinaryOperator expr) { for (int i = 0; i < expr.getNumChildren(); i++) { var child = expr.getChild(i); // Normalize node child = ClavaNodes.normalize(child); // Only supports DeclRefExpr if (!(child instanceof DeclRefExpr)) { continue; } if (varName.equals(((DeclRefExpr) child).getName())) { return i; } } return -1; } private static Optional<StepData> getStepData(Stmt incStmt, String iterVarName) { // Only supports ExprStmt if (!(incStmt instanceof ExprStmt)) { ClavaLog.debug(() -> "ForIterationsExpression: step statement is not an ExprStmt, " + incStmt); return Optional.empty(); } var incExpr = ((ExprStmt) incStmt).getExpr(); // var += incr // var -= incr // var = var + incr // var = incr + var // var = var - incr if (incExpr instanceof BinaryOperator) { BinaryOperator binaryOp = (BinaryOperator) incExpr; boolean hasIterVar = isVarReference(iterVarName, binaryOp.getLhs()); if (!hasIterVar) { ClavaLog.debug( () -> "ForIterationsExpression: could not find iteration variable '" + iterVarName + "' on left-hand side of step expression, " + binaryOp.getLhs()); return Optional.empty(); } BinaryOperatorKind kind = binaryOp.getOp(); if (kind == BinaryOperatorKind.AddAssign) { return Optional.of(new StepData(ForStepDirection.INC, binaryOp.getRhs())); } if (kind == BinaryOperatorKind.SubAssign) { return Optional.of(new StepData(ForStepDirection.DEC, binaryOp.getRhs())); } ClavaLog.debug( () -> "ForIterationsExpression: not implemented for a step with binary operator of kind " + kind); return Optional.empty(); } // ++var // var++ // --var // var-- if (incExpr instanceof UnaryOperator) { UnaryOperator unaryOp = (UnaryOperator) incExpr; boolean hasIterVar = isVarReference(iterVarName, unaryOp.getSubExpr()); if (!hasIterVar) { ClavaLog.debug( () -> "ForIterationsExpression: could not find iteration variable '" + iterVarName + "' on unary operator sub-expression, " + unaryOp.getSubExpr()); return Optional.empty(); } UnaryOperatorKind kind = unaryOp.getOp(); if (kind == UnaryOperatorKind.PreInc || kind == UnaryOperatorKind.PostInc) { return Optional.of(new StepData(ForStepDirection.INC, unaryOp.getFactory().integerLiteral(1))); } if (kind == UnaryOperatorKind.PreDec || kind == UnaryOperatorKind.PostDec) { return Optional.of(new StepData(ForStepDirection.DEC, unaryOp.getFactory().integerLiteral(1))); } ClavaLog.debug( () -> "ForIterationsExpression: not implemented for a step with unary operator of kind " + kind); return Optional.empty(); } ClavaLog.debug( () -> "ForIterationsExpression: not implemented for this kind of step expression, " + incExpr); return Optional.empty(); } private static boolean isVarReference(String iterVarName, Expr expr) { // Check if left-hand is iteration variable // Expecting decl ref expression if (!(expr instanceof DeclRefExpr)) { // ClavaLog.debug(() -> "ForIterationsExpression: left-hand side of step expression is not a DeclRefExpr, " // + expr); return false; } // Check name if (!iterVarName.equals(((DeclRefExpr) expr).getName())) { // ClavaLog.debug(() -> "ForIterationsExpression: step variable (" + ((DeclRefExpr) expr).getName() // + ") is not the same as the iteration variable (" + iterVarName + ")"); return false; } return true; } }
36.359447
152
0.601014
9ace454eacac54f08d9441b7313664f2827ff6c5
5,537
package net.catchpole.io.tool; // Copyright 2014 catchpole.net // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import net.catchpole.io.Arrays; import net.catchpole.io.DirectoryTree; import net.catchpole.io.Files; import net.catchpole.lang.Arguments; import net.catchpole.trace.Core; import javax.swing.*; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.zip.CRC32; public class Deduplicate { private final List<File> repeats = new ArrayList<File>(); public static void main(String[] args) { try { if (args.length == 0) { Core.getTrace().info(Deduplicate.class.getSimpleName() + " -dirs <dir1 dir2 ...> -delete -confirm -high -matchnames -trimdirs"); return; } Arguments arguments = new Arguments(args); File[] dirList = arguments.getFileArray("-dirs"); List<File> files = Files.getRecursiveFileList(dirList); Deduplicate fc = new Deduplicate(files, arguments.hasArgument("-high")); if (arguments.hasArgument("-delete")) { if (arguments.hasArgument("-confirm")) { if (JOptionPane.showConfirmDialog(null, "Delete " + fc.repeats.size() + " ?") == JOptionPane.OK_OPTION) { fc.deleteRepeats(); } } else { fc.deleteRepeats(); } } if (arguments.hasArgument("-trimdirs")) { for (File dir : dirList) { DirectoryTree dt = new DirectoryTree(dir); dt.deleteEmptyDirs(); } } } catch (Exception e) { e.printStackTrace(); } } public Deduplicate(List<File> files, boolean high) throws IOException { // create a map of lists of files with identicle size Map<Long, List<File>> lengthMap = new HashMap<Long, List<File>>(); if (files.size() > 1) { if (high) { Arrays.reverse(files); } for (File file : files) { List<File> list = lengthMap.get(file.length()); if (list == null) { list = new ArrayList<File>(); lengthMap.put(file.length(), list); } list.add(file); } } // remove lists with only one file Iterator<Long> i = lengthMap.keySet().iterator(); while (i.hasNext()) { Long key = i.next(); if (lengthMap.get(key).size() == 1) { i.remove(); } } Core.getTrace().info("Indenticle length groups: ", lengthMap.size()); for (List<File> list : lengthMap.values()) { compareIdenticleLengths(list); } } private void compareIdenticleLengths(List<File> files) throws IOException { // create list of CRCs for files List<Integer> crcs = new ArrayList<Integer>(); for (File file : files) { crcs.add(crc(file)); } // compare each file with every other for (int x = 0; x < files.size(); x++) { for (int y = 0; y < files.size(); y++) { if (x != y) { File fx = files.get(x); File fy = files.get(y); if (fx != null & fy != null & crcs.get(x).equals(crcs.get(y)) & Files.fileEquals(fx, fy)) { // tag lower file (if -high, list was reversed) repeats.add(fx); // removed taged file from compare files.set(x, null); Core.getTrace().info(fx, "\r\n\t\t\t=\t", fy); } } } } } public void deleteRepeats() throws IOException { for (File file : repeats) { try { file.delete(); } catch (Exception e) { e.printStackTrace(); } } Core.getTrace().info("Repeats deleted:" + repeats.size()); } // a crc of the start of the file, reduces the need to do binary compares of files which will never equate private static int crc(File file) throws IOException { // use small buffer, so that non-equal files dont need to load so much at start int bufferlen = (int) (file.length() < 1024 ? file.length() : 1024); byte[] buffer = new byte[bufferlen]; DataInputStream is = new DataInputStream(new FileInputStream(file)); try { is.readFully(buffer); } finally { is.close(); } CRC32 crc32 = new CRC32(); crc32.update(buffer); return (int) crc32.getValue(); } }
34.179012
144
0.54181
bdeca23cd5d2648158e1a3cec1b29af9def67aba
1,269
package model; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; /** * Tests Lane class * @author Simon Krol * @version Nov 16, 2018 */ public class TestSpot { Spot spot1; Spot spot2; Sunflower sunny; @Before public void setUp() throws Exception { spot1 = new Spot(false); spot2 = new Spot(true); sunny = new Sunflower(); } @Test public void testGetOccupied() { assertFalse("Spot not occupied", spot2.getOccupied()); spot2.addPlant(sunny); assertTrue("Spot occupied", spot2.getOccupied()); } @Test public void testGetPlant() { assertEquals("Spot is null", null, spot2.getPlant()); spot2.addPlant(sunny); assertTrue("Sunny is in spot", sunny.equals(spot2.getPlant())); } @Test(expected = NullPointerException.class) public void testKillPlant() { assertEquals("Spot is null", null, spot2.getPlant()); spot2.addPlant(sunny); assertTrue("Sunny is in spot", sunny.equals(spot2.getPlant())); spot2.killPlant(); assertEquals("Spot is null", null, spot2.getPlant()); spot2.killPlant(); } @Test public void testPlaceable() { assertEquals("Spot is null", null, spot1.getPlant()); assertFalse(spot1.addPlant(sunny)); assertEquals("Spot is null", null, spot1.getPlant()); } }
20.142857
65
0.693459
79ec75e31b3229e6281a935bdfcb4e529d212bbd
681
package com.smcpartners.shape.usecases.find_all_measures; import com.smcpartners.shape.shared.dto.shape.MeasureDTO; import com.smcpartners.shape.shared.usecasecommon.UseCaseException; import org.jboss.resteasy.annotations.cache.NoCache; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import java.util.List; /** * Responsible:<br/> * 1. Support REST framework * <p> * Created by johndestefano on 11/2/15. * <p> * Changes:<b/> */ @Path("/common") public interface FindAllMeasuresService { @GET @NoCache @Path("/measure/findAll") @Produces("application/json") List<MeasureDTO> findAllMeasures() throws UseCaseException; }
23.482759
67
0.741557
ce39ef40492665c176fd2d9d0f4628c54f825c82
2,079
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-147 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.02.09 at 10:59:16 AM EST // package org.cvrgrid.hl7aecg.jaxb.beans; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for ActRelationshipSequel. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="ActRelationshipSequel"> * &lt;restriction base="{urn:hl7-org:v3}ActRelationshipType"> * &lt;enumeration value="XCRPT"/> * &lt;enumeration value="VRXCRPT"/> * &lt;enumeration value="FLFS"/> * &lt;enumeration value="OCCR"/> * &lt;enumeration value="OREF"/> * &lt;enumeration value="SCH"/> * &lt;enumeration value="RPLC"/> * &lt;enumeration value="SUCC"/> * &lt;enumeration value="APND"/> * &lt;enumeration value="DOC"/> * &lt;enumeration value="ELNK"/> * &lt;enumeration value="GEN"/> * &lt;enumeration value="GEVL"/> * &lt;enumeration value="INST"/> * &lt;enumeration value="MTCH"/> * &lt;enumeration value="OPTN"/> * &lt;enumeration value="REV"/> * &lt;enumeration value="UPDT"/> * &lt;enumeration value="XFRM"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "ActRelationshipSequel") @XmlEnum(ActRelationshipType.class) public enum ActRelationshipSequel { XCRPT, VRXCRPT, FLFS, OCCR, OREF, SCH, RPLC, SUCC, APND, DOC, ELNK, GEN, GEVL, INST, MTCH, OPTN, REV, UPDT, XFRM; public String value() { return name(); } public static ActRelationshipSequel fromValue(String v) { return valueOf(v); } }
25.9875
127
0.607504
d7f2cacc31ce313034c569b3c6d94dea2eb03891
4,624
package jim.android.pieceWash; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.GridView; import android.widget.ImageView; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.HttpHeaderParser; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.google.gson.Gson; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import jim.android.Splash.R; import jim.android.adapter.PieceWashAdapter; import jim.android.bean.BasketBean; import jim.android.bean.Data; import jim.android.bean.PieceWashBean; import jim.android.bean.Results; import jim.android.mainFrame.Basket; import jim.android.mainFrame.FragmentMainActivity; import jim.android.mainFrame.LazyFragment; import jim.android.utils.BasketItemMsg; /** * Created by Jim Huang on 2015/8/9. */ public class FragmentAutumn extends LazyFragment { private View view; private GridView gridView; private RequestQueue myQueue; private List<Results> list; private Gson gson; private boolean isPrepared; private JianxiPopup jianxiPopup; private Results results; private BasketBean basketBean; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.activity_frag_autumn, container, false); initView(); isPrepared = true; return view; } @Override protected void lazyLoad() { if (isVisible && isPrepared) { StringRequest request = new StringRequest("http://123.56.138.192:8002/products/?category__name=" + parseUTF("冬装"), new Response.Listener<String>() { @Override public void onResponse(String s) { PieceWashBean pieceWashBean = gson.fromJson(s, PieceWashBean.class); Data data = pieceWashBean.getData(); list = data.getResults(); gridView.setAdapter(new PieceWashAdapter(list, getActivity())); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { } }) { @Override protected Response<String> parseNetworkResponse(NetworkResponse response) { try { String jsonObject = new String(response.data, "UTF-8"); return Response.success(jsonObject, HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (Exception je) { return Response.error(new ParseError(je)); } } }; myQueue.add(request); } } private String parseUTF(String str) { try { return URLEncoder.encode(str, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } private void initView() { gridView = (GridView) view.findViewById(R.id.grid_autumn); myQueue = Volley.newRequestQueue(getActivity()); list = new ArrayList<>(); gson = new Gson(); gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { results= (Results) gridView.getItemAtPosition(position); Iterator iterator= FragmentMainActivity.basketList.iterator(); Drawable drawable=((ImageView)view.findViewById(R.id.piece_grid_item_img)).getDrawable(); JianxiPopup jianxiPopup=new JianxiPopup(getActivity(),results,drawable); jianxiPopup.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); } }); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } }
33.266187
160
0.656142
4517e93fe1b2c3df23079d5f5537d0bb947f1e81
667
package kr.co.popone.fitts.feature.order.complete; import androidx.lifecycle.Observer; import kr.co.popone.fitts.base.extension.FragmentExtensionKt; final class OrderCompleteRenderReservationFragment$onViewCreated$8<T> implements Observer<Throwable> { final /* synthetic */ OrderCompleteRenderReservationFragment this$0; OrderCompleteRenderReservationFragment$onViewCreated$8(OrderCompleteRenderReservationFragment orderCompleteRenderReservationFragment) { this.this$0 = orderCompleteRenderReservationFragment; } public final void onChanged(Throwable th) { FragmentExtensionKt.handleError(this.this$0, th); } }
39.235294
140
0.785607
fb96e6cf40fbb3e99137e38c9d02a9bab5912650
1,287
package uk.gov.mca.beacons.api.shared.mappers.person; import org.springframework.stereotype.Component; import uk.gov.mca.beacons.api.shared.domain.person.Address; import uk.gov.mca.beacons.api.shared.rest.person.dto.AddressDTO; @Component public class AddressMapper { public Address fromDTO(AddressDTO addressDTO) { return Address .builder() .addressLine1(addressDTO.getAddressLine1()) .addressLine2(addressDTO.getAddressLine2()) .addressLine3(addressDTO.getAddressLine3()) .addressLine4(addressDTO.getAddressLine4()) .townOrCity(addressDTO.getTownOrCity()) .county(addressDTO.getCounty()) .postcode(addressDTO.getPostcode()) .country(addressDTO.getCountry()) .build(); } public AddressDTO toDTO(Address address) { if (address == null) { return new AddressDTO("", "", "", "", "", "", "", ""); } return AddressDTO .builder() .addressLine1(address.getAddressLine1()) .addressLine2(address.getAddressLine2()) .addressLine3(address.getAddressLine3()) .addressLine4(address.getAddressLine4()) .townOrCity(address.getTownOrCity()) .county(address.getCounty()) .postcode(address.getPostcode()) .country(address.getCountry()) .build(); } }
30.642857
64
0.685315
258ddfbc901ce54d245e36847a4974fd37b17356
7,752
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 2008-2009, The KiWi Project (http://www.kiwi-project.eu) * 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 KiWi Project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Contributor(s): * sschaffe * */ package kiwi.action.ui; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import kiwi.api.content.ContentItemService; import kiwi.api.perspectives.PerspectiveService; import kiwi.model.content.ContentItem; import kiwi.model.perspective.Perspective; import org.jboss.seam.Component; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.AutoCreate; import org.jboss.seam.annotations.Create; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Logger; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Scope; import org.jboss.seam.faces.FacesMessages; import org.jboss.seam.log.Log; /** * The PerspectiveAction is a core view backing bean that keeps track of the perspective that has been * chosen for the currently active content item. * * @author Sebastian Schaffert * */ @Name("kiwi.ui.perspectiveAction") @Scope(ScopeType.CONVERSATION) @AutoCreate public class PerspectiveAction { @Logger private Log log; @In private FacesMessages facesMessages; @In private PerspectiveService perspectiveService; @In(create=true) private ContentItem currentContentItem; private Perspective currentPerspective; private List<String> selectedPerspectives; private List<String> automaticPerspectives; private List<String> availablePerspectives; @Create public void begin() { init(); log.info("PerspectiveAction initalised; current content item has #0 perspectives.",currentContentItem.getPerspectives().size()); } public void init() { HashSet<Long> visitedPerspectives = new HashSet<Long>(); if(currentContentItem.getPerspectives().size() == 0) { perspectiveService.attachPerspective(currentContentItem, perspectiveService.getDefaultPerspective()); currentPerspective = perspectiveService.getDefaultPerspective(); } else { currentPerspective = currentContentItem.getPerspectives().get(0); } selectedPerspectives = new LinkedList<String>(); for(Perspective p : currentContentItem.getPerspectives()) { if(!visitedPerspectives.contains(p.getId())) { selectedPerspectives.add(p.getName()); visitedPerspectives.add(p.getId()); } } // add perspectives based on type automaticPerspectives = new LinkedList<String>(); for(Perspective p : perspectiveService.listPerspectivesByTypes(currentContentItem)) { if(!visitedPerspectives.contains(p.getId())) { automaticPerspectives.add(p.getName()); visitedPerspectives.add(p.getId()); } } } /** * @return the currentPerspective */ public Perspective getCurrentPerspective() { return currentPerspective; } /** * @param currentPerspective the currentPerspective to set */ public void setCurrentPerspective(Perspective currentPerspective) { log.info("switching to perspective #0",currentPerspective.getName()); this.currentPerspective = currentPerspective; } /** * Return the complete JSF path of the current perspective's view template. * @return */ public String getViewTemplate() { return "/perspectives/"+currentPerspective.getViewTemplate(); } /** * Return the complete JSF path of the current perspective's edit template. * @return */ public String getEditTemplate() { return "/perspectives/"+currentPerspective.getEditTemplate(); } public List<Perspective> listPerspectives() { return currentContentItem.getPerspectives(); } public List<Perspective> listAutomaticPerspectives() { // exclude perspectives that are already selected explicitly HashSet<Long> selectedPerspectives = new HashSet<Long>(); for(Perspective p : currentContentItem.getPerspectives()) { selectedPerspectives.add(p.getId()); } List<Perspective> result = new LinkedList<Perspective>(); for(Perspective p : perspectiveService.listPerspectivesByTypes(currentContentItem)) { if(!selectedPerspectives.contains(p.getId())) { result.add(p); } } return result; } /** * @return the selectedPerspectives */ public List<String> getSelectedPerspectives() { return selectedPerspectives; } /** * @param selectedPerspectives the selectedPerspectives to set */ public void setSelectedPerspectives(List<String> selectedPerspectives) { if(selectedPerspectives.size() > 0) { this.selectedPerspectives = selectedPerspectives; } else { facesMessages.add("please select at least one perspective!"); } } /** * @return the automaticPerspectives */ public List<String> getAutomaticPerspectives() { return automaticPerspectives; } /** * @param automaticPerspectives the automaticPerspectives to set */ public void setAutomaticPerspectives(List<String> automaticPerspectives) { this.automaticPerspectives = automaticPerspectives; } public List<String> getAvailablePerspectives() { if(availablePerspectives == null) { availablePerspectives = new LinkedList<String>(); for(Perspective p : perspectiveService.listPerspectives()) { if(!selectedPerspectives.contains(p.getName())) { availablePerspectives.add(p.getName()); } } } return availablePerspectives; } /** * @param allPerspectives the allPerspectives to set */ public void setAvailablePerspectives(List<String> allPerspectives) { this.availablePerspectives = allPerspectives; } public void saveSelectedPerspectives() { List<Perspective> result = new LinkedList<Perspective>(); for(String p : selectedPerspectives) { result.add(perspectiveService.getPerspective(p)); } log.info("adding #0 perspectives",result.size()); currentContentItem.setPerspectives(result); ContentItemService contentItemService = (ContentItemService) Component.getInstance("contentItemService"); contentItemService.saveContentItem(currentContentItem); } }
31.512195
133
0.728715
25f6a48871d34fc7f371a4a0ea0a37ea9cdcd29a
5,528
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package android.testing; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.test.suitebuilder.annotation.SmallTest; import android.testing.TestableLooper.MessageHandler; import android.testing.TestableLooper.RunWithLooper; @SmallTest @RunWith(AndroidTestingRunner.class) @RunWithLooper public class TestableLooperTest { private TestableLooper mTestableLooper; @Before public void setup() throws Exception { mTestableLooper = TestableLooper.get(this); } @Test public void testMessageExecuted() throws Exception { Handler h = new Handler(); Runnable r = mock(Runnable.class); h.post(r); verify(r, never()).run(); mTestableLooper.processAllMessages(); verify(r).run(); } @Test public void testMessageCallback() throws Exception { Handler h = new Handler(); Message m = h.obtainMessage(3); Runnable r = mock(Runnable.class); MessageHandler messageHandler = mock(MessageHandler.class); when(messageHandler.onMessageHandled(any())).thenReturn(false); mTestableLooper.setMessageHandler(messageHandler); m.sendToTarget(); h.post(r); mTestableLooper.processAllMessages(); verify(messageHandler).onMessageHandled(eq(m)); // This should never be run becaus the mock returns false on the first message, and // the second will get skipped. verify(r, never()).run(); } @Test public void testProcessNumberOfMessages() throws Exception { Handler h = new Handler(); Runnable r = mock(Runnable.class); h.post(r); h.post(r); h.post(r); mTestableLooper.processMessages(2); verify(r, times(2)).run(); } @Test public void testProcessAllMessages() throws Exception { Handler h = new Handler(); Runnable r = mock(Runnable.class); Runnable poster = () -> h.post(r); h.post(poster); mTestableLooper.processAllMessages(); verify(r).run(); } @Test public void test3Chain() throws Exception { Handler h = new Handler(); Runnable r = mock(Runnable.class); Runnable poster = () -> h.post(r); Runnable poster2 = () -> h.post(poster); h.post(poster2); mTestableLooper.processAllMessages(); verify(r).run(); } @Test public void testProcessAllMessages_2Messages() throws Exception { Handler h = new Handler(); Runnable r = mock(Runnable.class); Runnable r2 = mock(Runnable.class); h.post(r); h.post(r2); mTestableLooper.processAllMessages(); verify(r).run(); verify(r2).run(); } @Test public void testMainLooper() throws Exception { assertNotEquals(Looper.myLooper(), Looper.getMainLooper()); Runnable r = mock(Runnable.class); Runnable r2 = mock(Runnable.class); TestableLooper testableLooper = new TestableLooper(Looper.getMainLooper()); try { testableLooper.setMessageHandler(m -> { if (m.getCallback() == r) return true; return false; }); new Handler(Looper.getMainLooper()).post(r); testableLooper.processAllMessages(); verify(r).run(); verify(r2, never()).run(); } finally { testableLooper.destroy(); } } @Test public void testNonMainLooperAnnotation() { assertNotEquals(Looper.myLooper(), Looper.getMainLooper()); } @Test @RunWithLooper(setAsMainLooper = true) public void testMainLooperAnnotation() { assertEquals(Looper.myLooper(), Looper.getMainLooper()); } @Test public void testCorrectLooperExecution() throws Exception { boolean[] hasRun = new boolean[] { false }; Runnable r = () -> { assertEquals("Should run on main looper", Looper.getMainLooper(), Looper.myLooper()); hasRun[0] = true; }; TestableLooper testableLooper = new TestableLooper(Looper.getMainLooper()); try { new Handler(Looper.getMainLooper()).post(r); testableLooper.processAllMessages(); assertTrue(hasRun[0]); } finally { testableLooper.destroy(); } } }
30.541436
97
0.646165
292f72dfee11d7325d1b17aba41b5c24f7d2ab98
309
package gitee.com.ericfox.ddd.common.interfaces.starter; /** * 缓存策略接口 */ public interface CacheService { void put(Object key, Object value); Object get(Object key); Boolean remove(Object key); Long removeByPrefix(String prefix); Long removeByPrefix(String module, String prefix); }
18.176471
56
0.711974
dbd19458fc5236fd40cc7053393edf579b5bf7b8
5,807
/* * 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.flink.tools.ci.licensecheck; import org.apache.flink.annotation.VisibleForTesting; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URI; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Checks the Jar files created by the build process. */ public class JarFileChecker { private static final Logger LOG = LoggerFactory.getLogger(JarFileChecker.class); public static int checkPath(Path path) throws Exception { List<Path> files = getBuildJars(path); LOG.info("Checking directory {} with a total of {} jar files.", path, files.size()); int severeIssues = 0; for (Path file : files) { severeIssues += checkJar(file); } return severeIssues; } private static List<Path> getBuildJars(Path path) throws IOException { return Files.walk(path) .filter(file -> file.toString().endsWith(".jar")) .collect(Collectors.toList()); } @VisibleForTesting static int checkJar(Path file) throws Exception { final URI uri = file.toUri(); int numSevereIssues = 0; try (final FileSystem fileSystem = FileSystems.newFileSystem(new URI("jar:file", uri.getHost(), uri.getPath(), uri.getFragment()), Collections.emptyMap())) { if (isTestJarAndEmpty(file, fileSystem.getPath("/"))) { return 0; } if (!noticeFileExistsAndIsValid(fileSystem.getPath("META-INF", "NOTICE"), file)) { numSevereIssues++; } if (!licenseFileExistsAndIsValid(fileSystem.getPath("META-INF", "LICENSE"), file)) { numSevereIssues++; } numSevereIssues += getNumLicenseFilesOutsideMetaInfDirectory(file, fileSystem.getPath("/")); } return numSevereIssues; } private static boolean isTestJarAndEmpty(Path jar, Path jarRoot) throws IOException { if (jar.getFileName().toString().endsWith("-tests.jar")) { try (Stream<Path> files = Files.walk(jarRoot)) { long numClassFiles = files .filter(path -> !path.equals(jarRoot)) .filter(path -> path.getFileName().toString().endsWith(".class")) .count(); if (numClassFiles == 0) { return true; } } } return false; } private static boolean noticeFileExistsAndIsValid(Path noticeFile, Path jar) throws IOException { if (!Files.exists(noticeFile)) { LOG.error("Missing META-INF/NOTICE in {}", jar); return false; } final String noticeFileContents = new String(Files.readAllBytes(noticeFile), StandardCharsets.UTF_8); if (!noticeFileContents.toLowerCase().contains("flink") || !noticeFileContents.contains("The Apache Software Foundation")) { LOG.error("The notice file in {} does not contain the expected entries.", jar); return false; } return true; } private static boolean licenseFileExistsAndIsValid(Path licenseFile, Path jar) throws IOException { if (!Files.exists(licenseFile)) { LOG.error("Missing META-INF/LICENSE in {}", jar); return false; } final String licenseFileContents = new String(Files.readAllBytes(licenseFile), StandardCharsets.UTF_8); if (!licenseFileContents.contains("Apache License") || !licenseFileContents.contains("Version 2.0, January 2004")) { LOG.error("The license file in {} does not contain the expected entries.", jar); return false; } return true; } private static int getNumLicenseFilesOutsideMetaInfDirectory(Path jar, Path jarRoot) throws IOException { try (Stream<Path> files = Files.walk(jarRoot)) { /* * LICENSE or NOTICE files found outside of the META-INF directory are most likely shading mistakes (we are including the files from other dependencies, thus providing an invalid LICENSE file) * * <p>In such a case, we recommend updating the shading exclusions, and adding the license file to META-INF/licenses. */ final List<String> filesWithIssues = files .filter(path -> !path.equals(jarRoot)) .filter(path -> getFileName(path).contains("license") || getFileName(path).contains("notice")) .filter(path -> !Files.isDirectory(path)) // ignore directories, e.g. "license/" .filter(path -> !getFileName(path).endsWith(".class")) // some class files contain LICENSE in their name .filter(path -> !getFileName(path).endsWith(".ftl")) // a false positive in flink-python .map(Path::toString) .filter(path -> !path.contains("META-INF")) // license files in META-INF are expected .filter(path -> !path.endsWith("web/3rdpartylicenses.txt")) // a false positive in flink-runtime-web .collect(Collectors.toList()); for (String fileWithIssue : filesWithIssues) { LOG.error("Jar file {} contains a LICENSE file in an unexpected location: {}", jar, fileWithIssue); } return filesWithIssues.size(); } } private static String getFileName(Path path) { return path.getFileName().toString().toLowerCase(); } }
36.987261
195
0.722921
92ed8dd93cea50d4152605da779c07550a183722
1,855
package ch.travbit.practice.ej.chapter2.item2; /** * This class represents a T-bone steak. It is a beef cut from the short loin and includes a "T"-shaped lumbar * vertebrae with sections of abdominal internal oblique muscle on each side. * * @see <a href="https://en.wikipedia.org/wiki/T-bone_steak">from wikipedia</a> */ public class tBone extends CutOfBeef { /** * The United States Department of Agriculture's Institutional Meat Purchase Specifications state that the * tenderloin of T-bone must be at least 13 mm thick. */ private final static int MIN_THICKNESS = 13; private final double tenderloinThicknessInMilliM; private tBone(Builder builder) { tenderloinThicknessInMilliM = builder.tenderloinThicknessInMilliM; } public double getTenderloinThicknessInMilliM() { return tenderloinThicknessInMilliM; } public static class Builder extends CutOfBeef.Builder<Builder> { // Optional parameter private double tenderloinThicknessInMilliM = MIN_THICKNESS; public Builder(int weightInGrams, double price) { super(weightInGrams, price); } /** * Checks that the thickness satisfies the requirements. */ public Builder tenderloinThicknessInMilliM(int tenderloinThicknessInMilliM) { if (tenderloinThicknessInMilliM >= MIN_THICKNESS) { this.tenderloinThicknessInMilliM = tenderloinThicknessInMilliM; } else { throw new IllegalArgumentException("The tenderloin must be at least " + MIN_THICKNESS + " mm thick"); } return self(); } @Override tBone build() { return new tBone(this); } @Override protected Builder self() { return this; } } }
31.440678
117
0.654447
3832802de83bafcdd782fd3f0817cbe80c694d5a
7,969
/******************************************************************************* * Copyright 2011-2013 Sergey Tarasevich * * 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 opensource.component.imageloader.core; import java.io.File; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executor; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import opensource.component.imageloader.cache.disc.DiscCacheAware; import opensource.component.imageloader.cache.disc.impl.FileCountLimitedDiscCache; import opensource.component.imageloader.cache.disc.impl.TotalSizeLimitedDiscCache; import opensource.component.imageloader.cache.disc.impl.UnlimitedDiscCache; import opensource.component.imageloader.cache.disc.naming.FileNameGenerator; import opensource.component.imageloader.cache.disc.naming.HashCodeFileNameGenerator; import opensource.component.imageloader.cache.memory.MemoryCacheAware; import opensource.component.imageloader.cache.memory.impl.LRULimitedMemoryCache; import opensource.component.imageloader.cache.memory.impl.LruMemoryCache; import opensource.component.imageloader.core.assist.QueueProcessingType; import opensource.component.imageloader.core.assist.deque.LIFOLinkedBlockingDeque; import opensource.component.imageloader.core.decode.BaseImageDecoder; import opensource.component.imageloader.core.decode.ImageDecoder; import opensource.component.imageloader.core.display.BitmapDisplayer; import opensource.component.imageloader.core.display.SimpleBitmapDisplayer; import opensource.component.imageloader.core.download.BaseImageDownloader; import opensource.component.imageloader.core.download.ImageDownloader; import opensource.component.imageloader.utils.StorageUtils; import android.content.Context; import android.graphics.Bitmap; import android.os.Build; import android.text.TextUtils; import com.opencdk.core.CDK; /** * Factory for providing of default options for {@linkplain ImageLoaderConfiguration configuration} * * @author Sergey Tarasevich (nostra13[at]gmail[dot]com) * @since 1.5.6 */ public class DefaultConfigurationFactory { /** Creates default implementation of task executor */ public static Executor createExecutor(int threadPoolSize, int threadPriority, QueueProcessingType tasksProcessingType) { boolean lifo = tasksProcessingType == QueueProcessingType.LIFO; BlockingQueue<Runnable> taskQueue = lifo ? new LIFOLinkedBlockingDeque<Runnable>() : new LinkedBlockingQueue<Runnable>(); return new ThreadPoolExecutor(threadPoolSize, threadPoolSize, 0L, TimeUnit.MILLISECONDS, taskQueue, createThreadFactory(threadPriority)); } /** Creates {@linkplain HashCodeFileNameGenerator default implementation} of FileNameGenerator */ public static FileNameGenerator createFileNameGenerator() { return new HashCodeFileNameGenerator(); } /** Creates default implementation of {@link DiscCacheAware} depends on incoming parameters */ public static DiscCacheAware createDiscCache2(Context context, FileNameGenerator discCacheFileNameGenerator, int discCacheSize, int discCacheFileCount) { if (discCacheSize > 0) { File individualCacheDir = StorageUtils.getIndividualCacheDirectory(context); return new TotalSizeLimitedDiscCache(individualCacheDir, discCacheFileNameGenerator, discCacheSize); } else if (discCacheFileCount > 0) { File individualCacheDir = StorageUtils.getIndividualCacheDirectory(context); return new FileCountLimitedDiscCache(individualCacheDir, discCacheFileNameGenerator, discCacheFileCount); } else { File cacheDir = StorageUtils.getCacheDirectory(context); return new UnlimitedDiscCache(cacheDir, discCacheFileNameGenerator); } } /** Creates default implementation of {@link DiscCacheAware} depends on incoming parameters */ public static DiscCacheAware createDiscCache(Context context, String baseDir, FileNameGenerator discCacheFileNameGenerator, int discCacheSize, int discCacheFileCount) { String directory = null; if (TextUtils.isEmpty(baseDir)) { // FIXME: Support a default directory. directory = baseDir; } else { directory = baseDir; } File cacheDir = new File(directory); return new UnlimitedDiscCache(cacheDir, discCacheFileNameGenerator); } /** Creates reserve disc cache which will be used if primary disc cache becomes unavailable */ public static DiscCacheAware createReserveDiscCache(File cacheDir) { File individualDir = new File(cacheDir, "uil-images"); if (individualDir.exists() || individualDir.mkdir()) { cacheDir = individualDir; } return new TotalSizeLimitedDiscCache(cacheDir, 2 * 1024 * 1024); // limit - 2 Mb } /** * Creates default implementation of {@link MemoryCacheAware} depends on incoming parameters: <br /> * {@link LruMemoryCache} (for API >= 9) or {@link LRULimitedMemoryCache} (for API < 9).<br /> * Default cache size = 1/8 of available app memory. */ public static MemoryCacheAware<String, Bitmap> createMemoryCache(int memoryCacheSize) { if (memoryCacheSize == 0) { memoryCacheSize = (int) (Runtime.getRuntime().maxMemory() / 8); } MemoryCacheAware<String, Bitmap> memoryCache; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { memoryCache = new LruMemoryCache(memoryCacheSize); } else { memoryCache = new LRULimitedMemoryCache(memoryCacheSize); } return memoryCache; } /** Creates default implementation of {@link ImageDownloader} - {@link BaseImageDownloader} */ public static ImageDownloader createImageDownloader(Context context) { return new BaseImageDownloader(context); } /** Creates default implementation of {@link ImageDecoder} - {@link BaseImageDecoder} */ public static ImageDecoder createImageDecoder(boolean loggingEnabled) { return new BaseImageDecoder(loggingEnabled); } /** Creates default implementation of {@link BitmapDisplayer} - {@link SimpleBitmapDisplayer} */ public static BitmapDisplayer createBitmapDisplayer() { return new SimpleBitmapDisplayer(); } /** Creates default {@link SaveImageOptions} */ public static SaveImageOptions createSaveImageOptions() { return new SaveImageOptions.Builder().build(); } /** Creates default implementation of {@linkplain ThreadFactory thread factory} for task executor */ private static ThreadFactory createThreadFactory(int threadPriority) { return new DefaultThreadFactory(threadPriority); } private static class DefaultThreadFactory implements ThreadFactory { private static final AtomicInteger poolNumber = new AtomicInteger(1); private final ThreadGroup group; private final AtomicInteger threadNumber = new AtomicInteger(1); private final String namePrefix; private final int threadPriority; DefaultThreadFactory(int threadPriority) { this.threadPriority = threadPriority; SecurityManager s = System.getSecurityManager(); group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); namePrefix = "uil-pool-" + poolNumber.getAndIncrement() + "-thread-"; } @Override public Thread newThread(Runnable r) { Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); if (t.isDaemon()) t.setDaemon(false); t.setPriority(threadPriority); return t; } } }
44.027624
169
0.77676
de00b547502545dbd34713d75a8b978847099735
92,615
/* * Copyright 1997-2019 Unidata Program Center/University Corporation for * Atmospheric Research, P.O. Box 3000, Boulder, CO 80307, * support@unidata.ucar.edu. * * 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 ucar.unidata.idv.ui; import ij.ImagePlus; import org.w3c.dom.Element; import ucar.unidata.data.GeoLocationInfo; import ucar.unidata.data.gis.KmlDataSource; import ucar.unidata.idv.IdvObjectStore; import ucar.unidata.idv.IntegratedDataViewer; import ucar.unidata.idv.MapViewManager; import ucar.unidata.idv.ViewManager; import ucar.unidata.idv.flythrough.Flythrough; import ucar.unidata.ui.AnimatedGifEncoder; import ucar.unidata.ui.ImagePanel; import ucar.unidata.ui.ImageUtils; import ucar.unidata.ui.JpegImagesToMovie; import ucar.unidata.util.FileManager; import ucar.unidata.util.GuiUtils; import ucar.unidata.util.IOUtil; import ucar.unidata.util.LogUtil; import ucar.unidata.util.Misc; import ucar.unidata.util.PatternFileFilter; import ucar.unidata.util.StringUtil; import ucar.unidata.xml.XmlUtil; import ucar.visad.display.Animation; import ucar.visad.display.AnimationWidget; import visad.DateTime; import visad.Real; import java.awt.AWTException; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.GraphicsConfiguration; import java.awt.Image; import java.awt.Insets; import java.awt.Point; import java.awt.Rectangle; import java.awt.Robot; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.text.DecimalFormat; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JSlider; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; /** * Class ImageSequenceGrabber. Manages the movie capture dialog, * capturing a series of jpegs from a ViewManager, writing them out * to disk, previewing them and generating quicktime movies. * * * @author IDV Development Team */ public class ImageSequenceGrabber implements Runnable, ActionListener { /** xml tag or attr name */ public static final String ATTR_ANIS_HEIGHT = "anis_height"; /** xml tag or attr name */ public static final String ATTR_ANIS_POSTHTML = "anis_posthtml"; /** xml tag or attr name */ public static final String ATTR_ANIS_PREHTML = "anis_prehtml"; /** xml tag or attr name */ public static final String ATTR_ANIS_TYPE = "anis_type"; /** xml tag or attr name */ public static final String ATTR_ANIS_WIDTH = "anis_width"; /** igml xml attributes */ public static final String ATTR_APPENDTIME = "appendtime"; /** igml xml attributes */ public static final String ATTR_FILENAME = "filename"; /** igml xml attributes */ public static final String ATTR_IMAGEDIR = "imagedir"; /** igml xml attributes */ public static final String ATTR_IMAGEPREFIX = "imageprefix"; /** igml xml attributes */ public static final String ATTR_IMAGESUFFIX = "imagesuffix"; /** xml tag or attr name */ public static final String ATTR_IMAGETEMPLATE = "imagetemplate"; /** xml tag or attr name */ public static final String ATTR_KML_DESC = "kml_desc"; /** xml tag or attr name */ public static final String ATTR_KML_NAME = "kml_name"; /** xml tag or attr name */ public static final String ATTR_KML_OPEN = "kml_open"; /** xml tag or attr name */ public static final String ATTR_KML_VISIBILITY = "kml_visibility"; /** igml xml attributes */ public static final String ATTR_STEPS = "steps"; /** the viewpoint file */ public static final String ATTR_VIEWPOINTFILE = "viewpointfile"; /** Action commands for gui buttons */ public static final String CMD_CLEAR = "clear"; /** Action commands for gui buttons */ public static final String CMD_GRAB = "grab"; /** Action commands for gui buttons */ public static final String CMD_GRAB_ANIMATION = "grab.animation"; /** Action commands for gui buttons */ public static final String CMD_PREVIEW_CLOSE = "preview.close"; /** Action commands for gui buttons */ public static final String CMD_PREVIEW_DELETE = "preview.delete"; /** Action commands for gui buttons */ public static final String CMD_PREVIEW_NEXT = "preview.next"; /** Action commands for gui buttons */ public static final String CMD_PREVIEW_PLAY = "preview.play"; /** Action commands for gui buttons */ public static final String CMD_PREVIEW_PREV = "preview.prev"; /** Action commands for gui buttons */ public static final String CMD_PREVIEW_SHOW = "preview.show"; /** Action commands for gui buttons */ public static final String CMD_PUBLISH = "publish"; /** Property for the image file template */ public static final String PROP_IMAGEALTDIR = "imagesequencegrabber.altdir"; /** Property for the image file template */ public static final String PROP_IMAGETEMPLATE = "imagesequencegrabber.template"; /** {@literal "Global"} GIF palette preference ID. */ public static final String PREF_USE_GLOBAL_PALETTE = "idv.capture.gif.useGlobalTable"; /** Tooltip text for global palette checkbox. */ public static final String GLOBAL_PALETTE_TOOLTIP = "<html>Turn off to correct colors for varying color animations.<br/>" + "<br/></br/>This option controls whether or not a resulting GIF " + "image will use a color palette<br/>taken from all the frames of the" + " animation.<br/><br/>If the option is turned off, the animation's " + "frames will use their own color palettes.<br/>This can result in " + "the same color value looking different between different frames" + "<br/>in the resulting animated GIF.</html>"; /** How much we pause between animation captures */ private static int SLEEP_TIME = 500; /** Filter for HTML files */ public static final PatternFileFilter FILTER_ANIS = new PatternFileFilter(".+\\.html|.+\\.htm", "AniS or FlAniS HTML File (*.html)", ".html"); /** xml tag or attr name */ public static final String TAG_DESCRIPTION = "description"; /** xml tag or attr name */ public static final String TAG_VISIBILITY = "visibility"; /** widget for saving html */ private static JCheckBox copyCbx; /** default */ private static String dfltAltDir; /** The default image file template */ private static String dfltTemplate; /** widget for saving html */ private static JTextField heightFld; /** widget for saving html */ private static JTextArea postFld; /** widget for saving html */ private static JTextArea preFld; /** widget for switching between AniS and FlAniS */ private static JCheckBox typeCbx; /** widget for saving html */ private static JTextField widthFld; /** Used for synchronization_ */ private Object MUTEX = new Object(); /** * A virtual timestamp to keep us form having two animation captures running at the same time. */ private int captureTimeStamp = 0; /** * A flag that tells us when we are automatically capturing the animation timesteps */ private boolean capturingAnim = false; /** * A flag that tells us when we are doing the automatic capture. */ private boolean capturingAuto = false; /** annoying beep checkbox */ private JCheckBox beepCbx = new JCheckBox("Beep", false); /** How many images have been captured */ int imageCnt = 0; /** Index in the list of images we are currently showing as a preview */ int previewIndex = 0; /** image quality */ private float quality = 1.0f; /** Has the user paused the previews */ boolean paused = false; /** Flag to see when we are playing a preview */ private boolean isPlaying = false; /** List of earth locations corresponding to each image */ List<ImageWrapper> images = new ArrayList<ImageWrapper>(); /** Used for managing the current preview thread */ private int timestamp = 0; /** Have we told the user about constraints of writing transparent images */ boolean notifiedForTransparent = false; /** flag for just capturing the images */ private boolean justCaptureAnimation = false; /** capture flythrough */ private JCheckBox grabFlythroughCbx = new JCheckBox("Capture Flythrough", false); /** widget */ JCheckBox animationResetCbx = new JCheckBox("Reset to start time", true); /** Components to enable/disable */ private List alternateComps = new ArrayList(); /** write positions */ private boolean writePositions = false; /** Capture all views */ JRadioButton allViewsBtn; /** If non null then we capture from this */ private JComponent alternateComponent; /** Should use alternate dir */ private JCheckBox alternateDirCbx; /** Holds the directory */ private JTextField alternateDirFld; /** Is the background of the image transparent_ */ JCheckBox backgroundTransparentBtn; /** Specifies the capture rate */ JTextField captureRateFld; /** Clear all captured frames */ JButton clearButton; /** Close the window */ JButton closeButton; /** Capture the contents */ JRadioButton contentsBtn; /** Write out the movie */ JButton createButton; /** Button to delete a frame */ JButton deleteFrameButton; /** The directory we write to */ String directory; /** Specifies the display rate in the generated movie */ JTextField displayRateFld; /** Specifies the display rate in the generated movie */ JTextField endPauseFld; /** Holds the file prefix */ private JTextField fileTemplateFld; /** Shows how many frames have been captured */ JLabel frameLbl; /** fullscreen mode */ JRadioButton fullScreenBtn; /** Capture full window */ JRadioButton fullWindowBtn; /** Turns on animation based capture */ JButton grabAnimationBtn; /** Turns on automatic capture */ JButton grabAutoBtn; /** Captures one frame */ JButton grabBtn; /** radio button for high image quality */ private JRadioButton hiBtn; /** The IDV */ private IntegratedDataViewer idv; /** The igml */ private ImageGenerator imageGenerator; /** imagesize */ Dimension imageSize; /** File path of the last previewed image */ String lastPreview; /** radio button for low image quality */ private JRadioButton lowBtn; /** The window for the main gui */ JDialog mainDialog; /** Capture the main display */ JRadioButton mainDisplayBtn; /** radio button for medium image quality */ private JRadioButton medBtn; /** If non-null then we use this and don't ask the user. */ private String movieFileName; /** Button to step forward one frame */ JButton nextButton; /** overwrite */ private JCheckBox overwriteCbx; /** Button to play preview */ JButton playButton; /** Image icon for playing */ private ImageIcon playIcon; /** Button to step back one frame */ JButton prevButton; /** Button to show the preview window */ JButton previewButton; /** The window for the previews */ JDialog previewDialog; /** The label for showing previews */ JLabel previewLbl; /** Where we show the preview */ // JLabel previewImage; ImagePanel previewPanel; /** preview rate field */ JTextField previewRateFld; /** publish checkbox */ private JComboBox publishCbx; /** The igml movie node. May be null */ private Element scriptingNode; /** Image icon for stopping */ private ImageIcon stopIcon; /** * The {@ref ViewManager} we are capturing. */ private ViewManager viewManager; /** * Create me with the given {@link ucar.unidata.idv.ViewManager} * * @param viewManager The view manager we are capturing images from * */ public ImageSequenceGrabber(ViewManager viewManager) { this(viewManager, null); } /** * Create me with the given {@link ucar.unidata.idv.ViewManager} * * @param viewManager The view manager we are capturing images from * @param alternateComponent If non null then use this component as * the source of the image * */ public ImageSequenceGrabber(ViewManager viewManager, JComponent alternateComponent) { this(viewManager, alternateComponent, false); } /** * Create a new ImageSequenceGrabber * * @param viewManager associated ViewManager * @param alternateComponent alternate component * @param justCaptureAnimation true to just capture the animation */ public ImageSequenceGrabber(ViewManager viewManager, JComponent alternateComponent, boolean justCaptureAnimation) { this.alternateComponent = alternateComponent; this.viewManager = viewManager; this.idv = viewManager.getIdv(); this.justCaptureAnimation = justCaptureAnimation; init(); if (this.justCaptureAnimation) { startAnimationCapture(); } } /** * This gets called when we automatically create a movie. It will not show the * dialog window and will start up the animation capture * * @param viewManager The view manager we are capturing images from * @param filename The file we are writing to * @param idv The IDV */ public ImageSequenceGrabber(ViewManager viewManager, String filename, IntegratedDataViewer idv) { this(viewManager, filename, idv, null, null); } /** * This gets called when we automatically create a movie. It will not show the * dialog window and will start up the animation capture * * @param viewManager The view manager we are capturing images from * @param filename The file we are writing to * @param idv The IDV * @param scriptingNode The igml node * @param imageGenerator imageGenerator */ public ImageSequenceGrabber(ViewManager viewManager, String filename, IntegratedDataViewer idv, ImageGenerator imageGenerator, Element scriptingNode) { this.viewManager = viewManager; this.imageGenerator = imageGenerator; this.scriptingNode = scriptingNode; movieFileName = filename; if (scriptingNode != null) { movieFileName = imageGenerator.applyMacros(scriptingNode, ATTR_FILENAME, movieFileName); } this.idv = idv; init(); startAnimationCapture(); } /** * This gets called when we automatically create a movie. It will not show the * dialog window and will start up the animation capture * * @param filename The file we are writing to * @param idv The IDV * @param scriptingNode The igml node * @param imageGenerator imageGenerator * @param imageFiles List of files to write * @param size Size of image * @param displayRate Display rate */ public ImageSequenceGrabber(String filename, IntegratedDataViewer idv, ImageGenerator imageGenerator, Element scriptingNode, List<ImageWrapper> imageFiles, Dimension size, double displayRate) { this(filename, idv, imageGenerator, scriptingNode, imageFiles, size, displayRate, -1); } /** * This gets called when we automatically create a movie. It will not show the * dialog window and will start up the animation capture * * @param filename The file we are writing to * @param idv The IDV * @param scriptingNode The igml node * @param imageGenerator imageGenerator * @param imageFiles List of files to write * @param size Size of image * @param displayRate Display rate * @param endPause end pause (seconds) */ public ImageSequenceGrabber(String filename, IntegratedDataViewer idv, ImageGenerator imageGenerator, Element scriptingNode, List<ImageWrapper> imageFiles, Dimension size, double displayRate, double endPause) { this.idv = idv; this.imageGenerator = imageGenerator; this.scriptingNode = scriptingNode; this.images = ImageWrapper.makeImageWrappers(imageFiles); this.idv = idv; movieFileName = filename; createMovie(movieFileName, images, size, displayRate, scriptingNode, endPause); } /** * Show the main window */ public void show() { mainDialog.setVisible(true); } /** * Utility to make a button * * @param icon The button icon * @param cmd The action command * @param tooltip The tooltip * @return The button */ private JButton makeButton(ImageIcon icon, String cmd, String tooltip) { JButton b = GuiUtils.getImageButton(icon); b.setActionCommand(cmd); b.addActionListener(this); b.setToolTipText(tooltip); return b; } /** * Utility to make a button * * @param label The button label * @param cmd The action command * @return The button */ private JButton makeButton(String label, String cmd) { JButton b = new JButton(label); b.setActionCommand(cmd); b.addActionListener(this); return b; } /** * Add the component to the list of components for the alternate dir stuff. * * @param comp The component * * @return The component */ private JComponent addAltComp(JComponent comp) { alternateComps.add(comp); GuiUtils.enableTree(comp, false); return comp; } /** * Get the animation widget * * @return the animation widget */ private AnimationWidget getAnimationWidget() { if ((grabFlythroughCbx != null) && grabFlythroughCbx.isSelected() && (viewManager instanceof MapViewManager)) { Flythrough flythrough = ((MapViewManager) viewManager).getFlythrough(); if (flythrough != null) { return flythrough.getAnimationWidget(); } } AnimationWidget animationWidget = viewManager.getAnimationWidget(); if (animationWidget == null) { animationWidget = viewManager.getExternalAnimationWidget(); } return animationWidget; } /** * Get the Animation * * @return the Animation */ private Animation getAnimation() { if ((grabFlythroughCbx != null) && grabFlythroughCbx.isSelected() && (viewManager instanceof MapViewManager)) { Flythrough flythrough = ((MapViewManager) viewManager).getFlythrough(); if (flythrough != null) { return flythrough.getAnimation(); } } Animation anime = viewManager.getAnimation(); if (anime == null) { anime = viewManager.getExternalAnimation(); } return anime; } /** * Initialize me. Create the windows, etc. */ private void init() { // Store the images in a unique (by current time) subdir of the user's tmp dir directory = IOUtil.joinDir(viewManager.getStore().getUserTmpDirectory(), "images_" + System.currentTimeMillis()); // Make sure the dir exists IOUtil.makeDir(directory); mainDialog = GuiUtils.createDialog("Movie Capture", false); frameLbl = GuiUtils.cLabel("No frames"); displayRateFld = new JTextField("2", 3); endPauseFld = new JTextField("2", 3); endPauseFld.setToolTipText( "Number of seconds to pause on last frame of animated GIF"); captureRateFld = new JTextField("2", 3); String imgp = "/auxdata/ui/icons/"; mainDisplayBtn = new JRadioButton("Current View", true); allViewsBtn = new JRadioButton("All Views", false); contentsBtn = new JRadioButton("Current View & Legend", false); fullWindowBtn = new JRadioButton("Full Window", false); fullScreenBtn = new JRadioButton("Full Screen", false); ButtonGroup bg = GuiUtils.buttonGroup(mainDisplayBtn, fullWindowBtn); bg.add(allViewsBtn); bg.add(contentsBtn); bg.add(fullScreenBtn); beepCbx.setToolTipText("Beep when an image is captured"); List btns = Misc.newList(new Object[] { new JLabel("What to capture:"), mainDisplayBtn, allViewsBtn, contentsBtn, fullWindowBtn, fullScreenBtn }); btns.add(beepCbx); JComponent whatPanel = GuiUtils.vbox(btns); if (dfltAltDir == null) { dfltAltDir = idv.getStore().get(PROP_IMAGEALTDIR, ""); } alternateDirFld = new JTextField(dfltAltDir, 30); JButton alternateDirBtn = new JButton("Select"); GuiUtils.setupDirectoryChooser(alternateDirBtn, alternateDirFld); if (dfltTemplate == null) { dfltTemplate = idv.getStore().get(PROP_IMAGETEMPLATE, "image_%count%_%time%"); } fileTemplateFld = new JTextField(dfltTemplate, 30); fileTemplateFld.setToolTipText( "<html>Enter the file name template to use.<br>" + "<b>%count%</b> is the image counter<br>" + "<b>%count:decimal format%</b> allows you to format the count. Google 'java decimalformat' for more information.<br>" + "<b>%time%</b> is the animation time in the default format<br>" + "<b>%time:some time format string%</b> a macro that begins with &quot;time:&quot;,contains a time format string using the:<br>" + "java SimpleDateFormat formatting (see google)." + "</html>"); overwriteCbx = new JCheckBox("Overwrite", false); alternateDirCbx = new JCheckBox("Save Files To:", false); alternateDirCbx.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { for (int i = 0; i < alternateComps.size(); i++) { GuiUtils.enableTree((JComponent) alternateComps.get(i), alternateDirCbx.isSelected()); } } }); hiBtn = new JRadioButton("High", true); medBtn = new JRadioButton("Better", false); lowBtn = new JRadioButton("Low", false); GuiUtils.buttonGroup(hiBtn, medBtn).add(lowBtn); grabBtn = makeButton("One Image", CMD_GRAB); grabAutoBtn = makeButton("Automatically", GuiUtils.CMD_START); grabAnimationBtn = makeButton("Time Animation", CMD_GRAB_ANIMATION); grabFlythroughCbx = new JCheckBox("Flythrough", false); boolean hasFlythrough = false; if ((viewManager instanceof MapViewManager) && ((MapViewManager) viewManager).getFlythrough() != null) { hasFlythrough = ((MapViewManager) viewManager).getFlythrough().hasPoints(); } List frameButtons = new ArrayList(); frameButtons.add(previewButton = makeButton("Preview", CMD_PREVIEW_SHOW)); frameButtons.add(clearButton = makeButton("Delete All", CMD_CLEAR)); frameButtons.add(createButton = makeButton("Save Movie", GuiUtils.CMD_OK)); JComponent publishButton; if (idv.getPublishManager().isPublishingEnabled()) { // frameButtons.add(publishButton = makeButton("Publish Movie", // CMD_PUBLISH)); } else { // publishButton = new JPanel(); } closeButton = makeButton("Close", GuiUtils.CMD_CLOSE); JLabel titleLbl = GuiUtils.cLabel( "Note: Make sure the view window is not obscured"); JPanel titlePanel = GuiUtils.inset(titleLbl, 8); JPanel runPanel = GuiUtils.hflow(Misc.newList(GuiUtils.rLabel(" Rate: "), captureRateFld, new JLabel(" seconds"))); int maxBtnWidth = Math.max(grabAnimationBtn.getPreferredSize().width, Math.max(grabBtn.getPreferredSize().width, grabAutoBtn.getPreferredSize().width)); GuiUtils.tmpInsets = new Insets(5, 5, 5, 5); JPanel capturePanel = GuiUtils.doLayout(new Component[] { grabBtn, GuiUtils.filler(), GuiUtils.top(grabAnimationBtn), GuiUtils.vbox(animationResetCbx, (hasFlythrough ? (JComponent) grabFlythroughCbx : GuiUtils.filler())), grabAutoBtn, runPanel, GuiUtils.filler(maxBtnWidth + 10, 1), GuiUtils.filler(), }, 2, GuiUtils.WT_N, GuiUtils.WT_N); backgroundTransparentBtn = new JCheckBox("Background Transparent"); backgroundTransparentBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { if (backgroundTransparentBtn.isSelected() && !notifiedForTransparent) { LogUtil.userMessage( "Note: Only KMZ files can be saved with background transparency on"); } notifiedForTransparent = true; } }); capturePanel = GuiUtils.hbox( GuiUtils.top(capturePanel), GuiUtils.top( GuiUtils.inset( GuiUtils.vbox(whatPanel, backgroundTransparentBtn), new Insets(0, 10, 0, 0)))); capturePanel = GuiUtils.inset(GuiUtils.left(capturePanel), 5); capturePanel.setBorder(BorderFactory.createTitledBorder("Capture")); GuiUtils.setHFill(); JPanel filePanel = GuiUtils.doLayout(null, new Component[] { GuiUtils.rLabel("Image Quality:"), GuiUtils.left(GuiUtils.hbox(hiBtn, medBtn, lowBtn)), GuiUtils.filler(), GuiUtils.right(alternateDirCbx), // GuiUtils.filler(), // GuiUtils.filler(), // addAltComp(GuiUtils.rLabel("Directory:")), addAltComp(alternateDirFld), addAltComp(alternateDirBtn), addAltComp(GuiUtils.rLabel("Filename Template:")), addAltComp(fileTemplateFld), addAltComp(overwriteCbx) }, 3, GuiUtils.WT_NYN, GuiUtils.WT_N, null, null, new Insets(0, 5, 0, 0)); filePanel = GuiUtils.inset(filePanel, 5); filePanel.setBorder(BorderFactory.createTitledBorder("Image Files")); JPanel framesPanel = GuiUtils.vbox(GuiUtils.left(frameLbl), GuiUtils.hflow(frameButtons, 4, 0)); framesPanel = GuiUtils.inset(framesPanel, 5); framesPanel.setBorder(BorderFactory.createTitledBorder("Frames")); JPanel contents = GuiUtils.vbox(capturePanel, filePanel, framesPanel); contents = GuiUtils.inset(contents, 5); mainDialog.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { close(); } }); contents = GuiUtils.topCenter(titlePanel, contents); imagesChanged(); checkEnabled(); // Only show the window if init filename is null if ( !justCaptureAnimation && (movieFileName == null) && (scriptingNode == null)) { GuiUtils.packDialog(mainDialog, GuiUtils.centerBottom(contents, GuiUtils.wrap(GuiUtils.inset(closeButton, 4)))); mainDialog.setVisible(true); } } /** * Return the value of the {@literal "idv.capture.gif.useGlobalTable"} * preference. * * <p>Note: if the preference is not set, the value will default to * {@code true}.</p> * * @return Value of {@code idv.capture.gif.useGlobalTable}. */ private boolean getGlobalPaletteValue() { IdvObjectStore store = idv.getStore(); return store.get(PREF_USE_GLOBAL_PALETTE, true); } /** * Load in the current preview image into the gui */ private void setPreviewImage() { // if (previewImage == null) { if (previewPanel == null) { return; } synchronized (MUTEX) { if (previewIndex >= images.size()) { previewIndex = images.size() - 1; } if (previewIndex < 0) { previewIndex = 0; } boolean haveImages = images.size() > 0; prevButton.setEnabled(haveImages); nextButton.setEnabled(haveImages); playButton.setEnabled(haveImages); deleteFrameButton.setEnabled(haveImages); if (haveImages) { String current = images.get(previewIndex).getPath(); if ( !Misc.equals(current, lastPreview)) { previewPanel.loadFile(current); /* * Image image = * Toolkit.getDefaultToolkit().createImage(current); * previewPanel.setImage(image); */ /* * ImageIcon icon = new ImageIcon(image); * previewImage.setIcon(icon); * previewImage.setText(null); */ lastPreview = current; } previewLbl.setText(" Frame: " + (previewIndex + 1) + "/" + images.size()); } else { previewLbl.setText(" No images "); previewPanel.setImage(null); /* * previewLbl.setText(" Frame: "); * previewImage.setText(" No images "); * previewImage.setIcon(null); */ lastPreview = null; } } } /** * Show the preview window */ private void showPreview() { if (previewDialog == null) { previewDialog = new JDialog(mainDialog, "Movie Preview", false); String imgp = "/auxdata/ui/icons/"; playIcon = GuiUtils.getImageIcon(imgp + "Play16.gif"); stopIcon = GuiUtils.getImageIcon(imgp + "Stop16.gif"); previewRateFld = new JTextField("1", 3); ChangeListener rateListener = new ChangeListener() { public void stateChanged(ChangeEvent e) { JSlider slide = (JSlider) e.getSource(); if (slide.getValueIsAdjusting()) { // return; } double value = slide.getValue() / 4.0; previewRateFld.setText("" + value); } }; JComponent[] comps = GuiUtils.makeSliderPopup(1, 20, 4, rateListener); JComponent sliderBtn = comps[0]; playButton = makeButton(playIcon, CMD_PREVIEW_PLAY, "Play/Stop"); nextButton = makeButton(GuiUtils.getImageIcon(imgp + "StepForward16.gif"), CMD_PREVIEW_NEXT, "Go to next frame"); prevButton = makeButton(GuiUtils.getImageIcon(imgp + "StepBack16.gif"), CMD_PREVIEW_PREV, "Go to previous frame"); deleteFrameButton = makeButton("Delete this frame", CMD_PREVIEW_DELETE); List buttonList = Misc.newList(prevButton, playButton, nextButton); buttonList.add(GuiUtils.filler(20, 5)); buttonList.add(new JLabel(" Delay: ")); buttonList.add(previewRateFld); buttonList.add(new JLabel("(s) ")); buttonList.add(sliderBtn); JPanel buttons = GuiUtils.hflow(buttonList); buttons = GuiUtils.inset(buttons, 5); previewLbl = new JLabel(" "); // previewImage = new JLabel(); previewPanel = new ImagePanel(); previewPanel.setPreferredSize(new Dimension(640, 480)); lastPreview = null; previewIndex = 0; setPreviewImage(); // previewImage.setBorder(BorderFactory.createEtchedBorder()); previewPanel.setBorder(BorderFactory.createEtchedBorder()); JComponent topComp = GuiUtils.leftRight(buttons, GuiUtils.hbox(deleteFrameButton, previewLbl)); JPanel contents = GuiUtils.topCenterBottom(topComp, previewPanel, GuiUtils.wrap(makeButton("Close", CMD_PREVIEW_CLOSE))); GuiUtils.packDialog(previewDialog, contents); } previewDialog.setVisible(true); } /** * Enable/disable buttons as needed */ private void checkEnabled() { // if (capturingAuto || capturingAnim) { // grabAutoBtn.setIcon (stopIcon); // } // else { // grabAutoBtn.setIcon (startIcon); // } grabAnimationBtn.setEnabled( !capturingAuto); grabBtn.setEnabled( !capturingAuto && !capturingAnim); } /** * Turn on automatic capture */ private void startCapturingAuto() { grabAutoBtn.setText("Stop"); if (capturingAuto) { return; } capturingAuto = true; Misc.run(this); checkEnabled(); } /** * Turn off automatic capture */ private void stopCapturingAuto() { grabAutoBtn.setText("Automatically"); if ( !capturingAuto) { return; } capturingAuto = false; checkEnabled(); } /** * Turn on animation based capture */ private void startAnimationCapture() { if (capturingAnim || (getAnimation() == null)) { return; } grabAnimationBtn.setText("Stop animation"); capturingAnim = true; checkEnabled(); // Run the imageGrab in another thread because visad errors when the getImage // is called from the awt event thread // runAnimationCapture(++captureTimeStamp); Misc.run(new Runnable() { public void run() { Misc.sleep(2000); runAnimationCapture(++captureTimeStamp); } }); } /** * Should we keep running * * @param timestamp The virtual timestamp we started the run with * * @return keep running */ private boolean keepRunning(int timestamp) { if ( !capturingAnim || (timestamp != captureTimeStamp)) { return false; } return true; } /** * Actually step through each timestep. We use the timestamp argument to determine * if the user hit Stop/Start in quick succession. THis prevents us from having two threads * active at once. * * @param timestamp Used to know which thread should be running */ private void runAnimationCapture(int timestamp) { try { getAnimation().setAnimating(false); if ((animationResetCbx != null) && animationResetCbx.isSelected()) { getAnimationWidget().gotoBeginning(); } int sleepTime = idv.getStateManager().getProperty("idv.capture.sleep", SLEEP_TIME); if ((scriptingNode != null) && XmlUtil.hasAttribute(scriptingNode, ATTR_STEPS)) { String stepsString = imageGenerator.applyMacros(scriptingNode, ATTR_STEPS); int[] steps = Misc.parseInts(stepsString, ","); for (int i = 0; i < steps.length; i++) { if (steps[i] > getAnimation().getNumSteps()) { break; } getAnimation().setCurrent(steps[i]); // Sleep for a bit to allow for the display to redraw itself try { Misc.sleep(sleepTime); } catch (Exception exc) {} // Has the user pressed Stop? if ( !keepRunning(timestamp)) { break; } // Now grab the image in block mode grabImageAndBlock(); } } else if ((scriptingNode != null) && (viewManager != null) && XmlUtil.hasAttribute(scriptingNode, ATTR_VIEWPOINTFILE)) { String viewpointFile = imageGenerator.applyMacros(scriptingNode, ATTR_VIEWPOINTFILE); List viewpoints = (List) idv.decodeObject( IOUtil.readContents( viewpointFile, getClass())); for (int i = 0; i < viewpoints.size(); i++) { double[] matrix = (double[]) viewpoints.get(i); viewManager.setDisplayMatrix(matrix); // Sleep for a bit to allow for the display to redraw itself try { Misc.sleep(sleepTime); } catch (Exception exc) {} // Has the user pressed Stop? if ( !keepRunning(timestamp)) { break; } // Now grab the image in block mode grabImageAndBlock(); } } else { ///if(animationResetCbx.isSelected()) // getAnimationWidget().gotoBeginning(); int start = getAnimation().getCurrent(); while (true) { // Sleep for a bit to allow for the display to redraw itself try { Misc.sleep(sleepTime); } catch (Exception exc) {} // Has the user pressed Stop? if ((getAnimation() == null) || !keepRunning(timestamp)) { break; } // Now grab the image in block mode grabImageAndBlock(); if (getAnimation() == null) { break; } getAnimationWidget().stepForward(); int current = getAnimation().getCurrent(); if (current <= start) { break; } } } if ( !keepRunning(timestamp)) { return; } stopAnimationCapture(true); } catch (Exception exc) { LogUtil.logException("Creating movie", exc); } } /** * Turn off animation based capture * * @param andWrite write movie */ private void stopAnimationCapture(boolean andWrite) { if (viewManager != null) { viewManager.useImages(ImageWrapper.makeFileList(images), justCaptureAnimation); if (justCaptureAnimation) { return; } } capturingAnim = false; if (andWrite) { writeMovie(); } // This implies we write the animation and then are done if (imageGenerator != null) { // close(); imageGenerator.doneCapturingMovie(); // return; } grabAnimationBtn.setText("Time Animation"); checkEnabled(); } /** * Get the image quality * * @return the image quality */ private float getImageQuality() { float quality = 1.0f; if (medBtn.isSelected()) { quality = 0.6f; } else if (lowBtn.isSelected()) { quality = 0.2f; } return quality; } /** * Stop playing preview */ private void previewStopPlaying() { isPlaying = false; playButton.setIcon(playIcon); } /** * Start playing preview. This calls {@see #previewStartPlaying(int)} * in a thread. */ private void previewStartPlaying() { isPlaying = true; playButton.setIcon(stopIcon); Misc.run(new Runnable() { public void run() { previewStartPlaying(++timestamp); } }); } /** * Start playing preview. Called from a thread * * @param ts The timestamp for thread management */ private void previewStartPlaying(int ts) { while (isPlaying && (ts == timestamp) && (images.size() > 0)) { previewNext(); try { double sleepTime = 1; try { sleepTime = new Double( previewRateFld.getText().trim()).doubleValue(); } catch (Exception noop) {} Misc.sleep((long) (sleepTime * 1000)); } catch (Exception exc) {} if (previewIndex >= images.size() - 1) { isPlaying = false; } } if ( !isPlaying) { previewStopPlaying(); } } /** * GO to the next frame in the previews */ private void previewNext() { previewIndex++; if (previewIndex >= images.size()) { previewIndex = 0; } setPreviewImage(); } /** * Handle gui actions * * @param ae The <code>ActionEvent</code> */ public void actionPerformed(ActionEvent ae) { String cmd = ae.getActionCommand(); if (cmd.equals(GuiUtils.CMD_START)) { if ( !capturingAuto) { startCapturingAuto(); } else { stopCapturingAuto(); } } else if (cmd.equals(CMD_CLEAR)) { capturingAuto = false; deleteFiles(); imagesChanged(); checkEnabled(); } else if (cmd.equals(CMD_PREVIEW_PLAY)) { if (isPlaying) { previewStopPlaying(); } else { previewStartPlaying(); } } else if (cmd.equals(CMD_PREVIEW_SHOW)) { showPreview(); } else if (cmd.equals(CMD_PREVIEW_CLOSE)) { if (previewDialog != null) { previewDialog.setVisible(false); } } else if (cmd.equals(CMD_PREVIEW_NEXT)) { previewNext(); } else if (cmd.equals(CMD_PREVIEW_PREV)) { previewIndex--; if (previewIndex < 0) { previewIndex = images.size() - 1; } setPreviewImage(); } else if (cmd.equals(CMD_PREVIEW_DELETE)) { if ((images.size() > 0) && (previewIndex >= 0) && (previewIndex < images.size())) { String filename = images.get(previewIndex).getPath(); images.remove(previewIndex); previewIndex--; imagesChanged(); new File(filename).delete(); } } else if (cmd.equals(CMD_GRAB_ANIMATION)) { synchronized (MUTEX) { if (capturingAnim) { stopAnimationCapture(false); } else { startAnimationCapture(); } } } else if (cmd.equals(CMD_GRAB)) { // Run the imageGrab in another thread because visad errors when the getImage // is called from the awt event thread Misc.run(new Runnable() { public void run() { grabImageAndBlock(); } }); } else if (cmd.equals(GuiUtils.CMD_CLOSE)) { close(); } else if (cmd.equals(CMD_PUBLISH)) { publishMovie(); } else if (cmd.equals(GuiUtils.CMD_OK)) { writeMovie(); } } /** * Is this being run interactively * * @return is interactive */ private boolean isInteractive() { return scriptingNode == null; } /** * Write out the movie */ private void writeMovie() { stopCapturingAuto(); String filename = null; if (isInteractive() && (movieFileName == null)) { JCheckBox writePositionsCbx = new JCheckBox("Save viewpoints", writePositions); writePositionsCbx.setToolTipText( "Also save the viewpoint matrices as an 'xidv' file"); JCheckBox otherGlobalPaletteBox = new JCheckBox("Use constant color palette for GIF", getGlobalPaletteValue()); otherGlobalPaletteBox.setToolTipText(GLOBAL_PALETTE_TOOLTIP); otherGlobalPaletteBox.addActionListener(e -> { boolean value = otherGlobalPaletteBox.isSelected(); IdvObjectStore store = idv.getStore(); store.put(PREF_USE_GLOBAL_PALETTE, value); store.save(); }); List<JComponent> accessoryComps = new ArrayList<>(10); accessoryComps.add( GuiUtils.leftRight( GuiUtils.rLabel(" Frames per second: "), displayRateFld)); accessoryComps.add( GuiUtils.leftRight( GuiUtils.rLabel(" End Frame Pause: "), endPauseFld)); accessoryComps.add(writePositionsCbx); accessoryComps.add(otherGlobalPaletteBox); if (publishCbx == null) { publishCbx = idv.getPublishManager().makeSelector(); } if (publishCbx != null) { accessoryComps.add(publishCbx); } JComponent extra = GuiUtils.topCenter(GuiUtils.vbox(accessoryComps), GuiUtils.filler()); filename = FileManager.getWriteFile(Misc.newList(FileManager.FILTER_MOV, FileManager.FILTER_AVI, FileManager.FILTER_ANIMATEDGIF, FileManager.FILTER_ZIP, FileManager.FILTER_KMZ, FILTER_ANIS), FileManager.SUFFIX_MOV, extra); writePositions = writePositionsCbx.isSelected(); } else { filename = movieFileName; } if (filename != null) { // if ( !filename.toLowerCase().endsWith(".mov")) { // filename = filename + ".mov"; // } createMovie(filename); } } /** * Used by the pubishing facility to publish movides to some external site */ private void publishMovie() { stopCapturingAuto(); String uid = Misc.getUniqueId(); String tail = uid + FileManager.SUFFIX_MOV; String file = idv.getStore().getTmpFile(tail); createMovie(file); idv.getPublishManager().doPublish("Publish Quicktime file", file); } /** * Close the window */ private void close() { captureTimeStamp++; capturingAuto = false; if (previewDialog != null) { previewDialog.dispose(); previewDialog = null; } viewManager.clearImageGrabber(this); mainDialog.dispose(); try { if ( !alternateDirCbx.isSelected()) { deleteFiles(); (new File(directory)).delete(); } } catch (Exception exc) { LogUtil.logException("Disposing of tmp directory", exc); } } /** * Get rid of generated files */ private void deleteFiles() { for (int i = 0; i < images.size(); i++) { images.get(i).deleteFile(); } images = new ArrayList<ImageWrapper>(); if (viewManager != null) { // TODO: viewManager.useImages(ImageWrapper.makeFileList(images), justCaptureAnimation); } } /** * Run in a thread. */ public void run() { capturingAuto = true; while (capturingAuto) { grabImageAndBlock(); if ( !capturingAuto) { return; } double captureRate = 2.0; try { captureRate = (new Double( captureRateFld.getText().trim())).doubleValue(); } catch (NumberFormatException nfe) { stopCapturingAuto(); LogUtil.userErrorMessage( "Bad number format for capture rate: " + captureRateFld.getText()); return; } Misc.sleep((long) (captureRate * 1000)); } } /** * What file suffix should we use for the images. For now better by jpg * * @return File suffix */ protected String getFileSuffix() { if (justCaptureAnimation) { return FileManager.SUFFIX_PNG; } String defSuffix = FileManager.SUFFIX_JPG; if ((scriptingNode != null) && (movieFileName != null)) { final String suffix = IOUtil.getFileExtension(movieFileName); if (suffix != null) { if (suffix.equalsIgnoreCase(FileManager.SUFFIX_KMZ) || suffix.equalsIgnoreCase(FileManager.SUFFIX_ZIP) || suffix.equalsIgnoreCase(FileManager.SUFFIX_KML)) { defSuffix = FileManager.SUFFIX_PNG; } else if (suffix.equalsIgnoreCase(FileManager.SUFFIX_MOV)) { defSuffix = FileManager.SUFFIX_JPG; } // TODO: GIF, AVI? } defSuffix = imageGenerator.applyMacros(scriptingNode, ATTR_IMAGESUFFIX, defSuffix); if ( !defSuffix.startsWith(".")) { defSuffix = "." + defSuffix; } } if ((backgroundTransparentBtn != null) && backgroundTransparentBtn.isSelected()) { defSuffix = FileManager.SUFFIX_PNG; } return defSuffix; } /** * Get the file prefix to use * * * @param cnt image count * @return File prefix */ private String getFilePrefix(int cnt) { String filename = ""; String template = "image_%count%_%time%"; boolean usingDefault = true; if (scriptingNode != null) { if ( !XmlUtil.hasAttribute(scriptingNode, ATTR_IMAGEPREFIX)) { template = imageGenerator.applyMacros(scriptingNode, ATTR_IMAGETEMPLATE, template); } else { template = imageGenerator.applyMacros(scriptingNode, ATTR_IMAGEPREFIX, "image"); template = template + "_%count%"; if (imageGenerator.applyMacros(scriptingNode, ATTR_APPENDTIME, false)) { template = template + "_%time%"; usingDefault = false; } } } else { if (alternateDirCbx.isSelected()) { template = fileTemplateFld.getText().trim(); if ( !template.equals(dfltTemplate)) { dfltTemplate = template; idv.getStore().put(PROP_IMAGETEMPLATE, dfltTemplate); idv.getStore().save(); usingDefault = false; } } } while (true) { String formatString = StringUtil.findFormatString("count", "%", template); if (formatString == null) { break; } System.err.println(formatString); DecimalFormat format = new DecimalFormat(formatString); String formattedValue = format.format(cnt); String tmp = StringUtil.replace(template, "%count:" + formatString + "%", formattedValue); if (tmp.equals(template)) { throw new IllegalStateException("Bad formatting:" + tmp); } template = tmp; } template = StringUtil.replace(template, "%count%", "" + cnt); try { Real r = getAnimation().getAniValue(); if (r != null) { DateTime dttm = new DateTime(r); String timeString = "" + dttm; timeString = StringUtil.replace(timeString, ":", "_"); timeString = StringUtil.replace(timeString, "-", "_"); timeString = StringUtil.replace(timeString, " ", "_"); template = StringUtil.replace(template, "%time%", timeString); template = ucar.visad.UtcDate.applyTimeMacro(template, dttm); } else { String stub = usingDefault ? "_%time%" : "%time%"; template = StringUtil.replace(template, stub, ""); } } catch (Exception exc) {} template = StringUtil.replace(template, "/", "_"); template = StringUtil.replace(template, "\\", "_"); return template; } /** * Get the dir to use * * @return dir */ private String getFileDirectory() { String filename = ""; if (scriptingNode != null) { filename = imageGenerator.applyMacros(scriptingNode, ATTR_IMAGEDIR, filename); } else { if (alternateDirCbx.isSelected()) { filename = alternateDirFld.getText().trim(); if ( !Misc.equals(filename, dfltAltDir)) { dfltAltDir = filename; idv.getStore().put(PROP_IMAGEALTDIR, dfltAltDir); idv.getStore().save(); } if (filename.length() == 0) { filename = directory; alternateDirFld.setText(directory); } else { // IOUtil.makeDir(filename); } } } if (filename.length() == 0) { filename = directory; } IOUtil.makeDir(filename); return filename; } /** * Take a screen snapshot in blocking mode */ private void grabImageAndBlock() { if ((beepCbx != null) && beepCbx.isSelected()) { Toolkit.getDefaultToolkit().beep(); } try { Hashtable imageProperties = new Hashtable(); synchronized (MUTEX) { if (viewManager != null) { if (viewManager.useDisplay()) { // Sleep a bit to let the display get updated // TODO??? Misc.sleep(500); } } // String filename = getFilePrefix(imageCnt++); String filename = getFilePrefix(images.size()); String tmp = filename.toLowerCase(); if ( !(tmp.endsWith(".gif") || tmp.endsWith(".png") || tmp.endsWith(".jpg") || tmp.endsWith(".jpeg"))) { filename = filename + getFileSuffix(); } String path = IOUtil.joinDir(getFileDirectory(), filename); if (isInteractive() && !overwriteCbx.isSelected() && alternateDirCbx.isSelected() && new File(path).exists()) { if (JOptionPane .showConfirmDialog(null, "File:" + path + " exists. Do you want to overwrite?", "File exists", JOptionPane .YES_NO_OPTION) == 1) { stopCapturingAuto(); stopAnimationCapture(false); return; } overwriteCbx.setSelected(true); } // System.err.println ("ImageSequenceGrabber file dir: " +getFileDirectory() +" path: " + path); DateTime time = null; time = (((getAnimation() != null) && (getAnimation().getAniValue() != null)) ? new DateTime(getAnimation().getAniValue()) : null); GeoLocationInfo bounds = null; if (viewManager != null) { bounds = viewManager.getVisibleGeoBounds(); } System.err.println("image sequence"); if (alternateComponent != null) { System.err.println("image sequence - alt"); GuiUtils.toFront(GuiUtils.getFrame(alternateComponent)); Misc.sleep(50); ImageUtils.writeImageToFile(alternateComponent, path); } else { if ( !idv.getArgsManager().getIsOffScreen()) { viewManager.toFront(); Misc.sleep(100); } if (imageGenerator != null) { //I guess we are in scripting mode. BufferedImage image; boolean combine = XmlUtil.getAttribute(scriptingNode, ImageGenerator.ATTR_COMBINE, false); if (combine) { List<Image> images = new LinkedList<Image>(); for (Object o : viewManager.getVMManager() .getViewManagers()) { ViewManager vm = (ViewManager) o; vm.getAnimation().setAniValue(time); images.add(vm.captureIslImage(scriptingNode)); } int cols = 2; cols = XmlUtil.getAttribute(scriptingNode, imageGenerator.ATTR_COLUMNS, cols); image = (BufferedImage) ImageUtils.gridImages2( images, 0, Color.BLACK, cols); } else { image = viewManager.captureIslImage(scriptingNode); } Hashtable props = new Hashtable(); props.put(ImageGenerator.PROP_IMAGEPATH, path); props.put(ImageGenerator.PROP_IMAGEFILE, IOUtil.getFileTail(path)); imageGenerator.putIndex(props, ImageGenerator.PROP_IMAGEINDEX, images.size()); imageGenerator.processImage(image, path, scriptingNode, props, viewManager, imageProperties); subsetBounds(bounds, imageProperties); } else { List<Component> components = new LinkedList<Component>(); if (fullWindowBtn.isSelected()) { // Full Window components .add(viewManager.getDisplayWindow() .getComponent()); } else if (mainDisplayBtn.isSelected()) { // View components.add( viewManager.getMaster().getComponent()); } else if (fullScreenBtn.isSelected()) { // Full Screen components.add( viewManager.getMaster().getComponent()); } else if (allViewsBtn.isSelected()) { // All Views for (Object o : viewManager.getDisplayWindow() .getViewManagers()) { components.add( ((MapViewManager) o).getComponent()); } } else { // View & Legend components.add(viewManager.getContents()); } Image image = captureImages( components, ImageUtils.getColumnCountFromComps( components)); if (allViewsBtn.isSelected()) { // Otherwise, this gets set in the captureImage method. imageSize = new Dimension(image.getWidth(null), image.getHeight(null)); } if (backgroundTransparentBtn.isSelected()) { image = ImageUtils.makeColorTransparent(image, viewManager.getBackground()); } ImageUtils.writeImageToFile(image, path, getImageQuality()); } } ImageWrapper imageWrapper; if (viewManager != null) { imageWrapper = new ImageWrapper(path, time, bounds, viewManager.getDisplayMatrix()); } else { imageWrapper = new ImageWrapper(path, time); } imageWrapper.setProperties(imageProperties); images.add(imageWrapper); imagesChanged(); } } catch (Throwable exc) { stopAnimationCapture(false); LogUtil.logException("Error capturing image", exc); } } /** * Capture images. * * @param components the components * @param cols number of columns * @return the image * @throws AWTException the aWT exception */ public Image captureImages(List<? extends Component> components, int cols) throws AWTException { List<Image> images = new LinkedList<Image>(); for (Component c : components) { images.add(captureImage(c)); } return ImageUtils.gridImages2(images, 0, Color.GRAY, cols); } /** * Capture image. * * @param comp the comp * @return the image * @throws AWTException the aWT exception */ public Image captureImage(Component comp) throws AWTException { Dimension dim; Point loc; if (fullScreenBtn.isSelected()) { // Full Screen dim = Toolkit.getDefaultToolkit().getScreenSize(); loc = new Point(0, 0); } else { dim = comp.getSize(); loc = comp.getLocationOnScreen(); } GraphicsConfiguration gc = comp.getGraphicsConfiguration(); Robot robot = new Robot(gc.getDevice()); if ((gc.getBounds().x > 0) || (gc.getBounds().y > 0)) { System.err.println("Offsetting location:" + loc + " by gc bounds: " + gc.getBounds().x + " " + gc.getBounds().y); loc.x -= gc.getBounds().x; loc.y -= gc.getBounds().y; System.err.println("new location:" + loc); } imageSize = new Dimension(dim.width, dim.height); return robot.createScreenCapture(new Rectangle(loc.x, loc.y, dim.width, dim.height)); } /** * Subset bounds * * @param bounds the bounds * @param returnProps the return properties */ public static void subsetBounds(GeoLocationInfo bounds, Hashtable returnProps) { if (bounds == null) { return; } Double d; if ((d = (Double) returnProps.get(ImageGenerator.ATTR_NORTH)) != null) { bounds.setMaxLat(d.doubleValue()); } if ((d = (Double) returnProps.get(ImageGenerator.ATTR_SOUTH)) != null) { bounds.setMinLat(d.doubleValue()); } if ((d = (Double) returnProps.get(ImageGenerator.ATTR_WEST)) != null) { bounds.setMinLon(d.doubleValue()); } if ((d = (Double) returnProps.get(ImageGenerator.ATTR_EAST)) != null) { bounds.setMaxLon(d.doubleValue()); } } /** * The list of images have changed. Update the UI. */ private void imagesChanged() { synchronized (MUTEX) { if (images.size() == 0) { lastPreview = null; } if (images.size() == 0) { frameLbl.setText("No frames"); } else if (images.size() == 1) { frameLbl.setText(images.size() + " frame"); } else { frameLbl.setText(images.size() + " frames"); } createButton.setEnabled(images.size() > 0); clearButton.setEnabled(images.size() > 0); previewButton.setEnabled(images.size() > 0); setPreviewImage(); } } /** * actually create the movie * * @param movieFile Where to write the movie */ private void createMovie(String movieFile) { Dimension size = imageSize; if ((size == null) && (viewManager != null)) { Component comp = viewManager.getMaster().getDisplayComponent(); // Get the size of the display size = comp.getSize(); } if (size == null) { size = new Dimension(600, 400); } double displayRate = (new Double(displayRateFld.getText())).doubleValue(); double endPause = (new Double(endPauseFld.getText())).doubleValue(); if (scriptingNode != null) { displayRate = imageGenerator.applyMacros(scriptingNode, imageGenerator.ATTR_FRAMERATE, displayRate); endPause = imageGenerator.applyMacros(scriptingNode, imageGenerator.ATTR_ENDFRAMEPAUSE, -1); } createMovie(movieFile, images, size, displayRate, scriptingNode, endPause); } /** * Create an image panel * * @param file file to write to * @param images list of images * @param scriptingNode scripting node */ private void createPanel(String file, List<ImageWrapper> images, Element scriptingNode) { try { imageGenerator.debug("Making image panel:" + file); int width = imageGenerator.applyMacros(scriptingNode, imageGenerator.ATTR_WIDTH, 100); int columns = imageGenerator.applyMacros(scriptingNode, imageGenerator.ATTR_COLUMNS, 1); int space = imageGenerator.applyMacros(scriptingNode, imageGenerator.ATTR_SPACE, 0); Color background = imageGenerator.applyMacros(scriptingNode, imageGenerator.ATTR_BACKGROUND, (Color) null); List sizedImages = new ArrayList(); for (ImageWrapper imageWrapper : images) { String imageFile = imageWrapper.getPath(); Image image = ImageUtils.readImage(imageFile); BufferedImage bufferedImage = ImageUtils.toBufferedImage(image); image = imageGenerator.resize(bufferedImage, scriptingNode); sizedImages.add(image); } Image image = ImageUtils.gridImages(sizedImages, space, background, columns); ImageUtils.writeImageToFile(image, file); } catch (Exception exc) { LogUtil.logException("Writing panel", exc); } } /** * actually create the movie * * * @param commaSeparatedFiles This can be a list of comma separated files. eg: .mov, .kmz, etc * @param images List of images to make a movie from * @param size size * @param displayRate display rate * @param scriptingNode isl node. May be null */ private void createMovie(String commaSeparatedFiles, List<ImageWrapper> images, Dimension size, double displayRate, Element scriptingNode) { createMovie(commaSeparatedFiles, images, size, displayRate, scriptingNode, -1); } /** * actually create the movie * * * @param commaSeparatedFiles This can be a list of comma separated files. eg: .mov, .kmz, etc * @param images List of images to make a movie from * @param size size * @param displayRate display rate * @param scriptingNode isl node. May be null * @param endPause end pause value */ private void createMovie(String commaSeparatedFiles, List<ImageWrapper> images, Dimension size, double displayRate, Element scriptingNode, double endPause) { List fileToks = StringUtil.split(commaSeparatedFiles, ",", true, true); boolean doingPanel = false; if ((scriptingNode != null) && scriptingNode.getTagName().equals("panel")) { doingPanel = true; } if (writePositions && (fileToks.size() > 0)) { try { String positionFilename = IOUtil.stripExtension((String) fileToks.get(0)) + ".xidv"; List<double[]> positions = new ArrayList<double[]>(); for (ImageWrapper imageWrapper : images) { positions.add(imageWrapper.getPosition()); } IOUtil.writeFile(positionFilename, idv.encodeObject(positions, true, true)); } catch (IOException ioe) { LogUtil.userErrorMessage("Error writing positions:" + ioe); return; } } // System.err.println("doingPanel:" + doingPanel + " " + scriptingNode); for (int i = 0; i < fileToks.size(); i++) { String movieFile = (String) fileToks.get(i); try { if (doingPanel) { createPanel(movieFile, images, scriptingNode); continue; } // IDV in non-interactive mode does not properly get the size // for n-panel views because ATTR_HEIGHT, ATTR_WIDTH are set // for one panel in ImageGenerator.captureMovie. if (( !isInteractive()) && (images.size() > 0)) { BufferedImage image = ImageUtils.toBufferedImage( ImageUtils.readImage( images.get(0).getPath())); ImageUtils.waitOnImage(image); size = new Dimension(image.getWidth(null), image.getHeight(null)); } // System.err.println("createMovie:" + movieFile); if (movieFile.toLowerCase().endsWith( FileManager.SUFFIX_GIF)) { double rate = 1.0 / displayRate; boolean useGCT = getGlobalPaletteValue(); AnimatedGifEncoder.createGif(movieFile, ImageWrapper.makeFileList(images), AnimatedGifEncoder.REPEAT_FOREVER, (int) (rate * 1000), (int) ((endPause == -1) ? -1 : endPause * 1000), useGCT); } else if (movieFile.toLowerCase().endsWith(".htm") || movieFile.toLowerCase().endsWith(".html")) { createAnisHtml(movieFile, images, size, displayRate, scriptingNode); } else if (movieFile.toLowerCase() .endsWith(FileManager.SUFFIX_KMZ)) { createKmz(movieFile, images, scriptingNode); } else if (movieFile.toLowerCase().endsWith(FileManager.SUFFIX_ZIP)) { createZip(movieFile, images, scriptingNode); } else if (movieFile.toLowerCase().endsWith( FileManager.SUFFIX_AVI)) { ImageUtils.writeAvi(ImageWrapper.makeFileList(images), displayRate, new File(movieFile)); } else { // System.err.println("mov:" + movieFile); SecurityManager backup = System.getSecurityManager(); System.setSecurityManager(null); if (size == null) { size = new Dimension(600, 400); } JpegImagesToMovie.createMovie(movieFile, size.width, size.height, (int) displayRate, new Vector(ImageWrapper.makeFileList(images))); System.setSecurityManager(backup); } } catch (NumberFormatException nfe) { LogUtil.userErrorMessage("Bad number format"); return; } catch (IOException ioe) { LogUtil.userErrorMessage("Error writing movie:" + ioe); return; } idv.getPublishManager().publishContent(movieFile, viewManager, publishCbx); } } /** * create the kmz * * @param movieFile file name * @param images list of images * @param scriptingNode isl node */ public void createKmz(String movieFile, List<ImageWrapper> images, Element scriptingNode) { try { ZipOutputStream zos = null; if (movieFile.toLowerCase().endsWith(FileManager.SUFFIX_KMZ)) { zos = new ZipOutputStream(new FileOutputStream(movieFile)); } StringBuffer sb = new StringBuffer( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); sb.append("<kml xmlns=\"http://earth.google.com/kml/2.0\">\n"); String open = "1"; String visibility = "1"; if (scriptingNode != null) { visibility = imageGenerator.applyMacros(scriptingNode, ATTR_KML_VISIBILITY, visibility); open = imageGenerator.applyMacros(scriptingNode, ATTR_KML_OPEN, open); } sb.append("<Folder>\n"); sb.append("<open>" + open + "</open>\n"); sb.append(XmlUtil.tag(TAG_VISIBILITY, "", visibility)); if (scriptingNode != null) { String folderName = imageGenerator.applyMacros(scriptingNode, ATTR_KML_NAME, (String) null); if (folderName != null) { sb.append("<name>" + folderName + "</name>\n"); } String desc = imageGenerator.applyMacros(scriptingNode, ATTR_KML_DESC, (String) null); if (desc == null) { desc = imageGenerator.applyMacros( XmlUtil.getChildText(scriptingNode)); if (desc != null) { desc = desc.trim(); } } if ((desc != null) && (desc.length() > 0)) { sb.append(XmlUtil.tag(TAG_DESCRIPTION, "", desc)); } } if (scriptingNode != null) { Element kmlElement = XmlUtil.findChild(scriptingNode, ImageGenerator.TAG_KML); if (kmlElement != null) { sb.append( imageGenerator.applyMacros( XmlUtil.getChildText(kmlElement))); } List nodes = XmlUtil.findChildren(scriptingNode, ImageGenerator.TAG_KMZFILE); for (int i = 0; i < nodes.size(); i++) { Element child = (Element) nodes.get(i); String file = XmlUtil.getAttribute(child, ATTR_FILENAME); if (zos != null) { zos.putNextEntry( new ZipEntry(IOUtil.getFileTail(file))); byte[] bytes = IOUtil.readBytes(IOUtil.getInputStream(file)); zos.write(bytes, 0, bytes.length); } } } // <name>Buienradar.nl</name> TimeZone tz = TimeZone.getTimeZone("GMT"); boolean didKmlFiles = false; for (ImageWrapper imageWrapper : images) { List kmlFiles = (List) imageWrapper.getProperty("kmlfiles"); if ( !didKmlFiles && (kmlFiles != null)) { didKmlFiles = true; for (String kmlFile : (List<String>) kmlFiles) { String tail = IOUtil.getFileTail(kmlFile); if (zos != null) { zos.putNextEntry(new ZipEntry(tail)); byte[] imageBytes = IOUtil.readBytes( new FileInputStream( kmlFile)); zos.write(imageBytes, 0, imageBytes.length); } } } String extraKml = (String) imageWrapper.getProperty("kml"); String image = imageWrapper.getPath(); String tail = IOUtil.getFileTail(image); // System.err.println("tail:" + tail); if (zos != null) { zos.putNextEntry(new ZipEntry(tail)); byte[] imageBytes = IOUtil.readBytes(new FileInputStream(image)); zos.write(imageBytes, 0, imageBytes.length); } DateTime dttm = imageWrapper.getDttm(); GeoLocationInfo bounds = imageWrapper.getBounds(); if (extraKml != null) { sb.append(extraKml); } sb.append("<GroundOverlay>\n"); sb.append("<name>" + ((dttm == null) ? tail : dttm.toString()) + "</name>\n"); sb.append(XmlUtil.tag(TAG_VISIBILITY, "", visibility)); sb.append("<Icon><href>" + tail + "</href></Icon>\n"); if (bounds != null) { KmlDataSource.createLatLonBox(bounds, sb); } if (dttm != null) { String when = dttm.formattedString("yyyy-MM-dd", tz) + "T" + dttm.formattedString("HH:mm:ss", tz) + "Z"; sb.append("<TimeStamp><when>" + when + "</when></TimeStamp>\n"); } sb.append("</GroundOverlay>\n"); } sb.append("</Folder></kml>\n"); if (zos != null) { zos.putNextEntry( new ZipEntry( IOUtil.stripExtension(IOUtil.getFileTail(movieFile)) + FileManager.SUFFIX_KML)); byte[] kmlBytes = sb.toString().getBytes(); // System.out.println("sb:" + sb); zos.write(kmlBytes, 0, kmlBytes.length); zos.close(); } else { IOUtil.writeFile(movieFile, sb.toString()); } } catch (Exception exc) { LogUtil.logException("Saving kmz file", exc); } } /** * create the kmz * * @param movieFile file name * @param images list of images * @param scriptingNode isl node */ public void createZip(String movieFile, List<ImageWrapper> images, Element scriptingNode) { try { ZipOutputStream zos = null; if (movieFile.toLowerCase().endsWith(FileManager.SUFFIX_ZIP)) { zos = new ZipOutputStream(new FileOutputStream(movieFile)); } StringBuffer sb = new StringBuffer( "<entries>\n"); DateTime time = null; time = (((getAnimation() != null) && (getAnimation().getAniValue() != null)) ? new DateTime(getAnimation().getAniValue()) : null); String pName = IOUtil.stripExtension(IOUtil.getFileTail(movieFile)); sb.append("<entry fromdate=\"" + time.toString() + "\" id=\"imageloopParent\" name=\"" + pName + "\" type=\"media_imageloop\">\n"); sb.append("</entry>\n"); int idx = 0; for (ImageWrapper imageWrapper : images) { zos.putNextEntry( new ZipEntry(IOUtil.getFileTail(imageWrapper.getPath()))); byte[] imageBytes = IOUtil.readBytes( new FileInputStream( imageWrapper.getPath())); zos.write(imageBytes, 0, imageBytes.length); String image = imageWrapper.getPath(); String tail = IOUtil.getFileTail(image); DateTime dttm = imageWrapper.getDttm(); GeoLocationInfo bounds = imageWrapper.getBounds(); String nameStr = "image_" + idx; sb.append("<entry fromdate=\"" + dttm.toString() + "\" file=\""+ tail + "\" name=\"" + nameStr + "\" parent=\"imageloopParent\" type=\"file\">\n"); sb.append("</entry>\n"); idx++; } sb.append("</entries>\n"); if (zos != null) { zos.putNextEntry( new ZipEntry("entries" + FileManager.SUFFIX_XML)); byte[] kmlBytes = sb.toString().getBytes(); // System.out.println("sb:" + sb); zos.write(kmlBytes, 0, kmlBytes.length); zos.close(); } else { IOUtil.writeFile(movieFile, sb.toString()); } } catch (Exception exc) { LogUtil.logException("Saving zip file", exc); } } /** * create the anis html * * @param movieFile file name * @param images list of images * @param size the size * @param displayRate rate * @param scriptingNode isl node */ private void createAnisHtml(String movieFile, List<ImageWrapper> images, Dimension size, double displayRate, Element scriptingNode) { try { boolean copyFiles = false; boolean doFlanis = false; String type = "anis"; String dir = IOUtil.getFileRoot(movieFile); String preText = ""; String postText = ""; String width = "" + ((size != null) ? "" + (size.width + 200) : "600"); String height = "" + ((size != null) ? "" + (size.height + 200) : "600"); if (scriptingNode == null) { if (preFld == null) { preFld = new JTextArea(5, 20); postFld = new JTextArea(5, 20); copyCbx = new JCheckBox("Copy image files to: " + dir); widthFld = new JTextField("600", 5); heightFld = new JTextField("600", 5); typeCbx = new JCheckBox("FlAniS? (default: AniS)"); typeCbx.setToolTipText( "Check this box to create HTML to use the Flash animator (FlAniS); otherwise, the java applet animator (AniS) will be used."); } widthFld.setText(width); heightFld.setText(height); copyCbx.setText("Copy image files to: " + dir); GuiUtils.tmpInsets = new Insets(5, 5, 5, 5); JPanel contents = GuiUtils.doLayout(new Component[] { GuiUtils.rLabel("Dimension:"), GuiUtils.left(GuiUtils.hbox(widthFld, new JLabel(" X "), heightFld)), GuiUtils.top(GuiUtils.rLabel("Top HTML:")), GuiUtils.makeScrollPane(preFld, 200, 100), GuiUtils.top(GuiUtils.rLabel("Bottom HTML:")), GuiUtils.makeScrollPane(postFld, 200, 100), GuiUtils.rLabel(""), typeCbx, GuiUtils.rLabel(""), copyCbx }, 2, GuiUtils.WT_NY, GuiUtils.WT_N); if ( !GuiUtils.showOkCancelDialog(null, "ANIS Applet Information", contents, null)) { return; } copyFiles = copyCbx.isSelected(); doFlanis = typeCbx.isSelected(); preText = preFld.getText(); postText = postFld.getText(); width = widthFld.getText().trim(); height = heightFld.getText().trim(); } else { width = XmlUtil.getAttribute(scriptingNode, ATTR_ANIS_WIDTH, width); height = XmlUtil.getAttribute(scriptingNode, ATTR_ANIS_HEIGHT, height); preText = XmlUtil.getAttribute(scriptingNode, ATTR_ANIS_PREHTML, preText); postText = XmlUtil.getAttribute(scriptingNode, ATTR_ANIS_POSTHTML, postText); type = XmlUtil.getAttribute(scriptingNode, ATTR_ANIS_TYPE, type); doFlanis = type.toLowerCase().equals("anis") ? false : true; } StringBuffer sb = new StringBuffer(); String files = ""; for (int i = 0; i < images.size(); i++) { ImageWrapper imageWrapper = images.get(i); String file = imageWrapper.getPath(); if (copyFiles) { IOUtil.copyFile(new File(file), new File(dir)); } if (i > 0) { files = files + ","; } files = files + IOUtil.getFileTail(file); } sb.append(preText); sb.append("\n"); if (doFlanis) { sb.append( "<OBJECT type=\"application/x-shockwave-flash\" data=\"./flanis.swf\" width=\"" + width + "\" height=\"" + height + "\" id=\"FlAniS\"> \n"); sb.append("<PARAM NAME=\"movie\" VALUE=\"./flanis.swf\"> \n"); sb.append("<PARAM NAME=\"quality\" VALUE=\"high\"> \n"); sb.append("<PARAM NAME=\"menu\" value=\"false\"> \n"); sb.append( "<PARAM NAME=\"FlashVars\" value=\"controls=startstop,step,speed,toggle,zoom&filenames=" + files + "\"> \n"); sb.append("</OBJECT>\n"); } else { sb.append("<APPLET code=\"AniS.class\" width=" + width + " height=" + height + ">\n"); sb.append( "<PARAM name=\"controls\" value=\"startstop,step, speed, toggle, zoom\">\n"); sb.append("<PARAM name=\"filenames\" value=\"" + files + "\">\n"); sb.append("</APPLET>\n"); } sb.append("\n"); sb.append(postText); IOUtil.writeFile(new File(movieFile), sb.toString()); } catch (Exception exc) { LogUtil.logException("Saving html file", exc); } } /** * main * * @param args args */ public static void main(String[] args) { AnimatedGifEncoder e = new AnimatedGifEncoder(); e.start("test.gif"); for (int i = 0; i < args.length; i++) { ImagePlus image = new ImagePlus(args[i]); e.addFrame(image); } e.finish(); } }
34.187892
150
0.524623
ae048a07fdd4943664c3005c8fa4518b5ebf15ed
316
/** * https://projecteuler.net/problem=20 * * Validated. */ class p020 { public static void main (String[] args) { long s = System.nanoTime(); System.out.println(Library.digitSum(Library.fact(100))); long e = System.nanoTime(); System.out.println((e-s)/1000000000.0); } }
22.571429
64
0.598101
dc225936b5e331dc9e91fab34cd235b4bb65adb9
1,966
package com.averkin.resolver; import com.averkin.resolver.mongo.CustomerRepository; import com.averkin.resolver.mongo.Xpath; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import java.util.List; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class WriteLogToDB { @Autowired private CustomerRepository repository; @Autowired private MockMvc mvc; @Test public void testWritingLogs() throws Exception { repository.deleteAll(); ObjectMapper mapper = new ObjectMapper(); ObjectNode node = mapper.createObjectNode(); node.put("classifier", "Library1"); node.put("className", "TestClass"); node.put("methodName","testSomethingMethod"); node.put("status", "passed"); node.put("xpath","//body"); MvcResult result = mvc.perform(MockMvcRequestBuilders.post("/add") .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .content(node.toString())).andExpect(status().isOk()).andReturn(); List<Xpath> all = repository.findAll(); assertThat(all.size()).isEqualTo(1); } }
30.246154
87
0.744659
b7267a21045fc64e1094f4e45a7a454a8ebd14f4
305
package com.andynordevelop.miraiexwrapper.domain; public enum MiraiexPairEnum { BTCNOK ("BTCNOK"), DAINOK ("DAINOK"), ETHNOK ("ETHNOK"), LTCNOK ("LTCNOK"), XRPNOK ("XRPNOK"), ADANOK ("ADANOK"); String pair; MiraiexPairEnum(String pair) { this.pair = pair; } }
16.944444
49
0.616393
8b3110bee3545dceae5dcd40de092373789490ff
13,976
package de.hhu.stups.plues.prob; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyObject; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import de.be4.classicalb.core.parser.exceptions.BCompoundException; import de.prob.animator.domainobjects.ClassicalB; import de.prob.animator.domainobjects.EvalElementType; import de.prob.animator.domainobjects.FormulaExpand; import de.prob.animator.domainobjects.IEvalElement; import de.prob.model.classicalb.ClassicalBModel; import de.prob.model.representation.AbstractModel; import de.prob.scripting.Api; import de.prob.scripting.ModelTranslationError; import de.prob.statespace.State; import de.prob.statespace.StateSpace; import de.prob.statespace.Trace; import de.prob.statespace.Transition; import de.prob.translator.Translator; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; public class ProBSolverTest { private ProBSolver solver; private Trace trace; private StateSpace stateSpace; private CommandFactory commandFactory; private AbstractModel model; @Test public void unsatCoreModules() throws Exception { final String[] modelReturnValues = new String[] {"{mod1, mod99}"}; final String op = "unsatCoreModules"; final String predicate = "ccss={\"foo\", \"bar\"}"; setupOperationCanBeExecuted(modelReturnValues, op, predicate); final Set<Integer> uc = solver.unsatCoreModules("foo", "bar"); assertEquals(2, uc.size()); assertTrue(uc.contains(1)); assertTrue(uc.contains(99)); } @Test public void unsatCoreAbstractUnits() throws Exception { final String[] modelReturnValues = new String[] {"{au2, au123}"}; final String op = "unsatCoreAbstractUnits"; final String predicate = "uc_modules={mod2, mod123}"; setupOperationCanBeExecuted(modelReturnValues, op, predicate); final Set<Integer> uc = solver.unsatCoreAbstractUnits(Arrays.asList(2, 123)); assertEquals(2, uc.size()); assertTrue(uc.contains(2)); assertTrue(uc.contains(123)); } @Test public void unsatCoreGroups() throws Exception { final String[] modelReturnValues = new String[] {"{group32, group2123}"}; final String op = "unsatCoreGroups"; final String predicate = "uc_modules={mod2, mod87} & uc_abstract_units={au1, au99}"; setupOperationCanBeExecuted(modelReturnValues, op, predicate); final Set<Integer> uc = solver.unsatCoreGroups(Arrays.asList(1, 99), Arrays.asList(2, 87)); assertEquals(2, uc.size()); assertTrue(uc.contains(32)); assertTrue(uc.contains(2123)); } @Test public void unsatCoreSessions() throws Exception { final String[] modelReturnValues = new String[] {"{session77, session1234}"}; final String op = "unsatCoreSessions"; final String predicate = "uc_groups={group1, group99}"; setupOperationCanBeExecuted(modelReturnValues, op, predicate); final Set<Integer> uc = solver.unsatCoreSessions(Arrays.asList(1, 99)); assertEquals(2, uc.size()); assertTrue(uc.contains(77)); assertTrue(uc.contains(1234)); } /** * Setup state for test. */ @Before public void setUp() throws SolverException, IOException, ModelTranslationError { this.stateSpace = mock(StateSpace.class); this.trace = mock(Trace.class); this.model = mock(ClassicalBModel.class); final Api api = mock(Api.class); final State state = mock(State.class); when(api.b_load("model")).thenReturn(stateSpace); when(stateSpace.asType(Trace.class)).thenReturn(trace); when(stateSpace.getModel()).thenReturn(model); when(trace.getCurrentState()).thenReturn(state); when(state.getId()).thenReturn("TEST-STATE-ID"); when(trace.addTransitions(anyList())).thenReturn(trace); when(trace.execute("$setup_constants")).thenReturn(trace); when(trace.execute("$initialise_machine")).thenReturn(trace); this.commandFactory = mock(CommandFactory.class); this.solver = new ProBSolver(api, commandFactory, "model"); } @Test public void interrupt() { this.solver.interrupt(); verify(this.stateSpace).sendInterrupt(); } @Test public void checkFeasibilityFeasibleCourse() throws Exception { final String[] t = new String[] {}; setupOperationCanBeExecuted(t, "check", "ccss={\"NoFoo\"}"); setupOperationCanBeExecuted(t, "check", "ccss={\"NoBar\"}"); setupOperationCanBeExecuted(t, "check", "ccss={\"NoFoo\", \"NoBar\"}"); assertTrue(solver.checkFeasibility("NoFoo", "NoBar")); final OperationPredicateKey key = new OperationPredicateKey("check", "ccss={\"NoFoo\", \"NoBar\"}"); assertTrue(solver.getOperationExecutionCache().containsKey(key)); } @Test(expected = SolverException.class) public void checkFeasibilityInfeasibleCourse() throws Exception { setupOperationCanBeExecuted(new String[] {}, "check", "ccss={\"NoFoo\"}"); setupOperationCanBeExecuted(new String[] {}, "check", "ccss={\"NoBar\"}"); setupOperationCannotBeExecuted("check", "ccss={\"NoFoo\", \"NoBar\"}"); // solver.checkFeasibility("NoFoo", "NoBar"); } @Test public void checkFeasibilityInfeasibleCourseCache() throws Exception { setupOperationCanBeExecuted(new String[] {},"check", "ccss={\"NoFoo\"}"); setupOperationCanBeExecuted(new String[] {},"check", "ccss={\"NoBar\"}"); setupOperationCannotBeExecuted("check", "ccss={\"NoFoo\", \"NoBar\"}"); try { solver.checkFeasibility("NoFoo", "NoBar"); } catch (final SolverException ignored) { // ignored } finally { final OperationPredicateKey key = new OperationPredicateKey("check", "ccss={\"NoFoo\", \"NoBar\"}"); assertTrue(solver.getOperationExecutionCache().containsKey(key)); } } @Test public void computeFeasiblity() throws Exception { final String op = "check"; final String predicate = "ccss={\"foo\", \"bar\"}"; final String[] modelReturnValues = new String[] {"{(au1,sem2)}", "{(au3,group4)}", "{(mod5 |-> au1), (mod5 |-> au2)}", "{\"foo\" |-> {mod5,mod6}}"}; setupOperationCanBeExecuted(modelReturnValues, op, predicate); final Map<Integer, Integer> gc = new HashMap<>(); final Map<Integer, Integer> sc = new HashMap<>(); final Map<Integer, Set<Integer>> ac = new HashMap<>(); final Map<String, Set<Integer>> mc = new HashMap<>(); final Set<Integer> modules = new HashSet<>(); ac.put(5, new HashSet<>(Arrays.asList(1, 2))); gc.put(3, 4); sc.put(1, 2); modules.add(5); modules.add(6); mc.put("foo", modules); final FeasibilityResult result = solver.computeFeasibility("foo", "bar"); assertEquals(result.getGroupChoice(), gc); assertEquals(result.getSemesterChoice(), sc); assertEquals(result.getModuleChoice(), mc); assertEquals(result.getAbstractUnitChoice(), ac); } @Test public void computePartialFeasiblity() throws Exception { final String op = "checkPartial"; final String predicate = "ccss={\"foo\", \"bar\"} " + "& partialModuleChoice={(\"foo\" |-> {mod5})}" + " & partialAbstractUnitChoice={(mod5, au7)}"; final String[] modelReturnValues = new String[] {"{(au1,sem2)}", "{(au3,group4)}", "{(mod5, au1), (mod5, au11)}", "{\"foo\" |-> {mod5,mod6}}"}; setupOperationCanBeExecuted(modelReturnValues, op, predicate); final Map<Integer, Integer> gc = new HashMap<>(); final Map<Integer, Integer> sc = new HashMap<>(); final Map<String, Set<Integer>> mc = new HashMap<>(); final Map<Integer, Set<Integer>> ac = new HashMap<>(); final Set<Integer> modules = new HashSet<>(); gc.put(3, 4); sc.put(1, 2); ac.put(5, new HashSet<>(Arrays.asList(1, 11))); modules.add(5); modules.add(6); mc.put("foo", modules); final List<String> courses = new ArrayList<>(); courses.add("foo"); courses.add("bar"); final Map<String, List<Integer>> partialMc = new HashMap<>(); final List<Integer> partialModules = new ArrayList<>(); partialModules.add(5); partialMc.put("foo", partialModules); final Map<Integer, List<Integer>> partialAuc = new HashMap<>(); partialAuc.put(5, Collections.singletonList(7)); final FeasibilityResult result = solver.computePartialFeasibility(courses, partialMc, partialAuc); assertEquals(result.getGroupChoice(), gc); assertEquals(result.getSemesterChoice(), sc); assertEquals(result.getModuleChoice(), mc); assertEquals(result.getAbstractUnitChoice(), ac); assertTrue(solver.getOperationExecutionCache().containsKey( new OperationPredicateKey(op, predicate))); } @Test(expected = SolverException.class) public void computeFeasibilityInfeasibleCourse() throws Exception { final String op = "check"; final String predicate = "ccss={\"foo\", \"bar\"}"; setupOperationCannotBeExecuted(op, predicate); solver.computeFeasibility("foo", "bar"); } @Test public void unsatCore() throws Exception { final String[] modelReturnValues = new String[] {"{session1, session77}"}; final String op = "unsatCore"; final String predicate = "ccss={\"foo\", \"bar\"}"; setupOperationCanBeExecuted(modelReturnValues, op, predicate); final Integer[] unsatCore = new Integer[] {1, 77}; assertEquals(solver.unsatCore("foo", "bar"), new HashSet<>(Arrays.asList(unsatCore))); } @Test public void getImpossibleCourses() throws Exception { final String[] modelReturnValues = new String[] { "rec(courses:{\"BK-C1-H-2013\", \"BA-C2-N-2011\"})"}; final String op = "getImpossibleCourses"; final String predicate = "1=1"; setupOperationCanBeExecuted(modelReturnValues, op, predicate); final String[] impossible = new String[] {"BK-C1-H-2013", "BA-C2-N-2011"}; assertTrue(solver.getImpossibleCourses().containsAll(Arrays.asList(impossible))); assertTrue(solver.getOperationExecutionCache().containsKey( new OperationPredicateKey(op, predicate))); } @Test public void move() throws Exception { final String op = "move"; final String predicate = "session=session101 & dow=mon & slot=slot8"; final String[] t = new String[] {}; setupOperationCanBeExecuted(t, op, predicate); solver.move("101", "mon", "8"); assertTrue(solver.getOperationExecutionCache().isEmpty()); verify(this.commandFactory).create( eq(stateSpace), eq("TEST-STATE-ID"), eq(op), any(IEvalElement.class), eq(1)); verify(stateSpace).execute(any(GetOperationByPredicateCommandDelegate.class)); } @Test public void alternatives() throws Exception { final String[] modelReturnValues = new String[] { "{rec(day:\"mon\", slot:slot1), rec(day:\"tue\", slot:slot2)}"}; final String op = "localAlternatives"; final String predicate = "ccss={\"foo\", \"bar\"} & session=session1"; setupOperationCanBeExecuted(modelReturnValues, op, predicate); final List<Alternative> r = solver.getLocalAlternatives(1, "foo", "bar"); final List<Alternative> alternatives = new ArrayList<>(); alternatives.add(new Alternative("mon", "slot1")); alternatives.add(new Alternative("tue", "slot2")); assertTrue(r.containsAll(alternatives)); assertTrue(solver.getOperationExecutionCache().containsKey( new OperationPredicateKey(op, predicate))); assertTrue(r.containsAll(alternatives)); } @SuppressWarnings("UnusedParameters") private void setupOperationCannotBeExecuted(final String op, final String pred) throws Exception { final GetOperationByPredicateCommandDelegate cmd = mock(GetOperationByPredicateCommandDelegate.class); final IEvalElement evalElement = mock(IEvalElement.class); when(this.model.parseFormula(pred)).thenReturn(evalElement); when(this.commandFactory.create( eq(stateSpace), anyString(), eq(op), eq(evalElement), eq(1))).thenReturn(cmd); when(cmd.hasErrors()).thenReturn(true); when(cmd.getErrors()).thenReturn(new ArrayList<>()); when(cmd.isCompleted()).thenReturn(true); when(cmd.isInterrupted()).thenReturn(false); when(cmd.hasErrors()).thenReturn(true); } @SuppressWarnings("UnusedParameters") private void setupOperationCanBeExecuted(final String[] modelReturnValues, final String op, final String predicate) throws Exception { final Transition transition = mock(Transition.class); when(trace.getCurrentTransition()).thenReturn(transition); when(transition.evaluate(FormulaExpand.EXPAND)).thenReturn(transition); when(transition.getTranslatedReturnValues()).thenReturn( Arrays.stream(modelReturnValues).map(s -> { try { return Translator.translate(s); } catch (BCompoundException exception) { return null; } }).collect(Collectors.toList())); final GetOperationByPredicateCommandDelegate cmd = mock(GetOperationByPredicateCommandDelegate.class); final IEvalElement evalElement = mock(IEvalElement.class); when(this.model.parseFormula(eq(predicate))).thenReturn(evalElement); when(this.commandFactory.create( eq(stateSpace), anyString(), eq(op), eq(evalElement), eq(1))).thenReturn(cmd); when(cmd.isCompleted()).thenReturn(true); when(cmd.isInterrupted()).thenReturn(false); when(cmd.hasErrors()).thenReturn(false); } }
35.928021
100
0.693689
35ba8efae5041283f1d1c35a5782199f6024d4bb
623
package com.uuhnaut69.core.service.coupon; import com.uuhnaut69.core.domain.model.Coupon; import com.uuhnaut69.core.payload.request.CouponRequest; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.List; import java.util.UUID; /** * @author uuhnaut * @project mall */ public interface CouponService { Page<Coupon> findAll(Pageable pageable); Coupon findByCode(String code); Coupon create(CouponRequest couponRequest); Coupon update(UUID id, CouponRequest couponRequest); void delete(UUID id); void deleteAll(List<UUID> ids); }
21.482759
56
0.75923
58e8b1ec13c2fce6bf5ae65e1063f83701f66cf5
457
package com.github.mambabosso.dropwizard.auth.jwt; import java.io.Serializable; import java.security.Principal; import java.util.Optional; /** * Encode JWT tokens * @param <T> Principal type */ public interface JwtEncoder<T extends Principal & Serializable> { /** * Encodes the principal into a JWT token * @param principal The principal * @return The generated JWT token */ public Optional<String> encode(T principal); }
21.761905
65
0.708972
297ed7eefa27053e52768fcf78f469e8ef556605
2,006
/* * This file is part of heisenberg, licensed under the MIT License (MIT). See the LICENSE.txt file * at the root of this project for more details. */ package io.github.nucleuspowered.nucleusheisenberg.commands; import io.github.nucleuspowered.nucleusheisenberg.NucleusHeisenberg; import io.github.nucleuspowered.nucleusheisenberg.services.GeoIpDatabaseHandler; import org.spongepowered.api.command.CommandException; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.args.CommandContext; import org.spongepowered.api.command.spec.CommandExecutor; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.format.TextColors; import org.spongepowered.api.util.annotation.NonnullByDefault; @NonnullByDefault public class GeoIpUpdateCommand implements CommandExecutor { private final NucleusHeisenberg plugin; private static final Text STARTING = Text.of(TextColors.YELLOW, "Starting download of GeoIP databases."); private static final Text COMPLETE = Text.of(TextColors.YELLOW, "Update of GeoIP databases has completed."); private static final Text LICENCE = Text.of(TextColors.YELLOW, "You must accept the GeoIP module licence in the main configration file before " + "downloading the IP location databases."); public GeoIpUpdateCommand(NucleusHeisenberg plugin) { this.plugin = plugin; } @Override public CommandResult execute(CommandSource src, CommandContext args) throws CommandException { src.sendMessage(STARTING); try { this.plugin.getHandler().load(GeoIpDatabaseHandler.LoadType.DOWNLOAD); src.sendMessage(COMPLETE); } catch (IllegalStateException e) { src.sendMessage(LICENCE); } catch (Exception e) { throw new CommandException(Text.of(TextColors.RED, "Could not download databases."), e); } return CommandResult.success(); } }
43.608696
147
0.754736
e7a3281554e5092793c517c6efddedbb800191c5
3,570
package com.inverseapps.punchcard.fragments; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import com.inverseapps.punchcard.R; import com.inverseapps.punchcard.adapters.PunchAdapter; import com.inverseapps.punchcard.model.UserCheckInOut; import com.inverseapps.punchcard.ui.ForegroundTaskDelegate; import java.lang.ref.WeakReference; import java.util.List; import java.util.Vector; import butterknife.BindView; public class MyPunchesFragment extends PCFragment implements SwipeRefreshLayout.OnRefreshListener { @Override protected int getRootLayoutRes() { return R.layout.fragment_my_punches; } @NonNull @BindView(R.id.swipeRefreshLayout) SwipeRefreshLayout swipeRefreshLayout; @NonNull @BindView(R.id.recyclerView) RecyclerView recyclerView; private List<UserCheckInOut> listOfUserCheckInOuts; private PunchAdapter adapter; private RecyclerView.LayoutManager layoutManager; private ForegroundTaskDelegate findUserCheckInOutDelegate; @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); findUserCheckInOutDelegate = new FindUserCheckInOutDelegate(this); listOfForegroundTaskDelegates.add(findUserCheckInOutDelegate); listOfUserCheckInOuts = new Vector<>(); layoutManager = new LinearLayoutManager(getActivity()); recyclerView.setLayoutManager(layoutManager); recyclerView.setHasFixedSize(true); recyclerView.setItemAnimator(new DefaultItemAnimator()); adapter = new PunchAdapter(listOfUserCheckInOuts); adapter.buildUserCheckInOutTable(); recyclerView.setAdapter(adapter); swipeRefreshLayout.setColorSchemeResources(R.color.logo_orange); swipeRefreshLayout.setOnRefreshListener(this); pcActivity.getPCApplication().getPcFunctionService().findUserCheckIns(findUserCheckInOutDelegate); } @Override public void onRefresh() { swipeRefreshLayout.setRefreshing(true); pcActivity.getPCApplication().getPcFunctionService().findUserCheckIns(findUserCheckInOutDelegate); } private static class FindUserCheckInOutDelegate extends ForegroundTaskDelegate<List<UserCheckInOut>> { private final WeakReference<MyPunchesFragment> fragmentWeakReference; public FindUserCheckInOutDelegate(MyPunchesFragment fragment) { super(fragment.pcActivity); fragmentWeakReference = new WeakReference<>(fragment); } @Override public void onPostExecute(List<UserCheckInOut> userCheckInOuts, Throwable throwable) { super.onPostExecute(userCheckInOuts, throwable); MyPunchesFragment fragment = fragmentWeakReference.get(); if (throwable == null && fragment != null && !fragment.isDetached() && !fragment.isRemoving()) { fragment.listOfUserCheckInOuts.clear(); fragment.listOfUserCheckInOuts.addAll(userCheckInOuts); fragment.adapter.buildUserCheckInOutTable(); fragment.adapter.notifyDataSetChanged(); fragment.swipeRefreshLayout.setRefreshing(false); } } } }
36.060606
106
0.741737
21df6e6396b43de93356b052d66438d56cbf66ce
454
package br.com.poupeAi.dto; import io.swagger.v3.oas.annotations.media.Schema; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.validation.constraints.NotNull; import javax.validation.constraints.Positive; @Schema(name = "OutroEnvelopeDto") @Getter @Setter @NoArgsConstructor @EqualsAndHashCode public class OutroEnvelopeDto { @NotNull @Positive private Long id; }
22.7
50
0.801762
b08cd88398ebc057372f70595c40b6886b6d00b3
352
/** * Copyright MaDgIK Group 2010 - 2015. */ package madgik.exareme.worker.arm.compute.containerMgr; import java.io.Serializable; /** * @author Herald Kllapi<br> * herald@di.uoa.gr<br> * University of Athens / * Department of Informatics and Telecommunications. * @since 1.0 */ public class ContainerManagerStatus implements Serializable { }
20.705882
61
0.735795
c39ce58c6a22f436faee61ad7c3b450e4efe34d0
113
public class main { public static void main(String[] args) { System.out.println(data.value); } }
18.833333
44
0.619469
0fd1ae3833693b7226c0aba18607a906c1bf4ab8
542
package slogo.backend.commands.basic.basiccommands; import slogo.backend.commands.basic.BasicCommandInterface; import slogo.backend.utils.TurtleHistory; import java.util.List; /** * @author Erie Seong Ho Han * Implementation of BasicCommandInterface that implements Random command */ public class RandomBasicCommand implements BasicCommandInterface { @Override public double getReturnValue(TurtleHistory turtleHistory, List<Double> parameters, int turtleID) { return (int) (Math.random() * parameters.get(0)); } }
27.1
102
0.773063
25163ed57f0c64e80cd2f93f57d62a17589cf7bc
3,347
/******************************************************************************* * Copyright (c) Intel Corporation * Copyright (c) 2017 * * 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.osc.core.broker.service.mc; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import org.osc.core.broker.model.entities.management.ApplianceManagerConnector; import org.osc.core.broker.model.plugin.ApiFactoryService; import org.osc.core.broker.service.ServiceDispatcher; import org.osc.core.broker.service.api.ListApplianceManagerConnectorServiceApi; import org.osc.core.broker.service.api.server.EncryptionApi; import org.osc.core.broker.service.dto.ApplianceManagerConnectorDto; import org.osc.core.broker.service.dto.BaseDto; import org.osc.core.broker.service.persistence.ApplianceManagerConnectorEntityMgr; import org.osc.core.broker.service.persistence.OSCEntityManager; import org.osc.core.broker.service.request.BaseRequest; import org.osc.core.broker.service.response.ListResponse; import org.osc.core.common.manager.ManagerType; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; @Component public class ListApplianceManagerConnectorService extends ServiceDispatcher<BaseRequest<BaseDto>, ListResponse<ApplianceManagerConnectorDto>> implements ListApplianceManagerConnectorServiceApi { @Reference private EncryptionApi encryption; @Reference private ApiFactoryService apiFactoryService; @Override public ListResponse<ApplianceManagerConnectorDto> exec(BaseRequest<BaseDto> request, EntityManager em) throws Exception { ListResponse<ApplianceManagerConnectorDto> response = new ListResponse<>(); // Initializing Entity Manager OSCEntityManager<ApplianceManagerConnector> emgr = new OSCEntityManager<>(ApplianceManagerConnector.class, em, this.txBroadcastUtil); // to do mapping List<ApplianceManagerConnectorDto> mcmList = new ArrayList<>(); // mapping all the MC objects to mc dto objects for (ApplianceManagerConnector mc : emgr.listAll("name")) { ApplianceManagerConnectorDto dto = new ApplianceManagerConnectorDto(); ApplianceManagerConnectorEntityMgr.fromEntity(mc, dto, this.encryption); if (request.isApi()) { ApplianceManagerConnectorDto.sanitizeManagerConnector(dto); } boolean isPolicyMappingSupported = this.apiFactoryService.syncsPolicyMapping(ManagerType.fromText(mc.getManagerType())); dto.setPolicyMappingSupported(isPolicyMappingSupported); mcmList.add(dto); } response.setList(mcmList); return response; } }
43.467532
141
0.731999
a5bd76e2c9f76fb6c0727a6c73b720980350a69e
5,118
package io.github.ititus.aoc.aoc21.day22; import io.github.ititus.math.vector.Vec3i; import java.util.Optional; import java.util.stream.Stream; public record Cuboid( Vec3i min, Vec3i max ) { public Cuboid { if (min.x() > max.x() || min.y() > max.y() || min.z() > max.z()) { throw new IllegalArgumentException(); } } public boolean contains(Vec3i v) { return min.x() <= v.x() && v.x() <= max.x() && min.y() <= v.y() && v.y() <= max.y() && min.z() <= v.z() && v.z() <= max.z(); } public boolean contains(Cuboid c) { return min.x() <= c.min.x() && c.max.x() <= max.x() && min.y() <= c.min.y() && c.max.y() <= max.y() && min.z() <= c.min.z() && c.max.z() <= max.z(); } public long volume() { return (long) (max.x() - min.x() + 1) * (long) (max.y() - min.y() + 1) * (long) (max.z() - min.z() + 1); } public boolean intersects(Cuboid that) { return intersection(that).isPresent(); } public Optional<Cuboid> intersection(Cuboid that) { if (this.contains(that)) { return Optional.of(that); } else if (that.contains(this)) { return Optional.of(this); } int minX = Math.max(this.min.x(), that.min.x()); int maxX = Math.min(this.max.x(), that.max.x()); if (minX > maxX) { return Optional.empty(); } int minY = Math.max(this.min.y(), that.min.y()); int maxY = Math.min(this.max.y(), that.max.y()); if (minY > maxY) { return Optional.empty(); } int minZ = Math.max(this.min.z(), that.min.z()); int maxZ = Math.min(this.max.z(), that.max.z()); if (minZ > maxZ) { return Optional.empty(); } return Optional.of(new Cuboid(new Vec3i(minX, minY, minZ), new Vec3i(maxX, maxY, maxZ))); } public Stream<Cuboid> difference(Cuboid that) { if (that.contains(this)) { return Stream.of(); } else if (!intersects(that)) { return Stream.of(this); } Optional<Cuboid> inv1; if (this.min.z() < that.min.z()) { inv1 = Optional.of(new Cuboid( this.min, new Vec3i(this.max.x(), this.max.y(), that.min.z() - 1) )); } else { inv1 = Optional.empty(); } Optional<Cuboid> inv2; if (this.max.z() > that.max.z()) { inv2 = Optional.of(new Cuboid( new Vec3i(this.min.x(), this.min.y(), that.max.z() + 1), this.max )); } else { inv2 = Optional.empty(); } Optional<Cuboid> inv3; if (this.min.y() < that.min.y()) { inv3 = Optional.of(new Cuboid( inv1.map(c -> new Vec3i(this.min.x(), this.min.y(), c.max.z() + 1)).orElseGet(this::min), inv2.map(c -> new Vec3i(this.max.x(), that.min.y() - 1, c.min.z() - 1)).orElseGet(() -> new Vec3i(this.max.x(), that.min.y() - 1, this.max.z())) )); } else { inv3 = Optional.empty(); } Optional<Cuboid> inv4; if (this.max.y() > that.max.y()) { inv4 = Optional.of(new Cuboid( inv1.map(c -> new Vec3i(this.min.x(), that.max.y() + 1, c.max.z() + 1)).orElseGet(() -> new Vec3i(this.min.x(), that.max.y() + 1, this.min.z())), inv2.map(c -> new Vec3i(this.max.x(), this.max.y(), c.min.z() - 1)).orElseGet(this::max) )); } else { inv4 = Optional.empty(); } Optional<Cuboid> inv5; if (this.min.x() < that.min.x()) { int minZ = inv1.isPresent() ? inv1.get().max.z() + 1 : this.min.z(); int minY = inv3.isPresent() ? inv3.get().max.y() + 1 : this.min.y(); int minX = this.min.x(); int maxZ = inv2.isPresent() ? inv2.get().min.z() - 1 : this.max.z(); int maxY = inv4.isPresent() ? inv4.get().min.y() - 1 : this.max.y(); int maxX = that.min.x() - 1; inv5 = Optional.of(new Cuboid(new Vec3i(minX, minY, minZ), new Vec3i(maxX, maxY, maxZ))); } else { inv5 = Optional.empty(); } Optional<Cuboid> inv6; if (this.max.x() > that.max.x()) { int minZ = inv1.isPresent() ? inv1.get().max.z() + 1 : this.min.z(); int minY = inv3.isPresent() ? inv3.get().max.y() + 1 : this.min.y(); int minX = that.max.x() + 1; int maxZ = inv2.isPresent() ? inv2.get().min.z() - 1 : this.max.z(); int maxY = inv4.isPresent() ? inv4.get().min.y() - 1 : this.max.y(); int maxX = this.max.x(); inv6 = Optional.of(new Cuboid(new Vec3i(minX, minY, minZ), new Vec3i(maxX, maxY, maxZ))); } else { inv6 = Optional.empty(); } return Stream.of(inv1, inv2, inv3, inv4, inv5, inv6) .flatMap(Optional::stream); } }
35.296552
165
0.472059
ceec94556737d267273106c6a0dd8d0ddf7530a1
3,468
package com.lothrazar.cyclic; import com.lothrazar.cyclic.compat.curios.CuriosRegistry; import com.lothrazar.cyclic.event.ClientInputEvents; import com.lothrazar.cyclic.event.EventRender; import com.lothrazar.cyclic.event.ItemEvents; import com.lothrazar.cyclic.event.PlayerAbilityEvents; import com.lothrazar.cyclic.event.PlayerDataEvents; import com.lothrazar.cyclic.event.PotionEvents; import com.lothrazar.cyclic.event.WorldGenEvents; import com.lothrazar.cyclic.registry.BlockRegistry; import com.lothrazar.cyclic.registry.ClientRegistry; import com.lothrazar.cyclic.registry.CommandRegistry; import com.lothrazar.cyclic.registry.FluidRegistry; import com.lothrazar.cyclic.registry.ItemRegistry; import com.lothrazar.cyclic.registry.PacketRegistry; import com.lothrazar.cyclic.registry.PotionRegistry; import com.lothrazar.cyclic.registry.RecipeRegistry; import com.lothrazar.cyclic.registry.TileRegistry; import com.lothrazar.cyclic.registry.WorldGenRegistry; import net.minecraft.item.crafting.IRecipeSerializer; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import net.minecraftforge.fml.loading.FMLPaths; import org.apache.logging.log4j.LogManager; // The value here should match an entry in the META-INF/mods.toml file @Mod(ModCyclic.MODID) public class ModCyclic { public static final String MODID = "cyclic"; public static final CyclicLogger LOGGER = new CyclicLogger(LogManager.getLogger()); public ModCyclic() { FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setupClient); ConfigRegistry.setup(FMLPaths.CONFIGDIR.get().resolve(MODID + ".toml")); FluidRegistry.setup(); //why is this event so freakin weird //https://github.com/Minecraft-Forge-Tutorials/Custom-Json-Recipes/blob/master/src/main/java/net/darkhax/customrecipeexample/CustomRecipesMod.java FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(IRecipeSerializer.class, RecipeRegistry::registerRecipeSerializers); MinecraftForge.EVENT_BUS.register(new CommandRegistry()); MinecraftForge.EVENT_BUS.register(new EventRender()); IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus(); BlockRegistry.BLOCKS.register(bus); ItemRegistry.ITEMS.register(bus); TileRegistry.TILES.register(bus); } private void setupClient(final FMLClientSetupEvent event) { ClientRegistry.setup(); } private void setup(final FMLCommonSetupEvent event) { //now all blocks/items exist CuriosRegistry.setup(event); PotionRegistry.setup(event); PacketRegistry.setup(); WorldGenRegistry.setup(); //TODO: maybe move all the following into the constructor, not here in setup? from forge discord //but crashes when i do with NPE so MinecraftForge.EVENT_BUS.register(new ClientInputEvents()); MinecraftForge.EVENT_BUS.register(new PotionEvents()); MinecraftForge.EVENT_BUS.register(new ItemEvents()); MinecraftForge.EVENT_BUS.register(new WorldGenEvents()); MinecraftForge.EVENT_BUS.register(new PlayerDataEvents()); MinecraftForge.EVENT_BUS.register(new PlayerAbilityEvents()); } }
46.864865
150
0.805075
013dcca8fd44b1f829ca7f5815df2cf3ee2c25e9
6,145
package net.whydah.sso.application; import net.whydah.sso.application.helpers.ApplicationHelper; import net.whydah.sso.application.mappers.ApplicationMapper; import net.whydah.sso.application.types.Application; import net.whydah.sso.basehelpers.JsonPathHelper; import net.whydah.sso.whydah.DEFCON; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import java.util.List; import static org.junit.Assert.*; import static org.slf4j.LoggerFactory.getLogger; public class ApplicationTest { private static final Logger log = getLogger(ApplicationTest.class); @Before public void setUp() throws Exception { } @Test public void testDefaultValuesInApplication() throws Exception { Application a = new Application("AppId", "appName"); log.debug(ApplicationMapper.toPrettyJson(a)); assertTrue(DEFCON.DEFCON5 == a.getSecurity().getMinimumDEFCONLevel()); assertTrue(0 == a.getSecurity().getMinSecurityLevel()); assertTrue(Boolean.valueOf(a.getSecurity().getUserTokenFilter())); assertFalse(a.isFullTokenApplication()); } @Test public void testValidFullTokenApplications() { List<Application> applications = ApplicationMapper.fromJsonList(ApplicationHelper.getDummyAppllicationListJson()); for (Application application : applications) { log.debug("has usertokenfilter {} appid:{}", Boolean.valueOf(application.getSecurity().getUserTokenFilter()), application.getId()); } } @Test public void testGetParameterForApplication_minSecurityLevel() { String param = "$.security.minSecurityLevel"; String applicationID = "2211"; List<Application> applications = ApplicationMapper.fromJsonList(ApplicationHelper.getDummyAppllicationListJson()); for (Application application : applications) { if (applicationID.equalsIgnoreCase(application.getId())) { log.info("Found application {}, looking for {}", ApplicationMapper.toPrettyJson(application), param); log.trace(JsonPathHelper.findJsonPathValue(ApplicationMapper.toPrettyJson(application), param)); } } } @Test public void testGetParameterForApplication_maxSessionTimeoutSeconds() { String param = "$.security.maxSessionTimeoutSeconds"; String applicationID = "2211"; List<Application> applications = ApplicationMapper.fromJsonList(ApplicationHelper.getDummyAppllicationListJson()); for (Application application : applications) { if (applicationID.equalsIgnoreCase(application.getId())) { log.info("Found application {}, looking for {}", ApplicationMapper.toJson(application), param); log.trace(JsonPathHelper.findJsonPathValue(ApplicationMapper.toPrettyJson(application), param)); } } } @Test public void testIfSecurityGetsMissing() { String applicationJson = "{\n" + " \"id\": \"100\",\n" + " \"name\": \"ACS\",\n" + " \"description\": \"Finn den kompetansen du trenger, når du trenger det. Lag eksklusive CV'er tillpasset leseren.\",\n" + " \"company\": \"Norway AS\",\n" + " \"tags\": \"HIDDEN, JURISDICTION_NORWAY\",\n" + " \"applicationUrl\": null,\n" + " \"logoUrl\": null,\n" + " \"roles\": [\n" + " {\n" + " \"id\": \"acs101\",\n" + " \"name\": \"Employee\"\n" + " },\n" + " {\n" + " \"id\": \"acs102\",\n" + " \"name\": \"Manager\"\n" + " },\n" + " {\n" + " \"id\": \"acs103\",\n" + " \"name\": \"Administrator\"\n" + " }\n" + " ],\n" + " \"defaultRoleName\": \"Employee\",\n" + " \"orgs\": [\n" + " {\n" + " \"id\": \"100\",\n" + " \"name\": \"Whydah\"\n" + " },\n" + " {\n" + " \"id\": \"101\",\n" + " \"name\": \"Cantara\"\n" + " },\n" + " {\n" + " \"id\": \"102\",\n" + " \"name\": \"Getwhydah\"\n" + " }\n" + " ],\n" + " \"defaultOrganizationName\": \"ACSOrganization\",\n" + " \"security\": {\n" + " \"minSecurityLevel\": \"0\",\n" + " \"minDEFCON\": \"DEFCON5\",\n" + " \"maxSessionTimeoutSeconds\": \"86400\",\n" + " \"allowedIpAddresses\": [\n" + " \"0.0.0.0/0\"\n" + " ],\n" + " \"userTokenFilter\": \"true\",\n" + " \"secret\": \"45fhRM6nbKZ2wfC6RMmMuzXpk\"\n" + " },\n" + " \"acl\": [\n" + " {\n" + " \"applicationId\": \"111\",\n" + " \"applicationACLPath\": \"/user\",\n" + " \"accessRights\": null\n" + " }\n" + " ],\n" + " \"organizationNames\": [\n" + " {\n" + " \"id\": \"100\",\n" + " \"name\": \"Whydah\"\n" + " },\n" + " {\n" + " \"id\": \"101\",\n" + " \"name\": \"Cantara\"\n" + " },\n" + " {\n" + " \"id\": \"102\",\n" + " \"name\": \"Getwhydah\"\n" + " }\n" + " ],\n" + " \"secret\": \"45fhRM6nbKZ2wfC6RMmMuzXpk\"\n" + "}"; Application testApp = ApplicationMapper.fromJson(applicationJson); assertNotNull(testApp.getSecurity()); } }
39.645161
143
0.477299
54f11d53f4da530865bc981890ab02c4ebea409c
3,069
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.search.documents.indexes.models; import com.azure.core.annotation.Fluent; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; /** * Base type for tokenizers. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "@odata.type", defaultImpl = LexicalTokenizer.class) @JsonTypeName("LexicalTokenizer") @JsonSubTypes({ @JsonSubTypes.Type(name = "#Microsoft.Azure.Search.ClassicTokenizer", value = ClassicTokenizer.class), @JsonSubTypes.Type(name = "#Microsoft.Azure.Search.EdgeNGramTokenizer", value = EdgeNGramTokenizer.class), @JsonSubTypes.Type(name = "#Microsoft.Azure.Search.KeywordTokenizer", value = KeywordTokenizer.class), @JsonSubTypes.Type(name = "#Microsoft.Azure.Search.KeywordTokenizerV2", value = KeywordTokenizer.class), @JsonSubTypes.Type(name = "#Microsoft.Azure.Search.MicrosoftLanguageTokenizer", value = MicrosoftLanguageTokenizer.class), @JsonSubTypes.Type(name = "#Microsoft.Azure.Search.MicrosoftLanguageStemmingTokenizer", value = MicrosoftLanguageStemmingTokenizer.class), @JsonSubTypes.Type(name = "#Microsoft.Azure.Search.NGramTokenizer", value = NGramTokenizer.class), @JsonSubTypes.Type(name = "#Microsoft.Azure.Search.PathHierarchyTokenizerV2", value = PathHierarchyTokenizer.class), @JsonSubTypes.Type(name = "#Microsoft.Azure.Search.PatternTokenizer", value = PatternTokenizer.class), @JsonSubTypes.Type(name = "#Microsoft.Azure.Search.StandardTokenizer", value = LuceneStandardTokenizer.class), @JsonSubTypes.Type(name = "#Microsoft.Azure.Search.UaxUrlEmailTokenizer", value = UaxUrlEmailTokenizer.class) }) @Fluent public abstract class LexicalTokenizer { /* * The name of the tokenizer. It must only contain letters, digits, spaces, * dashes or underscores, can only start and end with alphanumeric * characters, and is limited to 128 characters. */ @JsonProperty(value = "name", required = true) private String name; /** * Get the name property: The name of the tokenizer. It must only contain * letters, digits, spaces, dashes or underscores, can only start and end * with alphanumeric characters, and is limited to 128 characters. * * @return the name value. */ public String getName() { return this.name; } /** * Set the name property: The name of the tokenizer. It must only contain * letters, digits, spaces, dashes or underscores, can only start and end * with alphanumeric characters, and is limited to 128 characters. * * @param name the name value to set. * @return the LexicalTokenizer object itself. */ public LexicalTokenizer setName(String name) { this.name = name; return this; } }
45.132353
114
0.730857
441a40a372c331b68a3fb3e9b6b3552d276b6dce
2,978
/*- * #%L * Genome Damage and Stability Centre Test API * * Contains a generic framework for test predicates. * %% * Copyright (C) 2018 - 2022 Alex Herbert * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package uk.ac.sussex.gdsc.test.api; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @SuppressWarnings("javadoc") class ClassesTest { @Test void testGetClassName() { Assertions.assertEquals("null", Classes.getClassName(null)); // Objects final Integer zero = Integer.valueOf(0); Assertions.assertEquals("java.lang.Integer", Classes.getClassName(zero)); final Class<?> clazz = zero.getClass(); Assertions.assertEquals("java.lang.Integer", Classes.getClassName(clazz)); Assertions.assertEquals("java.lang.String", Classes.getClassName(String.class)); @SuppressWarnings("serial") final Object anonymous = new java.io.Serializable() { // Do nothing }; final String expected = this.getClass().getName() + "$1"; Assertions.assertEquals(expected, Classes.getClassName(anonymous)); Assertions.assertEquals(expected, Classes.getClassName(anonymous.getClass())); } @Test void testGetArrayClassName() { Assertions.assertEquals("boolean[]", Classes.getArrayClassName(new boolean[0])); Assertions.assertEquals("byte[]", Classes.getArrayClassName(new byte[0])); Assertions.assertEquals("char[]", Classes.getArrayClassName(new char[0])); Assertions.assertEquals("double[]", Classes.getArrayClassName(new double[0])); Assertions.assertEquals("float[]", Classes.getArrayClassName(new float[0])); Assertions.assertEquals("int[]", Classes.getArrayClassName(new int[0])); Assertions.assertEquals("long[]", Classes.getArrayClassName(new long[0])); Assertions.assertEquals("short[]", Classes.getArrayClassName(new short[0])); Assertions.assertEquals("null", Classes.getArrayClassName(null)); Assertions.assertEquals("java.lang.String", Classes.getArrayClassName(String.class)); Assertions.assertEquals("byte", Classes.getArrayClassName(byte.class)); Assertions.assertEquals("java.lang.Object[]", Classes.getArrayClassName(new Object[0])); Assertions.assertEquals("int[][]", Classes.getArrayClassName(new int[0][0])); Assertions.assertEquals("int[][][]", Classes.getArrayClassName(new int[0][0][0])); Assertions.assertEquals("java.lang.Integer[][]", Classes.getArrayClassName(new Integer[0][0])); } }
41.943662
99
0.725991
de5eca93b59131c9f59989e201611d22b409e458
300
package com.teammatch.resource; import lombok.Data; import javax.persistence.Lob; import javax.validation.constraints.NotNull; @Data public class SaveMessageResource { @Lob @NotNull private String message; @NotNull private String sentDate; private boolean isHyperLink; }
15.789474
44
0.746667
c0531e1ddbf43b02350e7846a2ad2ac89d19f59b
7,860
/* * Copyright (c) 2019. Hubery * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package pers.hubery.collapsar.utils; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.NoSuchElementException; /** * 环 * <p>首尾相连的链表组成,指针只能单向移动</p> * * @param <T> the type parameter * @author hubery */ public class Annular<T> implements Iterable<T> { /** * The number of times this Annular has been <i>structurally modified</i>. * Structural modifications are those that change the length of the * Annular, or otherwise perturb it in such a fashion that iterations in * progress may yield incorrect results. */ private transient int modCount = 0; /** 指针,当前位置 */ private AnnularNode<T> cursor; /** 上一位置 */ private AnnularNode<T> previous; /** 环的长度 */ private int length = 0; /** * Instantiates a new Annular. */ public Annular() { } /** * Instantiates a new Annular. * * @param collection the collection */ public Annular(Collection<T> collection) { for (T item : collection) { addNode(item); } } /** * 返回当前元素,并移到下一节点 * * @return 当前元素 t */ public T next() { T obj = this.cursor.obj; this.previous = this.cursor; this.cursor = this.cursor.next; return obj; } /** * 返回当前元素,指针不动 * * @return 当前元素 t */ public T peek() { return this.cursor.obj; } /** * 获取当前环的长度 * * @return 当前环的长度 length */ public int getLength() { return length; } /** * Is empty . * * @return the boolean */ public boolean isEmpty() { return length == 0; } /** * 添加一个对象 * * @param obj the obj */ public final void addNode(T obj) { if (cursor == null) { // 一个元素时,指向自身 this.cursor = new AnnularNode<T>(); this.cursor.obj = obj; this.cursor.next = this.cursor; //只有一个元素时,上一元素也指向自身 this.previous = this.cursor; this.length = 1; } else { //新增一个节点,插进当前位置的上一位置 AnnularNode<T> annularNode = new AnnularNode<T>(); annularNode.obj = obj; annularNode.next = this.cursor; this.previous.next = annularNode; this.previous = annularNode; this.length++; } } /** * 移除并返回当前节点,指针将移到下一节点 * * @return 被移除的节点对象 t */ public T remove() { //要返回的结果 final T result = this.cursor.obj; if (this.cursor == this.previous) { this.cursor = null; this.previous = null; this.length = 0; } else { //移除当前节点 this.cursor = this.cursor.next; this.previous.next = this.cursor; this.length--; } return result; } /** * @see Object#toString() */ @Override public String toString() { StringBuilder stringBuilder = new StringBuilder("Annular["); for (T node : this) { stringBuilder.append(node.toString()).append(","); } stringBuilder.append("]"); return stringBuilder.toString(); } /** * Returns an iterator over elements of type {@code T}. * * @return an Iterator. */ @Override public Iterator<T> iterator() { return new AnnularItr(); } /** * 环节点 * * @param <T> the type parameter */ private class AnnularNode<T> { /** * The Obj. */ T obj; /** * The Next. */ AnnularNode<T> next; /** * @see Object#toString() */ @Override public String toString() { return obj.toString(); } } /** * 环遍历器 */ private class AnnularItr implements Iterator<T> { /** 开始节点,用于判断是否已经结束 */ final AnnularNode<T> startNode = cursor; /** 游标 */ AnnularNode<T> cur = cursor; /** * The modCount value that the iterator believes that the backing * List should have. If this expectation is violated, the iterator * has detected concurrent modification. */ int expectedModCount = modCount; /** * Returns {@code true} if the iteration has more elements. * (In other words, returns {@code true} if {@link #next} would * return an element rather than throwing an exception.) * * @return {@code true} if the iteration has more elements */ @Override public boolean hasNext() { return this.cur != null; } /** * Returns the next element in the iteration. * * @return the next element in the iteration * @throws NoSuchElementException if the iteration has no more elements */ @Override public T next() { checkForComodification(); if (this.cur == null) { throw new NoSuchElementException(); } T next = this.cur.obj; if (this.cur.next == this.startNode) { //说明已经结束了 this.cur = null; } else { this.cur = this.cur.next; } return next; } /** * Removes from the underlying collection the last element returned * by this iterator (optional operation). This method can be called * only once per call to {@link #next}. The behavior of an iterator * is unspecified if the underlying collection is modified while the * iteration is in progress in any way other than by calling this * method. * * @throws UnsupportedOperationException if the {@code remove} * operation is not supported by this iterator * @throws IllegalStateException if the {@code next} method has not * yet been called, or the {@code remove} method has already * been called after the last call to the {@code next} * method * @implSpec The default implementation throws an instance of * {@link UnsupportedOperationException} and performs no other action. */ @Override public void remove() { throw new UnsupportedOperationException("remove"); } /** * 检查迭代过程中,环有没有被修改(不能增加或减少节点) */ final void checkForComodification() { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } } }
25.519481
94
0.562595
7cae5af186f8aee7bd94a514148c2828833eb066
344
package com.penglecode.xmodule.common.mybatis; /** * 数据库分页之mysql * * @author pengpeng * @date 2014年8月1日 下午3:53:41 * @version 1.0 */ public class MySQLDialect implements Dialect { public String getLimitSql(String sql, int offset, int limit) { sql = sql + " limit " + offset + ", " + limit; return sql; } }
20.235294
64
0.622093
011e97f15ca87df5ec23d212852aedf7b3136002
797
package io.github.kavahub.learnjava; import java.net.URL; import java.net.URLConnection; import io.github.kavahub.learnjava.util.UrlConnection; /** * * Http 代理 * * @author PinWei Wan * @since 1.0.0 */ public class ProxyWithSystemPropertyExample { public static final String RESOURCE_URL = "http://cn.bing.com"; public static void main(String[] args) throws Exception { System.setProperty("https.proxyHost", "127.0.0.1"); System.setProperty("https.proxyPort", "3128"); URL url = new URL(RESOURCE_URL); URLConnection con = url.openConnection(); System.out.println(UrlConnection.contentAsString(con)); // 清除变量 System.clearProperty("https.proxyHost"); // proxy will no longer be used for http connections } }
24.90625
67
0.673777
504e73bfb66a0c21592773b208f0de3e6eefc8e3
1,076
package uk.ac.bris.cs.databases.api; import java.util.List; /** * Detail view of a single forum, advanced version (more topic info). * @author csxdb */ public class AdvancedForumView { /* The id of this forum. */ private final long id; /* The title of this forum. */ private final String title; /* The topics in this forum ordered by most recent post. * If none, an empty list (never null). */ private final List<TopicSummaryView> topics; public AdvancedForumView(long id, String title, List<TopicSummaryView> topics) { this.id = id; this.title = title; this.topics = topics; } /** * @return the title */ public String getTitle() { return title; } /** * @return the topics */ public List<TopicSummaryView> getTopics() { return topics; } /** * @return the id */ public long getId() { return id; } }
20.692308
70
0.526022
51a423596902fb3b88752ca7e0ef2816f5912cf2
5,959
package com.cskaoyan.controller; import com.cskaoyan.bean.BaseRespVo; import com.cskaoyan.bean.Comment; import com.cskaoyan.bean.ListCondition; import com.cskaoyan.bean.topic; import com.cskaoyan.service.WxTopicService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.Map; @RestController public class WxTopicController { @Autowired WxTopicService wxTopicService; /** * 专题 */ /** * 功能: * 显示专题内容 * * 请求体: * page: 1 * size: 10 * * 响应体: * { * "errno": 0, * "data": { * "data": [{ * "id": 330, * "title": "12", * "subtitle": "12", * "price": 12.00, * "readCount": "12", * "picUrl": "http://192.168.2.100:8081/wx/storage/123.png" * }], * "count": 23 * }, * "errmsg": "成功" * } */ @RequestMapping("wx/topic/list") public BaseRespVo wxSelectTopic(ListCondition listCondition) { BaseRespVo<Object> baseRespVo = new BaseRespVo<>(); Map<Object, Object> map = wxTopicService.wxSelectTopic(listCondition); baseRespVo.setErrno(0); baseRespVo.setErrmsg("查询成功"); baseRespVo.setData(map); return baseRespVo; } /** * 专题详情 */ /** * 功能: * 显示专题详情 * * 请求体: * id:281 * * 响应体: * { * "errno": 0, * "data": { * "topic": { * "id": 281, * "title": "条纹新风尚", * "subtitle": "经典百搭,时尚线条", * "price": 29.00, * "readCount": "76.5k", * "picUrl": "https://yanxuan.nosdn.127.net/0826.jpg", * "sortOrder": 0, * "goods": [], * "addTime": "2018-01-31 19:00:00", * "updateTime": "2018-01-31 19:00:00", * "deleted": false, * "content": "<img src=\"//yanxuan.nosdn.127.net/75c55a.jpg\">" * }, * "goods": []* }, * "errmsg": "成功" * } */ @RequestMapping("wx/topic/detail") public BaseRespVo wxTopicDetail(topic toPic) { BaseRespVo<Object> baseRespVo = new BaseRespVo<>(); Map<Object, Object> map = wxTopicService.wxTopicDetail(toPic); baseRespVo.setErrno(0); baseRespVo.setErrmsg("查询成功"); baseRespVo.setData(map); return baseRespVo; } /** * 功能: * 专题相关/推荐 * * 请求体: * id: 281 * * 响应体: * { * "errno": 0, * "data": [专题数据,专题数据], * "errmsg": "成功" * } */ @RequestMapping("wx/topic/related") public BaseRespVo wxTopicRealated(topic toPic) { BaseRespVo<Object> baseRespVo = new BaseRespVo<>(); List<topic> topicLists = wxTopicService.wxTopicRelated(toPic); if (topicLists == null) { baseRespVo.setErrno(500); baseRespVo.setErrmsg("没有相关专题"); } else { baseRespVo.setErrno(0); baseRespVo.setErrmsg("查询成功"); baseRespVo.setData(topicLists); } return baseRespVo; } /** * 专题评论列表 */ /** * 功能: * 显示评论数量 * * 请求体: * valueId: 314 * type: 1 * * 响应体: * { * "errno": 0, * "data": { * "hasPicCount": 1, * "allCount": 8 * }, * "errmsg": "成功" * } */ @RequestMapping("wx/comment/count") public BaseRespVo wxCommentCount(ListCondition listCondition) { BaseRespVo<Object> baseRespVo = new BaseRespVo<>(); Map<Object,Object> map = wxTopicService.wxCommentCount(listCondition); baseRespVo.setErrno(0); baseRespVo.setErrmsg("查询成功"); baseRespVo.setData(map); return baseRespVo; } /** * 功能: * 显示评论列表 * * 请求体: * valueId: 314 * type: 1 * size: 20 * page: 1 * showType: 0 * * 响应体: * { * "errno": 0, * "data": { * "data": [{ * "userInfo": { * "nickName": "dr lan", * "avatarUrl": "" * }, * "addTime": "2019-12-31 08:06:15", * "picList": ["http://192.168.2.100:8081/wx.jpg"], * "content": "321"}], * "count": 8, * "currentPage": 1 * }, * "errmsg": "成功" * } */ @RequestMapping("wx/comment/list") public BaseRespVo wxCommentList(ListCondition listCondition) { BaseRespVo<Object> baseRespVo = new BaseRespVo<>(); Map map = wxTopicService.wxUserComment(listCondition); baseRespVo.setErrno(0); baseRespVo.setErrmsg("成功"); baseRespVo.setData(map); return baseRespVo; } /** * 专题评论添加 */ /** * 功能: * 发表评论 * * 请求体: * content: "1" * hasPicture: true * picUrls: ["http://192.168.2.100:8081/wx/c3st.png"] * star: 5 * type: 1 * valueId: "314" * * 响应体: * { * "errno": 0, * "data": { * "id": 1032, * "valueId": 314, * "type": 1, * "content": "1", * "userId": 1, * "hasPicture": true, * "picUrls": ["http://192.168.2.100:8081/wx/c3st.png"], * "star": 5, * "addTime": "2020-01-01 20:29:11", * "updateTime": "2020-01-01 20:29:11" * }, * "errmsg": "成功" * } * post请求 */ @RequestMapping("wx/comment/post") public BaseRespVo wxCommentPost(@RequestBody Comment comment) { BaseRespVo<Object> baseRespVo = new BaseRespVo<>(); Comment comment1 = wxTopicService.wxCommentPost(comment); baseRespVo.setErrno(0); baseRespVo.setErrmsg("添加成功"); baseRespVo.setData(comment1); return baseRespVo; } }
22.919231
78
0.505118
6d1cbc06054a080af394c70fa28ec14028ebc482
111
package com.example.complaintSystem.model.Util; public enum ComplaintType { EAU, DECHETS, ELECTRICITE }
13.875
47
0.765766
7a10b478c401a873aeb9647784626ed44e2da1f4
857
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode trimBST(final TreeNode root, final int L, final int R) { return trimLeft(trimRight(root, R), L); } private static TreeNode trimLeft(final TreeNode root, final int L) { if (root == null) return null; if (root.val < L) return trimLeft(root.right, L); root.left = trimLeft(root.left, L); return root; } private static TreeNode trimRight(final TreeNode root, final int R) { if (root == null) return null; if (root.val > R) return trimRight(root.left, R); root.right = trimRight(root.right, R); return root; } }
25.969697
76
0.564761
cb8f8e679d3db8b122ed2b769be5017a45044032
1,227
package br.com.vindi.models; import com.google.gson.annotations.SerializedName; public class PaymentMethod { public enum Method { CASH("cash"), CREDIT_CARD("credit_card"); private final String value; Method(final String value) { this.value = value; } public String string() { return value; } } private Long id; @SerializedName("public_name") private String publicName; private String name; private String code; private String type; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getPublicName() { return publicName; } public void setPublicName(String publicName) { this.publicName = publicName; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
17.041667
50
0.568052
f55f0abe3dacea321e17f5cbed793128ad0cdacf
231
package top.freerf.study.swipe.session; import top.freerf.study.swipe.sys.user.entity.User; import javax.servlet.http.HttpServletRequest; public interface LoginUserAware { User getCurrentLoginUser(HttpServletRequest req); }
23.1
53
0.813853
74f6687a939a8a2f8c7a1b8fedb34ca9401c29b2
1,264
package netcracker.study.monopoly.converters; import netcracker.study.monopoly.api.controllers.websocket.PlayersTracking; import netcracker.study.monopoly.api.dto.PlayerInfo; import netcracker.study.monopoly.models.entities.Player; import org.springframework.stereotype.Component; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; @Component public class PlayerInfoConverter { private final PlayersTracking playersTracking; public PlayerInfoConverter(PlayersTracking playersTracking) { this.playersTracking = playersTracking; } public PlayerInfo toDto(Player player) { PlayerInfo playerInfo = new PlayerInfo(); String playerStatus = playersTracking.getPlayerStatus(player.getId()); playerInfo.setStatus(playerStatus); playerInfo.setNickname(player.getNickname()); playerInfo.setAvatarUrl(player.getAvatarUrl()); playerInfo.setId(player.getId()); return playerInfo; } public List<PlayerInfo> toDtoAll(Collection<Player> players) { return players.stream() .map(this::toDto) .sorted((o1, o2) -> o2.getStatus().equals("Offline") ? -1 : 1) .collect(Collectors.toList()); } }
32.410256
78
0.714399
26430ac89f0a5f1432bea2ce376ea7a9598dc580
1,240
package fr.openwide.core.jpa.config.spring.provider; import java.sql.Driver; import org.springframework.beans.factory.annotation.Value; public class DatabaseConnectionPoolConfigurationProvider implements IDatabaseConnectionPoolConfigurationProvider { @Value("${${db.type}.db.driverClass}") private Class<Driver> driverClass; @Value("${db.jdbcUrl}") private String url; @Value("${db.user}") private String user; @Value("${db.password}") private String password; @Value("${db.minIdle}") private int minIdle; @Value("${db.maxPoolSize}") private int maxPoolSize; @Value("${${db.type}.db.preferredTestQuery}") private String validationQuery; @Value("${db.initSql}") private String initSql; @Override public Class<Driver> getDriverClass() { return driverClass; } @Override public String getUrl() { return url; } @Override public String getUser() { return user; } @Override public String getPassword() { return password; } @Override public int getMinIdle() { return minIdle; } @Override public int getMaxPoolSize() { return maxPoolSize; } @Override public String getValidationQuery() { return validationQuery; } @Override public String getInitSql() { return initSql; } }
16.756757
114
0.721774
806f6cbbe07be1bde3d07f8ea52dc775c3214716
1,960
package org.mxretrv.dns; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import java.util.ArrayList; import java.util.Collections; import java.util.Hashtable; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public final class MXRecordRetriever { private MXRecordRetriever() { throw new IllegalStateException("Utility Class"); } /** * Get MX records of a given domain name as an array * * @param domain domain name * @return list of MX records for the domain. If there are no records, null is returned. * @throws NamingException exception */ public static List<String> mxRecords(String domain) throws NamingException { Attribute mx = mxAttr(domain); if (mx == null) return Collections.singletonList(""); NamingEnumeration<?> nEnum = mx.getAll(); List<String> records = new ArrayList<>(); while (nEnum.hasMore()) { String mxRaw = (String) (nEnum.next()); Matcher m = Pattern.compile("\\p{Alpha}").matcher(mxRaw); int ind = 0; if (m.find()) ind = m.start(); String mxExcludePriority = mxRaw.substring(ind, mxRaw.length() - 1); records.add(mxExcludePriority); } return records; } public static Attribute mxAttr(String hostName ) throws NamingException { Hashtable<String, String> env = new Hashtable<>(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); DirContext ictx = new InitialDirContext( env ); Attributes attrs = ictx.getAttributes( hostName, new String[] { "MX" }); return attrs.get( "MX" ); } }
34.385965
92
0.65051
178760999d73cc42cbc01a213fbe7d6a57742e65
12,977
/* * 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.myfaces.trinidadbuild.plugin.faces.parse; /** * PropertyBean is a Java representation of the faces-config component property * XML element. */ public class PropertyBean extends AttributeBean { public void setUseMaxTime(boolean _useMaxTime) { this._useMaxTime = _useMaxTime; } public boolean getUseMaxTime() { return _useMaxTime; } /** * Sets the name of this property. * * @param propertyName the property name */ public void setPropertyName( String propertyName) { setAttributeName(propertyName); } /** * Returns the name of this property. * * @return the property name */ public String getPropertyName() { return getAttributeName(); } /** * Sets the property class for this property. * * @param propertyClass the property class */ public void setPropertyClass( String propertyClass) { setAttributeClass(propertyClass); } /** * Returns the property class for this property. * * @return the property class */ public String getPropertyClass() { return getAttributeClass(); } /** * Returns the array of parameterized types for this property * if it uses generics. * * @return the array of parameterized types for this property */ public String[] getPropertyClassParameters() { return getAttributeClassParameters(); } /** * Sets the possible values for this property. * * @param propertyValues the property values */ public void setPropertyValues( String[] propertyValues) { _propertyValues = propertyValues; } /** * Returns possible values for this property. * * @return the property values */ public String[] getPropertyValues() { return _propertyValues; } /** * Sets the stateHolder flag of this property. * * @param stateHolder the property stateHolder flag */ public void setStateHolder( boolean stateHolder) { _stateHolder = stateHolder; } /** * Returns stateHolder flag of this property. * * @return the property stateHolder flag */ public boolean isStateHolder() { return _stateHolder; } /** * Sets the mutable value of this property. * * @param mutable the property mutable value */ public void setMutable( String mutable) { _mutable = mutable; } /** * Returns mutable value of this property. * * @return the property mutable value */ public String getMutable() { return _mutable; } /** * Sets the transient flag of this property. * * @param transient_ the property transient flag */ public void setTransient( boolean transient_) { _transient = transient_; } /** * Returns transient flag of this property. * * @return the property transient flag */ public boolean isTransient() { return _transient; } /** * Sets the list flag of this property. * * @param list_ the property list flag */ public void setList( boolean list_) { _list = list_; } /** * Returns list flag of this property. * * @return the property list flag */ public boolean isList() { return _list; } /** * Sets the required flag of this property. * * @param required the property required flag */ public void setRequired( boolean required) { _required = required; } /** * Returns required flag of this property. * * @return the property required flag */ public boolean isRequired() { return _required; } /** * Sets the literalOnly flag of this property. * * @param literalOnly the property literalOnly flag */ public void setLiteralOnly( boolean literalOnly) { _literalOnly = literalOnly; } /** * Returns literalOnly flag of this property. * * @return the property literalOnly flag */ public boolean isLiteralOnly() { return _literalOnly; } /** * Set the property as allowing ${} syntax * @param rtexprvalue the rtexrvalue value */ public void setRtexprvalue(boolean rtexprvalue) { _rtexprvalue = rtexprvalue; } /** * Return the rtexrvalue flag */ public boolean isRtexprvalue() { return _rtexprvalue; } /** * Sets the alias of this property. * * @param aliasOf the property alias */ public void setAliasOf( String aliasOf) { _aliasOf = aliasOf; } /** * Returns the alias of this property. * * @return the property alias */ public String getAliasOf() { return _aliasOf; } /** * Sets the unsupported agents for this property. * * @param unsupportedAgents the unsupported agents */ public void setUnsupportedAgents( String[] unsupportedAgents) { if (unsupportedAgents == null) throw new NullPointerException("unsupportedAgents"); _unsupportedAgents = unsupportedAgents; } /** * Returns unsupported agents for this property. * * @return the unsupported agents */ public String[] getUnsupportedAgents() { return _unsupportedAgents; } /** * Sets the unsupported RenderKits for this property. * * @param unsupportedRenderKits the unsupported RenderKits */ public void setUnsupportedRenderKits( String[] unsupportedRenderKits) { if (unsupportedRenderKits == null) throw new NullPointerException("unsupportedRenderKits"); _unsupportedRenderKits = unsupportedRenderKits; } /** * Returns unsupported RenderKits for this property. * * @return the unsupported RenderKits */ public String[] getUnsupportedRenderKits() { return _unsupportedRenderKits; } /** * Sets the tag attribute excluded flag for this property. * * @param excluded true, if the tag attribute should be excluded; * false, otherwise */ public void setTagAttributeExcluded( boolean excluded) { _tagAttributeExcluded = excluded; } /** * Returns the tag attribute excluded flag for this property. * * @return true, if the tag attribute should be excluded; * false, otherwise */ public boolean isTagAttributeExcluded() { return _tagAttributeExcluded; } /** * Returns true if the property is an enumerated Java type. */ public boolean isEnum() { return _enum; } /** * Returns true if the property is an enumerated Java type. */ public void setEnum(boolean isEnum) { _enum = isEnum; } /** * Returns true if this property is a method binding. * * @return true if this property is a method binding, * otherwise false */ public boolean isMethodBinding() { return ("javax.faces.el.MethodBinding".equals(getPropertyClass())); } /** * Returns true if this property is a method binding. * * @return true if this property is a method binding, * otherwise false */ public boolean isMethodExpression() { return ("javax.el.MethodExpression".equals(getPropertyClass())); } /** * Parses the possible values for this property into a String array * using space as the separator between values. * * @param propertyValues the property values */ public void parsePropertyValues( String propertyValues) { setPropertyValues(propertyValues.split(" ")); } /** * Parses the unsupported agents for this property into a String array * using space as the separator between values. * * @param unsupportedAgents the unsupported agents */ public void parseUnsupportedAgents( String unsupportedAgents) { setUnsupportedAgents(unsupportedAgents.split(" ")); } /** * Parses the unsupported RenderKits for this property into a String array * using space as the separator between values. * * @param unsupportedRenderKits the unsupported RenderKits */ public void parseUnsupportedRenderKits( String unsupportedRenderKits) { setUnsupportedRenderKits(unsupportedRenderKits.split(" ")); } /** * Sets the JSP name of this property. * * @param jspPropertyName the JSP property name */ public void setJspPropertyName( String jspPropertyName) { _jspPropertyName = jspPropertyName; } /** * Returns the JSP name of this property. * * @return the JSP property name */ public String getJspPropertyName() { if (_jspPropertyName == null) return getPropertyName(); return _jspPropertyName; } /** * Sets the field name of this property, when not generating Trinidad components * * @param fieldPropertyName the field property name */ public void setFieldPropertyName( String fieldPropertyName) { _fieldPropertyName = fieldPropertyName; } /** * Returns the field name of this property, when not generating Trinidad components * * @return the field property name */ public String getFieldPropertyName() { if (_fieldPropertyName == null) return "_"+getPropertyName(); return _fieldPropertyName; } /** * If the property should be hidden from documentation * @return If the facet should be hidden */ public boolean isHidden() { return _hidden; } /** * Set if this facet should be hidden from documentation * @param hidden If the facet should be hidden */ public void setHidden(boolean hidden) { this._hidden = hidden; } /** * Sets the property deprecated flag * @param deprecated */ public void setDeprecated(String deprecated) { this._deprecated = deprecated; } /** * Value is provided through the deprecated extended property metadata. * @return deprecated description if the component property should be deprecated */ public String getDeprecated() { return _deprecated; } /** * @return <code>true</code> if the property should be generated with a no-op * setter. */ public boolean isNoOp() { return _noOp; } /** * Invoked if the no-op extended property meta-data is provided for the component * property. */ public void makeNoOp() { this._noOp = true; } /** * Sets the property valueExpression * @param valueExpression */ public void setValueExpression(String valueExpression) { this._valueExpression = valueExpression; // This is for backward compatibility from jsr-276 metadata. The old element // <mfp:literal-only>true</mfp:literal-only> is now // <fmd:value-expression>PROHIBITED</fmd:value-expression>. There are a number of places // that look at literalOnly, so we just make it transparent at the lowest level. if (valueExpression.equals("PROHIBITED")) setLiteralOnly(true); } /** * Value is provided through the valueExpression property metadata. * @return valueExpression of the property */ public String getValueExpression() { return _valueExpression; } /** * Set if this property is overridding a property in an ancestor class. * @param override if overridding a property */ public void setOverride(boolean override) { this._override = override; } /** * Get if this property is overridding a property in an ancestor class. * @return If the property is an overide */ public boolean isOverride() { return _override; } private String _aliasOf; private String _jspPropertyName; private String _fieldPropertyName; private boolean _required; private boolean _literalOnly; private boolean _rtexprvalue; private boolean _stateHolder; private boolean _transient; private boolean _list; private String _mutable; private boolean _tagAttributeExcluded; private boolean _enum; private boolean _useMaxTime; private boolean _hidden; private boolean _override; private String[] _propertyValues; private String[] _unsupportedAgents = _EMPTY_ARRAY; private String[] _unsupportedRenderKits = _EMPTY_ARRAY; private String _deprecated; private boolean _noOp = false; private String _valueExpression; static private String[] _EMPTY_ARRAY = new String[0]; }
21.957699
93
0.673114
031b25897cbcd333418c1c1d5ccf2978031b7946
2,562
package io.algobox.api.module.indicator.dao.impl; import com.mongodb.client.MongoDatabase; import io.algobox.api.AbstractMongoIT; import io.algobox.api.module.indicator.dao.PriceOhlcCacheDao; import io.algobox.api.module.instrument.service.impl.TestingConstants; import io.algobox.price.Ohlc; import io.algobox.price.PriceOhlc; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; public class PriceOhlcCacheDaoImplIT extends AbstractMongoIT<PriceOhlcCacheDao> { private static final Ohlc DEFAULT_OHLC_1 = new PriceOhlc(TestingConstants.DEFAULT_INSTRUMENT_DAX, 0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007, 0.008); private static final Ohlc DEFAULT_OHLC_2 = new PriceOhlc(TestingConstants.DEFAULT_INSTRUMENT_DAX, 0.008, 0.009, 0.010, 0.011, 0.012, 0.013, 0.014, 0.015); @Test public void testGetOhlcWhenPresent() { dao.saveOrUpdatePriceOhlc(DEFAULT_OHLC_1, 111L, 222L); dao.saveOrUpdatePriceOhlc(DEFAULT_OHLC_2, 333L, 444L); Ohlc ohlc = dao.getPriceOhlc(TestingConstants.DEFAULT_INSTRUMENT_DAX, 111L, 222L).get(); assertEquals(DEFAULT_OHLC_1.getInstrument(), ohlc.getInstrument()); assertEquals(DEFAULT_OHLC_1.getAskOpen(), ohlc.getAskOpen(), 0); assertEquals(DEFAULT_OHLC_1.getBidOpen(), ohlc.getBidOpen(), 0); assertEquals(DEFAULT_OHLC_1.getAskHigh(), ohlc.getAskHigh(), 0); assertEquals(DEFAULT_OHLC_1.getBidHigh(), ohlc.getBidHigh(), 0); assertEquals(DEFAULT_OHLC_1.getAskLow(), ohlc.getAskLow(), 0); assertEquals(DEFAULT_OHLC_1.getBidLow(), ohlc.getBidLow(), 0); assertEquals(DEFAULT_OHLC_1.getAskClose(), ohlc.getAskClose(), 0); assertEquals(DEFAULT_OHLC_1.getBidClose(), ohlc.getBidClose(), 0); } @Test public void testGetEmptyWhenAbsent() { dao.saveOrUpdatePriceOhlc(DEFAULT_OHLC_1, 111L, 222L); assertFalse(dao.getPriceOhlc(TestingConstants.DEFAULT_INSTRUMENT_DAX, 110L, 222L).isPresent()); assertFalse(dao.getPriceOhlc(TestingConstants.DEFAULT_INSTRUMENT_DAX, 111L, 221L).isPresent()); assertFalse(dao.getPriceOhlc(TestingConstants.DEFAULT_INSTRUMENT_DAX, 111L, 223L).isPresent()); assertFalse(dao.getPriceOhlc(TestingConstants.DEFAULT_INSTRUMENT_DAX, 112L, 222L).isPresent()); } @Test public void testAllowUpdates() { dao.saveOrUpdatePriceOhlc(DEFAULT_OHLC_1, 111L, 222L); dao.saveOrUpdatePriceOhlc(DEFAULT_OHLC_2, 111L, 222L); } @Override protected PriceOhlcCacheDao createDao(MongoDatabase mongoDatabase) { return new PriceOhlcCacheDaoImpl(mongoDatabase); } }
45.75
99
0.773614
ef8d1551658bc62574e07fca628496d184157736
2,365
package org.delaunay.dtfe.painters; import java.awt.BasicStroke; import java.awt.Graphics2D; import java.awt.Point; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import org.delaunay.dtfe.DensityModel; import org.delaunay.dtfe.DtfeTriangulationMap; import org.delaunay.model.Edge; import org.delaunay.model.Vector; import com.google.common.base.Function; import com.google.common.collect.Iterables; public class DtfePainter { private final DtfePainterModel model; public DtfePainter(DtfePainterModel model) { this.model = model; } public Iterable<BufferedImage> paintSlices( final DtfeTriangulationMap<? extends DensityModel> dtfe, PaintTransform transform, int slices) { return Iterables.transform(transform.createSlices(slices), new Function<PaintTransform, BufferedImage>() { public BufferedImage apply(PaintTransform pattern) { return paint(dtfe, pattern); } }); } public BufferedImage paint( DtfeTriangulationMap<? extends DensityModel> dtfe, PaintTransform transform) { BufferedImage img = new BufferedImage(transform.getWidth(), transform.getHeight(), BufferedImage.TYPE_4BYTE_ABGR); Graphics2D g = (Graphics2D) img.getGraphics(); // Fill scanlines for (int y = 0; y < transform.getHeight(); y++) { double[] scanline = new double[transform.getWidth()]; for (int x = 0; x < transform.getWidth(); x++) { Vector v = transform.toDtfeVector(x, y); scanline[x] = dtfe.getInterpolatedDensity(v, model.getInterpolationStrategy()); } int[] rgb = new int[transform.getWidth()]; for (int x = 0; x < transform.getWidth(); x++) { double scale = model.getDensityScalar() * dtfe.getRelativeDensity(scanline[x], model.getScaleType()); rgb[x] = model.getColorScale().get(scale).getRGB(); } img.setRGB(0, y, transform.getWidth(), 1, rgb, 0, transform.getWidth()); } // Draw Edges if (model.getEdgeColor() != null) { g.setColor(model.getEdgeColor()); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setStroke(new BasicStroke(model.getEdgeStrokeWidth())); for (Edge e : TriangulationPainter.getPaintableEdges(dtfe.getTriangulation())) { Point a = transform.toImagePoint(e.a); Point b = transform.toImagePoint(e.b); g.drawLine(a.x, a.y, b.x, b.y); } } return img; } }
31.959459
116
0.723044
363fdcf75b8496080ebfa1216204f612d620d63b
1,860
package cn.cy.web.advice; import cn.cy.web.exception.AbstractExceptionHandleAdvice; import cn.cy.web.exception.ApiException; import cn.cy.web.response.FailedResponse; import cn.hutool.core.exceptions.ExceptionUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.core.Ordered; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import javax.servlet.http.HttpServletRequest; /** * @Author: 友叔(xu) * @Date: 2020/12/4 15:09 * @Description: 全局异常处理 */ @Slf4j @ControllerAdvice public class GlobalExceptionHandleAdvice extends AbstractExceptionHandleAdvice implements Ordered { @ExceptionHandler(ApiException.class) public ResponseEntity<FailedResponse> handleApiException(HttpServletRequest request, ApiException e) { FailedResponse response = FailedResponse.builder() .code(HttpStatus.INTERNAL_SERVER_ERROR.value()) .msg(e.getMessage()) .exception(ExceptionUtil.stacktraceToString(e)) .build(); log.error(e.getMessage()); return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); } @ExceptionHandler(Exception.class) public ResponseEntity<FailedResponse> handle(HttpServletRequest request, Exception e) { FailedResponse response = FailedResponse.builder() .code(HttpStatus.INTERNAL_SERVER_ERROR.value()) .msg(e.getMessage()) .exception(ExceptionUtil.stacktraceToString(e)) .build(); log.error(e.getMessage()); return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); } @Override public int getOrder() { return 100; } }
35.769231
106
0.721505
d34c2439d6905133b7531f7a25a6ea2dd491443f
1,494
package com.sgaop.idea.linemarker; import com.intellij.codeInsight.daemon.LineMarkerInfo; import com.intellij.codeInsight.daemon.LineMarkerProviderDescriptor; import com.intellij.icons.AllIcons; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.markup.GutterIconRenderer; import com.intellij.psi.PsiElement; import com.sgaop.idea.linemarker.navigation.SqlsXmlNavigationHandler; import com.sgaop.util.SqlsXmlUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; /** * @author 黄川 huchuc@vip.qq.com * date: 2019/4/2 */ public class JavaSqlsXmlLineMarkerProvider extends LineMarkerProviderDescriptor { private static final Logger LOG = Logger.getInstance(JavaSqlsXmlLineMarkerProvider.class); @Nullable("null means disabled") @Override public String getName() { return "SqlsXml navigate"; } @Nullable @Override public LineMarkerInfo getLineMarkerInfo(@NotNull PsiElement psiElement) { try { if (SqlsXmlUtil.isSqlsXml(psiElement)) { Icon icon = AllIcons.FileTypes.Xml; return new LineMarkerInfo<>(psiElement, psiElement.getTextRange(), icon, new FunctionTooltip(), new SqlsXmlNavigationHandler(), GutterIconRenderer.Alignment.LEFT, this::getName); } } catch (Exception e) { LOG.warn(e); } return null; } }
31.787234
94
0.704819
08aa997b8c35563f6e79eec9387c77fb3162d616
3,554
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.data.fixer.world; import com.mojang.datafixers.DSL; import com.mojang.datafixers.DataFix; import com.mojang.datafixers.OpticFinder; import com.mojang.datafixers.TypeRewriteRule; import com.mojang.datafixers.Typed; import com.mojang.datafixers.schemas.Schema; import com.mojang.datafixers.types.Type; import com.mojang.datafixers.types.templates.List; import net.minecraft.util.datafix.fixes.References; import org.spongepowered.common.util.Constants; public final class SpongeLevelFixer extends DataFix { public SpongeLevelFixer(Schema outputSchema, boolean changesType) { super(outputSchema, changesType); } public TypeRewriteRule makeRule() { final Type<?> levelType = this.getOutputSchema().getType(References.LEVEL); return TypeRewriteRule.seq( this.fixTypeEverywhereTyped("FixWorldUniqueId", levelType, SpongeLevelFixer::updateUUIDIn), this.fixTypeEverywhereTyped("FixPlayerIdTable", levelType, type -> this.fixPlayerIdTable(type, levelType)) ); } private Typed<?> fixPlayerIdTable(Typed<?> typed, Type<?> levelType) { Type<?> fieldType = levelType.findFieldType(Constants.Sponge.LEGACY_SPONGE_PLAYER_UUID_TABLE); OpticFinder<List.ListType<?>> listFinder = DSL.fieldFinder(Constants.Sponge.LEGACY_SPONGE_PLAYER_UUID_TABLE, (List.ListType)fieldType); Typed<List.ListType<?>> listTyped = typed.getTyped(listFinder); // TODO is this correct? return listTyped.updateRecursiveTyped(DSL.remainderFinder(), SpongeLevelFixer::updateUUIDIn); } public static Typed<?> updateUUIDIn(Typed<?> typed) { return typed.update(DSL.remainderFinder(), data -> { final long least = data.get(Constants.Legacy.Entity.UUID_LEAST_1_8).asLong(0L); final long most = data.get(Constants.Legacy.Entity.UUID_MOST_1_8).asLong(0L); if (least != 0 && most != 0) { return data.remove(Constants.Legacy.Entity.UUID_LEAST_1_8) .remove(Constants.Legacy.Entity.UUID_MOST_1_8) .set(Constants.UUID_MOST, data.createLong(most)) .set(Constants.UUID_LEAST, data.createLong(least)); } return data; }); } }
47.386667
143
0.719471
c162b202b883ab2eb36adab99596f6b48ac5525e
9,849
package uk.gov.hmcts.probate.service.template.pdf; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import uk.gov.hmcts.probate.exception.BadRequestException; import uk.gov.hmcts.probate.model.ccd.caveat.request.CaveatCallbackRequest; import uk.gov.hmcts.probate.model.ccd.raw.request.CallbackRequest; import uk.gov.hmcts.probate.model.ccd.raw.request.CaseData; import uk.gov.hmcts.probate.model.ccd.raw.request.CaseDetails; import uk.gov.hmcts.probate.service.template.pdf.caseextra.decorator.SolicitorCoversheetPDFDecorator; import uk.gov.hmcts.probate.service.template.pdf.caseextra.decorator.SolicitorLegalStatementPDFDecorator; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import static uk.gov.hmcts.probate.model.DocumentType.GRANT_COVER; import static uk.gov.hmcts.probate.model.DocumentType.LEGAL_STATEMENT_ADMON; import static uk.gov.hmcts.probate.model.DocumentType.LEGAL_STATEMENT_INTESTACY; import static uk.gov.hmcts.probate.model.DocumentType.LEGAL_STATEMENT_PROBATE; import static uk.gov.hmcts.probate.model.DocumentType.LEGAL_STATEMENT_PROBATE_TRUST_CORPS; import static uk.gov.hmcts.probate.model.DocumentType.SOLICITOR_COVERSHEET; public class PDFDecoratorServiceTest { private PDFDecoratorService pdfDecoratorService; @Mock private ObjectMapper objectMapperMock; @Mock private SolicitorCoversheetPDFDecorator solicitorCoversheetPDFDecoratorMock; @Mock private SolicitorLegalStatementPDFDecorator solicitorLegalStatementPDFDecoratorMock; @Mock private CallbackRequest callbackRequestMock; @Mock private CaveatCallbackRequest caveatCallbackRequestMock; @Mock private CaseDetails caseDetailsMock; @Mock private CaseData caseDataMock; @Before public void setup() { initMocks(this); when(objectMapperMock.copy()).thenReturn(objectMapperMock); pdfDecoratorService = new PDFDecoratorService(objectMapperMock, solicitorCoversheetPDFDecoratorMock, solicitorLegalStatementPDFDecoratorMock); } @Test public void shouldNotDecorateForCaveatRequest() throws JsonProcessingException { String caseDetailsJson = "{\"case_details\":{\"case_data\":{\"solsSolicitorWillSignSOT\":\"Yes\"}," + "\"id\":1634732500947999,\"state\":\"SolAppUpdated\"}}"; when(objectMapperMock.writeValueAsString(caveatCallbackRequestMock)).thenReturn(caseDetailsJson); String json = pdfDecoratorService.decorate(caveatCallbackRequestMock, SOLICITOR_COVERSHEET); String expectedJson = "{\"case_details\":{\"case_data\":{\"solsSolicitorWillSignSOT\":\"Yes\"}," + "\"id\":1634732500947999,\"state\":\"SolAppUpdated\"},\"case_extras\":{}}"; assertEquals(expectedJson, json); } @Test public void shouldNotDecorateForNonCoversheet() throws JsonProcessingException { String caseDetailsJson = "{\"case_details\":{\"case_data\":{\"solsSolicitorWillSignSOT\":\"Yes\"}," + "\"id\":1634732500947999,\"state\":\"SolAppUpdated\"}}"; when(objectMapperMock.writeValueAsString(callbackRequestMock)).thenReturn(caseDetailsJson); String json = pdfDecoratorService.decorate(callbackRequestMock, GRANT_COVER); String expectedJson = "{\"case_details\":{\"case_data\":{\"solsSolicitorWillSignSOT\":\"Yes\"}," + "\"id\":1634732500947999,\"state\":\"SolAppUpdated\"},\"case_extras\":{}}"; assertEquals(expectedJson, json); } @Test(expected = BadRequestException.class) public void shouldNotDecorateThrowBadRequest() throws JsonProcessingException { when(objectMapperMock.writeValueAsString(caveatCallbackRequestMock)).thenThrow(JsonProcessingException.class); pdfDecoratorService.decorate(caveatCallbackRequestMock, SOLICITOR_COVERSHEET); } @Test public void shouldDecorateSolicitorCoversheet() throws JsonProcessingException { String caseDetailsJson = "{\"case_details\":{\"case_data\":{\"solsSolicitorWillSignSOT\":\"Yes\"}," + "\"id\":1634732500947999,\"state\":\"SolAppUpdated\"}}"; String caseExtraJson = "{\"showPa16Form\" : \"Yes\",\"pa16FormText\" : \"<PA16FormText>\"}"; when(objectMapperMock.writeValueAsString(callbackRequestMock)).thenReturn(caseDetailsJson); when(callbackRequestMock.getCaseDetails()).thenReturn(caseDetailsMock); when(caseDetailsMock.getData()).thenReturn(caseDataMock); String expectedJson = "{\"case_details\":{\"case_data\":{\"solsSolicitorWillSignSOT\":\"Yes\"}," + "\"id\":1634732500947999,\"state\":\"SolAppUpdated\"},\"case_extras\":{\"showPa16Form\" : \"Yes\"," + "\"pa16FormText\" : \"<PA16FormText>\"}}"; when(solicitorCoversheetPDFDecoratorMock.decorate(caseDataMock)).thenReturn(caseExtraJson); String json = pdfDecoratorService.decorate(callbackRequestMock, SOLICITOR_COVERSHEET); assertEquals(expectedJson, json); } @Test public void shouldDecorateSolicitorLegalStatementProbateTC() throws JsonProcessingException { String caseDetailsJson = "{\"case_details\":{\"case_data\":{\"solsSolicitorWillSignSOT\":\"Yes\"}," + "\"id\":1634732500947999,\"state\":\"SolAppUpdated\"}}"; String caseExtraJson = "{\"showPa16Form\" : \"Yes\",\"pa16FormText\" : \"<PA16FormText>\"}"; when(objectMapperMock.writeValueAsString(callbackRequestMock)).thenReturn(caseDetailsJson); when(callbackRequestMock.getCaseDetails()).thenReturn(caseDetailsMock); when(caseDetailsMock.getData()).thenReturn(caseDataMock); String expectedJson = "{\"case_details\":{\"case_data\":{\"solsSolicitorWillSignSOT\":\"Yes\"}," + "\"id\":1634732500947999,\"state\":\"SolAppUpdated\"},\"case_extras\":{\"showPa16Form\" : \"Yes\"," + "\"pa16FormText\" : \"<PA16FormText>\"}}"; when(solicitorLegalStatementPDFDecoratorMock.decorate(caseDataMock)).thenReturn(caseExtraJson); String json = pdfDecoratorService.decorate(callbackRequestMock, LEGAL_STATEMENT_PROBATE_TRUST_CORPS); assertEquals(expectedJson, json); } @Test public void shouldDecorateSolicitorLegalStatementProbate() throws JsonProcessingException { String caseDetailsJson = "{\"case_details\":{\"case_data\":{\"solsSolicitorWillSignSOT\":\"Yes\"}," + "\"id\":1634732500947999,\"state\":\"SolAppUpdated\"}}"; String caseExtraJson = "{\"showPa16Form\" : \"Yes\",\"pa16FormText\" : \"<PA16FormText>\"}"; when(objectMapperMock.writeValueAsString(callbackRequestMock)).thenReturn(caseDetailsJson); when(callbackRequestMock.getCaseDetails()).thenReturn(caseDetailsMock); when(caseDetailsMock.getData()).thenReturn(caseDataMock); String expectedJson = "{\"case_details\":{\"case_data\":{\"solsSolicitorWillSignSOT\":\"Yes\"}," + "\"id\":1634732500947999,\"state\":\"SolAppUpdated\"},\"case_extras\":{\"showPa16Form\" : \"Yes\"," + "\"pa16FormText\" : \"<PA16FormText>\"}}"; when(solicitorLegalStatementPDFDecoratorMock.decorate(caseDataMock)).thenReturn(caseExtraJson); String json = pdfDecoratorService.decorate(callbackRequestMock, LEGAL_STATEMENT_PROBATE); assertEquals(expectedJson, json); } @Test public void shouldDecorateSolicitorLegalStatementIntestacy() throws JsonProcessingException { String caseDetailsJson = "{\"case_details\":{\"case_data\":{\"solsSolicitorWillSignSOT\":\"Yes\"}," + "\"id\":1634732500947999,\"state\":\"SolAppUpdated\"}}"; String caseExtraJson = "{\"showPa16Form\" : \"Yes\",\"pa16FormText\" : \"<PA16FormText>\"}"; when(objectMapperMock.writeValueAsString(callbackRequestMock)).thenReturn(caseDetailsJson); when(callbackRequestMock.getCaseDetails()).thenReturn(caseDetailsMock); when(caseDetailsMock.getData()).thenReturn(caseDataMock); String expectedJson = "{\"case_details\":{\"case_data\":{\"solsSolicitorWillSignSOT\":\"Yes\"}," + "\"id\":1634732500947999,\"state\":\"SolAppUpdated\"},\"case_extras\":{\"showPa16Form\" : \"Yes\"," + "\"pa16FormText\" : \"<PA16FormText>\"}}"; when(solicitorLegalStatementPDFDecoratorMock.decorate(caseDataMock)).thenReturn(caseExtraJson); String json = pdfDecoratorService.decorate(callbackRequestMock, LEGAL_STATEMENT_INTESTACY); assertEquals(expectedJson, json); } @Test public void shouldDecorateSolicitorLegalStatementAdmon() throws JsonProcessingException { String caseDetailsJson = "{\"case_details\":{\"case_data\":{\"solsSolicitorWillSignSOT\":\"Yes\"}," + "\"id\":1634732500947999,\"state\":\"SolAppUpdated\"}}"; String caseExtraJson = "{\"showPa16Form\" : \"Yes\",\"pa16FormText\" : \"<PA16FormText>\"}"; when(objectMapperMock.writeValueAsString(callbackRequestMock)).thenReturn(caseDetailsJson); when(callbackRequestMock.getCaseDetails()).thenReturn(caseDetailsMock); when(caseDetailsMock.getData()).thenReturn(caseDataMock); String expectedJson = "{\"case_details\":{\"case_data\":{\"solsSolicitorWillSignSOT\":\"Yes\"}," + "\"id\":1634732500947999,\"state\":\"SolAppUpdated\"},\"case_extras\":{\"showPa16Form\" : \"Yes\"," + "\"pa16FormText\" : \"<PA16FormText>\"}}"; when(solicitorLegalStatementPDFDecoratorMock.decorate(caseDataMock)).thenReturn(caseExtraJson); String json = pdfDecoratorService.decorate(callbackRequestMock, LEGAL_STATEMENT_ADMON); assertEquals(expectedJson, json); } }
56.28
118
0.714489
045b1f8b91279f3e75df2a05539a3dce1d28f44c
1,298
package com.example.xzr.activitytest; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button nextBtn = findViewById(R.id.gotoNext); nextBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this,Main2Activity.class); intent.putExtra("mainExtra","this is a string from main activity"); // 1 is request code startActivityForResult(intent,1); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case 1: if (resultCode == RESULT_OK) { TextView mainText = findViewById(R.id.mainText); mainText.setText(data.getStringExtra("main2Extra")); } } } }
30.904762
83
0.632512
55bedafcd4c21341db6a758914ebb784b8f9bac0
21,412
/* * 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 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.watcher; import org.apache.lucene.util.LuceneTestCase; import org.elasticsearch.core.internal.io.IOUtils; import org.elasticsearch.test.ESTestCase; import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.nio.file.attribute.FileTime; import java.util.ArrayList; import java.util.List; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; @LuceneTestCase.SuppressFileSystems("ExtrasFS") public class FileWatcherTests extends ESTestCase { private class RecordingChangeListener implements FileChangesListener { private Path rootDir; private RecordingChangeListener(Path rootDir) { this.rootDir = rootDir; } private String getRelativeFileName(Path file) { return rootDir.toUri().relativize(file.toUri()).getPath(); } private List<String> notifications = new ArrayList<>(); @Override public void onFileInit(Path file) { notifications.add("onFileInit: " + getRelativeFileName(file)); } @Override public void onDirectoryInit(Path file) { notifications.add("onDirectoryInit: " + getRelativeFileName(file)); } @Override public void onFileCreated(Path file) { notifications.add("onFileCreated: " + getRelativeFileName(file)); } @Override public void onFileDeleted(Path file) { notifications.add("onFileDeleted: " + getRelativeFileName(file)); } @Override public void onFileChanged(Path file) { notifications.add("onFileChanged: " + getRelativeFileName(file)); } @Override public void onDirectoryCreated(Path file) { notifications.add("onDirectoryCreated: " + getRelativeFileName(file)); } @Override public void onDirectoryDeleted(Path file) { notifications.add("onDirectoryDeleted: " + getRelativeFileName(file)); } public List<String> notifications() { return notifications; } } public void testSimpleFileOperations() throws IOException { Path tempDir = createTempDir(); RecordingChangeListener changes = new RecordingChangeListener(tempDir); Path testFile = tempDir.resolve("test.txt"); touch(testFile); FileWatcher fileWatcher = new FileWatcher(testFile); fileWatcher.addListener(changes); fileWatcher.init(); assertThat(changes.notifications(), contains(equalTo("onFileInit: test.txt"))); changes.notifications().clear(); fileWatcher.checkAndNotify(); assertThat(changes.notifications(), hasSize(0)); append("Test", testFile, Charset.defaultCharset()); fileWatcher.checkAndNotify(); assertThat(changes.notifications(), contains(equalTo("onFileChanged: test.txt"))); changes.notifications().clear(); fileWatcher.checkAndNotify(); assertThat(changes.notifications(), hasSize(0)); // change modification date, but not contents [we set the time in the future to guarantee a change] Files.setLastModifiedTime(testFile, FileTime.fromMillis(System.currentTimeMillis() + 1)); fileWatcher.checkAndNotify(); assertThat(changes.notifications(), contains(equalTo("onFileChanged: test.txt"))); changes.notifications().clear(); Files.delete(testFile); fileWatcher.checkAndNotify(); assertThat(changes.notifications(), contains(equalTo("onFileDeleted: test.txt"))); } public void testSimpleFileOperationsWithContentChecking() throws IOException { Path tempDir = createTempDir(); RecordingChangeListener changes = new RecordingChangeListener(tempDir); Path testFile = tempDir.resolve("test.txt"); touch(testFile); FileWatcher fileWatcher = new FileWatcher(testFile, true); fileWatcher.addListener(changes); fileWatcher.init(); assertThat(changes.notifications(), contains(equalTo("onFileInit: test.txt"))); changes.notifications().clear(); fileWatcher.checkAndNotify(); assertThat(changes.notifications(), empty()); append("Test", testFile, Charset.defaultCharset()); fileWatcher.checkAndNotify(); assertThat(changes.notifications(), contains(equalTo("onFileChanged: test.txt"))); changes.notifications().clear(); // change modification date, but not contents Files.setLastModifiedTime(testFile, FileTime.fromMillis(System.currentTimeMillis() + 1)); fileWatcher.checkAndNotify(); assertThat(changes.notifications(), empty()); changes.notifications().clear(); // change modification date again, but not contents Files.setLastModifiedTime(testFile, FileTime.fromMillis(System.currentTimeMillis() + 2)); fileWatcher.checkAndNotify(); // This will not trigger a notification because the hash was calculated last time assertThat(changes.notifications(), empty()); // Change file length without changing modification time final FileTime modifiedTime = Files.getLastModifiedTime(testFile); append("Modified", testFile, Charset.defaultCharset()); Files.setLastModifiedTime(testFile, modifiedTime); fileWatcher.checkAndNotify(); assertThat(changes.notifications(), contains(equalTo("onFileChanged: test.txt"))); changes.notifications().clear(); Files.delete(testFile); fileWatcher.checkAndNotify(); assertThat(changes.notifications(), contains(equalTo("onFileDeleted: test.txt"))); } public void testSimpleDirectoryOperations() throws IOException { Path tempDir = createTempDir(); RecordingChangeListener changes = new RecordingChangeListener(tempDir); Path testDir = tempDir.resolve("test-dir"); Files.createDirectories(testDir); touch(testDir.resolve("test.txt")); touch(testDir.resolve("test0.txt")); FileWatcher fileWatcher = new FileWatcher(testDir); fileWatcher.addListener(changes); fileWatcher.init(); assertThat( changes.notifications(), contains( equalTo("onDirectoryInit: test-dir/"), equalTo("onFileInit: test-dir/test.txt"), equalTo("onFileInit: test-dir/test0.txt") ) ); changes.notifications().clear(); fileWatcher.checkAndNotify(); assertThat(changes.notifications(), hasSize(0)); for (int i = 0; i < 4; i++) { touch(testDir.resolve("test" + i + ".txt")); } // Make sure that first file is modified append("Test", testDir.resolve("test0.txt"), Charset.defaultCharset()); fileWatcher.checkAndNotify(); assertThat( changes.notifications(), contains( equalTo("onFileChanged: test-dir/test0.txt"), equalTo("onFileCreated: test-dir/test1.txt"), equalTo("onFileCreated: test-dir/test2.txt"), equalTo("onFileCreated: test-dir/test3.txt") ) ); changes.notifications().clear(); fileWatcher.checkAndNotify(); assertThat(changes.notifications(), hasSize(0)); Files.delete(testDir.resolve("test1.txt")); Files.delete(testDir.resolve("test2.txt")); fileWatcher.checkAndNotify(); assertThat( changes.notifications(), contains(equalTo("onFileDeleted: test-dir/test1.txt"), equalTo("onFileDeleted: test-dir/test2.txt")) ); changes.notifications().clear(); fileWatcher.checkAndNotify(); assertThat(changes.notifications(), hasSize(0)); Files.delete(testDir.resolve("test0.txt")); touch(testDir.resolve("test2.txt")); touch(testDir.resolve("test4.txt")); fileWatcher.checkAndNotify(); assertThat( changes.notifications(), contains( equalTo("onFileDeleted: test-dir/test0.txt"), equalTo("onFileCreated: test-dir/test2.txt"), equalTo("onFileCreated: test-dir/test4.txt") ) ); changes.notifications().clear(); Files.delete(testDir.resolve("test3.txt")); Files.delete(testDir.resolve("test4.txt")); fileWatcher.checkAndNotify(); assertThat( changes.notifications(), contains(equalTo("onFileDeleted: test-dir/test3.txt"), equalTo("onFileDeleted: test-dir/test4.txt")) ); changes.notifications().clear(); if (Files.exists(testDir)) { IOUtils.rm(testDir); } fileWatcher.checkAndNotify(); assertThat( changes.notifications(), contains( equalTo("onFileDeleted: test-dir/test.txt"), equalTo("onFileDeleted: test-dir/test2.txt"), equalTo("onDirectoryDeleted: test-dir") ) ); } public void testSimpleDirectoryOperationsWithContentChecking() throws IOException { final long startTime = System.currentTimeMillis(); Path tempDir = createTempDir(); RecordingChangeListener changes = new RecordingChangeListener(tempDir); Path testDir = tempDir.resolve("test-dir"); Files.createDirectories(testDir); for (String fileName : List.of("test1.txt", "test2.txt", "test3.txt", "test4.txt")) { Files.writeString(testDir.resolve(fileName), "initial", StandardCharsets.UTF_8); } FileWatcher fileWatcher = new FileWatcher(testDir, true); fileWatcher.addListener(changes); fileWatcher.init(); assertThat( changes.notifications(), contains( equalTo("onDirectoryInit: test-dir/"), equalTo("onFileInit: test-dir/test1.txt"), equalTo("onFileInit: test-dir/test2.txt"), equalTo("onFileInit: test-dir/test3.txt"), equalTo("onFileInit: test-dir/test4.txt") ) ); changes.notifications().clear(); fileWatcher.checkAndNotify(); assertThat(changes.notifications(), hasSize(0)); // Modify the length of file #1 append("Test-1", testDir.resolve("test1.txt"), Charset.defaultCharset()); // Change lastModified on file #2 (set it to before this test started so there's no chance of accidental matching) // However the contents haven't changed, so it won't be notified Files.setLastModifiedTime(testDir.resolve("test2.txt"), FileTime.fromMillis(startTime - 100)); // Add a new file Files.writeString(testDir.resolve("test5.txt"), "abc", StandardCharsets.UTF_8); fileWatcher.checkAndNotify(); assertThat(changes.notifications(), containsInAnyOrder("onFileChanged: test-dir/test1.txt", "onFileCreated: test-dir/test5.txt")); // Change file #2 but don't change the size Files.writeString(testDir.resolve("test2.txt"), "changed", StandardCharsets.UTF_8); // Change lastModified on file #3 (newer than the last update, but still before the test started) // But no change to contents, so no notification Files.setLastModifiedTime(testDir.resolve("test3.txt"), FileTime.fromMillis(startTime - 50)); changes.notifications().clear(); fileWatcher.checkAndNotify(); assertThat(changes.notifications(), containsInAnyOrder(equalTo("onFileChanged: test-dir/test2.txt"))); // change the contents of files #2 (change in size) and #3 (same size) Files.writeString(testDir.resolve("test2.txt"), "new contents", StandardCharsets.UTF_8); Files.writeString(testDir.resolve("test3.txt"), "updated", StandardCharsets.UTF_8); changes.notifications().clear(); fileWatcher.checkAndNotify(); assertThat( changes.notifications(), containsInAnyOrder(equalTo("onFileChanged: test-dir/test2.txt"), equalTo("onFileChanged: test-dir/test3.txt")) ); // Change lastModified on files #2 & #3, but not the contents Files.setLastModifiedTime(testDir.resolve("test2.txt"), FileTime.fromMillis(System.currentTimeMillis() + 3)); Files.setLastModifiedTime(testDir.resolve("test3.txt"), FileTime.fromMillis(System.currentTimeMillis() + 3)); changes.notifications().clear(); fileWatcher.checkAndNotify(); assertThat(changes.notifications(), hasSize(0)); // Do nothing fileWatcher.checkAndNotify(); assertThat(changes.notifications(), hasSize(0)); // Delete files Files.delete(testDir.resolve("test1.txt")); Files.delete(testDir.resolve("test2.txt")); fileWatcher.checkAndNotify(); assertThat( changes.notifications(), contains(equalTo("onFileDeleted: test-dir/test1.txt"), equalTo("onFileDeleted: test-dir/test2.txt")) ); } public void testNestedDirectoryOperations() throws IOException { Path tempDir = createTempDir(); RecordingChangeListener changes = new RecordingChangeListener(tempDir); Path testDir = tempDir.resolve("test-dir"); Files.createDirectories(testDir); touch(testDir.resolve("test.txt")); Files.createDirectories(testDir.resolve("sub-dir")); touch(testDir.resolve("sub-dir/test0.txt")); FileWatcher fileWatcher = new FileWatcher(testDir); fileWatcher.addListener(changes); fileWatcher.init(); assertThat( changes.notifications(), contains( equalTo("onDirectoryInit: test-dir/"), equalTo("onDirectoryInit: test-dir/sub-dir/"), equalTo("onFileInit: test-dir/sub-dir/test0.txt"), equalTo("onFileInit: test-dir/test.txt") ) ); changes.notifications().clear(); fileWatcher.checkAndNotify(); assertThat(changes.notifications(), hasSize(0)); // Create new file in subdirectory touch(testDir.resolve("sub-dir/test1.txt")); fileWatcher.checkAndNotify(); assertThat(changes.notifications(), contains(equalTo("onFileCreated: test-dir/sub-dir/test1.txt"))); changes.notifications().clear(); fileWatcher.checkAndNotify(); assertThat(changes.notifications(), hasSize(0)); // Create new subdirectory in subdirectory Files.createDirectories(testDir.resolve("first-level")); touch(testDir.resolve("first-level/file1.txt")); Files.createDirectories(testDir.resolve("first-level/second-level")); touch(testDir.resolve("first-level/second-level/file2.txt")); fileWatcher.checkAndNotify(); assertThat( changes.notifications(), contains( equalTo("onDirectoryCreated: test-dir/first-level/"), equalTo("onFileCreated: test-dir/first-level/file1.txt"), equalTo("onDirectoryCreated: test-dir/first-level/second-level/"), equalTo("onFileCreated: test-dir/first-level/second-level/file2.txt") ) ); changes.notifications().clear(); fileWatcher.checkAndNotify(); assertThat(changes.notifications(), hasSize(0)); // Delete a directory, check notifications for Path path = testDir.resolve("first-level"); if (Files.exists(path)) { IOUtils.rm(path); } fileWatcher.checkAndNotify(); assertThat( changes.notifications(), contains( equalTo("onFileDeleted: test-dir/first-level/file1.txt"), equalTo("onFileDeleted: test-dir/first-level/second-level/file2.txt"), equalTo("onDirectoryDeleted: test-dir/first-level/second-level"), equalTo("onDirectoryDeleted: test-dir/first-level") ) ); } public void testFileReplacingDirectory() throws IOException { Path tempDir = createTempDir(); RecordingChangeListener changes = new RecordingChangeListener(tempDir); Path testDir = tempDir.resolve("test-dir"); Files.createDirectories(testDir); Path subDir = testDir.resolve("sub-dir"); Files.createDirectories(subDir); touch(subDir.resolve("test0.txt")); touch(subDir.resolve("test1.txt")); FileWatcher fileWatcher = new FileWatcher(testDir); fileWatcher.addListener(changes); fileWatcher.init(); assertThat( changes.notifications(), contains( equalTo("onDirectoryInit: test-dir/"), equalTo("onDirectoryInit: test-dir/sub-dir/"), equalTo("onFileInit: test-dir/sub-dir/test0.txt"), equalTo("onFileInit: test-dir/sub-dir/test1.txt") ) ); changes.notifications().clear(); if (Files.exists(subDir)) { IOUtils.rm(subDir); } touch(subDir); fileWatcher.checkAndNotify(); assertThat( changes.notifications(), contains( equalTo("onFileDeleted: test-dir/sub-dir/test0.txt"), equalTo("onFileDeleted: test-dir/sub-dir/test1.txt"), equalTo("onDirectoryDeleted: test-dir/sub-dir"), equalTo("onFileCreated: test-dir/sub-dir") ) ); changes.notifications().clear(); Files.delete(subDir); Files.createDirectories(subDir); fileWatcher.checkAndNotify(); assertThat( changes.notifications(), contains(equalTo("onFileDeleted: test-dir/sub-dir/"), equalTo("onDirectoryCreated: test-dir/sub-dir/")) ); } public void testEmptyDirectory() throws IOException { Path tempDir = createTempDir(); RecordingChangeListener changes = new RecordingChangeListener(tempDir); Path testDir = tempDir.resolve("test-dir"); Files.createDirectories(testDir); touch(testDir.resolve("test0.txt")); touch(testDir.resolve("test1.txt")); FileWatcher fileWatcher = new FileWatcher(testDir); fileWatcher.addListener(changes); fileWatcher.init(); changes.notifications().clear(); Files.delete(testDir.resolve("test0.txt")); Files.delete(testDir.resolve("test1.txt")); fileWatcher.checkAndNotify(); assertThat( changes.notifications(), contains(equalTo("onFileDeleted: test-dir/test0.txt"), equalTo("onFileDeleted: test-dir/test1.txt")) ); } public void testNoDirectoryOnInit() throws IOException { Path tempDir = createTempDir(); RecordingChangeListener changes = new RecordingChangeListener(tempDir); Path testDir = tempDir.resolve("test-dir"); FileWatcher fileWatcher = new FileWatcher(testDir); fileWatcher.addListener(changes); fileWatcher.init(); assertThat(changes.notifications(), hasSize(0)); changes.notifications().clear(); Files.createDirectories(testDir); touch(testDir.resolve("test0.txt")); touch(testDir.resolve("test1.txt")); fileWatcher.checkAndNotify(); assertThat( changes.notifications(), contains( equalTo("onDirectoryCreated: test-dir/"), equalTo("onFileCreated: test-dir/test0.txt"), equalTo("onFileCreated: test-dir/test1.txt") ) ); } public void testNoFileOnInit() throws IOException { Path tempDir = createTempDir(); RecordingChangeListener changes = new RecordingChangeListener(tempDir); Path testFile = tempDir.resolve("testfile.txt"); FileWatcher fileWatcher = new FileWatcher(testFile); fileWatcher.addListener(changes); fileWatcher.init(); assertThat(changes.notifications(), hasSize(0)); changes.notifications().clear(); touch(testFile); fileWatcher.checkAndNotify(); assertThat(changes.notifications(), contains(equalTo("onFileCreated: testfile.txt"))); } static void touch(Path path) throws IOException { Files.newOutputStream(path).close(); } static void append(String string, Path path, Charset cs) throws IOException { try (BufferedWriter writer = Files.newBufferedWriter(path, cs, StandardOpenOption.APPEND)) { writer.append(string); } } }
38.930909
138
0.636979
20bcf357abbee7abe97d1dc2a82acaccbb70324c
752
package quick.pager.shop.activity.model; import com.baomidou.mybatisplus.annotation.TableName; import java.math.BigDecimal; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import quick.pager.shop.model.Model; /** * @author siguiyang */ @EqualsAndHashCode(callSuper = true) @Data @Accessors(chain = true) @TableName("t_exchange_activity_rule") public class ExchangeActivityRule extends Model { private static final long serialVersionUID = -6238358371738961355L; /** * t_exchange_activity id */ private Long activityId; /** * 规则名称 */ private String ruleName; /** * 购买商品满足的金额条件下限 */ private BigDecimal orderAmount; private Boolean serverStatus; }
22.117647
71
0.728723
71c315cad97153adb9616e9764271088783ac282
924
package com.github.franckyi.gameadapter; import com.github.franckyi.gameadapter.forge.ForgeGameClient; import com.github.franckyi.gameadapter.forge.ForgeGameCommon; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; @Mod("gameadapter") public final class ForgeGameAdapterMod { public ForgeGameAdapterMod() { FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onCommonInit); FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onClientInit); } private void onCommonInit(FMLCommonSetupEvent event) { Game.setCommon(ForgeGameCommon.INSTANCE); } private void onClientInit(FMLClientSetupEvent event) { Game.setClient(ForgeGameClient.INSTANCE); } }
36.96
88
0.792208
d381460f53385ea2231990c65140205a3c300e7a
1,694
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.github.anaelcarvalho.dao; import com.github.anaelcarvalho.model.UserLogin; /** * UserLogin Data Access Object interface, defining available operations * * @author anaelcarvalho */ public interface UserLoginDAO { /** * Persists a new UserLogin entity. * * @param userLogin the UserLogin entity to persist. */ public void addUserLogin(UserLogin userLogin); /** * Returns the UserLogin entity with the provided login. * * @param login the login of the UserLogin to return. * @return the UserLogin entity with the provided login or null if no UserLogin was found. */ public UserLogin getUserLoginByLogin(String login); /** * Updates an existing UserLogin entity. * * @param user the UserLogin entity to update. */ public void updateLogin(UserLogin userLogin); /** * Verifies an UserLogin entity exists with the provided attribute (login). * * @param login the login String attribute to verify. * @return the flag indicating whether a UserLogin was found with the provided attribute. */ public boolean userLoginExists(String login); }
33.215686
95
0.72255
6ba837e90728426052bb3470aa2a321bbf6a8ce8
662
package com.zhding.integration.Spring.aware; import com.zhding.integration.util.UnitTestBase; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.BlockJUnit4ClassRunner; @RunWith(BlockJUnit4ClassRunner.class) public class TestAware extends UnitTestBase { public TestAware() { super("classpath:spring-aware.xml"); } // @Test // public void testMoocApplicationContext() { // System.out.println("testMoocApplicationContext : " + super.getBean("moocApplicationContext").hashCode()); // } @Test public void textMoocBeanName() { System.out.println("textMoocBeanName : " + super.getBean("moocBeanName").hashCode()); } }
25.461538
109
0.758308
66d8a149f124d6891d9a6a3a040be406f99d0936
648
package response; /** singleton class for terminal output */ public class TerminalConsumer implements ResponseConsumer { private static TerminalConsumer terminal = null; /** private constructor, to disallow instantiation */ private TerminalConsumer(){} public static TerminalConsumer singleton() { if (terminal == null) { terminal = new TerminalConsumer(); } return terminal; } /** * outputs the response to the terminal as a raw string. */ @Override public void receiveResponse(CommandResponse response) { System.out.println(response.toString()); } }
24
60
0.658951
fb835010f44b6b292e147f2b2140e88d76f8330a
415
package com.flyonsky; import de.codecentric.boot.admin.server.config.EnableAdminServer; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; @SpringBootApplication @EnableAdminServer public class Application { public static void main(String[] args) { new SpringApplicationBuilder(Application.class).run(args); } }
27.666667
68
0.809639
330713274329fe5a45c18248199d341b5715f470
4,332
package uk.co.idealflatmate.appmanager; import com.codeborne.selenide.SelenideElement; import org.testng.Assert; import static com.codeborne.selenide.Condition.*; import static com.codeborne.selenide.Selectors.byXpath; import static com.codeborne.selenide.Selenide.*; import static com.codeborne.selenide.WebDriverRunner.url; import static uk.co.idealflatmate.appmanager.SearchHelper.getNumberOfListing; public class FooterHelper extends HelperBase{ public void verificationFooterHome() { $(byXpath("//div[@class='homepage-quiz-container container']")).waitUntil(exist, 6000).should(exist); } public void verificationBrowseFlatshares(String location, String area, final String searchText, final String text, final String rooms) { $(byXpath("//a/strong[contains(., '"+location+"')]")).click(); $(byXpath("//a/strong[contains(., '"+area+"')]")).click(); clickButton(searchText, "a"); closeAdvPopUp(); //switchTo().window(1); $(byXpath("//h1[@class='h4']")).shouldHave(text(text + getNumberOfListing() + rooms + area)); } public static int propertyCardOnPage() { int propertyCardOnPage = $$(byXpath("//div[@class='cards-container']/div[@id]")).size(); return propertyCardOnPage; } public void verificationHowItWorks() { $(byXpath("//h2")).waitUntil(visible, 10000).shouldHave(text("How Ideal Flatmate Works")); } public SelenideElement verificationHowItWorks1(String text) { return $(byXpath("//h2")).waitUntil(visible, 8000).shouldHave(text(text)); } public void verificationTipsWorks() { $(byXpath("//title[contains(text(), 'Tips')]")).waitUntil(exist, 6000).should(exist); } public void footerNLAWorks() { hoverClick("//div[@class='payment-logos']"); hoverClick("//div[@class='row']//div[@class='col-md-6 hidden-xs hidden-sm text-right']//img"); } public void verificationNLAWorks() { switchTo().window(0); hoverCShouldExist("(//ul/li/a[contains(text(), 'Join the NLA')])[1]"); sleep(3000); } public void footerFB() { hoverClick("//img[@alt='Facebook']"); } public void verificationFB() { switchTo().window(1); String urlNla= url(); String urlCurrent = "https://www.facebook.com/idealflatmate/"; Assert.assertEquals(urlCurrent, urlNla); //$(byXpath("//a[@class='_64-f' and @href='https://www.facebook.com/idealflatmate/']")).shouldBe(visible); toHomePage(); } public void footerTwitter() { $(byXpath("//img[@alt='Twitter']")).waitUntil(visible, 4000).click(); } public void verificationTwitter() { switchTo().window(1); $(byXpath("//img[@class='ProfileAvatar-image ' and @alt='ideal flatmate']")).waitUntil(exist, 30000).should(exist); } public void footerInstagram() { $(byXpath("//img[@alt='Instagram']")).waitUntil(visible, 4000).click(); } public void verificationInstagram() { switchTo().window(1); $(byXpath("(//h1)[1]")).waitUntil(exist, 30000).shouldHave(text("idealflatmate")); } public void footerYoutube() { $(byXpath("//img[@alt='YouTube']")).waitUntil(visible, 4000).click(); } public void verificationYoutube() { switchTo().window(1); $(byXpath("//span[@id='channel-title' and contains(text(), 'ideal flatmate')]")).waitUntil(exist, 30000).should(exist); } public void verificationAskLandlord() { switchTo().window(1); $(byXpath("//h1[contains(., '#AsktheLandlord')]")).should(exist); } public void verificationModern() { switchTo().window(1); $(byXpath("//h1[contains(., 'Modern Living Index')]")).should(exist); } public void footerClick(String item) { sleep(2000); hoverClick("//a[@class='u_ed-block u_p5-top u_p5-bottom' and contains(., '" + item + "')]"); } public void verificationFooter(String titleItem) { $(byXpath("//title[contains(text(), '" + titleItem + "')]")).waitUntil(exist, 10000).should(exist); } //pageobject /* public SelenideElement verificationHowItWorks1(String text) { return $(byXpath("//h2")).waitUntil(visible, 8000).shouldHave(text(text)); }*/ }
31.165468
140
0.62904